mcpField
A
atlas

atlas

github.com/ariga数据与数据库8.8k75 次安装1 周前更新
代码仓库

关于 atlas

Atlas 是一项指导 Agent 处理数据库架构变更、迁移、数据脚本和云端运维的技能。它涵盖版本化与声明式工作流,并包括验证、测试、检查、漂移检测和部署审查。

主要功能

  1. 01版本化与声明式架构工作流
  2. 02生成、检查和测试迁移
  3. 03架构验证与应用预览
  4. 04漂移检测与云端状态查询
  5. 05带测试和保护条件的 HCL 数据脚本

适用场景

  1. 01生成并审查数据库迁移
  2. 02经审批应用声明式架构变更
  3. 03检查数据库漂移或部署状态
  4. 04运行经过测试的数据回填或报告

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ariga/atlas --skill atlas

安装后在 Claude Code 中输入/atlas确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
cicd.md
cloud.md
declarative.md
drift.md
lint.md
schema-sources.md
scripts.md
testing.md
versioned.md

详细介绍

Atlas:架构迁移、数据脚本和云操作

文件

此技能包含 SKILL.md 和 references/ 下的九个参考文件,每个文件均位于 https://atlasgo.io/skills/atlas/references/<name>:schema-sources.md、versioned.md、declarative.md、 cicd.md、lint.md、testing.md、drift.md、cloud.md 和 scripts.md。仅在任务需要时阅读参考文件;下文的“选择工作流”会说明应阅读哪个文件。

安全

切勿硬编码凭据。在 atlas.hcl 中使用环境变量:

env "prod" {
  url = getenv("DATABASE_URL")
}

始终使用 --env <name> 运行命令,让数据库 URL 保存在 atlas.hcl 中,不要出现在对话里。先阅读 atlas.hcl,了解环境名称。

快速参考

对任意命令使用 --help 查看完整文档和示例:atlas migrate diff --help。

# Setup
atlas version                                        # Installed version
atlas whoami                                         # Login status and org
atlas login                                          # Needed by lint, test, drift, plan, scripts, schema lint, and cloud

# Schema
atlas schema inspect --env <name>                    # Inspect current schema
atlas schema validate --env <name>                   # Validate schema syntax/semantics
atlas schema diff --env <name> --from env://url --to file://schema.hcl   # Live database vs desired schema
atlas schema lint --env <name>                       # Check schema policies
atlas schema test --env <name>                       # Test schema logic

# Declarative workflow
atlas schema plan --env <name>                       # Pre-plan changes for review
atlas schema apply --env <name> --dry-run            # Preview changes
atlas schema apply --env <name>                      # Apply schema changes

# Versioned workflow
atlas migrate diff --env <name> "migration_name"     # Generate migration
atlas migrate lint --env <name> --latest 1           # Lint the newest migration
atlas migrate test --env <name>                      # Test migrations
atlas migrate apply --env <name> --dry-run           # Preview changes
atlas migrate apply --env <name>                     # Apply migration
atlas migrate status --env <name>                    # Live database vs migration directory
atlas migrate down --env <name> --dry-run            # Preview reverting the last migration
atlas migrate hash --env <name>                      # Recompute atlas.sum after manual edits
atlas migrate new --env <name> "name"                # Empty migration file for hand-written SQL
atlas migrate checkpoint --env <name>                # Squash history into a checkpoint file
atlas migrate rebase --env <name> <version>          # Rebase a migration onto newer files
atlas migrate push --env <name>                      # Push the directory to the Atlas Registry

# Linting and testing (see references/lint.md, references/testing.md)
atlas migrate lint --env ci                          # CI: new files vs the registry repo they match
atlas migrate lint --env ci --base atlas://<repo>    # The same, naming the repo: when several match
atlas migrate lint --env ci --git-base master        # No registry: new files vs the base branch
atlas schema lint --env <name>                       # Lint the whole schema against policy
atlas schema test --env <name> --run <case>          # Schema tests: functions, views, triggers
atlas schema plan test --env <name>                  # Test a declarative plan file

# Drift (see references/drift.md)
atlas migrate drift --env <name>                     # Database vs migration history, exit 1 on drift (login)
atlas schema diff --from <url> --to <url> --dev-url <dev>   # Any two states

# Atlas Cloud (see references/cloud.md)
atlas cloud repo list                                # Registry repos with synced/failed/pending counts
atlas cloud database list --env-name <env>           # Every tracked database and its status
atlas cloud migration list --status FAILED           # Failed deployments
atlas schema plan list --env <name> --pending        # Plans waiting for approval

