每天 Shaarli
使用sea-orm-cli管理数据库的一般操作:
安装sea-orm-cli
cargo install sea-orm-cli
rustup component add rustfmt
在项目文件夹下创建.env数据库连接配置文件:
DATABASE_URL=postgres://postgres:123456@localhost:5432/purchasing?options=-c%20search_path%3Ddev_001
使用 sea-orm-cli migrate init 进行初始化操作。
然后记得修改./migration/Cargo.toml
改成这样:
...
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.1.0"
features = [
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
# e.g.
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", # `DATABASE_DRIVER` feature
]
也就是去掉下面的"#"号注释。
# "runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
# "sqlx-postgres", # `DATABASE_DRIVER` feature
生成或更新实体文件 →
使用 sea-orm-cli generate entity 生成或更新实体文件
sea-orm-cli generate entity --output-dir ./src/entity --database-schema dev_001 --database-url "postgres://postgres:123456@localhost:5432/purchasing"
创建新的数据库或修改数据库结构迁移 →
使用 sea-orm-cli migrate generate 生成当前状态的迁移文件
sea-orm-cli migrate generate status_name
这样会在./migration/src文件夹下生成指定的status_name.rs
然后设计你的数据库改动,以后改动一次就执行一次并设计一次。
应用数据库变更 →
使用 sea-orm-cli migrate up 或 sea-orm-cli migrate down
如果需要重新进行迁移重置 →
使用 sea-orm-cli migrate init 进行重置操作。
然后记得修改./migration/Cargo.toml
改成这样:
...
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "1.1.0"
features = [
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
# e.g.
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", # `DATABASE_DRIVER` feature
]
也就是去掉下面的"#"号注释。
# "runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
# "sqlx-postgres", # `DATABASE_DRIVER` feature
通过实体文件进行数据库操作 →
在代码中通过实体文件执行 CRUD 操作