Rust 实战:SQLx CLI 工具使用与数据库迁移指南
Table of Contents
Rust 实战:SQLx CLI 工具使用与数据库迁移指南
在 Rust 的 Web 开发生态中,SQLx 凭借其异步特性和独特的“编译时 SQL 检查”功能,成为了许多开发者的首选。它不需要复杂的 DSL(领域特定语言),让你能直接编写原生 SQL,同时享受 Rust 强类型的安全保障。
但在开始编写 Rust 代码之前,如何搭建数据库环境?如何高效地管理数据库表结构的变更?本文将带你从零开始,实操 SQLx CLI 工具的安装、PostgreSQL 数据库的创建、pgcli 的使用,以及最核心的数据库迁移(Migration)流程。让我们先把基础设施搭建好,为后续的业务开发扫清障碍。
本文记录了 Rust 异步数据库库 SQLx 的环境搭建与实操流程。内容涵盖 SQLx CLI 的安装配置、PostgreSQL 数据库的创建及 pgcli 命令行工具的使用技巧。重点演示了 sqlx migrate 系列命令的实战应用,包括创建迁移脚本、执行数据库升级、以及通过 psql 元命令验证表结构变更。适合 Rust 初学者及希望规范化管理数据库版本的开发者阅读。
Rust SQLx
SQLx 是一个异步的、纯 Rust† SQL crate,具有编译时检查查询的功能,没有 DSL。
实操
安装 SQLx CLI
➜ cargo install sqlx-cli --no-default-features --features rustls --features postgres
查看SQLx CLI命令
➜ sqlx
Command-line utility for SQLx, the Rust SQL toolkit.
Usage: sqlx [OPTIONS] <COMMAND>
Commands:
database Group of commands for creating and dropping your database
prepare Generate query metadata to support offline compile-time verification
migrate Group of commands for creating and running migrations
help Print this message or the help of the given subcommand(s)
Options:
--no-dotenv Do not automatically load `.env` files
-h, --help Print help
-V, --version Print version
创建数据库
➜ createdb chat
安装 pgcli
brew install pgcli
使用 pgcli进入数据库
➜ pgcli chat
Using local time zone Asia/Shanghai (server uses Asia/Shanghai)
Use `set time zone <TZ>` to override, or set `use_local_timezone = False` in the config
Server: PostgreSQL 17.6 (Homebrew)
Version: 4.3.0
Home: http://pgcli.com
qiaopengjun@/tmp:chat>
[F2] Smart Completion: ON [F3] Multiline: OFF [F4] Emacs-mode [F5] Explain: OFF
查看数据库中的表
\dt 是 psql 元命令,用于列出当前数据库中的 表(tables)。
它相当于:
SELECT * FROM pg_catalog.pg_tables;
实操:
➜ pgcli chat
Using local time zone Asia/Shanghai (server uses Asia/Shanghai)
Use `set time zone <TZ>` to override, or set `use_local_timezone = False` in the config
Server: PostgreSQL 17.6 (Homebrew)
Version: 4.3.0
Home: http://pgcli.com
qiaopengjun@/tmp:chat> \dt
+--------+------+------+-------+
| Schema | Name | Type | Owner |
|--------+------+------+-------|
+--------+------+------+-------+
SELECT 0
Time: 0.037s
qiaopengjun@/tmp:chat> \dt;
+--------+------+------+-------+
| Schema | Name | Type | Owner |
|--------+------+------+-------|
+--------+------+------+-------+
SELECT 0
Time: 0.007s
qiaopengjun@/tmp:chat>
[F2] Smart Completion: ON [F3] Multiline: OFF [F4] Emacs-mode [F5] Explain: OFF
Psql 常用命令
PostgreSQL(psql 命令行工具) 中常用命令
| 命令 | 作用 |
|---|---|
\dt | 列出所有普通表 |
\dv | 列出视图 |
\di | 列出索引 |
\ds | 列出序列 |
\d <table> | 查看表结构 |
\l | 列出所有数据库 |
\c dbname | 切换数据库 |
\dn | 列出 schema |
查看sqlx migrate
🚀 sqlx migrate 命令解释(Rust 项目常用)
sqlx migrate 是 SQLx 提供的数据库迁移工具,用于:
- 创建 migration 文件(up/down)
- 执行数据库表结构更新
- 回滚迁移
- 查看迁移状态
➜ sqlx migrate
Group of commands for creating and running migrations
Usage: sqlx migrate <COMMAND>
Commands:
add Create a new migration with the given description
run Run all pending migrations
revert Revert the latest migration with a down file
info List all available migrations
build-script Generate a `build.rs` to trigger recompilation when a new migration is added
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help
执行migrate add命令
➜ sqlx migrate add initial
Creating migrations/20251203080702_initial.sql
查看生成的脚本目录结构
├── migrations
│ └── 20251203080702_initial.sql
生成文件后,我们需要在 migrations/2025xxx_initial.sql 文件中写入建表语句(Create Table…),保存后再执行迁移。
执行migrate run命令
➜ sqlx migrate run
Applied 20251203080702/migrate initial (23.433375ms)
查看运行结果
➜ pgcli chat
Using local time zone Asia/Shanghai (server uses Asia/Shanghai)
Use `set time zone <TZ>` to override, or set `use_local_timezone = False` in the config
Server: PostgreSQL 17.6 (Homebrew)
Version: 4.3.0
Home: http://pgcli.com
qiaopengjun@/tmp:chat> \dt
+--------+------------------+-------+----------+
| Schema | Name | Type | Owner |
|--------+------------------+-------+----------|
| public | _sqlx_migrations | table | postgres |
| public | chats | table | postgres |
| public | messages | table | postgres |
| public | users | table | postgres |
+--------+------------------+-------+----------+
SELECT 4
Time: 0.017s
qiaopengjun@/tmp:chat> select * FROM _sqlx_migrations;
+----------------+-------------+------------------------------+---------+----------------------------------------------------------------------------------------------------+----------------+
| version | description | installed_on | success | checksum | execution_time |
|----------------+-------------+------------------------------+---------+----------------------------------------------------------------------------------------------------+----------------|
| 20251203080702 | initial | 2025-12-03 17:09:47.59188+08 | True | \x33d8304d5f29003cdd8320d95b1c5ba1a32ed60a1663f850bac7e4d807f00efce535159dcd2a5a60ab2a18a0670ef29c | 23433375 |
+----------------+-------------+------------------------------+---------+----------------------------------------------------------------------------------------------------+----------------+
SELECT 1
Time: 0.013s
qiaopengjun@/tmp:chat>
Goodbye!
总结
通过本文的实操,我们完成了 Rust 项目中数据库基础设施的搭建。从安装 sqlx-cli 和辅助工具 pgcli 开始,我们成功创建了 chat 数据库,并掌握了通过 sqlx migrate add 生成版本控制脚本,以及利用 sqlx migrate run 将变更应用到实际数据库的全过程。
这一套标准化的流程(Migration Workflow)是多人协作和生产环境部署的基石。掌握了这些 CLI 命令后,你就可以放心地在 Rust 项目中引入数据库依赖,开始构建真正的业务逻辑了。