Examples with migration (#509)

* Update examples sea-orm version

* Update example sea-schema version

* Update [cli] sea-schema version

* Fix [cli] cargo publish failed

* Update CHANGELOG

* Edit rocket example

* Poem example with migration

* Axum example with migration

* Refactoring

* Actix4 example with migration

* Actix example with migration

* Use sea_schema::migration::prelude
This commit is contained in:
Billy Chan 2022-02-09 11:45:04 +08:00 committed by GitHub
parent e9a460b47d
commit f418c4e580
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 620 additions and 228 deletions

View File

@ -1,3 +1,3 @@
HOST=127.0.0.1
PORT=8000
DATABASE_URL="mysql://root:@localhost/actix_example"
DATABASE_URL="mysql://root:root@localhost/actix_example"

View File

@ -6,6 +6,7 @@ edition = "2021"
publish = false
[workspace]
members = [".", "entity", "migration"]
[dependencies]
actix-files = "0.6.0-beta.4"
@ -19,14 +20,5 @@ dotenv = "0.15"
listenfd = "0.3.3"
serde = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dependencies.sea-orm]
path = "../../" # remove this line in your own project
version = "^0.6.0"
features = ["macros", "runtime-actix-native-tls", "debug-print"]
default-features = false
[features]
default = ["sqlx-mysql"]
sqlx-mysql = ["sea-orm/sqlx-mysql"]
sqlx-postgres = ["sea-orm/sqlx-postgres"]
entity = { path = "entity" }
migration = { path = "migration" }

View File

@ -1,13 +1,14 @@
![screenshot](Screenshot.png)
# Actix 4 Beta with SeaORM example app
Edit `Cargo.toml` to use `sqlx-mysql` or `sqlx-postgres`.
1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database
```toml
[features]
default = ["sqlx-$DATABASE"]
```
1. Turn on the appropriate database feature for your chosen db in `entity/Cargo.toml` (the `"sqlx-mysql",` line)
Edit `.env` to point to your database.
1. Execute `cargo run` to start the server
1. Visit [localhost:8000](http://localhost:8000) in browser
Run server with auto-reloading:

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 KiB

View File

@ -0,0 +1,25 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "entity"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
[dependencies.sea-orm]
# path = "../../../" # remove this line in your own project
version = "^0.6.0"
features = [
"macros",
"debug-print",
"runtime-actix-native-tls",
"sqlx-mysql",
# "sqlx-postgres",
# "sqlx-sqlite",
]
default-features = false

View File

@ -0,0 +1,3 @@
pub mod post;
pub use sea_orm;

View File

@ -0,0 +1,13 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
sea-schema = { version = "^0.5.0", default-features = false, features = [ "migration", "debug-print" ] }
entity = { path = "../entity" }

View File

@ -0,0 +1,37 @@
# Running Migrator CLI
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@ -0,0 +1,12 @@
pub use sea_schema::migration::prelude::*;
mod m20220120_000001_create_post_table;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220120_000001_create_post_table::Migration)]
}
}

View File

@ -0,0 +1,39 @@
use entity::post::*;
use sea_schema::migration::prelude::*;
pub struct Migration;
impl MigrationName for Migration {
fn name(&self) -> &str {
"m20220120_000001_create_post_table"
}
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Entity)
.if_not_exists()
.col(
ColumnDef::new(Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Column::Title).string().not_null())
.col(ColumnDef::new(Column::Text).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Entity).to_owned())
.await
}
}

View File

@ -0,0 +1,7 @@
use migration::Migrator;
use sea_schema::migration::*;
#[async_std::main]
async fn main() {
cli::run_cli(Migrator).await;
}

View File

