From 76c3b2f05397d4f55b1ba932d35e0d41273772ff Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 14 Oct 2023 23:06:28 +0800 Subject: [PATCH 1/6] add sea_orm file --- src/template/migration/Cargo.toml.hbs | 30 +++++ src/template/migration/README.md | 41 +++++++ src/template/migration/src/lib.rs | 12 ++ .../src/m20220101_000001_create_table.rs | 45 ++++++++ src/template/migration/src/main.rs | 6 + src/utils/create_project.rs | 108 +++++++++++++----- src/utils/get_selection.rs | 8 +- 7 files changed, 218 insertions(+), 32 deletions(-) create mode 100644 src/template/migration/Cargo.toml.hbs create mode 100644 src/template/migration/README.md create mode 100644 src/template/migration/src/lib.rs create mode 100644 src/template/migration/src/m20220101_000001_create_table.rs create mode 100644 src/template/migration/src/main.rs diff --git a/src/template/migration/Cargo.toml.hbs b/src/template/migration/Cargo.toml.hbs new file mode 100644 index 0000000..8273a21 --- /dev/null +++ b/src/template/migration/Cargo.toml.hbs @@ -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}} +] diff --git a/src/template/migration/README.md b/src/template/migration/README.md new file mode 100644 index 0000000..b3ea53e --- /dev/null +++ b/src/template/migration/README.md @@ -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 + ``` diff --git a/src/template/migration/src/lib.rs b/src/template/migration/src/lib.rs new file mode 100644 index 0000000..2c605af --- /dev/null +++ b/src/template/migration/src/lib.rs @@ -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> { + vec![Box::new(m20220101_000001_create_table::Migration)] + } +} diff --git a/src/template/migration/src/m20220101_000001_create_table.rs b/src/template/migration/src/m20220101_000001_create_table.rs new file mode 100644 index 0000000..34501e3 --- /dev/null +++ b/src/template/migration/src/m20220101_000001_create_table.rs @@ -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, +} diff --git a/src/template/migration/src/main.rs b/src/template/migration/src/main.rs new file mode 100644 index 0000000..c6b6e48 --- /dev/null +++ b/src/template/migration/src/main.rs @@ -0,0 +1,6 @@ +use sea_orm_migration::prelude::*; + +#[async_std::main] +async fn main() { + cli::run_cli(migration::Migrator).await; +} diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 68f14b8..e2b54a9 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -38,14 +38,15 @@ pub fn create_project(project: Project) -> Result<()> { init_git(project_path)?; success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); - if config.db_conn_type== DbConnectionType::Sqlx { - success(t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n")); + if config.db_conn_type == DbConnectionType::Sqlx { + success( + t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), + ); if config.db_type == DbType::Sqlite { success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - } - else { + } else { success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); - } + } } } None => anyhow::bail!("cli quit!"), @@ -63,6 +64,7 @@ fn write_project_file( let is_web_site = user_selected.template_type == TemplateType::SalvoWebSite; let need_db_conn = user_selected.db_conn_type != DbConnectionType::Nothing; let is_sqlx = user_selected.db_conn_type == DbConnectionType::Sqlx; + let is_sea_orm = user_selected.db_conn_type == DbConnectionType::SeaOrm; let is_mysql = user_selected.db_type == DbType::Mysql; let is_postgres = user_selected.db_type == DbType::Postgres; let is_sqlite = user_selected.db_type == DbType::Sqlite; @@ -93,6 +95,7 @@ fn write_project_file( "is_mysql":is_mysql, "is_postgres":is_postgres, "is_sqlite":is_sqlite, + "is_sea_orm":is_sea_orm, "main_log_message":t!("main_log_message"), "config_error_no_exits":t!("config_error_no_exits"), "config_error_read":t!("config_error_read"), @@ -114,26 +117,47 @@ fn write_project_file( "operation":t!("operation"), "create_success_mysql_or_pgsql_fist_use":t!("create_success_mysql_or_pgsql_fist_use").replace(r"\n", "\n"), }); - if is_sqlx { + if need_db_conn { // Add sqlx dependencies let mut dependencies = data["dependencies"].clone(); - if is_mysql { - dependencies["sqlx"] = json!({ - "version": "0.7", - "features": ["runtime-tokio", "macros", "mysql"] - }); - } - if is_postgres { - dependencies["sqlx"] = json!({ - "version": "0.7", - "features": ["runtime-tokio", "macros", "postgres"] - }); - } - if is_sqlite { - dependencies["sqlx"] = json!({ - "version": "0.7", - "features": ["runtime-tokio", "macros", "sqlite"] - }); + if is_sqlx { + if is_mysql { + dependencies["sqlx"] = json!({ + "version": "0.7", + "features": ["runtime-tokio", "macros", "mysql"] + }); + } + if is_postgres { + dependencies["sqlx"] = json!({ + "version": "0.7", + "features": ["runtime-tokio", "macros", "postgres"] + }); + } + if is_sqlite { + dependencies["sqlx"] = json!({ + "version": "0.7", + "features": ["runtime-tokio", "macros", "sqlite"] + }); + } + } else if is_sea_orm { + if is_mysql { + dependencies["sea-orm"] = json!({ + "version": "0", + "features": ["sqlx-mysql"] + }); + } + if is_postgres { + dependencies["sea-orm"] = json!({ + "version": "0", + "features": ["sqlx-postgres"] + }); + } + if is_sqlite { + dependencies["sea-orm"] = json!({ + "version": "0", + "features": ["sqlx-sqlite"] + }); + } } //add uuid dependency dependencies["uuid"] = json!({ @@ -354,15 +378,14 @@ fn write_project_file( if is_sqlx { //data let data_path = project_path.join("data"); - std::fs::create_dir_all(&data_path)?; + std::fs::create_dir_all(&data_path)?; if is_sqlite { //data/demo.db let demo_db_bytes = include_bytes!("../template/data/demo.db"); let mut demo_db_file = File::create(data_path.join("demo.db"))?; demo_db_file.write_all(demo_db_bytes)?; - } - else{ - //data/init_sql.sql + } else { + //data/init_sql.sql let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; @@ -381,8 +404,37 @@ fn write_project_file( let mut env_file = File::create(project_path.join(".env"))?; env_file.write_all(env_rendered.as_bytes())?; } + if is_sea_orm + { + //migration + let migration_path = project_path.join("migration"); + std::fs::create_dir_all(&migration_path)?; + //migration/src + let migration_src_path = migration_path.join("src"); + std::fs::create_dir_all(&migration_src_path)?; + //migration/src/main.rs + let migration_main_byetes = include_bytes!("../template/migration/src/main.rs"); + let mut migration_main_file = File::create(migration_src_path.join("main.rs"))?; + migration_main_file.write_all(migration_main_byetes)?; + //migration/src/lib.rs + let migration_lib_byetes = include_bytes!("../template/migration/src/lib.rs"); + let mut migration_lib_file = File::create(migration_src_path.join("lib.rs"))?; + migration_lib_file.write_all(migration_lib_byetes)?; + //migration/src/m20220101_000001_create_table.rs + let migration_create_table_byetes = include_bytes!("../template/migration/src/m20220101_000001_create_table.rs"); + let mut migration_create_table_file = File::create(migration_src_path.join("m20220101_000001_create_table.rs"))?; + migration_create_table_file.write_all(migration_create_table_byetes)?; + //migration/Cargo.toml + let migration_cargo_template = include_str!("../template/migration/Cargo.toml.hbs"); + let migration_cargo_rendered = handlebars.render_template(migration_cargo_template, &data)?; + let mut migration_cargo_file = File::create(migration_path.join("Cargo.toml"))?; + migration_cargo_file.write_all(migration_cargo_rendered.as_bytes())?; + //migration/README.md + let migration_readme_bytes = include_bytes!("../template/migration/README.md"); + let mut migration_readme_file = File::create(migration_path.join("README.md"))?; + migration_readme_file.write_all(migration_readme_bytes)?; + } } - Ok(()) } diff --git a/src/utils/get_selection.rs b/src/utils/get_selection.rs index 3893bc7..9573d49 100644 --- a/src/utils/get_selection.rs +++ b/src/utils/get_selection.rs @@ -2,7 +2,7 @@ use anyhow::Result; use dialoguer::{console::Style, theme::ColorfulTheme, Select}; use rust_i18n::t; -#[derive(Debug,Clone)] +#[derive(Debug, Clone)] pub struct UserSelected { pub template_type: TemplateType, pub db_type: DbType, @@ -83,20 +83,20 @@ pub fn get_user_selected() -> Result> { db_conn_type, })) } -#[derive(Debug, PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)] pub enum TemplateType { SalvoWebSite, SalvoWebApi, } -#[derive(Debug, PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)] pub enum DbType { Sqlite, Mysql, Postgres, } -#[derive(Debug, PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)] pub enum DbConnectionType { Sqlx, Diesel, From 5e3f9268db131236808c2d6a85bfdb8a2837b55c Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 14 Oct 2023 23:26:27 +0800 Subject: [PATCH 2/6] rename models to entities --- src/template/data/demo_sea_orm.db | Bin 0 -> 24576 bytes src/template/src/app_error.hbs | 4 +++ src/template/src/db.hbs | 24 ++++++++++++++- src/template/src/{models => entities}/mod.hbs | 0 .../src/{models => entities}/user.hbs | 0 src/template/src/main_template.hbs | 2 +- src/template/src/services/user.hbs | 2 +- src/utils/create_project.rs | 28 +++++++++--------- 8 files changed, 43 insertions(+), 17 deletions(-) create mode 100644 src/template/data/demo_sea_orm.db rename src/template/src/{models => entities}/mod.hbs (100%) rename src/template/src/{models => entities}/user.hbs (100%) diff --git a/src/template/data/demo_sea_orm.db b/src/template/data/demo_sea_orm.db new file mode 100644 index 0000000000000000000000000000000000000000..3619d8ff487b057c4b797cc3636801d87b2c0fb2 GIT binary patch literal 24576 zcmeI&T~C`(7zgl!eQ|EFEHh27OwO7n&P5hLYF!qy;Z}_f-(_39A%}8oNn5Bu)p*xW zwU4n|vzvVhFT5PIX%@RocWIOV6Ap#L13k|#+;HINz;Gi@PyL|7BDzeT6G0#!C?$lX zXUdV%_r9U24_2Vi%*4K?HEhb$>`id4^r${4y8PVOn zW4db^2Hij0+R+bd^mDbgG)(kZhmU8OyITilHBRWVFud@Czb>=5kjWO_V#NRrU64N40+J8N4Vw-K<&^}TR>f9h_@ z0fn@|Er~p_oU*R=}B@! z&Bjd-f0B4XKmY;|fB*y_009U<00Izz00bZ~aRMbFwVCdyvZ~68tXOgqid7Fdi|0fJ za~b^g*4)#$EkG=_x~*-wkESc zj2Z$EfB*y_009U<00Izz00bcL$OQT?gp4`g->W;0%;i;CD%-XqX_}@=_R48RQf;;( zJGLX2%jK&k^BN)ZN-Svjp6WWK^EKsdsS~fX^2$=QrY?2Ylu}UlL!;c?+jn%eUU9XP zo}p_8rBL49Y*tpytDR0yIXl_uelhiBd$skoW_+ukG%qT>_0x-H?bEiV58wY^6Y=_y zX<;}JfB*y_009U<00Izz00bZa0SG)Ou#hrm{%4|L`22rE#G3~%i3A8h00Izz00bZa X0SG_<0uX=z1SUw}S!#Y}^nt-|-#PDz literal 0 HcmV?d00001 diff --git a/src/template/src/app_error.hbs b/src/template/src/app_error.hbs index 84b507c..a79e3c5 100644 --- a/src/template/src/app_error.hbs +++ b/src/template/src/app_error.hbs @@ -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 = Result; diff --git a/src/template/src/db.hbs b/src/template/src/db.hbs index 0d8864d..a1c5596 100644 --- a/src/template/src/db.hbs +++ b/src/template/src/db.hbs @@ -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; @@ -22,7 +26,6 @@ pub static DB: OnceCell = OnceCell::const_new(); {{#if is_mysql}} pub static DB: OnceCell = OnceCell::const_new(); {{/if}} -{{/if}} pub async fn init_db_conn() { DB.get_or_init(|| async { {{#if is_sqlx}} @@ -45,3 +48,22 @@ pub async fn init_db_conn() { }) .await; } +{{/if}} + +{{#if is_sea_orm}} +pub static DB: OnceCell = 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}} \ No newline at end of file diff --git a/src/template/src/models/mod.hbs b/src/template/src/entities/mod.hbs similarity index 100% rename from src/template/src/models/mod.hbs rename to src/template/src/entities/mod.hbs diff --git a/src/template/src/models/user.hbs b/src/template/src/entities/user.hbs similarity index 100% rename from src/template/src/models/user.hbs rename to src/template/src/entities/user.hbs diff --git a/src/template/src/main_template.hbs b/src/template/src/main_template.hbs index 0d998c8..a262acf 100644 --- a/src/template/src/main_template.hbs +++ b/src/template/src/main_template.hbs @@ -19,7 +19,7 @@ mod config; mod db; mod dtos; mod services; -mod models; +mod entities; mod utils; {{/if}} mod middleware; diff --git a/src/template/src/services/user.hbs b/src/template/src/services/user.hbs index ea1cf2d..60ab51b 100644 --- a/src/template/src/services/user.hbs +++ b/src/template/src/services/user.hbs @@ -6,7 +6,7 @@ use crate::{ UserUpdateRequest, }, middleware::jwt::get_token, - models::user::User, + entities::user::User, utils::rand_utils, }; use uuid::Uuid; diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index e2b54a9..93542dd 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -360,20 +360,20 @@ fn write_project_file( let mut dtos_user_file = File::create(dtos_path.join("user.rs"))?; dtos_user_file.write_all(dtos_user_rendered.as_bytes())?; - //src/models - let models_path = src_path.join("models"); - std::fs::create_dir_all(&models_path)?; - //src/models/mod.rs - let models_mod_template = include_str!("../template/src/models/mod.hbs"); - let models_mod_rendered = handlebars.render_template(models_mod_template, &data)?; - let mut models_mod_file = File::create(models_path.join("mod.rs"))?; - models_mod_file.write_all(models_mod_rendered.as_bytes())?; + //src/entities + let entities_path = src_path.join("entities"); + std::fs::create_dir_all(&entities_path)?; + //src/entities/mod.rs + let entities_mod_template = include_str!("../template/src/entities/mod.hbs"); + let entities_mod_rendered = handlebars.render_template(entities_mod_template, &data)?; + let mut entities_mod_file = File::create(entities_path.join("mod.rs"))?; + entities_mod_file.write_all(entities_mod_rendered.as_bytes())?; - //src/models/user.rs - let models_user_template = include_str!("../template/src/models/user.hbs"); - let models_user_rendered = handlebars.render_template(models_user_template, &data)?; - let mut models_user_file = File::create(models_path.join("user.rs"))?; - models_user_file.write_all(models_user_rendered.as_bytes())?; + //src/entities/user.rs + let entities_user_template = include_str!("../template/src/entities/user.hbs"); + let entities_user_rendered = handlebars.render_template(entities_user_template, &data)?; + let mut entities_user_file = File::create(entities_path.join("user.rs"))?; + entities_user_file.write_all(entities_user_rendered.as_bytes())?; if is_sqlx { //data @@ -500,7 +500,7 @@ pub fn init_git(project_path: &Path) -> Result<()> { fn write_ignore_file(project_path: &Path) -> Result<()> { let fp_ignore = project_path.join(".gitignore"); let mut fp_ignore_file = File::create(fp_ignore)?; - fp_ignore_file.write_all(b"/target\n")?; + fp_ignore_file.write_all(b"/target\n/migration/target")?; Ok(()) } From 28f46204692d529ab040e3a6d2d86fd45c770d33 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 15 Oct 2023 00:11:24 +0800 Subject: [PATCH 3/6] add sea_orm support --- src/template/src/entities/mod.hbs | 9 +++ src/template/src/entities/prelude.hbs | 3 + src/template/src/entities/user.hbs | 23 ++++++++ src/template/src/services/user.hbs | 80 +++++++++++++++++++++++++++ src/utils/create_project.rs | 30 +++++++--- src/utils/get_selection.rs | 14 ++--- 6 files changed, 145 insertions(+), 14 deletions(-) create mode 100644 src/template/src/entities/prelude.hbs diff --git a/src/template/src/entities/mod.hbs b/src/template/src/entities/mod.hbs index 22d12a3..2fff605 100644 --- a/src/template/src/entities/mod.hbs +++ b/src/template/src/entities/mod.hbs @@ -1 +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}} diff --git a/src/template/src/entities/prelude.hbs b/src/template/src/entities/prelude.hbs new file mode 100644 index 0000000..7c8fdd7 --- /dev/null +++ b/src/template/src/entities/prelude.hbs @@ -0,0 +1,3 @@ +//! `SeaORM` Entity. Generated by sea-orm-codegen 0.11.3 + +pub use super::user::Entity as User; diff --git a/src/template/src/entities/user.hbs b/src/template/src/entities/user.hbs index 025bf41..218a0aa 100644 --- a/src/template/src/entities/user.hbs +++ b/src/template/src/entities/user.hbs @@ -1,3 +1,4 @@ +{{#if is_sqlx}} use serde::Serialize; use sqlx::FromRow; @@ -7,3 +8,25 @@ pub struct User { 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}} \ No newline at end of file diff --git a/src/template/src/services/user.hbs b/src/template/src/services/user.hbs index 60ab51b..b632583 100644 --- a/src/template/src/services/user.hbs +++ b/src/template/src/services/user.hbs @@ -9,6 +9,9 @@ use crate::{ entities::user::User, utils::rand_utils, }; +{{#if is_sea_orm}} +use sea_orm::{EntityTrait, Set, ActiveModelTrait, QueryFilter, ColumnTrait}; +{{/if}} use uuid::Uuid; {{#if is_sqlx}} pub async fn add_user(req: UserAddRequest) -> AppResult { @@ -121,4 +124,81 @@ pub async fn users() -> AppResult> { .collect::>(); Ok(res) } +{{/if}} +{{#if is_sea_orm}} +pub async fn add_user(req: UserAddRequest) -> AppResult { + let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let model =user::ActiveModel { + id: Set(Uuid::new_v4().to_string()), + username: Set(req.username.clone()), + password: Set(rand_utils::hash_password(req.password).await?), + }; + let user = User::insert(model).exec(db).await?; + Ok(UserResponse { + id: user.last_insert_id, + username: req.username, + }) +} + +pub async fn login(req: UserLoginRequest) -> AppResult { + let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let user = User::find().filter(user::Column::Username.eq(req.username)).one(db).await?; + if user.is_none() { + return Err(anyhow::anyhow!("用户不存在").into()); + } + let user = user.unwrap(); + if rand_utils::verify_password(req.password, user.password) + .await + .is_err() + { + return Err(anyhow::anyhow!("密码不正确").into()); + } + let (token, exp) = get_token(user.username.clone(), user.id.clone())?; + let res = UserLoginResponse { + id: user.id, + username: user.username, + token, + exp, + }; + Ok(res) +} + +pub async fn update_user(req: UserUpdateRequest) -> AppResult { + let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + + let user = User::find_by_id(req.id).one(db).await?; + if user.is_none() { + return Err(anyhow::anyhow!("用户不存在").into()); + } + let mut user: user::ActiveModel = user.unwrap().into(); + + user.username = Set(req.username.to_owned()); + user.password = Set(rand_utils::hash_password(req.password).await?); + + let user: user::Model = user.update(db).await?; + + Ok(UserResponse { + id: user.id, + username: user.username, + }) +} + +pub async fn delete_user(req: UserDeleteRequest) -> AppResult<()> { + let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + User::delete_by_id(req.id, ).exec(db).await?; + Ok(()) +} + +pub async fn users() -> AppResult> { + let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let users = User::find().all(db).await?; + let res = users + .into_iter() + .map(|user| UserResponse { + id: user.id, + username: user.username, + }) + .collect::>(); + Ok(res) +} {{/if}} \ No newline at end of file diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 93542dd..e58a416 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -374,7 +374,14 @@ fn write_project_file( let entities_user_rendered = handlebars.render_template(entities_user_template, &data)?; let mut entities_user_file = File::create(entities_path.join("user.rs"))?; entities_user_file.write_all(entities_user_rendered.as_bytes())?; - + if is_sea_orm { + //src/entities/prelude.rs + let entities_prelude_template = include_str!("../template/src/entities/prelude.hbs"); + let entities_prelude_rendered = + handlebars.render_template(entities_prelude_template, &data)?; + let mut entities_prelude_file = File::create(entities_path.join("prelude.rs"))?; + entities_prelude_file.write_all(entities_prelude_rendered.as_bytes())?; + } if is_sqlx { //data let data_path = project_path.join("data"); @@ -404,9 +411,8 @@ fn write_project_file( let mut env_file = File::create(project_path.join(".env"))?; env_file.write_all(env_rendered.as_bytes())?; } - if is_sea_orm - { - //migration + if is_sea_orm { + //migration let migration_path = project_path.join("migration"); std::fs::create_dir_all(&migration_path)?; //migration/src @@ -421,18 +427,28 @@ fn write_project_file( let mut migration_lib_file = File::create(migration_src_path.join("lib.rs"))?; migration_lib_file.write_all(migration_lib_byetes)?; //migration/src/m20220101_000001_create_table.rs - let migration_create_table_byetes = include_bytes!("../template/migration/src/m20220101_000001_create_table.rs"); - let mut migration_create_table_file = File::create(migration_src_path.join("m20220101_000001_create_table.rs"))?; + let migration_create_table_byetes = + include_bytes!("../template/migration/src/m20220101_000001_create_table.rs"); + let mut migration_create_table_file = + File::create(migration_src_path.join("m20220101_000001_create_table.rs"))?; migration_create_table_file.write_all(migration_create_table_byetes)?; //migration/Cargo.toml let migration_cargo_template = include_str!("../template/migration/Cargo.toml.hbs"); - let migration_cargo_rendered = handlebars.render_template(migration_cargo_template, &data)?; + let migration_cargo_rendered = + handlebars.render_template(migration_cargo_template, &data)?; let mut migration_cargo_file = File::create(migration_path.join("Cargo.toml"))?; migration_cargo_file.write_all(migration_cargo_rendered.as_bytes())?; //migration/README.md let migration_readme_bytes = include_bytes!("../template/migration/README.md"); let mut migration_readme_file = File::create(migration_path.join("README.md"))?; migration_readme_file.write_all(migration_readme_bytes)?; + + if is_sqlite { + //data/demo.db + let demo_db_bytes = include_bytes!("../template/data/demo_sea_orm.db"); + let mut demo_db_file = File::create(project_path.join("/data/demo.db"))?; + demo_db_file.write_all(demo_db_bytes)?; + } } } Ok(()) diff --git a/src/utils/get_selection.rs b/src/utils/get_selection.rs index 9573d49..49796d5 100644 --- a/src/utils/get_selection.rs +++ b/src/utils/get_selection.rs @@ -34,8 +34,8 @@ pub fn get_user_selected() -> Result> { }; let db_conn_types = &[ t!("db_conn_types_sqlx"), - // t!("db_conn_types_diesel"), t!("db_conn_types_sea_orm"), + // t!("db_conn_types_diesel"), // t!("db_conn_types_rbatis"), t!("db_conn_types_nothing"), // "custom", @@ -48,10 +48,10 @@ pub fn get_user_selected() -> Result> { let db_conn_type = match db_conn_type_selection { 0 => DbConnectionType::Sqlx, - 1 => DbConnectionType::Diesel, - 2 => DbConnectionType::SeaOrm, - 3 => DbConnectionType::Rbatis, - 4 => DbConnectionType::Nothing, + 1 => DbConnectionType::SeaOrm, + 2 => DbConnectionType::Nothing, + // 2 => DbConnectionType::Diesel, + // 3 => DbConnectionType::Rbatis, _ => anyhow::bail!("Invalid db connection type selection"), }; if db_conn_type == DbConnectionType::Nothing { @@ -99,8 +99,8 @@ pub enum DbType { #[derive(Debug, PartialEq, Clone)] pub enum DbConnectionType { Sqlx, - Diesel, SeaOrm, - Rbatis, + // Diesel, + // Rbatis, Nothing, } From acabfc4c865c8efcc83137f556c22aeddfa36b66 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 15 Oct 2023 11:44:04 +0800 Subject: [PATCH 4/6] add sea_orm support done --- locales/code_comment.yml | 122 +++++++++++++++++++++-------- src/template/data/init_sql_sql.hbs | 6 ++ src/template/src/services/user.hbs | 29 +++++-- src/utils/create_project.rs | 44 ++++++++--- 4 files changed, 150 insertions(+), 51 deletions(-) diff --git a/locales/code_comment.yml b/locales/code_comment.yml index b5a14ef..de73d95 100644 --- a/locales/code_comment.yml +++ b/locales/code_comment.yml @@ -418,24 +418,42 @@ create_success_sqlx: th: 🎯 คุณได้เลือก sqlx คุณสามารถดูเอกสารได้ที่นี่:https://github.com/launchbadge/sqlx el: 🎯 Επιλέξατε sqlx, η τεκμηρίωση μπορεί να προβληθεί εδώ:https://github.com/launchbadge/sqlx da: 🎯 Du har valgt sqlx, dokumentationen kan ses her:https://github.com/launchbadge/sqlx +create_success_sea_orm: + en: 🐚 You have chosen sea-orm, documentation can be viewed here:https://www.sea-ql.org/SeaORM/docs/index/ + zh_CN: 🐚 您选择了sea-orm,文档可以在这里查看:https://www.sea-ql.org/SeaORM/docs/index/ + zh_TW: 🐚 您選擇了sea-orm,文檔可以在這裡查看:https://www.sea-ql.org/SeaORM/docs/index/ + fr: 🐚 Vous avez choisi sea-orm, la documentation peut être consultée ici:https://www.sea-ql.org/SeaORM/docs/index/ + ja: 🐚 sea-ormを選択しました。ドキュメントはこちらからご覧ください:https://www.sea-ql.org/SeaORM/docs/index/ + es: 🐚 Ha elegido sea-orm, la documentación se puede ver aquí:https://www.sea-ql.org/SeaORM/docs/index/ + de: 🐚 Sie haben sea-orm gewählt, die Dokumentation kann hier eingesehen werden:https://www.sea-ql.org/SeaORM/docs/index/ + ru: 🐚 Вы выбрали sea-orm, документацию можно посмотреть здесь:https://www.sea-ql.org/SeaORM/docs/index/ + it: 🐚 Hai scelto sea-orm, la documentazione può essere visualizzata qui:https://www.sea-ql.org/SeaORM/docs/index/ + pt: 🐚 Você escolheu sea-orm, a documentação pode ser visualizada aqui:https://www.sea-ql.org/SeaORM/docs/index/ + ko: 🐚 sea-orm을 선택했습니다. 여기에서 문서를 볼 수 있습니다:https://www.sea-ql.org/SeaORM/docs/index/ + no: 🐚 Du har valgt sea-orm, dokumentasjonen kan ses her:https://www.sea-ql.org/SeaORM/docs/index/ + is: 🐚 Þú hefur valið sea-orm, hægt er að skoða kennslu hér:https://www.sea-ql.org/SeaORM/docs/index/ + uk: 🐚 Ви вибрали sea-orm, документацію можна переглянути тут:https://www.sea-ql.org/SeaORM/docs/index/ + th: 🐚 คุณได้เลือก sea-orm คุณสามารถดูเอกสารได้ที่นี่:https://www.sea-ql.org/SeaORM/docs/index/ + el: 🐚 Επιλέξατε sea-orm, η τεκμηρίωση μπορεί να προβληθεί εδώ:https://www.sea-ql.org/SeaORM/docs/index/ + da: 🐚 Du har valgt sea-orm, dokumentationen kan ses her:https://www.sea-ql.org/SeaORM/docs/index/ create_success_sqlx_sqlite: - en: 🎯 Default database created in `/data/demo.db`.\n After running it, you can access /login with the default username:'zhangsan' and password:'123'. - zh_CN: 🎯 默认数据库创建在`/data/demo.db`。\n 运行后,您可以使用默认用户名:'zhangsan'和密码:'123'访问/login。 - zh_TW: 🎯 預設資料庫創建在`/data/demo.db`。\n 運行後,您可以使用預設用戶名:'zhangsan'和密碼:'123'訪問/login。 - fr: 🎯 Base de données par défaut créée dans `/data/demo.db`. \n Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:'zhangsan' et le mot de passe:'123'. - ja: 🎯 デフォルトのデータベースが`/data/demo.db`に作成されました。\n 実行後、デフォルトのユーザー名:'zhangsan'とパスワード:'123'で/loginにアクセスできます。 - es: 🎯 Base de datos predeterminada creada en `/data/demo.db`. \n Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:'zhangsan' y la contraseña:'123'. - de: 🎯 Standarddatenbank erstellt in `/data/demo.db`. \n Nach dem Ausführen können Sie mit dem Standardbenutzernamen:'zhangsan' und dem Passwort:'123' auf /login zugreifen. - ru: 🎯 База данных по умолчанию создана в `/data/demo.db`. \n После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:'zhangsan' и паролем:'123'. - it: 🎯 Database predefinita creata in `/data/demo.db`. \n Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:'zhangsan' e la password:'123'. - pt: 🎯 Banco de dados padrão criado em `/data/demo.db`. \n Após executá-lo, você pode acessar /login com o nome de usuário padrão:'zhangsan' e a senha:'123'. - ko: 🎯 기본 데이터베이스가 `/data/demo.db`에 생성되었습니다. \n 실행 후 기본 사용자 이름:'zhangsan'과 비밀번호:'123'으로 /login에 접속할 수 있습니다. - no: 🎯 Standarddatabasen er opprettet i `/data/demo.db`. \n Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:'zhangsan' og passord:'123'. - is: 🎯 Sjálfgefin gagnagrunn búin til í `/data/demo.db`. \n Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:'zhangsan' og lykilorði:'123'. - uk: 🎯 База даних за замовчуванням створена в `/data/demo.db`. \n Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:'zhangsan' та пароля:'123'. - th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/demo.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:'zhangsan' และรหัสผ่าน:'123'. - el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/demo.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:'zhangsan' και τον κωδικό πρόσβασης:'123'. - da: 🎯 Standarddatabasen er oprettet i `/data/demo.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:'zhangsan' og adgangskoden:'123'. + en: 🎯 Default database created in `/data/demo.db`.\n After running it, you can access /login with the default username:zhangsan and password:123. + zh_CN: 🎯 默认数据库创建在`/data/demo.db`。\n 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login。 + zh_TW: 🎯 預設資料庫創建在`/data/demo.db`。\n 運行後,您可以使用預設用戶名:zhangsan和密碼:123訪問/login。 + fr: 🎯 Base de données par défaut créée dans `/data/demo.db`. \n Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123. + ja: 🎯 デフォルトのデータベースが`/data/demo.db`に作成されました。\n 実行後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます。 + es: 🎯 Base de datos predeterminada creada en `/data/demo.db`. \n Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123. + de: 🎯 Standarddatenbank erstellt in `/data/demo.db`. \n Nach dem Ausführen können Sie mit dem Standardbenutzernamen:zhangsan und dem Passwort:123 auf /login zugreifen. + ru: 🎯 База данных по умолчанию создана в `/data/demo.db`. \n После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:zhangsan и паролем:123. + it: 🎯 Database predefinita creata in `/data/demo.db`. \n Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:zhangsan e la password:123. + pt: 🎯 Banco de dados padrão criado em `/data/demo.db`. \n Após executá-lo, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123. + ko: 🎯 기본 데이터베이스가 `/data/demo.db`에 생성되었습니다. \n 실행 후 기본 사용자 이름:zhangsan과 비밀번호:123으로 /login에 접속할 수 있습니다. + no: 🎯 Standarddatabasen er opprettet i `/data/demo.db`. \n Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123. + is: 🎯 Sjálfgefin gagnagrunn búin til í `/data/demo.db`. \n Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:zhangsan og lykilorði:123. + uk: 🎯 База даних за замовчуванням створена в `/data/demo.db`. \n Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:zhangsan та пароля:123. + th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/demo.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123. + el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/demo.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123. + da: 🎯 Standarddatabasen er oprettet i `/data/demo.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123. create_success_mysql_or_pgsql: en: 📊 Follow the instructions in the data/init_sql.sql file to complete the initialization of data zh_CN: 📊 按照data/init_sql.sql文件中的说明完成数据初始化 @@ -455,20 +473,56 @@ create_success_mysql_or_pgsql: el: 📊 Ακολουθήστε τις οδηγίες στο αρχείο data/init_sql.sql για να ολοκληρώσετε την αρχικοποίηση των δεδομένων da: 📊 Følg instruktionerne i data/init_sql.sql-filen for at fuldføre initialiseringen af data create_success_mysql_or_pgsql_fist_use: - en: -- Please first use cargo install sqlx-cli \n -- Modify the database connection string in .env and config/config.toml \n -- Then execute sqlx database create to create the database \n -- Execute sqlx migrate run to restore the database, run the following SQL in the database to add default data. \n -- After running, you can access /login with the default username:'zhangsan' and password:'123'. - zh_CN: -- 请先使用 cargo install sqlx-cli \n -- 修改.env和config/config.toml中的数据库连接字符串 \n -- 然后执行sqlx database create 创建数据库 \n -- 执行sqlx migrate run 还原数据库, 在数据库中运以下SQL以添加默认数据。 \n -- 运行后,您可以使用默认用户名:'zhangsan'和密码:'123'访问/login。 - zh_TW: -- 首先,使用 cargo install sqlx-cli \n -- 修改.env和config/config.toml中的數據庫連接字符串 \n -- 然後執行sqlx database create 創建數據庫 \n -- 執行sqlx migrate run 恢复數據庫, 在數據庫中運行以下SQL以添加默認數據。 \n -- 運行後,您可以使用默認用戶名:'zhangsan'和密碼:'123'訪問/login。 - fr: -- D'abord, utilisez cargo install sqlx-cli \n -- Modifiez la chaîne de connexion à la base de données dans .env et config/config.toml \n -- Ensuite, exécutez sqlx database create pour créer la base de données \n -- Exécutez sqlx migrate run pour restaurer la base de données, exécutez le SQL suivant dans la base de données pour ajouter les données par défaut. \n -- Après l'exécution, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:'zhangsan' et le mot de passe:'123'. - ja: -- まず、cargo install sqlx-cliを使用してください \n -- .envとconfig/config.tomlのデータベース接続文字列を変更します \n -- 次に、sqlx database createを実行してデータベースを作成します \n -- sqlx migrate runを実行してデータベースを復元し、次のSQLをデータベースで実行してデフォルトデータを追加します。 \n -- 実行後、デフォルトのユーザー名:'zhangsan'とパスワード:'123'で/loginにアクセスできます。 - es: -- Primero, use cargo install sqlx-cli \n -- Modifique la cadena de conexión de la base de datos en .env y config/config.toml \n -- Luego, ejecute sqlx database create para crear la base de datos \n -- Ejecute sqlx migrate run para restaurar la base de datos, ejecute el siguiente SQL en la base de datos para agregar datos predeterminados. \n -- Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:'zhangsan' y la contraseña:'123'. - de: -- Bitte verwenden Sie zuerst cargo install sqlx-cli \n -- Ändern Sie die Verbindungszeichenfolge zur Datenbank in .env und config/config.toml \n -- Führen Sie dann sqlx database create aus, um die Datenbank zu erstellen \n -- Führen Sie sqlx migrate run aus, um die Datenbank wiederherzustellen. Führen Sie den folgenden SQL in der Datenbank aus, um Standarddaten hinzuzufügen. \n -- Nach dem Ausführen können Sie mit dem Standardbenutzernamen:'zhangsan' und dem Passwort:'123' auf /login zugreifen. - ru: -- Пожалуйста, сначала используйте cargo install sqlx-cli \n -- Измените строку подключения к базе данных в .env и config/config.toml \n -- Затем выполните sqlx database create, чтобы создать базу данных \n -- Выполните sqlx migrate run, чтобы восстановить базу данных, выполните следующий SQL в базе данных, чтобы добавить данные по умолчанию. \n -- После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:'zhangsan' и паролем:'123'. - it: -- Si prega di utilizzare prima cargo install sqlx-cli \n -- Modifica la stringa di connessione al database in .env e config/config.toml \n -- Quindi esegui sqlx database create per creare il database \n -- Esegui sqlx migrate run per ripristinare il database, esegui il seguente SQL nel database per aggiungere dati predefiniti. \n -- Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:'zhangsan' e la password:'123'. - pt: -- Por favor, use primeiro cargo install sqlx-cli \n -- Modifique a string de conexão do banco de dados em .env e config/config.toml \n -- Em seguida, execute sqlx database create para criar o banco de dados \n -- Execute sqlx migrate run para restaurar o banco de dados, execute o seguinte SQL no banco de dados para adicionar dados padrão. \n -- Após a execução, você pode acessar /login com o nome de usuário padrão:'zhangsan' e a senha:'123'. - ko: -- 먼저 cargo install sqlx-cli를 사용하십시오. \n -- .env 및 config/config.toml에서 데이터베이스 연결 문자열을 수정하십시오. \n -- 그런 다음 sqlx database create를 실행하여 데이터베이스를 만듭니다. \n -- 데이터베이스를 복원하려면 sqlx migrate run을 실행하고 다음 SQL을 데이터베이스에서 실행하여 기본 데이터를 추가하십시오. \n -- 실행 후 기본 사용자 이름:'zhangsan'과 비밀번호:'123'으로 /login에 액세스 할 수 있습니다. - no: -- Vennligst bruk først cargo install sqlx-cli \n -- Endre database-tilkoblingsstrengen i .env og config/config.toml \n -- Kjør deretter sqlx database create for å opprette databasen \n -- Kjør sqlx migrate run for å gjenopprette databasen, kjør følgende SQL i databasen for å legge til standarddata. \n -- Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:'zhangsan' og passord:'123'. - is: -- Vinsamlegast notaðu fyrst cargo install sqlx-cli \n -- Breyttu tengingu strenginn í .env og config/config.toml \n -- Keyrið svo sqlx database create til að búa til gagnagrunninn \n -- Keyrið sqlx migrate run til að endurheimta gagnagrunninn, keyrið eftirfarandi SQL í gagnagrunninum til að bæta við sjálfgefnum gögnum. \n -- Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:'zhangsan' og lykilorði:'123'. - uk: -- Будь ласка, спочатку використовуйте cargo install sqlx-cli \n -- Змініть рядок підключення до бази даних в .env та config/config.toml \n -- Потім виконайте sqlx database create, щоб створити базу даних \n -- Виконайте sqlx migrate run, щоб відновити базу даних, виконайте наступний SQL в базі даних, щоб додати дані за замовчуванням. \n -- Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:'zhangsan' та пароля:'123'. - th: -- โปรดใช้ก่อน cargo install sqlx-cli \n -- แก้ไขสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml \n -- จากนั้นเรียกใช้ sqlx database create เพื่อสร้างฐานข้อมูล \n -- รัน sqlx migrate run เพื่อกู้คืนฐานข้อมูล รัน SQL ต่อไปนี้ในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้น \n -- หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:'zhangsan' และรหัสผ่าน:'123'. - el: -- Παρακαλώ χρησιμοποιήστε πρώτα cargo install sqlx-cli \n -- Τροποποιήστε τη συμβολοσειρά σύνδεσης της βάσης δεδομένων στα .env και config/config.toml \n -- Στη συνέχεια, εκτελέστε sqlx database create για να δημιουργήσετε τη βάση δεδομένων \n -- Εκτελέστε το sqlx migrate run για να επαναφέρετε τη βάση δεδομένων, εκτελέστε το ακόλουθο SQL στη βάση δεδομένων για να προσθέσετε προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να έχετε πρόσβαση στο /login με προεπιλεγμένο όνομα χρήστη:'zhangsan' και κωδικό πρόσβασης:'123'. - da: -- Brug venligst først cargo install sqlx-cli \n -- Rediger databaseforbindelsesstrengen i .env og config/config.toml \n -- Kør derefter sqlx database create for at oprette databasen \n -- Kør sqlx migrate run for at gendanne databasen, kør følgende SQL i databasen for at tilføje standarddata. \n -- Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:'zhangsan' og adgangskoden:'123'. \ No newline at end of file + en: -- Please first use cargo install sqlx-cli \n -- Modify the database connection string in .env and config/config.toml \n -- Then execute sqlx database create to create the database \n -- Execute sqlx migrate run to restore the database, run the following SQL in the database to add default data. \n -- After running, you can access /login with the default username:zhangsan and password:123. + zh_CN: -- 请先使用 cargo install sqlx-cli \n -- 修改.env和config/config.toml中的数据库连接字符串 \n -- 然后执行sqlx database create 创建数据库 \n -- 执行sqlx migrate run 还原数据库, 在数据库中运以下SQL以添加默认数据。 \n -- 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login。 + zh_TW: -- 首先,使用 cargo install sqlx-cli \n -- 修改.env和config/config.toml中的數據庫連接字符串 \n -- 然後執行sqlx database create 創建數據庫 \n -- 執行sqlx migrate run 恢复數據庫, 在數據庫中運行以下SQL以添加默認數據。 \n -- 運行後,您可以使用默認用戶名:zhangsan和密碼:123訪問/login。 + fr: -- D'abord, utilisez cargo install sqlx-cli \n -- Modifiez la chaîne de connexion à la base de données dans .env et config/config.toml \n -- Ensuite, exécutez sqlx database create pour créer la base de données \n -- Exécutez sqlx migrate run pour restaurer la base de données, exécutez le SQL suivant dans la base de données pour ajouter les données par défaut. \n -- Après l'exécution, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123. + ja: -- まず、cargo install sqlx-cliを使用してください \n -- .envとconfig/config.tomlのデータベース接続文字列を変更します \n -- 次に、sqlx database createを実行してデータベースを作成します \n -- sqlx migrate runを実行してデータベースを復元し、次のSQLをデータベースで実行してデフォルトデータを追加します。 \n -- 実行後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます。 + es: -- Primero, use cargo install sqlx-cli \n -- Modifique la cadena de conexión de la base de datos en .env y config/config.toml \n -- Luego, ejecute sqlx database create para crear la base de datos \n -- Ejecute sqlx migrate run para restaurar la base de datos, ejecute el siguiente SQL en la base de datos para agregar datos predeterminados. \n -- Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123. + de: -- Bitte verwenden Sie zuerst cargo install sqlx-cli \n -- Ändern Sie die Verbindungszeichenfolge zur Datenbank in .env und config/config.toml \n -- Führen Sie dann sqlx database create aus, um die Datenbank zu erstellen \n -- Führen Sie sqlx migrate run aus, um die Datenbank wiederherzustellen. Führen Sie den folgenden SQL in der Datenbank aus, um Standarddaten hinzuzufügen. \n -- Nach dem Ausführen können Sie mit dem Standardbenutzernamen:zhangsan und dem Passwort:123 auf /login zugreifen. + ru: -- Пожалуйста, сначала используйте cargo install sqlx-cli \n -- Измените строку подключения к базе данных в .env и config/config.toml \n -- Затем выполните sqlx database create, чтобы создать базу данных \n -- Выполните sqlx migrate run, чтобы восстановить базу данных, выполните следующий SQL в базе данных, чтобы добавить данные по умолчанию. \n -- После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:zhangsan и паролем:123. + it: -- Si prega di utilizzare prima cargo install sqlx-cli \n -- Modifica la stringa di connessione al database in .env e config/config.toml \n -- Quindi esegui sqlx database create per creare il database \n -- Esegui sqlx migrate run per ripristinare il database, esegui il seguente SQL nel database per aggiungere dati predefiniti. \n -- Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:zhangsan e la password:123. + pt: -- Por favor, use primeiro cargo install sqlx-cli \n -- Modifique a string de conexão do banco de dados em .env e config/config.toml \n -- Em seguida, execute sqlx database create para criar o banco de dados \n -- Execute sqlx migrate run para restaurar o banco de dados, execute o seguinte SQL no banco de dados para adicionar dados padrão. \n -- Após a execução, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123. + ko: -- 먼저 cargo install sqlx-cli를 사용하십시오. \n -- .env 및 config/config.toml에서 데이터베이스 연결 문자열을 수정하십시오. \n -- 그런 다음 sqlx database create를 실행하여 데이터베이스를 만듭니다. \n -- 데이터베이스를 복원하려면 sqlx migrate run을 실행하고 다음 SQL을 데이터베이스에서 실행하여 기본 데이터를 추가하십시오. \n -- 실행 후 기본 사용자 이름:zhangsan과 비밀번호:123으로 /login에 액세스 할 수 있습니다. + no: -- Vennligst bruk først cargo install sqlx-cli \n -- Endre database-tilkoblingsstrengen i .env og config/config.toml \n -- Kjør deretter sqlx database create for å opprette databasen \n -- Kjør sqlx migrate run for å gjenopprette databasen, kjør følgende SQL i databasen for å legge til standarddata. \n -- Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123. + is: -- Vinsamlegast notaðu fyrst cargo install sqlx-cli \n -- Breyttu tengingu strenginn í .env og config/config.toml \n -- Keyrið svo sqlx database create til að búa til gagnagrunninn \n -- Keyrið sqlx migrate run til að endurheimta gagnagrunninn, keyrið eftirfarandi SQL í gagnagrunninum til að bæta við sjálfgefnum gögnum. \n -- Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:zhangsan og lykilorði:123. + uk: -- Будь ласка, спочатку використовуйте cargo install sqlx-cli \n -- Змініть рядок підключення до бази даних в .env та config/config.toml \n -- Потім виконайте sqlx database create, щоб створити базу даних \n -- Виконайте sqlx migrate run, щоб відновити базу даних, виконайте наступний SQL в базі даних, щоб додати дані за замовчуванням. \n -- Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:zhangsan та пароля:123. + th: -- โปรดใช้ก่อน cargo install sqlx-cli \n -- แก้ไขสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml \n -- จากนั้นเรียกใช้ sqlx database create เพื่อสร้างฐานข้อมูล \n -- รัน sqlx migrate run เพื่อกู้คืนฐานข้อมูล รัน SQL ต่อไปนี้ในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้น \n -- หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123. + el: -- Παρακαλώ χρησιμοποιήστε πρώτα cargo install sqlx-cli \n -- Τροποποιήστε τη συμβολοσειρά σύνδεσης της βάσης δεδομένων στα .env και config/config.toml \n -- Στη συνέχεια, εκτελέστε sqlx database create για να δημιουργήσετε τη βάση δεδομένων \n -- Εκτελέστε το sqlx migrate run για να επαναφέρετε τη βάση δεδομένων, εκτελέστε το ακόλουθο SQL στη βάση δεδομένων για να προσθέσετε προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να έχετε πρόσβαση στο /login με προεπιλεγμένο όνομα χρήστη:zhangsan και κωδικό πρόσβασης:123. + da: -- Brug venligst først cargo install sqlx-cli \n -- Rediger databaseforbindelsesstrengen i .env og config/config.toml \n -- Kør derefter sqlx database create for at oprette databasen \n -- Kør sqlx migrate run for at gendanne databasen, kør følgende SQL i databasen for at tilføje standarddata. \n -- Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123. +create_success_sea_orm__mysql_or_pgsql_install_sea_orm: + en: -- Please first use cargo install sea-orm-cli \n + zh_CN: -- 请先使用 cargo install sea-orm-cli \n + zh_TW: -- 請先使用 cargo install sea-orm-cli \n + fr: -- Veuillez d'abord utiliser cargo install sea-orm-cli \n + ja: -- まず、cargo install sea-orm-cliを使用してください \n + es: -- Por favor, primero use cargo install sea-orm-cli \n + de: -- Bitte verwenden Sie zuerst cargo install sea-orm-cli \n + ru: -- Пожалуйста, сначала используйте cargo install sea-orm-cli \n + it: -- Si prega di utilizzare prima cargo install sea-orm-cli \n + pt: -- Por favor, use primeiro cargo install sea-orm-cli \n + ko: -- 먼저 cargo install sea-orm-cli를 사용하십시오. \n + no: -- Vennligst bruk først cargo install sea-orm-cli \n + is: -- Vinsamlegast notaðu fyrst cargo install sea-orm-cli \n + uk: -- Будь ласка, спочатку використовуйте cargo install sea-orm-cli \n + th: -- โปรดใช้ก่อน cargo install sea-orm-cli \n + el: -- Παρακαλώ χρησιμοποιήστε πρώτα cargo install sea-orm-cli \n + da: -- Brug venligst først cargo install sea-orm-cli \n +create_success_sea_orm__mysql_or_pgsql_fist_use: + en: -- Please modify the database connection string in .env and config/config.toml first \n -- Make sure the database exists, then run sea-orm migration to restore the database, and run the following SQL in the database to add the default data. \n -- After running, you can use the default username:zhangsan and password:123 to access /login. \n -- For more sea-orm-cli functionality, please check /migration/README.md. + zh_CN: -- 请先修改.env和config/config.toml中的数据库连接字符串 \n -- 确保数据库存在,然后运行sea-orm migration还原数据库, 在数据库中运以下SQL以添加默认数据。 \n -- 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login。 \n -- 更多sea-orm-cli功能,请查看/migration/README.md。 + zh_TW: -- 請先修改.env和config/config.toml中的數據庫連接字符串 \n -- 確保數據庫存在,然後運行sea-orm migration還原數據庫, 在數據庫中運行以下SQL以添加默認數據。 \n -- 運行後,您可以使用默認用戶名:zhangsan和密碼:123訪問/login。 \n -- 更多sea-orm-cli功能,請查看/migration/README.md。 + fr: -- Veuillez d'abord modifier la chaîne de connexion à la base de données dans .env et config/config.toml \n -- Assurez-vous que la base de données existe, puis exécutez la migration de sea-orm pour restaurer la base de données, et exécutez le SQL suivant dans la base de données pour ajouter les données par défaut. \n -- Après exécution, vous pouvez utiliser le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 pour accéder à /login. \n -- Pour plus de fonctionnalités de sea-orm-cli, veuillez consulter /migration/README.md. + ja: -- 最初に.envとconfig/config.tomlのデータベース接続文字列を変更してください \n -- データベースが存在することを確認し、次にsea-orm migrationを実行してデータベースを復元し、デフォルトのデータを追加するためにデータベースで以下のSQLを実行してください。 \n -- 実行後、デフォルトのユーザーネーム:zhangsanとパスワード:123を使用して/loginにアクセスできます。 \n -- その他のsea-orm-cliの機能については、/migration/README.mdをご覧ください。 + es: -- Por favor, modifique primero la cadena de conexión a la base de datos en .env y config/config.toml \n -- Asegúrese de que la base de datos exista, luego ejecute la migración de sea-orm para restaurar la base de datos, y ejecute el siguiente SQL en la base de datos para agregar los datos predeterminados. \n -- Después de ejecutar, puede usar el nombre de usuario predeterminado:zhangsan y la contraseña:123 para acceder a /login. \n -- Para más funcionalidad de sea-orm-cli, por favor consulte /migration/README.md. + de: -- Bitte ändern Sie zuerst die Datenbankverbindungszeichenkette in .env und config/config.toml \n -- Stellen Sie sicher, dass die Datenbank existiert, führen Sie dann die sea-orm-Migration aus, um die Datenbank wiederherzustellen, und führen Sie das folgende SQL in der Datenbank aus, um die Standarddaten hinzuzufügen. \n -- Nach dem Ausführen können Sie den Standardbenutzernamen:zhangsan und das Passwort:123 verwenden, um auf /login zuzugreifen. \n -- Weitere Funktionen von sea-orm-cli finden Sie unter /migration/README.md. + ru: -- Пожалуйста, сначала измените строку подключения к базе данных в .env и config/config.toml \n -- Убедитесь, что база данных существует, затем запустите миграцию sea-orm для восстановления базы данных и выполните следующий SQL в базе данных, чтобы добавить данные по умолчанию. \n -- После выполнения вы можете использовать имя пользователя по умолчанию:zhangsan и пароль:123 для доступа к /login. \n -- Для более подробной информации о функциях sea-orm-cli, пожалуйста, смотрите /migration/README.md. + it: -- Si prega di modificare prima la stringa di connessione al database in .env e config/config.toml \n -- Assicurarsi che il database esista, poi eseguire la migrazione di sea-orm per ripristinare il database, e eseguire il seguente SQL nel database per aggiungere i dati predefiniti. \n -- Dopo l'esecuzione, è possibile utilizzare il nome utente predefinito:zhangsan e la password:123 per accedere a /login. \n -- Per ulteriori funzionalità di sea-orm-cli, si prega di consultare /migration/README.md. + pt: -- Por favor, modifique primeiro a string de conexão do banco de dados em .env e config/config.toml \n -- Certifique-se de que o banco de dados existe, em seguida, execute a migração do sea-orm para restaurar o banco de dados, e execute oSQL seguinte no banco de dados para adicionar os dados padrão. \n -- Após a execução, você pode usar o nome de usuário padrão:zhangsan e a senha:123 para acessar /login. \n -- Para mais funcionalidades do sea-orm-cli, por favor, verifique /migration/README.md. + ko: -- 먼저 .env와 config/config.toml의 데이터베이스 연결 문자열을 수정해 주세요 \n -- 데이터베이스가 존재하는지 확인한 후 sea-orm migration을 실행하여 데이터베이스를 복원하고, 데이터베이스에서 아래 SQL을 실행하여 기본 데이터를 추가합니다. \n -- 실행 후, 기본 사용자 이름:zhangsan과 비밀번호:123을 사용하여 /login에 접속할 수 있습니다. \n -- sea-orm-cli의 추가 기능은 /migration/README.md를 확인해 주세요. + no: -- Vennligst endre databaseforbindelsesstrengen i .env og config/config.toml først \n -- Forsikre deg om at databasen eksisterer, kjør deretter sea-orm migration for å gjenopprette databasen, og kjør følgende SQL i databasen for å legge til standarddata. \n -- Etter kjøring, kan du bruke standard brukernavn:zhangsan og passord:123 for å få tilgang til /login. \n -- For mer sea-orm-cli-funksjonalitet, vennligst sjekk /migration/README.md. + is: -- Vinsamlegast breyttu gagnagrunnstengistrengjuna í .env og config/config.toml fyrst \n -- Gakktu úr skugga um að gagnagrunnurinn sé til, keyrðu svo sea-orm flytjingu til að endurheimta gagnagrunninn og keyrðu eftirfarandi SQL í gagnagrunninum til að bæta við sjálfgefnum gögnum. \n -- Eftir keyrslu, getur þú notað sjálfgefið notendanafn:zhangsan og lykilorð:123 til að fá aðgang að /login. \n -- Fyrir meira um sea-orm-cli virkni, vinsamlegast athugaðu /migration/README.md. + uk: -- Будь ласка, спочатку змініть рядок підключення до бази даних в .env та config/config.toml \n -- Переконайтеся, що база даних існує, потім запустіть міграцію sea-orm для відновлення бази даних та виконайте наступний SQL в базі даних, щоб додати дані за замовчуванням. \n -- Після запуску ви можете використовувати ім'я користувача за замовчуванням:zhangsan та пароль:123 для доступу до /login. \n -- Для отримання додаткових функцій sea-orm-cli, будь ласка, перевірте /migration/README.md. + th: -- ขอโทษที่ทำให้คุณสับสน ข้างล่างนี้คือคำอธิบายในภาษาไทย:คุณต้องเปลี่ยนสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml ก่อนตรวจสอบว่าฐานข้อมูลมีอยู่จริง จากนั้นรันการย้ายของ sea-orm เพื่อคืนค่าฐานข้อมูล และรัน SQL ด้านล่างในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้นหลังจากรัน คุณสามารถใช้ชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 เพื่อเข้าถึง /loginสำหรับฟังก์ชันเพิ่มเติมของ sea-orm-cli โปรดดูที่ /migration/README.md. + el: -- Παρακαλώ αλλάξτε πρώτα τη συμβολοσειρά σύνδεσης στη βάση δεδομένων στο .env και config/config.toml \n -- Βεβαιωθείτε ότι η βάση δεδομένων υπάρχει, στη συνέχεια εκτελέστε τη μετεγκατάσταση sea-orm για να επαναφέρετε τη βάση δεδομένων, και εκτελέστε το παρακάτω SQL στη βάση δεδομένων για να προσθέσετε τα προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να χρησιμοποιήσετε το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό:123 για να έχετε πρόσβαση στο /login. \n -- Για περισσότερες λειτουργίες του sea-orm-cli, παρακαλώ δείτε το /migration/README.md. + da: -- Ændre først forbindelsesstrengen til databasen i .env og config/config.toml \n -- Sørg for, at databasen eksisterer, kør derefter sea-orm-migrationen for at gendanne databasen, og kør den følgende SQL i databasen for at tilføje standarddataene. \n -- Efter kørsel, kan du bruge standard brugernavnet:zhangsan og adgangskoden:123 for at få adgang til /login. \n -- For mere funktionalitet fra sea-orm-cli, se venligst /migration/README.md. diff --git a/src/template/data/init_sql_sql.hbs b/src/template/data/init_sql_sql.hbs index 9367c2b..0032d68 100644 --- a/src/template/data/init_sql_sql.hbs +++ b/src/template/data/init_sql_sql.hbs @@ -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; diff --git a/src/template/src/services/user.hbs b/src/template/src/services/user.hbs index b632583..9ef7eff 100644 --- a/src/template/src/services/user.hbs +++ b/src/template/src/services/user.hbs @@ -1,3 +1,4 @@ +{{#if is_sqlx}} use crate::{ app_error::AppResult, db::DB, @@ -9,7 +10,19 @@ use crate::{ entities::user::User, utils::rand_utils, }; +{{/if}} {{#if is_sea_orm}} +use crate::{ + app_error::AppResult, + db::DB, + dtos::user::{ + UserAddRequest, UserDeleteRequest, UserLoginRequest, UserLoginResponse, UserResponse, + UserUpdateRequest, + }, + middleware::jwt::get_token, + entities::{prelude::User,user}, + utils::rand_utils, +}; use sea_orm::{EntityTrait, Set, ActiveModelTrait, QueryFilter, ColumnTrait}; {{/if}} use uuid::Uuid; @@ -127,7 +140,7 @@ pub async fn users() -> AppResult> { {{/if}} {{#if is_sea_orm}} pub async fn add_user(req: UserAddRequest) -> AppResult { - let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let db = DB.get().ok_or(anyhow::anyhow!("{{database_connection_failed}}"))?; let model =user::ActiveModel { id: Set(Uuid::new_v4().to_string()), username: Set(req.username.clone()), @@ -141,17 +154,17 @@ pub async fn add_user(req: UserAddRequest) -> AppResult { } pub async fn login(req: UserLoginRequest) -> AppResult { - let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let db = DB.get().ok_or(anyhow::anyhow!("{{database_connection_failed}}"))?; let user = User::find().filter(user::Column::Username.eq(req.username)).one(db).await?; if user.is_none() { - return Err(anyhow::anyhow!("用户不存在").into()); + return Err(anyhow::anyhow!("{{user_does_not_exist}}").into()); } let user = user.unwrap(); if rand_utils::verify_password(req.password, user.password) .await .is_err() { - return Err(anyhow::anyhow!("密码不正确").into()); + return Err(anyhow::anyhow!("{{incorrect_password}}").into()); } let (token, exp) = get_token(user.username.clone(), user.id.clone())?; let res = UserLoginResponse { @@ -164,11 +177,11 @@ pub async fn login(req: UserLoginRequest) -> AppResult { } pub async fn update_user(req: UserUpdateRequest) -> AppResult { - let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let db = DB.get().ok_or(anyhow::anyhow!("{{database_connection_failed}}"))?; let user = User::find_by_id(req.id).one(db).await?; if user.is_none() { - return Err(anyhow::anyhow!("用户不存在").into()); + return Err(anyhow::anyhow!("{{user_does_not_exist}}").into()); } let mut user: user::ActiveModel = user.unwrap().into(); @@ -184,13 +197,13 @@ pub async fn update_user(req: UserUpdateRequest) -> AppResult { } pub async fn delete_user(req: UserDeleteRequest) -> AppResult<()> { - let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let db = DB.get().ok_or(anyhow::anyhow!("{{database_connection_failed}}"))?; User::delete_by_id(req.id, ).exec(db).await?; Ok(()) } pub async fn users() -> AppResult> { - let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; + let db = DB.get().ok_or(anyhow::anyhow!("{{database_connection_failed}}"))?; let users = User::find().all(db).await?; let res = users .into_iter() diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index e58a416..6695414 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -38,10 +38,17 @@ pub fn create_project(project: Project) -> Result<()> { init_git(project_path)?; success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); - if config.db_conn_type == DbConnectionType::Sqlx { - success( - t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), - ); + if config.db_conn_type == DbConnectionType::Sqlx||config.db_conn_type == DbConnectionType::SeaOrm{ + if config.db_conn_type == DbConnectionType::Sqlx { + success( + t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), + ); + } + if config.db_conn_type == DbConnectionType::SeaOrm { + success( + t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), + ); + } if config.db_type == DbType::Sqlite { success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); } else { @@ -115,7 +122,9 @@ fn write_project_file( "yes":t!("yes"), "cancel":t!("cancel"), "operation":t!("operation"), + "create_success_sea_orm__mysql_or_pgsql_install_sea_orm":t!("create_success_sea_orm__mysql_or_pgsql_install_sea_orm"), "create_success_mysql_or_pgsql_fist_use":t!("create_success_mysql_or_pgsql_fist_use").replace(r"\n", "\n"), + "create_success_sea_orm__mysql_or_pgsql_fist_use":t!("create_success_sea_orm__mysql_or_pgsql_fist_use").replace(r"\n", "\n"), }); if need_db_conn { // Add sqlx dependencies @@ -143,19 +152,19 @@ fn write_project_file( if is_mysql { dependencies["sea-orm"] = json!({ "version": "0", - "features": ["sqlx-mysql"] + "features": ["runtime-tokio-native-tls","sqlx-mysql"] }); } if is_postgres { dependencies["sea-orm"] = json!({ "version": "0", - "features": ["sqlx-postgres"] + "features": ["runtime-tokio-native-tls","sqlx-postgres"] }); } if is_sqlite { dependencies["sea-orm"] = json!({ "version": "0", - "features": ["sqlx-sqlite"] + "features": ["runtime-tokio-native-tls","sqlx-sqlite"] }); } } @@ -399,7 +408,7 @@ fn write_project_file( init_sql_file.write_all(init_sql_rendered.as_bytes())?; } //migrations - let migrations_path = project_path.join("migrations"); + let migrations_path: std::path::PathBuf = project_path.join("migrations"); std::fs::create_dir_all(&migrations_path)?; //migrations/2021-10-20-000000_create_users_table/up.sql let up_sql_bytes = include_bytes!("../template/migrations/20231001143156_users.sql"); @@ -444,11 +453,28 @@ fn write_project_file( migration_readme_file.write_all(migration_readme_bytes)?; if is_sqlite { + //data + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; //data/demo.db let demo_db_bytes = include_bytes!("../template/data/demo_sea_orm.db"); - let mut demo_db_file = File::create(project_path.join("/data/demo.db"))?; + let mut demo_db_file = File::create(data_path.join("demo.db"))?; demo_db_file.write_all(demo_db_bytes)?; } + else { + let data_path = project_path.join("data"); + std::fs::create_dir_all(&data_path)?; + //data/init_sql.sql + let init_sql_templte = include_str!("../template/data/init_sql_sql.hbs"); + let init_sql_rendered = handlebars.render_template(init_sql_templte, &data)?; + let mut init_sql_file = File::create(data_path.join("init_sql.sql"))?; + init_sql_file.write_all(init_sql_rendered.as_bytes())?; + } + //.env + let env_template = include_str!("../template/.env.hbs"); + let env_rendered = handlebars.render_template(env_template, &data)?; + let mut env_file = File::create(project_path.join(".env"))?; + env_file.write_all(env_rendered.as_bytes())?; } } Ok(()) From 62ee128a96f985338c29f1d8949ea49d665f3176 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 15 Oct 2023 11:47:04 +0800 Subject: [PATCH 5/6] update version --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0a24801..9a681c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.8" +version = "0.1.9" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 4ab71af..07ad112 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.8" +version = "0.1.9" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] From a2252c9ed7a0ddd9f28fffe90731b066378b811f Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 15 Oct 2023 11:51:07 +0800 Subject: [PATCH 6/6] update readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 35eb877..0d0f0c1 100644 --- a/README.md +++ b/README.md @@ -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|