Skip to content

Commit

Permalink
add sea_orm support
Browse files Browse the repository at this point in the history
  • Loading branch information
fankaiLiu committed Oct 14, 2023
1 parent 5e3f926 commit 28f4620
Show file tree
Hide file tree
Showing 6 changed files with 145 additions and 14 deletions.
9 changes: 9 additions & 0 deletions src/template/src/entities/mod.hbs
Original file line number Diff line number Diff line change
@@ -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}}
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;
23 changes: 23 additions & 0 deletions src/template/src/entities/user.hbs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{#if is_sqlx}}
use serde::Serialize;
use sqlx::FromRow;

Expand All @@ -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}}
80 changes: 80 additions & 0 deletions src/template/src/services/user.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -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<UserResponse> {
Expand Down Expand Up @@ -121,4 +124,81 @@ pub async fn users() -> AppResult<Vec<UserResponse>> {
.collect::<Vec<_>>();
Ok(res)
}
{{/if}}
{{#if is_sea_orm}}
pub async fn add_user(req: UserAddRequest) -> AppResult<UserResponse> {
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<UserLoginResponse> {
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<UserResponse> {
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<Vec<UserResponse>> {
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::<Vec<_>>();
Ok(res)
}
{{/if}}
30 changes: 23 additions & 7 deletions src/utils/create_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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
Expand All @@ -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(())
Expand Down
14 changes: 7 additions & 7 deletions src/utils/get_selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ pub fn get_user_selected() -> Result<Option<UserSelected>> {
};
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",
Expand All @@ -48,10 +48,10 @@ pub fn get_user_selected() -> Result<Option<UserSelected>> {

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 {
Expand Down Expand Up @@ -99,8 +99,8 @@ pub enum DbType {
#[derive(Debug, PartialEq, Clone)]
pub enum DbConnectionType {
Sqlx,
Diesel,
SeaOrm,
Rbatis,
// Diesel,
// Rbatis,
Nothing,
}

0 comments on commit 28f4620

Please sign in to comment.