@ -3,17 +3,17 @@ use actix_web::{
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result,
};
use entity::post;
use entity::post::Entity as Post;
use entity::sea_orm;
use listenfd::ListenFd;
use migration::{Migrator, MigratorTrait};
use sea_orm::DatabaseConnection;
use sea_orm::{entity::*, query::*};
use serde::{Deserialize, Serialize};
use std::env;
use tera::Tera;
mod post;
pub use post::Entity as Post;
mod setup;
const DEFAULT_POSTS_PER_PAGE: usize = 5;
#[derive(Debug, Clone)]
@ -92,7 +92,9 @@ async fn create(
.await
.expect("could not insert post");
Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}
#[get("/{id}")]
@ -133,7 +135,9 @@ async fn update(
.await
.expect("could not edit post");
Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}
#[post("/delete/{id}")]
@ -149,7 +153,9 @@ async fn delete(data: web::Data<AppState>, id: web::Path<i32>) -> Result<HttpRes
post.delete(conn).await.unwrap();
Ok(HttpResponse::Found().append_header(("location", "/")).finish())
Ok(HttpResponse::Found()
.append_header(("location", "/"))
.finish())
}
#[actix_web::main]
@ -166,7 +172,7 @@ async fn main() -> std::io::Result<()> {
// create post table if not exists
let conn = sea_orm::Database::connect(&db_url).await.unwrap();
let _ = setup::create_post_table(&conn).await;
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = AppState { templates, conn };

View File

@ -1,33 +0,0 @@
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {
let builder = db.get_database_backend();
db.execute(builder.build(stmt)).await
}
pub async fn create_post_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(super::post::Entity)
.if_not_exists()
.col(
ColumnDef::new(super::post::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(super::post::Column::Title)
.string()
.not_null(),
)
.col(
ColumnDef::new(super::post::Column::Text)
.string()
.not_null(),
)
.to_owned();
create_table(db, &stmt).await
}

View File

@ -1,3 +1,3 @@
HOST=127.0.0.1
PORT=8000
DATABASE_URL="sql://root:@localhost/actix_example"
DATABASE_URL="mysql://root:root@localhost/actix_example"

View File

@ -6,6 +6,7 @@ edition = "2021"
publish = false
[workspace]
members = [".", "entity", "migration"]
[dependencies]
actix-http = "2"
@ -19,14 +20,5 @@ dotenv = "0.15"
listenfd = "0.3.3"
serde = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dependencies.sea-orm]
path = "../../" # remove this line in your own project
version = "^0.6.0"
features = ["macros", "runtime-async-std-native-tls", "debug-print"]
default-features = false
[features]
default = ["sqlx-mysql"]
sqlx-mysql = ["sea-orm/sqlx-mysql"]
sqlx-postgres = ["sea-orm/sqlx-postgres"]
entity = { path = "entity" }
migration = { path = "migration" }

View File

@ -1,13 +1,14 @@
![screenshot](Screenshot.png)
# Actix with SeaORM example app
Edit `Cargo.toml` to use `sqlx-mysql` or `sqlx-postgres`.
1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database
```toml
[features]
default = ["sqlx-$DATABASE"]
```
1. Turn on the appropriate database feature for your chosen db in `entity/Cargo.toml` (the `"sqlx-mysql",` line)
Edit `.env` to point to your database.
1. Execute `cargo run` to start the server
1. Visit [localhost:8000](http://localhost:8000) in browser
Run server with auto-reloading:

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 KiB

View File

@ -0,0 +1,25 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "entity"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
[dependencies.sea-orm]
# path = "../../../" # remove this line in your own project
version = "^0.6.0"
features = [
"macros",
"debug-print",
"runtime-async-std-native-tls",
"sqlx-mysql",
# "sqlx-postgres",
# "sqlx-sqlite",
]
default-features = false

View File

@ -0,0 +1,3 @@
pub mod post;
pub use sea_orm;

View File

@ -0,0 +1,13 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
sea-schema = { version = "^0.5.0", default-features = false, features = [ "migration", "debug-print" ] }
entity = { path = "../entity" }

View File

@ -0,0 +1,37 @@
# Running Migrator CLI
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@ -0,0 +1,12 @@
pub use sea_schema::migration::prelude::*;
mod m20220120_000001_create_post_table;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220120_000001_create_post_table::Migration)]
}
}