# Data Scripts (see references/scripts.md)
atlas script exec  --env <name> --run '^name$'       # Transactional mutation
atlas script query --env <name> --run '^name$' -q    # Read or report
atlas script loop  --env <name> --run '^name$'       # Batched backfill or purge
atlas script test  --env <name>                      # Test scripts on the dev database

选择工作流

What is the request?
├─ A schema change
│  ├─ Project has migrations/ dir or a migration block in atlas.hcl?
│  │  ├─ Yes → Versioned: migrate diff → lint → test → apply   (references/versioned.md)
│  │  └─ No  → Declarative: schema apply --dry-run → apply     (references/declarative.md)
│  ├─ Change must be reviewed and approved before it runs?
│  │  └─ schema plan (declarative) or a PR with migrate lint (versioned)
│  ├─ Iterating on a local database?
│  │  └─ schema apply --auto-approve for fast edit-apply cycles
│  └─ Not sure → Read atlas.hcl first
├─ CI/CD: lint on PRs, push to the registry, deploy from it
│  └─ references/cicd.md (each step's inputs and errors on each platform: the atlas-action skill)
├─ A data change (backfill, purge, report, invariant check)
│  └─ Data Scripts: references/scripts.md
├─ A lint failure, a lint policy, or a custom rule
│  └─ references/lint.md
├─ Tests for functions, views, triggers, data migrations, or plans
│  └─ references/testing.md
├─ "Has this database drifted?" or a drift check for deploys
│  └─ references/drift.md
├─ A question about deployments, database status, or the registry
│  └─ Atlas Cloud: references/cloud.md
└─ ORM or schema source setup
   └─ references/schema-sources.md

atlas schema apply 会直接将架构更改应用到数据库,不会生成迁移文件。开发过程中快速迭代时可使用此命令:编辑架构,运行 schema apply,查看结果。

示例

版本化项目(atlas.hcl 中包含 migration 块):

User: Add an email column to the users table

Agent steps:
1. atlas schema inspect --env dev           # understand current state
2. Edit schema source file                  # add email column
3. atlas schema validate --env dev          # verify syntax
4. atlas migrate diff --env dev "add_users_email"  # generate migration
5. atlas migrate lint --env dev --latest 1  # check for issues
6. atlas migrate apply --env dev --dry-run  # preview before applying

声明式项目(包含 schema 块,没有迁移目录):

Agent steps:
1. Edit schema source file                  # add email column
2. atlas schema validate --env dev          # verify syntax
3. atlas schema apply --env dev --dry-run   # read the planned SQL to the user
4. atlas schema apply --env dev             # apply (or --auto-approve on a local database)

核心概念

配置文件(atlas.hcl)

始终先阅读项目的 atlas.hcl。其中包含环境配置:

env "<name>" {
  url = getenv("DATABASE_URL")
  dev = "docker://postgres/17/dev?search_path=public"

  migration {
    dir = "file://migrations"       # or "atlas://<repo>" for the Atlas Registry
  }

  schema {
    src = "file://schema.hcl"
  }

  script {
    src = "file://scripts"          # Data Scripts source
  }
}
开发数据库

Atlas 使用临时开发数据库来处理和验证架构。URL 的作用域必须与目标匹配:项目管理一个架构时使用架构作用域,管理多个架构、扩展或事件触发器时使用数据库作用域。

# Schema-scoped (single schema, most common)
--dev-url "docker://mysql/8/dev"
--dev-url "docker://postgres/17/dev?search_path=public"
--dev-url "sqlite://dev?mode=memory"
--dev-url "docker://sqlserver/2022-latest/dev?mode=schema"

# Database-scoped (multiple schemas, extensions, or event triggers)
--dev-url "docker://mysql/8"
--dev-url "docker://postgres/17/dev"
--dev-url "docker://sqlserver/2022-latest/dev?mode=database"

作用域错误会导致诸如 modify schema "public" is not allowed when migration plan is scoped to one schema 的错误,或使扩展、事件触发器等数据库级对象在迁移中被静默丢弃。对于 PostGIS 或 pgvector 架构,请使用 docker://postgis/latest/dev 或 docker://pgvector/pg17/dev。

如果架构依赖扩展或外部对象,请使用带有 baseline 的 docker 块:

docker "postgres" "dev" {
  image  = "postgres:17"
  schema = "public"
  baseline = <<SQL
   CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
  SQL
}

env "local" {
  src = "file://schema.hcl"
  dev = docker.postgres.dev.url
}

工作流

1. 架构检查

先了解整体情况,再深入查看细节。默认输出格式为 HCL。使用 --format "{{ json . }}" 输出 JSON,或使用 --format "{{ sql . }}" 输出 SQL。

# List tables (overview first, JSON output)
atlas schema inspect --env <name> --format "{{ json . }}" | jq ".schemas[].tables[].name"

# Full SQL schema
atlas schema inspect --env <name> --format "{{ sql . }}"

# Filter with --include/--exclude (useful for large schemas)
atlas schema inspect --env <name> --include "users_*"           # Only matching tables (needs atlas login)
atlas schema inspect --env <name> --exclude "*_backup"          # Skip matching tables
atlas schema inspect --env <name> --exclude "*.*[type=trigger]" # Skip triggers (database scope: "*.*.*[type=trigger]")

# Open a visual ERD in the browser (requires atlas login)
atlas schema inspect --env <name> -w
2. 架构比较(差异)
# Live database vs desired schema. --from and --to are always required; --env supplies the dev database.
# env://url reads the env's url so the database URL never appears on the command line.
# On a versioned database add --exclude atlas_schema_revisions, or the revisions table shows up as a drop.
atlas schema diff --env <name> --from env://url --to file://schema.hcl --exclude atlas_schema_revisions

# Compare specific sources
atlas schema diff --env <name> --from file://migrations --to file://schema.hcl
3. 生成迁移
# Generate a migration from the schema diff
atlas migrate diff --env <name> "add_users_table"

# With explicit parameters
atlas migrate diff \
  --dir file://migrations \
  --dev-url docker://postgres/17/dev \
  --to file://schema.hcl \
  "add_users_table"
4. 架构验证

每次编辑后以及生成迁移前,都要验证架构定义:

atlas schema validate --env <name>
atlas schema validate --dev-url docker://postgres/17/dev --url file://schema.hcl

如果有效,命令会成功退出。如果无效,则会打印错误(未解析的引用、语法问题、不受支持的属性)。

5. 迁移检查
atlas migrate lint --env <name> --latest 1    # Lint the latest migration
atlas migrate lint --env ci                   # CI: new files vs the registry (no registry: --git-base master)
atlas schema lint --env <name>                # Check the whole schema against policy

这些分析器会捕获破坏性更改(DS*)、依赖数据的更改(MF*)、向后不兼容的更改(BC*)、表锁和重写(MY*、PG*)、命名和所有权策略,以及使用 HCL 编写的自定义规则。策略配置位于 atlas.hcl 的 lint 块中。

修复检查问题:

  • 尚未应用的迁移:编辑文件,然后运行 atlas migrate hash --env <name>。
  • 已应用的迁移:创建修正迁移。切勿编辑已应用的迁移。
  • 仅在获得用户批准后使用 -- atlas:nolint <code>。

检查代码、策略配置和自定义规则:references/lint.md。

6. 测试
atlas schema test --env <name>                # Functions, views, triggers, constraints, queries
atlas migrate test --env <name>               # Data migrations between versions
atlas schema plan test --env <name>           # Declarative plan files
atlas script test --env <name>                # Data Scripts

测试是针对开发数据库运行的 HCL 用例(test "schema" "<name>" { exec, catch, assert, ... })。添加每个函数、视图、触发器和数据迁移时,都要编写测试。块语法、环境配置和修复流程:references/testing.md。

7. 应用迁移
atlas migrate apply --env <name> --dry-run    # Always preview first
atlas migrate apply --env <name>              # Apply
atlas migrate status --env <name>             # Verify

将迁移应用到共享环境或生产环境之前,先检查 Atlas Cloud 状态(相同目标上是否有失败或进行中的部署)。请参阅 references/cloud.md 中的部署前检查清单。

8. 声明式计划与审批

在声明式工作流中,atlas schema plan 会将迁移计划保存到 Atlas Registry,以便在运行 atlas schema apply 前进行审查和批准:

atlas schema plan --env <name>                        # Plan, lint, review, approve and push
atlas schema plan --env <name> --pending              # Push for someone else to approve
atlas schema plan list --env <name> --pending         # Plans waiting for approval
atlas schema plan approve --url "atlas://<repo>/plans/<name>"
atlas schema apply --env <name>                       # Applies the approved plan as-is

计划编辑、push、pull、lint、validate、审查策略和 schema push:references/declarative.md。迁移目录格式、差异策略、基线、down、checkpoint、rebase、执行前检查和多租户应用:references/versioned.md。

9. CI/CD

在拉取请求中执行 lint(或生成计划),合并时将目录或架构推送到 Atlas Registry,并从 atlas://<repo> 部署,同时进行漂移和执行前检查。GitHub Actions 的工作流,以及 GitLab、CircleCI、Bitbucket、Azure DevOps、Kubernetes 和 Terraform 的对应工作流:references/cicd.md。每个步骤的输入、输出、令牌、权限和失败消息:atlas-action 技能(https://atlasgo.io/guides/ai-tools/agent-skills#cicd-skill)。

标准工作流

  1. atlas schema inspect --env <name>:了解当前状态(数据库为空时跳过)
  2. 编辑架构文件
  3. atlas schema validate --env <name>:检查语法
  4. atlas migrate diff --env <name> "change_name":生成迁移
  5. atlas migrate lint --env <name> --latest 1:验证(需要登录)
  6. atlas migrate test --env <name>:测试(需要登录)
  7. 如有问题:编辑迁移,然后运行 atlas migrate hash
  8. 运行 atlas migrate apply --env <name> --dry-run,然后应用

在检查、生成差异或为现有数据库设定基线之前,运行 atlas whoami;如果失败,请让用户登录。未登录时,atlas schema inspect 和 atlas schema diff 会跳过视图、函数、存储过程、触发器、序列、扩展及其他对象,但仍以退出码 0 结束,因此输出看起来完整,实际上并不完整。

其他需要登录的命令会报错 command requires 'atlas login' 或 available only to Atlas Pro users。告知用户跳过了该步骤及原因,并继续执行其余步骤。

漂移检测

漂移是数据库与其事实来源之间的差异。四种工具,各自回答一个问题:

问题工具
此数据库现在或按计划运行时是否与其迁移历史一致?atlas migrate drift --env <name>(检测到漂移时退出码为 1;适合 cron;需要 atlas login)
如果目标数据库发生漂移,则阻止部署atlas.hcl 中的 check "migrate_apply" { drift { on_error = FAIL } }
两种状态有何差异(声明式,或数据库与数据库之间)?atlas schema diff --from <url> --to <url>(两个标志都必需)
基于 Agent 的持续监控与告警Atlas Cloud 中的 Schema Monitoring

命令、标志、exclude 模式和报告工作流:references/drift.md。

Atlas Cloud

atlas cloud 命令会报告 Atlas Cloud 掌握的信息:注册表仓库、每个受跟踪数据库的同步状态(SYNCED、PENDING、FAILED)和当前版本,以及每个部署事件(PASSED、FAILED、NO_ACTION、DRY_RUN)。使用这些命令回答运维问题:

问题命令
汇总我们的数据库基础设施atlas cloud repo list,然后按环境运行 atlas cloud database list
哪些部署失败了?atlas cloud migration list --status FAILED
部署过程中发生了什么?atlas cloud migration describe --id <id>
哪些数据库正在等待部署?atlas cloud database list 并筛选 Status=PENDING
哪些计划正在等待批准?atlas schema plan list --env <name> --pending
生产环境使用的是什么版本?atlas cloud database list --env-name prod

完整命令参考、报告模板和决策规则:references/cloud.md。

数据脚本

atlas script 可运行以 HCL 编写的数据操作:用于事务性变更的 exec、用于读取和报告的 query,以及用于批量回填和清理的 loop,并支持 condition 守卫、assert 检查、expect_rows、输出脱敏和测试。数据操作请使用脚本,架构操作请使用迁移。完整参考:references/scripts.md。

架构源

有关 HCL 架构、ORM 集成(GORM、Drizzle、SQLAlchemy、Django、Ent、Sequelize、TypeORM)、复合架构和开发数据库方言 URL,请参阅 references/schema-sources.md。

为现有项目启用

若要引导整个项目或团队完成接入(盘点、将大型数据库拆分为多个单元、CI 和部署,并验证每个阶段),用户可以运行 atlas-onboard 技能 (https://atlasgo.io/guides/ai-tools/agent-skills#onboarding-skill)。

若要开始使用版本化迁移管理现有数据库,请先登录:未登录时执行 inspect,不会报错,但会将视图、函数、触发器和其他对象排除在基线之外。然后在 atlas.hcl 中固定组织,这样任何之后读取该文件的命令(--env)都会在无人登录该组织时中止。直接接受 --url 的命令不会读取该文件,因此运行这些命令前请先执行 atlas whoami:

atlas {
  cloud {
    org = "<org printed by atlas whoami>"
  }
}
# 1. Export the current schema to code
atlas schema inspect --env <name> --format '{{ sql . | split | write "src" }}'

# 2. Generate a baseline migration from the exported schema
atlas migrate diff --env <name> "baseline" --to "file://src"

# 3. Record the baseline as applied on each existing database (the version from the filename).
#    Deploy envs can set baseline = "<version>" in their migration block instead.
#    Preview first; --dry-run writes nothing:
atlas migrate apply --env <name> --baseline '<version>' --dry-run
#    Then, only after the user approves the named target, record it (this writes the revisions table):
atlas migrate apply --env <name> --baseline '<version>'

基线迁移会记录当前状态,但不会在现有数据库上执行。在新数据库上,它会完整运行以创建初始架构。

故障排查

atlas version                                 # Check installation
atlas whoami                                  # Check login and org
atlas migrate hash --env <name>               # Repair migration integrity after manual edits
  • command requires 'atlas login' 或 available only to Atlas Pro users:该命令需要登录。运行 atlas login,或在 CI 中运行 atlas login --token "$ATLAS_TOKEN"。报告跳过的步骤并继续。
  • 'atlas login' is required for organization <org> as specified in atlas.hcl:项目固定了组织。请用户使用该组织中的帐户运行 atlas login。
  • 缺少驱动程序错误:确保正确指定了 --url 或 --dev-url。
  • 当迁移计划限定在单个架构时,不允许执行 add、drop 或 modify schema "<name>":开发 URL 的范围与目标不匹配。请参阅上文“开发数据库”。
  • migrate lint 提示 Multiple directories found. Select one to lint against,并在 CI 中因 Error: ^D 失败:有多个注册表仓库与本地目录匹配。请传入 --base atlas://<repo>。
  • missing data source handler for "<name>",或文档中有说明的命令仅输出其父级命令的用法(例如 atlas migrate drift):当前安装的 Atlas 不支持该功能(版本较旧或为 Community Edition 构建),或者数据源类型拼写错误。未知数据源会导致文件中的所有 env 失败,包括从未引用它的 env。请根据 https://atlasgo.io/atlas-schema/projects#data-sources 检查类型,运行 atlas version,并安装最新版本(https://atlasgo.io/getting-started#step-1-install-atlas)。
  • Call to unknown function:atlas.hcl 支持 file、fileset、getenv 以及 https://atlasgo.io/hcl/functions 中列出的函数。不支持 coalesce。
  • docker:// 开发 URL 启动容器后失败,并显示 dial tcp <address>: connect: connection refused:Atlas 运行在使用主机 Docker 守护程序的容器中(例如 devcontainer),无法访问该守护程序发布的端口。请自行启动开发数据库容器,并将 dev 设置为容器可访问的 URL,例如其在 Docker 网络上的 IP(https://atlasgo.io/faq/docker-in-docker)。

关键规则

  1. 首先读取 atlas.hcl,并使用其中的环境名称。
  2. 切勿硬编码凭据。使用 getenv() 和 --env。
  3. 修改架构后运行 atlas schema validate。
  4. 应用迁移前始终运行 lint。
  5. 应用前始终先试运行。
  6. 编辑迁移文件后运行 atlas migrate hash。
  7. 切勿编辑已应用的迁移。应创建一个修正迁移。
  8. 切勿忽略 lint 错误。修复错误,或征得用户明确批准。
  9. 每台机器运行一次 atlas login。Lint、测试、漂移检测、schema plan、审查策略、脚本、ERD、migrate checkpoint、schema inspect --include 和 Atlas Cloud 都需要登录,否则会失败:报告跳过的步骤并继续。 检查和比较数据库差异时无需登录;未登录时会跳过对象。执行上述任一操作前先登录。 没有账户的用户可以通过 atlas login 开始免费试用。
  10. 部署到共享环境前,检查 Atlas Cloud 中是否有状态为 FAILED 或 PENDING 的目标,以及近期失败的部署(references/cloud.md)。
  11. 更改数据时使用 Data Scripts,而不是临时 SQL:使用 condition 添加保护、断言结果,并在报告中屏蔽 PII(references/scripts.md)。
  12. 分别报告云端状态和实时数据库状态。atlas cloud 显示 Atlas Cloud 已知的信息;atlas migrate status 显示数据库中的信息。

文档

评论

支持 Markdown