Skip to content

Commit

Permalink
Merge pull request #6 from salvo-rs/db
Browse files Browse the repository at this point in the history
add rbatis template
  • Loading branch information
fankaiLiu authored Oct 27, 2023
2 parents c4fe3c4 + c9f0a0a commit 923ae66
Show file tree
Hide file tree
Showing 14 changed files with 421 additions and 140 deletions.
18 changes: 18 additions & 0 deletions locales/code_comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -544,3 +544,21 @@ create_success_diesel__mysql_or_pgsql_fist_use:
th: -- ขอโทษที่ทำให้คุณสับสน ข้างล่างนี้คือคำอธิบายในภาษาไทย:คุณต้องเปลี่ยนสตริงการเชื่อมต่อฐานข้อมูลใน .env และ config/config.toml ก่อนตรวจสอบว่าฐานข้อมูลมีอยู่จริง จากนั้นรันการย้ายของ diesel เพื่อคืนค่าฐานข้อมูล และรัน SQL ด้านล่างในฐานข้อมูลเพื่อเพิ่มข้อมูลเริ่มต้นหลังจากรัน คุณสามารถใช้ชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 เพื่อเข้าถึง /loginสำหรับฟังก์ชันเพิ่มเติมของ diesel-cli โปรดดูที่ /migration/README.md.
el: -- Παρακαλώ αλλάξτε πρώτα τη συμβολοσειρά σύνδεσης στη βάση δεδομένων στο .env και config/config.toml \n -- Βεβαιωθείτε ότι η βάση δεδομένων υπάρχει, στη συνέχεια εκτελέστε τη μετεγκατάσταση diesel για να επαναφέρετε τη βάση δεδομένων, και εκτελέστε το παρακάτω SQL στη βάση δεδομένων για να προσθέσετε τα προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να χρησιμοποιήσετε το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό:123 για να έχετε πρόσβαση στο /login. \n -- Για περισσότερες λειτουργίες του diesel-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 diesel migration run 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 diesel-cli, se venligst /migration/README.md.
create_success_rbatis:
en: 🎯 Reminder:Please modify the database connection string in the /config/config.toml file before running it
zh_CN: 🎯 提醒:在运行之前,请在 /config/config.toml 文件中修改数据库连接字符串
zh_TW: 🎯 提醒:在運行之前,請在 /config/config.toml 文件中修改數據庫連接字符串
fr: 🎯 Rappel:Veuillez modifier la chaîne de connexion à la base de données dans le fichier /config/config.toml avant de l'exécuter
ja: 🎯 リマインダー:実行する前に、/config/config.toml ファイル内のデータベース接続文字列を変更してください
es: 🎯 Recordatorio:Por favor modifique la cadena de conexión de la base de datos en el archivo /config/config.toml antes de ejecutarlo
de: 🎯 Erinnerung:Bitte ändern Sie die Datenbankverbindungszeichenfolge in der /config/config.toml-Datei, bevor Sie sie ausführen
ru: 🎯 Напоминание:Перед запуском измените строку подключения к базе данных в файле /config/config.toml
it: 🎯 Promemoria:Modificare la stringa di connessione al database nel file /config/config.toml prima di eseguirlo
pt: 🎯 Lembrete:Por favor, modifique a string de conexão do banco de dados no arquivo /config/config.toml antes de executá-lo
ko: 🎯 알림:실행하기 전에 /config/config.toml 파일에서 데이터베이스 연결 문자열을 수정하세요
no: 🎯 Påminnelse:Vennligst endre databaseforbindelsesstrengen i /config/config.toml-filen før du kjører den
is: 🎯 Áminning:Vinsamlegast breyttu gagnagrunnstengistrenginu í /config/config.toml skránni áður en þú keyrir það
uk: 🎯 Нагадування:Будь ласка, змініть рядок підключення до бази даних у файлі /config/config.toml перед його запуском
th: 🎯 แจ้งเตือน:โปรดแก้ไขสตริงการเชื่อมต่อฐานข้อมูลในไฟล์ /config/config.toml ก่อนที่จะทำการรัน
el: 🎯 Υπενθύμιση:Παρακαλώ τροποποιήστε τη συμβολοσειρά σύνδεσης βάσης δεδομένων στο αρχείο /config/config.toml πριν το τρέξετε
da: 🎯 Påmindelse:Ændr venligst databaseforbindelsesstrengen i /config/config.toml-filen, før du kører den
17 changes: 16 additions & 1 deletion src/template/config/config.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,22 @@ database_url="file:data/test.db"
{{#if is_mysql}}
database_url="mysql://root:[email protected]:3306/diesel_example"
{{/if}}
{{/if}}{{/if}}
{{/if}}
{{#if is_rbatis}}
{{#if is_postgres}}
database_url=postgres://liufankai:1@localhost/rbatis_example
{{/if}}
{{#if is_sqlite}}
database_url="data/rbatis_sqlite.db"
{{/if}}
{{#if is_mysql}}
database_url="mysql://root:[email protected]:3306/rbatis_example"
{{/if}}
{{#if is_mssql}}
database_url="mssql://SA:TestPass!123456@localhost:1433/rbatis_example"
{{/if}}
{{/if}}
{{/if}}
[jwt]
jwt_secret = "secret"
jwt_exp = 6000
Expand Down
15 changes: 15 additions & 0 deletions src/template/data/table_mssql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(511) NOT NULL
);
BEGIN;
MERGE INTO users AS target
USING (VALUES ('cdd0e080-5bb1-4442-b6f7-2ba60dbd0555', 'zhangsan', '$argon2id$v=19$m=19456,t=2,p=1$rcosL5pOPdA2c7i4ZuLA4Q$s0JGh78UzMmu1qZMpVUA3b8kWYLXcZhw7uBfwhYDJ4A'))
AS source (id, username, password)
ON (target.id = source.id)
WHEN NOT MATCHED THEN
INSERT (id, username, password)
VALUES (source.id, source.username, source.password);
COMMIT;
9 changes: 9 additions & 0 deletions src/template/data/table_mysql.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(511) NOT NULL
);
BEGIN;
INSERT IGNORE INTO "users" ("id", "username", "password") VALUES ('cdd0e080-5bb1-4442-b6f7-2ba60dbd0555', 'zhangsan', '$argon2id$v=19$m=19456,t=2,p=1$rcosL5pOPdA2c7i4ZuLA4Q$s0JGh78UzMmu1qZMpVUA3b8kWYLXcZhw7uBfwhYDJ4A');
COMMIT;
9 changes: 9 additions & 0 deletions src/template/data/table_postgres.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(511) NOT NULL
);
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') ON CONFLICT DO NOTHING;
COMMIT;
9 changes: 9 additions & 0 deletions src/template/data/table_sqlite.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS users
(
id TEXT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(511) NOT NULL
);
BEGIN;
INSERT OR IGNORE INTO "users" ("id", "username", "password") VALUES ('cdd0e080-5bb1-4442-b6f7-2ba60dbd0555', 'zhangsan', '$argon2id$v=19$m=19456,t=2,p=1$rcosL5pOPdA2c7i4ZuLA4Q$s0JGh78UzMmu1qZMpVUA3b8kWYLXcZhw7uBfwhYDJ4A');
COMMIT;
4 changes: 4 additions & 0 deletions src/template/src/app_error.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ pub enum AppError {
#[error("diesel::result::Error:`{0}`")]
DieselErr(#[from] diesel::result::Error),
{{/if}}
{{#if is_rbatis}}
#[error("rbatis::Error:`{0}`")]
RbatisErr(#[from] rbatis::Error),
{{/if}}
}

pub type AppResult<T> = Result<T, AppError>;
Expand Down
45 changes: 44 additions & 1 deletion src/template/src/db.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,47 @@ pub async fn init_db_conn() {
})
.await;
}
{{/if}}
{{/if}}

{{#if is_rbatis}}
use tokio::sync::OnceCell;
use rbatis::rbatis::RBatis;
pub static DB: OnceCell<RBatis> = OnceCell::const_new();

pub async fn init_db_conn() {
DB.get_or_init(|| async {
let rb = RBatis::new();

{{#if is_postgres}}
// PostgreSQL
rb.init(rbdc_pg::driver::PgDriver {}, &CFG.database.database_url).unwrap();
{{/if}}
{{#if is_mysql}}
// MySQL
rb.init(rbdc_mysql::driver::MysqlDriver {}, &CFG.database.database_url).unwrap();
{{/if}}
{{#if is_sqlite}}
// SQLite
rb.init(rbdc_sqlite::driver::SqliteDriver {}, &CFG.database.database_url).unwrap();
{{/if}}
{{#if is_mssql}}
// MS SQL
rb.init(rbdc_mssql::driver::MssqlDriver {}, &CFG.database.database_url).unwrap();
{{/if}}

let sql_file = match rb.driver_type().unwrap() {
"sqlite" => "./data/table_sqlite.sql",
"postgres" => "./data/table_postgres.sql",
"mysql" => "./data/table_mysql.sql",
"mssql" => "./data/table_mssql.sql",
_ => { "" }
};
if sql_file != "" {
let sql = std::fs::read_to_string(sql_file).unwrap();
let _ = rb.exec(&sql, vec![]).await;
}
return rb;
})
.await;
}
{{/if}}
3 changes: 3 additions & 0 deletions src/template/src/entities/mod.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ pub mod prelude;

pub mod user;
{{/if}}
{{#if is_rbatis}}
pub mod user;
{{/if}}
11 changes: 11 additions & 0 deletions src/template/src/entities/user.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,15 @@ pub struct Model {
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
{{/if}}
{{#if is_rbatis}}
use rbatis::crud;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Users{
pub id: String,
pub username: String,
pub password: String,
}

crud!(Users {});
{{/if}}
9 changes: 9 additions & 0 deletions src/template/src/main_template.hbs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{{#if is_sea_orm_or_sqlx}}
use crate::db::init_db_conn;
{{/if}}
{{#if is_rbatis}}
use crate::db::init_db_conn;
{{/if}}
use crate::middleware::handle_404::handle_404;
use crate::routers::router;
use config::{CERT_KEY, CFG};
Expand Down Expand Up @@ -28,6 +31,9 @@ mod entities;
mod models;
mod schema;
{{/if}}
{{#if is_rbatis}}
mod entities;
{{/if}}
mod middleware;
mod routers;

Expand All @@ -38,6 +44,9 @@ async fn main() {
{{#if is_sea_orm_or_sqlx}}
init_db_conn().await;
{{/if}}
{{#if is_rbatis}}
init_db_conn().await;
{{/if}}
let (tx, rx) = oneshot::channel();
let router = router();
let service: Service = router.into();
Expand Down
80 changes: 80 additions & 0 deletions src/template/src/services/user.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,84 @@ pub async fn users() -> AppResult<Vec<UserResponse>> {

Ok(res)
}
{{/if}}
{{#if is_rbatis}}
use uuid::Uuid;

use crate::{
app_error::AppResult,
dtos::user::{
UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest,
},
middleware::jwt::get_token,
utils::rand_utils, db::DB, entities::user::Users,
};

pub async fn add_user(req: UserAddRequest) -> AppResult<UserResponse> {
let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?;
let user = Users {
id: Uuid::new_v4().to_string(),
username: req.username.clone(),
password: rand_utils::hash_password(req.password).await?,
};
Users::insert(db,&user).await?;

Ok(UserResponse {
id: user.id,
username: user.username,
})
}

pub async fn login(req: UserLoginRequest) -> AppResult<UserLoginResponse> {
let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?;
let user = Users::select_by_column(db,"username",&req.username).await?;
if user.len()==0 {
return Err(anyhow::anyhow!("用户不存在").into());
}
if rand_utils::verify_password(req.password, user[0].password.clone()).await.is_err() {
return Err(anyhow::anyhow!("密码不正确").into());
}
let (token, exp) = get_token(user[0].username.clone(), user[0].id.clone())?;
let res = UserLoginResponse {
id: user[0].id.clone(),
username: user[0].username.clone(),
token,
exp,
};
Ok(res)
}

pub async fn update_user(req: UserUpdateRequest) -> AppResult<UserResponse> {
let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?;
let user = Users::select_by_column(db,"id",&req.id).await?;
if user.len()==0 {
return Err(anyhow::anyhow!("用户不存在").into());
}
Users::update_by_column(db,&user[0],"id").await?;

Ok(UserResponse {
id: user[0].id.clone(),
username: user[0].username.clone(),
})
}

pub async fn delete_user(req: String) -> AppResult<()> {
let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?;
Users::delete_by_column(db, "id",&req).await?;
Ok(())
}

pub async fn users() -> AppResult<Vec<UserResponse>> {
let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?;
let users=Users::select_all(db).await?;

let res = users
.into_iter()
.map(|user| UserResponse {
id: user.id,
username: user.username,
})
.collect::<Vec<_>>();
Ok(res)
}
{{/if}}
Loading

0 comments on commit 923ae66

Please sign in to comment.