Skip to content

Add proxy transaction impl #2573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2025

Conversation

logicin
Copy link
Contributor

@logicin logicin commented Apr 20, 2025

PR Info

  • Closes
  • Dependencies:
  • Dependents:

New Features

Bug Fixes

Breaking Changes

Changes

  • [√ ] Support ProxyDatabase in DatabaseTransaction impl.

@oulover
Copy link

oulover commented Apr 20, 2025

//! Proxy connection example.



mod entity;
mod system_users;

use std::{
    collections::BTreeMap,
    sync::{Arc, Mutex},
};
use std::error::Error;
use std::future::Future;
use std::pin::Pin;
use gluesql::{memory_storage::MemoryStorage, prelude::Glue};
use gluesql::core::store::Transaction;
use sea_orm::{AccessMode, ActiveValue, ActiveValue::Set, ConnectOptions, ConnectionTrait, Database, DatabaseBackend, DatabaseConnection, DatabaseTransaction, DbBackend, DbErr, EntityTrait, ExecResult, IsolationLevel, ProxyDatabaseTrait, ProxyExecResult, ProxyRow, QueryResult, Statement, TransactionError, TransactionTrait};

use entity::post::{ActiveModel, Entity};
use sea_orm::prelude::DateTime;
use crate::system_users::prelude::{SystemUsers, SystemUsersActiveModel};

#[derive(Debug)]
pub struct DatabaseTransactionProxyNew {
    inner: DatabaseConnection,
}
#[async_trait::async_trait]
impl ProxyDatabaseTrait for DatabaseTransactionProxyNew {
    async fn query(&self, statement: Statement) -> Result<Vec<ProxyRow>, DbErr> {
        println!("ProxyDatabaseTrait-----query--------A{:?}", statement);
        Ok(vec![])
    }

    async fn execute(&self, statement: Statement) -> Result<ProxyExecResult, DbErr> {
        println!("ProxyDatabaseTrait-----query--------B{:?}", statement);
        Ok(ProxyExecResult { last_insert_id: 0, rows_affected: 0 })
    }
}
impl DatabaseTransactionProxyNew {
    pub async fn new(opt: DatabaseConnection) -> Result<DatabaseTransactionProxyNew, DbErr>
    {
        Ok(DatabaseTransactionProxyNew {
            inner: opt,
        })
    }
    pub async fn connect<C>(opt: C) -> Result<DatabaseTransactionProxyNew, DbErr>
    where
        C: Into<ConnectOptions>,
    {
        Ok(DatabaseTransactionProxyNew {
            inner: Database::connect(opt).await?,
        })
    }
}

#[async_std::main]
async fn main()-> Result<(), Box<dyn Error>> {

    let dc =Database::connect("mysql://*********/test").await?;

    let proxy =  DatabaseTransactionProxyNew::new(dc).await?;
    let db_proxy =   Database::connect_proxy(DatabaseBackend::MySql, Arc::new(Box::new(proxy))).await?;

    // begin ok
    db_proxy.transaction(
        |txn| {
            Box::pin(async move {
                let am = SystemUsersActiveModel{
                    id: ActiveValue::Set(333),
                    username: ActiveValue::Set("1".to_string()),
                    password: ActiveValue::Set("1".to_string()),
                    nickname: ActiveValue::Set("1".to_string()),
                    remark: ActiveValue::Set(Some("1".to_string())),
                    dept_id: Default::default(),
                    post_ids: Default::default(),
                    email: Default::default(),
                    mobile: Default::default(),
                    sex: Default::default(),
                    avatar: Default::default(),
                    status:  ActiveValue::Set(1),
                    login_ip: Default::default(),
                    login_date: Default::default(),
                    creator: Default::default(),
                    create_time:  ActiveValue::Set(DateTime::default()),
                    updater: Default::default(),
                    update_time:ActiveValue::Set(DateTime::default()),
                    deleted: ActiveValue::Set(false),
                    tenant_id: ActiveValue::Set(22),
                };
                SystemUsers::insert(am).exec(txn).await
            })
        }
    ).await?;

    Ok(())
}

#[cfg(test)]
mod tests {
    #[smol_potat::test]
    async fn try_run() {
        crate::main()
    }
}

Error: Transaction(RecordNotInserted)

@logicin
Copy link
Contributor Author

logicin commented Apr 21, 2025

i think this error cause by " fn execute " rows_affected return 0; @oulover

   async fn execute(&self, statement: Statement) -> Result<ProxyExecResult, DbErr> {
        println!("ProxyDatabaseTrait-----query--------B{:?}", statement);
        Ok(ProxyExecResult { last_insert_id: 0, rows_affected: 0 })
    }

@oulover
Copy link

oulover commented Apr 21, 2025

Yes, I forgot to implement execute, thank you @logicin

    async fn execute(&self, statement: Statement) -> Result<ProxyExecResult, DbErr> {
        self.inner.execute(statement).await.map(|r|
            ProxyExecResult {
                last_insert_id: r.last_insert_id(),
                rows_affected: r.rows_affected(),
            }
        )
    }
// successfully execute

@logicin
Copy link
Contributor Author

logicin commented Apr 24, 2025

@tyt2y3 hello, Cloud you merge this PR? I want to use this feature. 😂

@Expurple
Copy link
Member

@logicin Until the PR is merged, you can use Cargo's [patch] functionality. Your project can depend on SeaORM from this pull request. Search this page for pull/ to see an example

@tyt2y3 tyt2y3 changed the base branch from master to proxy-transaction May 7, 2025 18:14
@tyt2y3
Copy link
Member

tyt2y3 commented May 7, 2025

thank you. I'll run some CI before merge

@tyt2y3 tyt2y3 merged commit 4436ad5 into SeaQL:proxy-transaction May 7, 2025
36 checks passed
tyt2y3 added a commit that referenced this pull request May 7, 2025
Co-authored-by: logicin <[email protected]>
Co-authored-by: Logicin <[email protected]>
Copy link

github-actions bot commented May 7, 2025

🎉 Released In 1.1.11 🎉

Thank you everyone for the contribution!
This feature is now available in the latest release. Now is a good time to upgrade!
Your participation is what makes us unique; your adoption is what drives us forward.
You can support SeaQL 🌊 by starring our repos, sharing our libraries and becoming a sponsor ⭐.

@logicin logicin deleted the proxy-transaction branch May 9, 2025 07:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants