init basic database folder structure

This commit is contained in:
GW_MC
2025-11-11 20:15:08 +08:00
commit c9daeeab4c
12 changed files with 3322 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
target/
# Generated by Cargo
# will have compiled files and executables
debug
target
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# Generated by cargo mutants
# Contains mutation testing data
**/mutants.out*/
# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

3036
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

10
Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[workspace]
members = [
"public/database",
"public/migration",
]
resolver = "3"
[workspace.lints.clippy]
module_inception = "allow"

View File

@@ -0,0 +1,19 @@
[package]
name = "database"
version = "0.1.0"
edition = "2024"
[lib]
path = "src/lib.rs"
[dependencies]
shared = { path = "../shared" }
migration = { path = "../migration" }
chrono = { version = "0.4", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.47.0", features = ["full"] }
sea-orm = { version = "2.0.0-rc", features = [ "sqlx-postgres", "sqlx-mysql", "sqlx-sqlite", "runtime-tokio-rustls", "macros", "mock", "with-chrono", "with-json", "with-uuid", "sqlite-use-returning-for-3_35", "mariadb-use-returning" ] }
[lints]
workspace = true

View File

@@ -0,0 +1,22 @@
use sea_orm::ConnectOptions;
pub async fn get_connection<T: FnOnce(&mut ConnectOptions) -> &mut ConnectOptions>(
connection_string: &str,
option_fn: Option<T>,
) -> Result<sea_orm::DatabaseConnection, sea_orm::DbErr> {
use sea_orm::Database;
let mut opt = ConnectOptions::new(connection_string.to_string());
opt.max_connections(10)
.min_connections(0)
.connect_timeout(std::time::Duration::from_secs(8))
.idle_timeout(std::time::Duration::from_secs(8))
.test_before_acquire(true)
.sqlx_logging(false);
if let Some(option_fn) = option_fn {
option_fn(&mut opt);
}
Database::connect(opt).await
}

View File

@@ -0,0 +1,20 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2024"
rust-version = "1.85.0"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }
[dependencies.sea-orm-migration]
version = "2.0.0-rc"
features = [
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
"sqlx-postgres", "sqlx-mysql", "sqlx-sqlite" # `DATABASE_DRIVER` features
]

View File

@@ -0,0 +1,59 @@
# 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
```

View File

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

View File

@@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;
#[tokio::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

View File

@@ -0,0 +1,2 @@
pub mod m20251011_000001_create_user_table;
pub mod m20251011_000002_create_config_table;

View File

@@ -0,0 +1,60 @@
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveMigrationName)]
pub struct Migration;
#[derive(DeriveIden)]
enum User {
Table,
Id,
//
Name,
IsAdmin,
PasswordHash,
Salt,
//
CreatedAt,
UpdatedAt,
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(User::Table)
.if_not_exists()
.col(pk_uuid(User::Id))
.col(ColumnDef::new(User::Name).string().not_null().unique_key())
.col(
ColumnDef::new(User::IsAdmin)
.boolean()
.default(false)
.not_null(),
)
.col(ColumnDef::new(User::PasswordHash).string().not_null())
.col(ColumnDef::new(User::Salt).string().not_null())
.col(
ColumnDef::new(User::CreatedAt)
.timestamp()
.default(SimpleExpr::Keyword(Keyword::CurrentTimestamp))
.not_null(),
)
.col(
ColumnDef::new(User::UpdatedAt)
.timestamp()
.default(SimpleExpr::Keyword(Keyword::CurrentTimestamp))
.not_null(),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(User::Table).to_owned())
.await
}
}

View File

@@ -0,0 +1,49 @@
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[derive(DeriveIden)]
enum Config {
Table,
//
Key,
Value,
//
CreatedAt,
UpdatedAt,
}
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
Table::create()
.table(Config::Table)
.if_not_exists()
.col(ColumnDef::new(Config::Key).string().not_null().unique_key())
.col(ColumnDef::new(Config::Value).string().not_null())
.col(
ColumnDef::new(Config::CreatedAt)
.timestamp()
.default(SimpleExpr::Keyword(Keyword::CurrentTimestamp))
.not_null(),
)
.col(
ColumnDef::new(Config::UpdatedAt)
.timestamp()
.default(SimpleExpr::Keyword(Keyword::CurrentTimestamp))
.not_null(),
)
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Config::Table).to_owned())
.await
}
}