Skip to content

Commit

Permalink
Examples with migration (#509)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
billy1624 authored Feb 9, 2022
1 parent e9a460b commit f418c4e
Show file tree
Hide file tree
Showing 58 changed files with 620 additions and 228 deletions.
2 changes: 1 addition & 1 deletion examples/actix4_example/.env
Original file line number Diff line number Diff line change
@@ -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"
14 changes: 3 additions & 11 deletions examples/actix4_example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"
publish = false

[workspace]
members = [".", "entity", "migration"]

[dependencies]
actix-files = "0.6.0-beta.4"
Expand All @@ -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" }
13 changes: 7 additions & 6 deletions examples/actix4_example/README.md
Original file line number Diff line number Diff line change
@@ -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)

1. Execute `cargo run` to start the server

Edit `.env` to point to your database.
1. Visit [localhost:8000](http://localhost:8000) in browser

Run server with auto-reloading:

Expand Down
Binary file added examples/actix4_example/Screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions examples/actix4_example/entity/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions examples/actix4_example/entity/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod post;

pub use sea_orm;
File renamed without changes.
13 changes: 13 additions & 0 deletions examples/actix4_example/migration/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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" }
37 changes: 37 additions & 0 deletions examples/actix4_example/migration/README.md
Original file line number Diff line number Diff line change
@@ -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
```
12 changes: 12 additions & 0 deletions examples/actix4_example/migration/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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)]
}
}
Original file line number Diff line number Diff line change
@@ -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
}
}
7 changes: 7 additions & 0 deletions examples/actix4_example/migration/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use migration::Migrator;
use sea_schema::migration::*;

#[async_std::main]
async fn main() {
cli::run_cli(Migrator).await;
}
22 changes: 14 additions & 8 deletions examples/actix4_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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}")]
Expand Down Expand Up @@ -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}")]
Expand All @@ -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]
Expand All @@ -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 };

Expand Down
33 changes: 0 additions & 33 deletions examples/actix4_example/src/setup.rs

This file was deleted.

2 changes: 1 addition & 1 deletion examples/actix_example/.env
Original file line number Diff line number Diff line change
@@ -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"
14 changes: 3 additions & 11 deletions examples/actix_example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ edition = "2021"
publish = false

[workspace]
members = [".", "entity", "migration"]

[dependencies]
actix-http = "2"
Expand All @@ -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" }
13 changes: 7 additions & 6 deletions examples/actix_example/README.md
Original file line number Diff line number Diff line change
@@ -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)

1. Execute `cargo run` to start the server

Edit `.env` to point to your database.
1. Visit [localhost:8000](http://localhost:8000) in browser

Run server with auto-reloading:

Expand Down
Binary file added examples/actix_example/Screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions examples/actix_example/entity/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions examples/actix_example/entity/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod post;

pub use sea_orm;
File renamed without changes.
13 changes: 13 additions & 0 deletions examples/actix_example/migration/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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" }
Loading

0 comments on commit f418c4e

Please sign in to comment.