Skip to content

Commit

Permalink
Merge pull request #2 from fankaiLiu/db
Browse files Browse the repository at this point in the history
add sea_orm template
  • Loading branch information
fankaiLiu authored Oct 15, 2023
2 parents b404490 + a2252c9 commit 8512378
Show file tree
Hide file tree
Showing 22 changed files with 548 additions and 106 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "salvo-cli"
version = "0.1.8"
version = "0.1.9"
edition = "2021"
authors = ["Fankai Liu [email protected]"]
keywords = ["salvo", "cli","template"]
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ cargo install --force salvo-cli

### Feature Development Plan

| Status |Task |
| Status |Plan |
|:---:|:---:|
|| web api template |
|| web site with htmlx template |
||with sqlx template|
||basic midware |
||suport sqlite,pgsql,mysql|
||with seaorm template|
||with seaorm template|
|| better web site |
|| with diese template|
|| with Rbatis template|
Expand Down
122 changes: 88 additions & 34 deletions locales/code_comment.yml

Large diffs are not rendered by default.

Binary file added src/template/data/demo_sea_orm.db
Binary file not shown.
6 changes: 6 additions & 0 deletions src/template/data/init_sql_sql.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{{#if is_sqlx}}
{{create_success_mysql_or_pgsql_fist_use}}
{{/if}}
{{#if is_sea_orm}}
{{create_success_sea_orm__mysql_or_pgsql_install_sea_orm}}
{{create_success_sea_orm__mysql_or_pgsql_fist_use}}
{{/if}}
BEGIN;
INSERT INTO "users" ("id", "username", "password") VALUES ('cdd0e080-5bb1-4442-b6f7-2ba60dbd0555', 'zhangsan', '$argon2id$v=19$m=19456,t=2,p=1$rcosL5pOPdA2c7i4ZuLA4Q$s0JGh78UzMmu1qZMpVUA3b8kWYLXcZhw7uBfwhYDJ4A');
COMMIT;
30 changes: 30 additions & 0 deletions src/template/migration/Cargo.toml.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[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.11.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
{{#if is_postgres}}
"sqlx-postgres", # `DATABASE_DRIVER` feature
{{/if}}
{{#if is_sqlite}}
"sqlx-sqlite" # `DATABASE_DRIVER` feature
{{/if}}
{{#if is_mysql}}
"sqlx-mysql", # `DATABASE_DRIVER` feature
{{/if}}
]
41 changes: 41 additions & 0 deletions src/template/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 -- migrate 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
```
12 changes: 12 additions & 0 deletions src/template/migration/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
pub use sea_orm_migration::prelude::*;

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)]
}
}
45 changes: 45 additions & 0 deletions src/template/migration/src/m20220101_000001_create_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
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(User::Table)
.if_not_exists()
.col(
ColumnDef::new(User::Id)
.string()
.not_null()
.primary_key(),
)
.col(
ColumnDef::new(User::Username)
.string()
.not_null()
.unique_key(),
)
.col(ColumnDef::new(User::Password).string().not_null())
.to_owned(),
)
.await
}

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

#[derive(Iden)]
enum User {
Table,
Id,
Username,
Password,
}
6 changes: 6 additions & 0 deletions src/template/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;
}
4 changes: 4 additions & 0 deletions src/template/src/app_error.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ pub enum AppError {
#[error("sqlx::Error:`{0}`")]
SqlxError(#[from] sqlx::Error),
{{/if}}
{{#if is_sea_orm}}
#[error("sea_orm::DbErr:Error:`{0}`")]
DbErr(#[from] sea_orm::DbErr),
{{/if}}
}

pub type AppResult<T> = Result<T, AppError>;
Expand Down
24 changes: 23 additions & 1 deletion src/template/src/db.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ use sqlx::PgPool;
use sqlx::SqlitePool;
{{/if}}
{{/if}}
{{#if is_sea_orm}}
use std::time::Duration;
use sea_orm::{entity::prelude::DatabaseConnection, ConnectOptions, Database};
{{/if}}
use tokio::sync::OnceCell;

use crate::config::CFG;
Expand All @@ -22,7 +26,6 @@ pub static DB: OnceCell<PgPool> = OnceCell::const_new();
{{#if is_mysql}}
pub static DB: OnceCell<MySqlPool> = OnceCell::const_new();
{{/if}}
{{/if}}
pub async fn init_db_conn() {
DB.get_or_init(|| async {
{{#if is_sqlx}}
Expand All @@ -45,3 +48,22 @@ pub async fn init_db_conn() {
})
.await;
}
{{/if}}

{{#if is_sea_orm}}
pub static DB: OnceCell<DatabaseConnection> = OnceCell::const_new();

pub async fn init_db_conn() {
DB.get_or_init(|| async {
let mut opt = ConnectOptions::new(CFG.database.database_url.to_owned());
opt.max_connections(1000)
.min_connections(5)
.connect_timeout(Duration::from_secs(8))
.idle_timeout(Duration::from_secs(8))
.sqlx_logging(false);

Database::connect(opt).await.expect("数据库打开失败")
})
.await;
}
{{/if}}
10 changes: 10 additions & 0 deletions src/template/src/entities/mod.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{{#if is_sqlx}}
pub mod user;
{{/if}}
{{#if is_sea_orm}}
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

pub mod prelude;

pub mod user;
{{/if}}
3 changes: 3 additions & 0 deletions src/template/src/entities/prelude.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

pub use super::user::Entity as User;
32 changes: 32 additions & 0 deletions src/template/src/entities/user.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{{#if is_sqlx}}
use serde::Serialize;
use sqlx::FromRow;

#[derive(FromRow, Serialize, Debug)]
pub struct User {
pub id: String,
pub username: String,
pub password: String,
}
{{/if}}
{{#if is_sea_orm}}
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3

use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: String,
#[sea_orm(unique)]
pub username: String,
pub password: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
{{/if}}
2 changes: 1 addition & 1 deletion src/template/src/main_template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ mod config;
mod db;
mod dtos;
mod services;
mod models;
mod entities;
mod utils;
{{/if}}
mod middleware;
Expand Down
1 change: 0 additions & 1 deletion src/template/src/models/mod.hbs

This file was deleted.

9 changes: 0 additions & 9 deletions src/template/src/models/user.hbs

This file was deleted.

Loading

0 comments on commit 8512378

Please sign in to comment.