WIP: composite primary keys

This commit is contained in:
Billy Chan 2021-09-01 18:23:23 +08:00
parent 0e0ee0ede6
commit a49f880f4f
No known key found for this signature in database
GPG Key ID: A2D690CAC7DF3CC7
3 changed files with 65 additions and 36 deletions

View File

@ -92,7 +92,9 @@ where
}
_ => {
let last_insert_id = db.execute(statement).await?.last_insert_id();
ValueTypeOf::<A>::try_from_u64(last_insert_id)?
ValueTypeOf::<A>::try_from_u64(last_insert_id)
.ok()
.unwrap_or_default()
}
};
Ok(InsertResult { last_insert_id })

View File

@ -410,32 +410,6 @@ pub trait TryFromU64: Sized {
fn try_from_u64(n: u64) -> Result<Self, DbErr>;
}
macro_rules! try_from_u64 {
( $type: ty ) => {
impl TryFromU64 for $type {
fn try_from_u64(n: u64) -> Result<Self, DbErr> {
use std::convert::TryInto;
n.try_into().map_err(|_| {
DbErr::Exec(format!(
"fail to convert '{}' into '{}'",
n,
stringify!($type)
))
})
}
}
};
}
try_from_u64!(i8);
try_from_u64!(i16);
try_from_u64!(i32);
try_from_u64!(i64);
try_from_u64!(u8);
try_from_u64!(u16);
try_from_u64!(u32);
try_from_u64!(u64);
macro_rules! try_from_u64_err {
( $type: ty ) => {
impl TryFromU64 for $type {
@ -449,5 +423,60 @@ macro_rules! try_from_u64_err {
};
}
macro_rules! try_from_u64_tuple {
( $type: ty ) => {
try_from_u64_err!(($type, $type));
try_from_u64_err!(($type, $type, $type));
};
}
macro_rules! try_from_u64_numeric {
( $type: ty ) => {
impl TryFromU64 for $type {
fn try_from_u64(n: u64) -> Result<Self, DbErr> {
use std::convert::TryInto;
n.try_into().map_err(|_| {
DbErr::Exec(format!(
"fail to convert '{}' into '{}'",
n,
stringify!($type)
))
})
}
}
try_from_u64_tuple!($type);
};
}
try_from_u64_numeric!(i8);
try_from_u64_numeric!(i16);
try_from_u64_numeric!(i32);
try_from_u64_numeric!(i64);
try_from_u64_numeric!(u8);
try_from_u64_numeric!(u16);
try_from_u64_numeric!(u32);
try_from_u64_numeric!(u64);
macro_rules! try_from_u64_string {
( $type: ty ) => {
impl TryFromU64 for $type {
fn try_from_u64(n: u64) -> Result<Self, DbErr> {
Ok(n.to_string())
}
}
try_from_u64_tuple!($type);
};
}
try_from_u64_string!(String);
macro_rules! try_from_u64_dummy {
( $type: ty ) => {
try_from_u64_err!($type);
try_from_u64_err!(($type, $type));
try_from_u64_err!(($type, $type, $type));
};
}
#[cfg(feature = "with-uuid")]
try_from_u64_err!(uuid::Uuid);
try_from_u64_dummy!(uuid::Uuid);

View File

@ -26,16 +26,14 @@ async fn create_metadata(db: &DatabaseConnection) -> Result<(), DbErr> {
value: Set("1.18".to_owned()),
};
let res = Metadata::insert(metadata.clone()).exec(db).await;
let res = Metadata::insert(metadata.clone()).exec(db).await?;
if cfg!(feature = "sqlx-postgres") {
assert_eq!(metadata.uuid.unwrap(), res?.last_insert_id);
let expected_uuid = if cfg!(feature = "sqlx-postgres") {
metadata.uuid.unwrap()
} else {
assert_eq!(
res.unwrap_err(),
DbErr::Exec("uuid::Uuid cannot be converted from u64".to_owned())
);
}
Uuid::default()
};
assert_eq!(res.last_insert_id, expected_uuid);
Ok(())
}