Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sea_orm connect, migration-cli #83

Merged
merged 1 commit into from
Jul 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
363 changes: 356 additions & 7 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ members = [
"macros/make-public",
"macros/make-private",
"macros/panic-to-result/panic-to-result-usage",
"macros/panic-to-result/panic-to-result-macro", "sea_orm/bakery-backend",
"macros/panic-to-result/panic-to-result-macro",
# "bevy/three_d_shapes", "bevy/pong",
# "bevy/quickstart/my_bevy_game",
# "macros/builder",
]
"sea_orm/bakery-backend", "sea_orm/bakery-backend/migration"
]
26 changes: 24 additions & 2 deletions sea_orm/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
# tutorial - bakery backend
https://www.sea-ql.org/sea-orm-tutorial

## setup
```bash
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=XXXXXX -d mysql:latest
```
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql:latest
docker container ps
docker container stop / start mysql

cargo install sea-orm-cli
# List all available migration commands that are supported by `sea-orm-cli`
$ sea-orm-cli migrate -h
# Initialize the migration folder:
$ sea-orm-cli migrate init
DATABASE_URL="mysql://root:password@localhost:3306/bakeries_db" sea-orm-cli migrate refresh
mysql -u root -p --host 0.0.0.0 --port 3306
use bakeries_db; show tables;
```

## [Cargo.toml](Cargo.toml)
```toml
[dependencies]
futures = "0.3.30"
sea-orm = {version="0.12.15" , features = [ "sqlx-mysql", "runtime-async-std-native-tls", "macros" ]}
```
24 changes: 24 additions & 0 deletions sea_orm/bakery-backend/migration/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
name = "migration"
path = "src/lib.rs"

[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }

[dependencies.sea-orm-migration]
version = "0.12.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
"sqlx-mysql",
"runtime-async-std-native-tls",
]
41 changes: 41 additions & 0 deletions sea_orm/bakery-backend/migration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Running Migrator CLI

- Generate a new migration file
```sh
cargo run -- generate MIGRATION_NAME
```
- 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
```
18 changes: 18 additions & 0 deletions sea_orm/bakery-backend/migration/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub use sea_orm_migration::prelude::*;

// Add each migration file as a module
mod m20240716_000001_create_bakery_table;
mod m20240716_000002_create_chef_table;

pub struct Migrator;

#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![
// Define the order of migrations.
Box::new(m20240716_000001_create_bakery_table::Migration),
Box::new(m20240716_000002_create_chef_table::Migration),
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use sea_orm_migration::prelude::*;

pub struct Migration;

impl MigrationName for Migration {
fn name(&self) -> &str {
"m20240716_000001_create_bakery_table" // Make sure this matches with the file name
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
// Define how to apply this migration: Create the Bakery table.
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Bakery::Table)
.col(
ColumnDef::new(Bakery::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Bakery::Name).string().not_null())
.col(ColumnDef::new(Bakery::ProfitMargin).double().not_null())
.to_owned(),
)
.await
}

// Define how to rollback this migration: Drop the Bakery table.
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Bakery::Table).to_owned())
.await
}
}

#[derive(Iden)]
pub enum Bakery {
Table,
Id,
Name,
ProfitMargin,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use sea_orm_migration::prelude::*;

use super::m20240716_000001_create_bakery_table::Bakery;

pub struct Migration;

impl MigrationName for Migration {
fn name(&self) -> &str {
"m20240716_000002_create_chef_table" // Make sure this matches with the file name
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
// Define how to apply this migration: Create the Chef table.
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Chef::Table)
.col(
ColumnDef::new(Chef::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Chef::Name).string().not_null())
.col(ColumnDef::new(Chef::ContactDetails).json())
.col(ColumnDef::new(Chef::BakeryId).integer().not_null())
.foreign_key(
ForeignKey::create()
.name("fk-chef-bakery_id")
.from(Chef::Table, Chef::BakeryId)
.to(Bakery::Table, Bakery::Id),
)
.to_owned(),
)
.await
}

// Define how to rollback this migration: Drop the Chef table.
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Chef::Table).to_owned())
.await
}
}

// For ease of access
#[derive(Iden)]
pub enum Chef {
Table,
Id,
Name,
ContactDetails,
BakeryId,
}
6 changes: 6 additions & 0 deletions sea_orm/bakery-backend/migration/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;

#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}
34 changes: 32 additions & 2 deletions sea_orm/bakery-backend/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,47 @@
#![allow(unused)]

use futures::executor::block_on;
use sea_orm::{Database, DbErr};
use sea_orm::{ConnectionTrait, Database, DbBackend, DbErr, Statement};

const DATABASE_URL: &str = "mysql://root:password@localhost:3306";
const DB_NAME: &str = "bakeries_db";

async fn run() -> Result<(), DbErr> {
let db = Database::connect(DATABASE_URL).await?;

let db = &match db.get_database_backend() {
DbBackend::MySql => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE IF NOT EXISTS `{}`;", DB_NAME),
))
.await?;

let url = format!("{}/{}", DATABASE_URL, DB_NAME);
Database::connect(&url).await?
}
DbBackend::Postgres => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("DROP DATABASE IF EXISTS \"{}\";", DB_NAME),
))
.await?;
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE \"{}\";", DB_NAME),
))
.await?;

let url = format!("{}/{}", DATABASE_URL, DB_NAME);
Database::connect(&url).await?
}
DbBackend::Sqlite => db,
};
Ok(())
}

fn main() {
if let Err(err) = block_on(run()) {
panic!("{}", err);
}
}
}