Skip to content

Commit

Permalink
Try to insert non-numberic value without default value.
Browse files Browse the repository at this point in the history
  • Loading branch information
langyo committed Oct 17, 2024
1 parent 2495b40 commit 3356023
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 18 deletions.
1 change: 1 addition & 0 deletions examples/proxy_gluesql_example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ publish = false
[workspace]

[dependencies]
anyhow = "^1"
async-std = { version = "1.12", features = ["attributes", "tokio1"] }
serde_json = { version = "1" }
serde = { version = "1" }
Expand Down
17 changes: 14 additions & 3 deletions examples/proxy_gluesql_example/src/entity/post.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use sea_orm::entity::prelude::*;
use sea_orm::{entity::prelude::*, ActiveValue::*};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Deserialize, Serialize)]
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub id: Uuid,

pub title: String,
pub text: String,
Expand All @@ -14,4 +14,15 @@ pub struct Model {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
println!("Before save");
let mut ret = self.clone();
ret.id = Set(Uuid::new_v4());
Ok(ret)
}
}
38 changes: 27 additions & 11 deletions examples/proxy_gluesql_example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

mod entity;

use anyhow::{anyhow, Result};
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};

use gluesql::{memory_storage::MemoryStorage, prelude::Glue};
use sea_orm::{
ActiveValue::Set, Database, DbBackend, DbErr, EntityTrait, ProxyDatabaseTrait, ProxyExecResult,
ProxyRow, Statement,
ActiveModelTrait, ActiveValue::Set, Database, DbBackend, DbErr, EntityTrait,
ProxyDatabaseTrait, ProxyExecResult, ProxyRow, Statement,
};

use entity::post::{ActiveModel, Entity};
Expand Down Expand Up @@ -99,6 +100,12 @@ impl ProxyDatabaseTrait for ProxyDb {
val.unwrap_or(0).to_string(),
false,
),
sea_orm::Value::Uuid(val) => {
Value::SingleQuotedString(match val {
Some(val) => val.to_string(),
None => "".to_string(),
})
}
_ => todo!(),
};
}
Expand Down Expand Up @@ -132,14 +139,14 @@ impl ProxyDatabaseTrait for ProxyDb {
}

#[async_std::main]
async fn main() {
async fn main() -> Result<()> {
let mem = MemoryStorage::default();
let mut glue = Glue::new(mem);

glue.execute(
r#"
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY,
id UUID PRIMARY KEY,
title TEXT NOT NULL,
text TEXT NOT NULL
)
Expand All @@ -160,32 +167,41 @@ async fn main() {
println!("Initialized");

let data = ActiveModel {
id: Set(11),
title: Set("Homo".to_owned()),
text: Set("いいよ、来いよ".to_owned()),
..Default::default()
};
Entity::insert(data).exec(&db).await.unwrap();

println!("data: {:?}", data);
let ret = data.insert(&db).await.map_err(|err| anyhow!("{:?}", err))?;
println!("ret: {:?}", ret);

let data = ActiveModel {
id: Set(45),
title: Set("Homo".to_owned()),
text: Set("そうだよ".to_owned()),
..Default::default()
};
Entity::insert(data).exec(&db).await.unwrap();
let ret = data.insert(&db).await.map_err(|err| anyhow!("{:?}", err))?;
println!("ret: {:?}", ret);

let data = ActiveModel {
id: Set(14),
title: Set("Homo".to_owned()),
text: Set("悔い改めて".to_owned()),
..Default::default()
};
Entity::insert(data).exec(&db).await.unwrap();
let ret = data.insert(&db).await.map_err(|err| anyhow!("{:?}", err))?;
println!("ret: {:?}", ret);

let list = Entity::find().all(&db).await.unwrap().to_vec();
println!("Result: {:?}", list);

Ok(())
}

#[cfg(test)]
mod tests {
#[smol_potat::test]
async fn try_run() {
crate::main()
crate::main().unwrap();
}
}
7 changes: 3 additions & 4 deletions src/executor/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,9 @@ where
if db_backend == DbBackend::MySql && last_insert_id == 0 {
return Err(DbErr::RecordNotInserted);
}
Some(
ValueTypeOf::<A>::try_from_u64(last_insert_id)
.map_err(|_| DbErr::UnpackInsertId)?,
)
ValueTypeOf::<A>::try_from_u64(last_insert_id)
.map(|val| Some(val))
.unwrap_or(None)
} else {
None
}
Expand Down

0 comments on commit 3356023

Please sign in to comment.