View File

@ -0,0 +1,39 @@
use entity::post::*;
use sea_schema::migration::prelude::*;
pub struct Migration;
impl MigrationName for Migration {
fn name(&self) -> &str {
"m20220120_000001_create_post_table"
}
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Entity)
.if_not_exists()
.col(
ColumnDef::new(Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Column::Title).string().not_null())
.col(ColumnDef::new(Column::Text).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Entity).to_owned())
.await
}
}

View File

@ -0,0 +1,7 @@
use migration::Migrator;
use sea_schema::migration::*;
#[async_std::main]
async fn main() {
cli::run_cli(Migrator).await;
}

View File

@ -2,17 +2,18 @@ use actix_files as fs;
use actix_web::{
error, get, middleware, post, web, App, Error, HttpRequest, HttpResponse, HttpServer, Result,
};
use entity::post;
use entity::post::Entity as Post;
use entity::sea_orm;
use listenfd::ListenFd;
use migration::{Migrator, MigratorTrait};
use sea_orm::DatabaseConnection;
use sea_orm::{entity::*, query::*};
use serde::{Deserialize, Serialize};
use std::env;
use tera::Tera;
mod post;
pub use post::Entity as Post;
mod setup;
const DEFAULT_POSTS_PER_PAGE: usize = 5;
#[derive(Debug, Clone)]
@ -192,7 +193,7 @@ async fn main() -> std::io::Result<()> {
// create post table if not exists
let conn = sea_orm::Database::connect(&db_url).await.unwrap();
let _ = setup::create_post_table(&conn).await;
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = AppState { templates, conn };

View File

@ -1,33 +0,0 @@
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {
let builder = db.get_database_backend();
db.execute(builder.build(stmt)).await
}
pub async fn create_post_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(super::post::Entity)
.if_not_exists()
.col(
ColumnDef::new(super::post::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(super::post::Column::Title)
.string()
.not_null(),
)
.col(
ColumnDef::new(super::post::Column::Text)
.string()
.not_null(),
)
.to_owned();
create_table(db, &stmt).await
}

View File

@ -1,3 +1,3 @@
HOST=127.0.0.1
PORT=8000
DATABASE_URL="postgres://postgres:password@localhost/axum_exmaple"
DATABASE_URL="postgres://root:root@localhost/axum_exmaple"

View File

@ -7,6 +7,7 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[workspace]
members = [".", "entity", "migration"]
[dependencies]
tokio = { version = "1.14", features = ["full"] }
@ -20,14 +21,5 @@ serde = "1"
serde_json = "1"
tera = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dependencies.sea-orm]
path = "../../" # remove this line in your own project
version = "^0.6.0"
features = ["macros", "runtime-tokio-native-tls", "debug-print"]
default-features = false
[features]
default = ["sqlx-postgres"]
sqlx-mysql = ["sea-orm/sqlx-mysql"]
sqlx-postgres = ["sea-orm/sqlx-postgres"]
entity = { path = "entity" }
migration = { path = "migration" }

View File

@ -1,10 +1,11 @@
![screenshot](Screenshot.png)
# Axum with SeaORM example app
Edit `Cargo.toml` to use `sqlx-mysql` or `sqlx-postgres`.
1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database
```toml
[features]
default = ["sqlx-$DATABASE"]
```
1. Turn on the appropriate database feature for your chosen db in `entity/Cargo.toml` (the `"sqlx-postgres",` line)
Edit `.env` to point to your database.
1. Execute `cargo run` to start the server
1. Visit [localhost:8000](http://localhost:8000) in browser

Binary file not shown.

After

Width:  |  Height:  |  Size: 610 KiB

View File

@ -0,0 +1,25 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "entity"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
[dependencies.sea-orm]
# path = "../../../" # remove this line in your own project
version = "^0.6.0"
features = [
"macros",
"debug-print",
"runtime-tokio-native-tls",
"sqlx-postgres",
# "sqlx-mysql",
# "sqlx-sqlite",
]
default-features = false

View File

@ -0,0 +1,3 @@
pub mod post;
pub use sea_orm;

View File

@ -0,0 +1,13 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
sea-schema = { version = "^0.5.0", default-features = false, features = [ "migration", "debug-print" ] }
entity = { path = "../entity" }

View File

@ -0,0 +1,37 @@
# Running Migrator CLI
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@ -0,0 +1,12 @@
pub use sea_schema::migration::prelude::*;
mod m20220120_000001_create_post_table;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220120_000001_create_post_table::Migration)]
}
}

