Skip to content

Commit

Permalink
Use rows_affected when DB does not support returning
Browse files Browse the repository at this point in the history
  • Loading branch information
tyt2y3 committed Jan 18, 2023
1 parent a465d1e commit 6ec7dae
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 14 deletions.
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ pub enum DbErr {
/// None of the records are being inserted into the database,
/// if you insert with upsert expression that means
/// all of them conflict with existing records in the database
#[error("RecordNotInserted Error: {0}")]
RecordNotInserted(String),
#[error("None of the records are being inserted")]
RecordNotInserted,
}

/// Runtime error
Expand Down
2 changes: 1 addition & 1 deletion src/executor/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl ExecResult {
}
}

/// Get the number of rows affedted by the operation
/// Get the number of rows affected by the operation
pub fn rows_affected(&self) -> u64 {
match &self.result {
#[cfg(feature = "sqlx-mysql")]
Expand Down
9 changes: 4 additions & 5 deletions src/executor/insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,7 @@ where
let mut rows = db.query_all(statement).await?;
let row = match rows.pop() {
Some(row) => row,
None => {
return Err(DbErr::RecordNotInserted(
"None of the records are being inserted".to_owned(),
))
}
None => return Err(DbErr::RecordNotInserted),
};
let cols = PrimaryKey::<A>::iter()
.map(|col| col.to_string())
Expand All @@ -161,6 +157,9 @@ where
}
(None, false) => {
let res = db.execute(statement).await?;
if res.rows_affected() == 0 {
return Err(DbErr::RecordNotInserted);
}
let last_insert_id = res.last_insert_id();
ValueTypeOf::<A>::try_from_u64(last_insert_id).map_err(|_| DbErr::UnpackInsertId)?
}
Expand Down
7 changes: 1 addition & 6 deletions tests/upsert_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,7 @@ pub async fn create_insert_default(db: &DatabaseConnection) -> Result<(), DbErr>
.exec(db)
.await;

assert_eq!(
res.err(),
Some(DbErr::RecordNotInserted(
"None of the records are being inserted".to_owned()
))
);
assert_eq!(res.err(), Some(DbErr::RecordNotInserted));

Ok(())
}

0 comments on commit 6ec7dae

Please sign in to comment.