Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 9cebf0b

Browse filesBrowse files
committed
Merge remote-tracking branch 'origin/master'
# Conflicts: # src/executor.rs
2 parents 66d3c68 + 2f14ca7 commit 9cebf0b
Copy full SHA for 9cebf0b

File tree

Expand file treeCollapse file tree

10 files changed

+81
-108
lines changed
Filter options
Expand file treeCollapse file tree

10 files changed

+81
-108
lines changed

‎Cargo.toml

Copy file name to clipboardExpand all lines: Cargo.toml
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ members = [
88

99
[package]
1010
name = "rbatis"
11-
version = "4.5.44"
11+
version = "4.5.46"
1212
description = "The Rust SQL Toolkit and ORM Library. An async, pure Rust SQL crate featuring compile-time Dynamic SQL"
1313
readme = "Readme.md"
1414
authors = ["ce <zhuxiujia@qq.com>"]

‎Readme.md

Copy file name to clipboardExpand all lines: Readme.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ You are welcome to submit the merge, and make sure that any functionality you ad
362362
# Ask AI For Help(AI帮助)
363363

364364
<a href="https://chatglm.cn/main/gdetail/6604ffe818d17f1aaa8d9cf8">
365-
<img style="width: 200px;height: 300px;" width="200" height="300" src="ai.jpg" alt="" />
365+
<img style="width: 200px;height: 290px;" width="200" height="290" src="ai.jpg" alt="" />
366366
</a>
367367

368368

‎example/src/transaction.rs

Copy file name to clipboardExpand all lines: example/src/transaction.rs
+28-21Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,11 @@ pub async fn main() -> Result<(), Error> {
3333
// rb.init(rbdc_mysql::driver::MysqlDriver {}, "mysql://root:123456@localhost:3306/test").unwrap();
3434
// rb.init(rbdc_pg::driver::PgDriver {}, "postgres://postgres:123456@localhost:5432/postgres").unwrap();
3535
// rb.init(rbdc_mssql::driver::MssqlDriver {}, "mssql://jdbc:sqlserver://localhost:1433;User=SA;Password={TestPass!123456};Database=master;").unwrap();
36-
rb.init(rbdc_sqlite::driver::SqliteDriver {}, "sqlite://target/sqlite.db").unwrap();
36+
rb.init(
37+
rbdc_sqlite::driver::SqliteDriver {},
38+
"sqlite://target/sqlite.db",
39+
)
40+
.unwrap();
3741
// table sync done
3842
fast_log::logger().set_level(LevelFilter::Off);
3943
_ = RBatis::sync(
@@ -55,7 +59,7 @@ pub async fn main() -> Result<(), Error> {
5559
},
5660
"activity",
5761
)
58-
.await;
62+
.await;
5963
fast_log::logger().set_level(LevelFilter::Debug);
6064

6165
//clear data
@@ -68,40 +72,43 @@ pub async fn main() -> Result<(), Error> {
6872
// will do commit
6973
let conn = rb.acquire().await?;
7074
let tx = conn.begin().await?;
71-
transaction(tx, false)
72-
.await?;
75+
transaction(tx, false).await?;
7376

7477
Ok(())
7578
}
7679

7780
async fn transaction(tx: RBatisTxExecutor, forget_commit: bool) -> Result<(), Error> {
7881
let tx = tx.defer_async(|tx| async move {
7982
if tx.done() {
80-
log::info!("transaction [{}] complete.",tx.tx_id);
83+
log::info!("transaction [{}] complete.", tx.tx_id);
8184
} else {
8285
let r = tx.rollback().await;
8386
if let Err(e) = r {
84-
log::error!("transaction [{}] rollback fail={}" ,tx.tx_id, e);
87+
log::error!("transaction [{}] rollback fail={}", tx.tx_id, e);
8588
} else {
8689
log::info!("transaction [{}] rollback", tx.tx_id);
8790
}
8891
}
8992
});
90-
log::info!("transaction [{}] start", tx.tx.as_ref().unwrap().tx_id);
91-
let _ = Activity::insert(&tx, &Activity {
92-
id: Some("3".into()),
93-
name: Some("3".into()),
94-
pc_link: Some("3".into()),
95-
h5_link: Some("3".into()),
96-
pc_banner_img: None,
97-
h5_banner_img: None,
98-
sort: None,
99-
status: Some(3),
100-
remark: Some("3".into()),
101-
create_time: Some(DateTime::now()),
102-
version: Some(1),
103-
delete_flag: Some(1),
104-
}).await;
93+
log::info!("transaction [{}] start", tx.tx_id());
94+
let _ = Activity::insert(
95+
&tx,
96+
&Activity {
97+
id: Some("3".into()),
98+
name: Some("3".into()),
99+
pc_link: Some("3".into()),
100+
h5_link: Some("3".into()),
101+
pc_banner_img: None,
102+
h5_banner_img: None,
103+
sort: None,
104+
status: Some(3),
105+
remark: Some("3".into()),
106+
create_time: Some(DateTime::now()),
107+
version: Some(1),
108+
delete_flag: Some(1),
109+
},
110+
)
111+
.await;
105112
//if not commit or rollback,tx.done = false,
106113
if !forget_commit {
107114
tx.commit().await?;

‎src/executor.rs

Copy file name to clipboardExpand all lines: src/executor.rs
+37-69Lines changed: 37 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,14 @@ use std::fmt::{Debug, Formatter};
1414
use std::sync::atomic::{AtomicBool, Ordering};
1515
use std::sync::Arc;
1616

17-
/// the rbatis's Executor. this trait impl with structs = RBatis,RBatisConnExecutor,RBatisTxExecutor,RBatisTxExecutorGuard
17+
/// the RBatis Executor. this trait impl with structs = RBatis,RBatisConnExecutor,RBatisTxExecutor,RBatisTxExecutorGuard
1818
pub trait Executor: RBatisRef + Send + Sync {
19-
/// executor id
2019
fn id(&self) -> i64;
21-
22-
/// Executor type name
2320
fn name(&self) -> &str {
2421
std::any::type_name::<Self>()
2522
}
26-
/// exec sql to get ExecResult
2723
fn exec(&self, sql: &str, args: Vec<Value>) -> BoxFuture<'_, Result<ExecResult, Error>>;
28-
29-
/// query sql to get Value
3024
fn query(&self, sql: &str, args: Vec<Value>) -> BoxFuture<'_, Result<Value, Error>>;
31-
32-
/// to any trait
3325
fn as_any(&self) -> &dyn Any
3426
where
3527
Self: Sized,
@@ -205,7 +197,6 @@ impl RBatisRef for RBatisConnExecutor {
205197
}
206198

207199
impl RBatisConnExecutor {
208-
///run begin
209200
pub fn begin(self) -> BoxFuture<'static, Result<RBatisTxExecutor, Error>> {
210201
Box::pin(async move {
211202
let mut conn = self.conn.into_inner();
@@ -218,17 +209,22 @@ impl RBatisConnExecutor {
218209
})
219210
}
220211

221-
/// rollback tx
222212
pub fn rollback(&self) -> BoxFuture<'_, Result<(), Error>> {
223213
Box::pin(async { Ok(self.conn.lock().await.rollback().await?) })
224214
}
225215

226-
/// commit tx
227216
pub fn commit(&self) -> BoxFuture<'_, Result<(), Error>> {
228217
Box::pin(async { Ok(self.conn.lock().await.commit().await?) })
229218
}
230219
}
231220

221+
/// `RBatisTxExecutor` is a type that represents an executor for transactional operations in RBatis.
222+
///
223+
/// # Type Description
224+
///
225+
/// The `RBatisTxExecutor` is responsible for executing SQL statements within the context of a transaction.
226+
/// It provides methods to execute queries, updates, and other SQL operations, ensuring that all operations
227+
/// are part of the same transactional context.
232228
#[derive(Clone)]
233229
pub struct RBatisTxExecutor {
234230
pub tx_id: i64,
@@ -420,7 +416,7 @@ impl RBatisRef for RBatisTxExecutor {
420416
}
421417

422418
impl RBatisTxExecutor {
423-
pub fn take_conn(self) -> Option<Box<dyn Connection>> {
419+
pub fn take_connection(self) -> Option<Box<dyn Connection>> {
424420
match Arc::into_inner(self.conn) {
425421
None => None,
426422
Some(v) => {
@@ -431,9 +427,17 @@ impl RBatisTxExecutor {
431427
}
432428
}
433429

430+
/// `RBatisTxExecutorGuard` is a guard object that manages transactions for RBatis.
431+
///
432+
/// # Type Description
433+
///
434+
/// The `RBatisTxExecutorGuard` implements the `Drop` trait to ensure that transactions are
435+
/// automatically committed or rolled back when the guard goes out of scope. It encapsulates
436+
/// the transaction executor and provides a set of methods to manipulate database transactions.
437+
#[derive(Clone)]
434438
pub struct RBatisTxExecutorGuard {
435-
pub tx: Option<RBatisTxExecutor>,
436-
pub callback: Box<dyn FnMut(RBatisTxExecutor) + Send + Sync>,
439+
pub tx: RBatisTxExecutor,
440+
pub callback: Arc<dyn FnMut(RBatisTxExecutor) + Send + Sync>,
437441
}
438442

439443
impl Debug for RBatisTxExecutorGuard {
@@ -445,55 +449,29 @@ impl Debug for RBatisTxExecutorGuard {
445449
}
446450

447451
impl RBatisTxExecutorGuard {
448-
449-
///run begin
450-
pub async fn begin(&mut self) -> crate::Result<()> {
451-
let v = self
452-
.tx
453-
.take()
454-
.ok_or_else(|| Error::from("[rb] tx is committed"))?
455-
.begin()
456-
.await?;
457-
self.tx = Some(v);
458-
Ok(())
452+
pub fn tx_id(&self) -> i64 {
453+
self.tx.tx_id
459454
}
460455

461-
///commit tx
462456
pub async fn commit(&self) -> crate::Result<()> {
463-
let tx = self
464-
.tx
465-
.as_ref()
466-
.ok_or_else(|| Error::from("[rb] tx is committed"))?;
467-
tx.commit().await?;
457+
self.tx.commit().await?;
468458
Ok(())
469459
}
470460

471-
///rollback tx
472461
pub async fn rollback(&self) -> crate::Result<()> {
473-
let tx = self
474-
.tx
475-
.as_ref()
476-
.ok_or_else(|| Error::from("[rb] tx is committed"))?;
477-
tx.rollback().await?;
462+
self.tx.rollback().await?;
478463
Ok(())
479464
}
480465

481-
pub fn take_conn(mut self) -> Option<Box<dyn Connection>> {
482-
match self.tx.take() {
483-
None => None,
484-
Some(s) => s.take_conn(),
485-
}
466+
pub fn take_connection(self) -> Option<Box<dyn Connection>> {
467+
self.tx.clone().take_connection()
486468
}
487469

488470
pub async fn query_decode<T>(&self, sql: &str, args: Vec<Value>) -> Result<T, Error>
489471
where
490472
T: DeserializeOwned,
491473
{
492-
let tx = self
493-
.tx
494-
.as_ref()
495-
.ok_or_else(|| Error::from("[rb] tx is committed"))?;
496-
tx.query_decode(sql, args).await
474+
self.tx.query_decode(sql, args).await
497475
}
498476
}
499477

@@ -516,8 +494,8 @@ impl RBatisTxExecutor {
516494
F: Future<Output = ()> + Send + 'static,
517495
{
518496
RBatisTxExecutorGuard {
519-
tx: Some(self.clone()),
520-
callback: Box::new(move |arg| {
497+
tx: self.clone(),
498+
callback: Arc::new(move |arg| {
521499
let future = callback(arg);
522500
rbdc::rt::spawn(future);
523501
}),
@@ -527,44 +505,34 @@ impl RBatisTxExecutor {
527505

528506
impl Drop for RBatisTxExecutorGuard {
529507
fn drop(&mut self) {
530-
if let Some(tx) = self.tx.take() {
531-
(self.callback)(tx);
508+
match Arc::get_mut(&mut self.callback) {
509+
None => {}
510+
Some(callback) => {
511+
callback(self.tx.clone());
512+
}
532513
}
533514
}
534515
}
535516

536517
impl RBatisRef for RBatisTxExecutorGuard {
537518
fn rb_ref(&self) -> &RBatis {
538-
self.tx.as_ref().expect("tx is empty").rb_ref()
519+
self.tx.rb_ref()
539520
}
540521
}
541522

542523
impl Executor for RBatisTxExecutorGuard {
543524
fn id(&self) -> i64 {
544-
match &self.tx {
545-
None => -1,
546-
Some(v) => v.id(),
547-
}
525+
self.tx.id()
548526
}
549527

550528
fn exec(&self, sql: &str, args: Vec<Value>) -> BoxFuture<'_, Result<ExecResult, Error>> {
551529
let sql = sql.to_string();
552-
Box::pin(async move {
553-
match self.tx.as_ref() {
554-
None => Err(Error::from("the tx is done!")),
555-
Some(tx) => tx.exec(&sql, args).await,
556-
}
557-
})
530+
Box::pin(async move { self.tx.exec(&sql, args).await })
558531
}
559532

560533
fn query(&self, sql: &str, args: Vec<Value>) -> BoxFuture<'_, Result<Value, Error>> {
561534
let sql = sql.to_string();
562-
Box::pin(async move {
563-
match self.tx.as_ref() {
564-
None => Err(Error::from("the tx is done!")),
565-
Some(tx) => tx.query(&sql, args).await,
566-
}
567-
})
535+
Box::pin(async move { self.tx.query(&sql, args).await })
568536
}
569537
}
570538

‎src/plugin/intercept_page.rs

Copy file name to clipboardExpand all lines: src/plugin/intercept_page.rs
+5-1Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ use std::sync::Arc;
99

1010
/// make count sql remove `limit`
1111
/// make select sql append limit ${page_no},${page_size}
12-
/// notice: the sql must be starts with 'select '
12+
/// notice:
13+
/// ```log
14+
/// sql must be starts with 'select ' and ' from '
15+
/// this PageIntercept only support sqlite,mysql,mssql,postgres...
16+
///```
1317
/// how to use?
1418
/// ```rust
1519
///

‎src/plugin/table_sync/mssql_mapper.rs

Copy file name to clipboardExpand all lines: src/plugin/table_sync/mssql_mapper.rs
-3Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,6 @@ impl ColumnMapper for MssqlTableMapper {
1919
Value::F64(_) => "FLOAT".to_string(),
2020
Value::String(v) => {
2121
if v != "" {
22-
if v.eq("id") {
23-
return "NVARCHAR(MAX)".to_string();
24-
}
2522
v.to_string()
2623
} else {
2724
"NVARCHAR(MAX)".to_string()

‎src/plugin/table_sync/mysql_mapper.rs

Copy file name to clipboardExpand all lines: src/plugin/table_sync/mysql_mapper.rs
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ impl ColumnMapper for MysqlTableMapper {
1313
fn driver_type(&self) -> String {
1414
"mysql".to_string()
1515
}
16-
fn get_column_type(&self, _column: &str, v: &Value) -> String {
16+
fn get_column_type(&self, column: &str, v: &Value) -> String {
1717
match v {
1818
Value::Null => "NULL".to_string(),
1919
Value::Bool(_) => "TINYINT".to_string(),
@@ -25,11 +25,11 @@ impl ColumnMapper for MysqlTableMapper {
2525
Value::F64(_) => "DOUBLE".to_string(),
2626
Value::String(v) => {
2727
if v != "" {
28-
if v.eq("id") {
29-
return "TEXT".to_string();
30-
}
3128
v.to_string()
3229
} else {
30+
if column.eq("id") || column.ends_with("_id") || column.starts_with("id_") {
31+
return "VARCHAR(50)".to_string();
32+
}
3333
"TEXT".to_string()
3434
}
3535
}

‎src/plugin/table_sync/pg_mapper.rs

Copy file name to clipboardExpand all lines: src/plugin/table_sync/pg_mapper.rs
+4-4Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ impl ColumnMapper for PGTableMapper {
66
fn driver_type(&self) -> String {
77
"postgres".to_string()
88
}
9-
fn get_column_type(&self, _column: &str, v: &Value) -> String {
9+
fn get_column_type(&self, column: &str, v: &Value) -> String {
1010
match v {
1111
Value::Null => "NULL".to_string(),
1212
Value::Bool(_) => "BOOLEAN".to_string(),
@@ -18,11 +18,11 @@ impl ColumnMapper for PGTableMapper {
1818
Value::F64(_) => "DOUBLE PRECISION".to_string(),
1919
Value::String(v) => {
2020
if v != "" {
21-
if v.eq("id") {
22-
return "TEXT".to_string();
23-
}
2421
v.to_string()
2522
} else {
23+
if column.eq("id") || column.ends_with("_id") || column.starts_with("id_") {
24+
return "VARCHAR(50)".to_string();
25+
}
2626
"TEXT".to_string()
2727
}
2828
}

‎src/plugin/table_sync/sqlite_mapper.rs

Copy file name to clipboardExpand all lines: src/plugin/table_sync/sqlite_mapper.rs
-3Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,6 @@ impl ColumnMapper for SqliteTableMapper {
2020
Value::F64(_) => "DOUBLE".to_string(),
2121
Value::String(v) => {
2222
if v != "" {
23-
if v.eq("id") {
24-
return "TEXT".to_string();
25-
}
2623
v.to_string()
2724
} else {
2825
"TEXT".to_string()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.