View File

@ -0,0 +1,39 @@
use entity::post::*;
use sea_schema::migration::prelude::*;
pub struct Migration;
impl MigrationName for Migration {
fn name(&self) -> &str {
"m20220120_000001_create_post_table"
}
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Entity)
.if_not_exists()
.col(
ColumnDef::new(Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Column::Title).string().not_null())
.col(ColumnDef::new(Column::Text).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Entity).to_owned())
.await
}
}

View File

@ -0,0 +1,7 @@
use migration::Migrator;
use sea_schema::migration::*;
#[async_std::main]
async fn main() {
cli::run_cli(Migrator).await;
}

View File

@ -1,15 +1,16 @@
mod flash;
mod post;
mod setup;
use axum::{
extract::{Extension, Form, Path, Query},
http::StatusCode,
response::Html,
routing::{get, post, get_service},
routing::{get, get_service, post},
AddExtensionLayer, Router, Server,
};
use entity::post;
use entity::sea_orm;
use flash::{get_flash_cookie, post_response, PostResponse};
use migration::{Migrator, MigratorTrait};
use post::Entity as Post;
use sea_orm::{prelude::*, Database, QueryOrder, Set};
use serde::{Deserialize, Serialize};
@ -34,7 +35,7 @@ async fn main() -> anyhow::Result<()> {
let conn = Database::connect(db_url)
.await
.expect("Database connection failed");
let _ = setup::create_post_table(&conn).await;
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"))
.expect("Tera initialization failed");
// let state = AppState { templates, conn };

View File

@ -1,33 +0,0 @@
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {
let builder = db.get_database_backend();
db.execute(builder.build(stmt)).await
}
pub async fn create_post_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(super::post::Entity)
.if_not_exists()
.col(
ColumnDef::new(super::post::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(super::post::Column::Title)
.string()
.not_null(),
)
.col(
ColumnDef::new(super::post::Column::Text)
.string()
.not_null(),
)
.to_owned();
create_table(db, &stmt).await
}

View File

@ -5,6 +5,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[workspace]
members = [".", "entity", "migration"]
[dependencies]
tokio = { version = "1.15.0", features = ["macros", "rt-multi-thread"] }
@ -13,15 +14,5 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
serde = { version = "1", features = ["derive"] }
tera = "1.8.0"
dotenv = "0.15"
[dependencies.sea-orm]
path = "../../" # remove this line in your own project
version = "^0.6.0"
features = ["macros", "runtime-tokio-native-tls", "debug-print"]
default-features = false
[features]
default = ["sqlx-sqlite"]
sqlx-mysql = ["sea-orm/sqlx-mysql"]
sqlx-postgres = ["sea-orm/sqlx-postgres"]
sqlx-sqlite = ["sea-orm/sqlx-sqlite"]
entity = { path = "entity" }
migration = { path = "migration" }

View File

@ -1,10 +1,11 @@
![screenshot](Screenshot.png)
# Poem with SeaORM example app
Edit `Cargo.toml` to use `sqlx-mysql` or `sqlx-postgres`.
1. Modify the `DATABASE_URL` var in `.env` to point to your chosen database
```toml
[features]
default = ["sqlx-$DATABASE"]
```
1. Turn on the appropriate database feature for your chosen db in `entity/Cargo.toml` (the `"sqlx-sqlite",` line)
Edit `.env` to point to your database.
1. Execute `cargo run` to start the server
1. Visit [localhost:8000](http://localhost:8000) in browser after seeing the `server started` line

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 KiB

View File

@ -0,0 +1,25 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "entity"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
[dependencies.sea-orm]
# path = "../../../" # remove this line in your own project
version = "^0.6.0"
features = [
"macros",
"debug-print",
"runtime-tokio-native-tls",
"sqlx-sqlite",
# "sqlx-postgres",
# "sqlx-mysql",
]
default-features = false

View File

@ -0,0 +1,3 @@
pub mod post;
pub use sea_orm;

View File

@ -0,0 +1,13 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
sea-schema = { version = "^0.5.0", default-features = false, features = [ "migration", "debug-print" ] }
entity = { path = "../entity" }

View File

@ -0,0 +1,37 @@
# Running Migrator CLI
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@ -0,0 +1,12 @@
pub use sea_schema::migration::prelude::*;
mod m20220120_000001_create_post_table;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220120_000001_create_post_table::Migration)]
}
}

