Skip to content

Commit

Permalink
add transaction example
Browse files Browse the repository at this point in the history
  • Loading branch information
soulww committed Dec 28, 2023
1 parent 977cfa4 commit d29a816
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 0 deletions.
11 changes: 11 additions & 0 deletions examples/transaction/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "transaction"
edition = "2021"
version.workspace = true

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
luna-orm = "0.3.3"
sqlx = { version = "0.7", features = [ "runtime-tokio" ] }
tokio = { version = "1.35.1", features = ["full"] }
69 changes: 69 additions & 0 deletions examples/transaction/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use luna_orm::prelude::*;
use luna_orm::LunaOrmResult;

#[derive(Schema, Clone, Debug)]
#[TableName = "user"]
pub struct UserEntity {
#[PrimaryKey]
id: i32,
name: String,
cash: Option<i32>,
}

#[tokio::main]
async fn main() -> LunaOrmResult<()> {
let config = SqliteLocalConfig {
work_dir: "./workspace".to_string(),
db_file: "test.db".to_string(),
};

let mut db: DB<SqliteDatabase> = SqliteDatabase::build(config).await.unwrap().into();

let result = db.execute_plain("DROP TABLE IF EXISTS `user`").await?;
let result = db.execute_plain(
"CREATE TABLE IF NOT EXISTS `user`(`id` INT PRIMARY KEY, `cash` INT, `name` VARCHAR(64))",
).await?;

// 1. insert entity
let entity = UserEntity {
id: 1,
name: "Allen".to_string(),
cash: Some(100),
};
db.insert(&entity).await?;
let entity = UserEntity {
id: 2,
name: "Bob".to_string(),
cash: Some(0),
};
db.insert(&entity).await?;

// 2. execute transaction commands
let mut trx = db.transaction().await?;
let mutation1 = UserMutation {
name: None,
cash: Some(50),
};
let primary1 = UserPrimary { id: 1 };
let mutation2 = UserMutation {
name: None,
cash: Some(50),
};
let primary2 = UserPrimary { id: 2 };
trx.update(&mutation1, &primary1).await?;
trx.update(&mutation2, &primary2).await?;
trx.commit().await?;

// 3. check
let selection = UserSelection {
id: false,
name: true,
cash: true,
};
let entity1: Option<UserSelectedEntity> = db.select(&primary1, &selection).await?;
let entity2: Option<UserSelectedEntity> = db.select(&primary2, &selection).await?;
assert_eq!(entity1.unwrap().cash, Some(50));
assert_eq!(entity2.unwrap().cash, Some(50));

Ok(())
}
Binary file added examples/transaction/workspace/test.db
Binary file not shown.
Binary file added examples/transaction/workspace/test.db-shm
Binary file not shown.
Binary file added examples/transaction/workspace/test.db-wal
Binary file not shown.

0 comments on commit d29a816

Please sign in to comment.