Skip to content

Commit

Permalink
feat: Switch to db agnostic migrations (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
szinn authored Aug 13, 2024
1 parent 131950f commit 766b48f
Show file tree
Hide file tree
Showing 15 changed files with 198 additions and 79 deletions.
65 changes: 0 additions & 65 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 47 additions & 0 deletions crates/arch-db-pg/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
[package]
name = "arch-db"
version.workspace = true
edition.workspace = true
authors.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
readme.workspace = true
rust-version.workspace = true
publish = false

build = "build.rs"

[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tracing.workspace = true
tracing-log.workspace = true

[dependencies.rust-embed]
version = "8.3.0"
features = ["debug-embed"]

[dependencies.sea-orm]
version = "1.0.0"
features = [
"debug-print",
"mock",
"postgres-array",
"runtime-tokio-rustls",
"sqlx-postgres",
"with-chrono",
"with-json",
"with-uuid",
]

[dependencies.sea-orm-migration]
version = "1.0.0"
features = [
"sqlx-postgres",
"runtime-tokio-rustls",
"with-chrono",
"with-json",
"with-uuid",
]
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
22 changes: 22 additions & 0 deletions crates/arch-db-pg/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use sea_orm::DbErr;

#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
Message(String),

#[error(transparent)]
Any(#[from] Box<dyn std::error::Error + Send + Sync>),

#[error("Can't read database configuration file")]
CantReadConfiguration,

#[error(transparent)]
SeaOrm(#[from] DbErr),
}

pub fn handle_dberr(error: DbErr) -> Error {
tracing::error!("Got DbErr {:?}", error);

Error::SeaOrm(error)
}
32 changes: 32 additions & 0 deletions crates/arch-db-pg/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::sync::Arc;

use migration::apply_migrations;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use tracing_log::log;

pub mod entities;
pub mod error;
pub mod migration;

pub use error::*;

pub struct DatabaseRepository {
pub database: DatabaseConnection,
}

pub async fn create_database_connection(url: &str) -> Result<Arc<DatabaseRepository>, Error> {
tracing::debug!("Connecting to database...");
let mut opt = ConnectOptions::new(url);
opt.max_connections(100)
.min_connections(5)
.sqlx_logging(true)
.sqlx_logging_level(log::LevelFilter::Info);

let database = Database::connect(opt).await.map_err(handle_dberr)?;
apply_migrations(&database).await?;

let database = Arc::new(DatabaseRepository { database });
tracing::debug!("...connected to database");

Ok(database)
}
File renamed without changes.
11 changes: 4 additions & 7 deletions crates/arch-db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,17 @@ homepage.workspace = true
repository.workspace = true
readme.workspace = true
rust-version.workspace = true
publish = false

build = "build.rs"
[lib]
name = "arch_db"
path = "src/lib.rs"

[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tracing.workspace = true
tracing-log.workspace = true

[dependencies.rust-embed]
version = "8.3.0"
features = ["debug-embed"]

[dependencies.sea-orm]
version = "1.0.0"
features = [
Expand Down
41 changes: 41 additions & 0 deletions crates/arch-db/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
```
24 changes: 18 additions & 6 deletions crates/arch-db/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
use std::sync::Arc;

use migration::apply_migrations;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use tracing_log::log;
pub use sea_orm_migration::prelude::*;

pub mod entities;
pub mod error;
pub mod migration;

pub use error::*;
use tracing_log::log;

mod m20220101_000001_create_table;

pub struct Migrator;

#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220101_000001_create_table::Migration)]
}
}

pub struct DatabaseRepository {
pub database: DatabaseConnection,
Expand All @@ -23,10 +31,14 @@ pub async fn create_database_connection(url: &str) -> Result<Arc<DatabaseReposit
.sqlx_logging_level(log::LevelFilter::Info);

let database = Database::connect(opt).await.map_err(handle_dberr)?;
apply_migrations(&database).await?;
Migrator::up(&database, None).await?;

let database = Arc::new(DatabaseRepository { database });
tracing::debug!("...connected to database");

Ok(database)
}

pub async fn run_migration_cli() {
cli::run_cli(Migrator).await
}
33 changes: 33 additions & 0 deletions crates/arch-db/src/m20220101_000001_create_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Post::Table)
.if_not_exists()
.col(ColumnDef::new(Post::Id).integer().not_null().auto_increment().primary_key())
.col(ColumnDef::new(Post::Title).string().not_null())
.col(ColumnDef::new(Post::Text).string().not_null())
.to_owned(),
)
.await
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.drop_table(Table::drop().table(Post::Table).to_owned()).await
}
}

#[derive(DeriveIden)]
enum Post {
Table,
Id,
Title,
Text,
}
2 changes: 1 addition & 1 deletion crates/rust-arch/src/bin/migrator.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use arch_db::migration::run_migration_cli;
use arch_db::run_migration_cli;

#[tokio::main]
async fn main() {
Expand Down

0 comments on commit 766b48f

Please sign in to comment.