View File

@ -0,0 +1,39 @@
use entity::post::*;
use sea_schema::migration::prelude::*;
pub struct Migration;
impl MigrationName for Migration {
fn name(&self) -> &str {
"m20220120_000001_create_post_table"
}
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Entity)
.if_not_exists()
.col(
ColumnDef::new(Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Column::Title).string().not_null())
.col(ColumnDef::new(Column::Text).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Entity).to_owned())
.await
}
}

View File

@ -0,0 +1,7 @@
use migration::Migrator;
use sea_schema::migration::*;
#[async_std::main]
async fn main() {
cli::run_cli(Migrator).await;
}

View File

@ -1,5 +1,8 @@
use std::env;
use entity::post;
use entity::sea_orm;
use migration::{Migrator, MigratorTrait};
use poem::endpoint::StaticFilesEndpoint;
use poem::error::{BadRequest, InternalServerError};
use poem::http::StatusCode;
@ -10,9 +13,6 @@ use sea_orm::{entity::*, query::*, DatabaseConnection};
use serde::Deserialize;
use tera::Tera;
mod post;
mod setup;
const DEFAULT_POSTS_PER_PAGE: usize = 5;
#[derive(Debug, Clone)]
@ -142,7 +142,7 @@ async fn main() -> std::io::Result<()> {
// create post table if not exists
let conn = sea_orm::Database::connect(&db_url).await.unwrap();
let _ = setup::create_post_table(&conn).await;
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
let state = AppState { templates, conn };

View File

@ -1,33 +0,0 @@
use sea_orm::sea_query::{ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
async fn create_table(db: &DbConn, stmt: &TableCreateStatement) -> Result<ExecResult, DbErr> {
let builder = db.get_database_backend();
db.execute(builder.build(stmt)).await
}
pub async fn create_post_table(db: &DbConn) -> Result<ExecResult, DbErr> {
let stmt = sea_query::Table::create()
.table(super::post::Entity)
.if_not_exists()
.col(
ColumnDef::new(super::post::Column::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(super::post::Column::Title)
.string()
.not_null(),
)
.col(
ColumnDef::new(super::post::Column::Text)
.string()
.not_null(),
)
.to_owned();
create_table(db, &stmt).await
}

View File

@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Actix Example</title>
<title>Poem Example</title>
<meta name="description" content="Actix - SeaOrm integration example" />
<meta name="author" content="Sam Samai" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

View File

@ -6,6 +6,6 @@
1. Turn on the appropriate database feature for your chosen db in `entity/Cargo.toml` (the `"sqlx-postgres",` line)
1. `cargo run` to start the server
1. Execute `cargo run` to start the server
1. Open in browser after seeing the `🚀 Rocket has launched from http://localhost:8000` line
1. Visit [localhost:8000](http://localhost:8000) in browser after seeing the `🚀 Rocket has launched from http://localhost:8000` line

View File

@ -21,5 +21,6 @@ features = [
"runtime-tokio-native-tls",
"sqlx-postgres",
# "sqlx-mysql",
# "sqlx-sqlite",
]
default-features = false