Skip to content

Commit e6dccc2

Browse files
authored
Merge pull request diesel-rs#2728 from m-rots/sqlite-error-handling
Parse error from sqlite exec instead of returning `DatabaseErrorKind::Unknown`
2 parents 1339840 + 25ea6c8 commit e6dccc2

2 files changed

Lines changed: 11 additions & 24 deletions

File tree

diesel/src/sqlite/connection/raw.rs

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
extern crate libsqlite3_sys as ffi;
22

3-
use std::ffi::{CStr, CString, NulError};
3+
use std::ffi::{CString, NulError};
44
use std::io::{stderr, Write};
55
use std::os::raw as libc;
66
use std::ptr::NonNull;
77
use std::{mem, ptr, slice, str};
88

99
use super::functions::{build_sql_function_args, process_sql_function_result};
1010
use super::serialized_value::SerializedValue;
11+
use super::stmt::ensure_sqlite_ok;
1112
use super::{Sqlite, SqliteAggregateFunction};
1213
use crate::deserialize::FromSqlRow;
1314
use crate::result::Error::DatabaseError;
@@ -62,27 +63,20 @@ impl RawConnection {
6263
}
6364

6465
pub fn exec(&self, query: &str) -> QueryResult<()> {
65-
let mut err_msg = ptr::null_mut();
6666
let query = CString::new(query)?;
6767
let callback_fn = None;
6868
let callback_arg = ptr::null_mut();
69-
unsafe {
69+
let result = unsafe {
7070
ffi::sqlite3_exec(
7171
self.internal_connection.as_ptr(),
7272
query.as_ptr(),
7373
callback_fn,
7474
callback_arg,
75-
&mut err_msg,
76-
);
77-
}
75+
ptr::null_mut(),
76+
)
77+
};
7878

79-
if err_msg.is_null() {
80-
Ok(())
81-
} else {
82-
let msg = convert_to_string_and_free(err_msg);
83-
let error_kind = DatabaseErrorKind::Unknown;
84-
Err(DatabaseError(error_kind, Box::new(msg)))
85-
}
79+
ensure_sqlite_ok(result, self.internal_connection.as_ptr())
8680
}
8781

8882
pub fn rows_affected_by_last_query(&self) -> usize {
@@ -235,16 +229,6 @@ impl Drop for RawConnection {
235229
}
236230
}
237231

238-
fn convert_to_string_and_free(err_msg: *const libc::c_char) -> String {
239-
let msg = unsafe {
240-
let bytes = CStr::from_ptr(err_msg).to_bytes();
241-
// sqlite is documented to return utf8 strings here
242-
str::from_utf8_unchecked(bytes).into()
243-
};
244-
unsafe { ffi::sqlite3_free(err_msg as *mut libc::c_void) };
245-
msg
246-
}
247-
248232
enum SqliteCallbackError {
249233
Abort(&'static str),
250234
DieselError(crate::result::Error),

diesel/src/sqlite/connection/stmt.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ impl Statement {
6161
}
6262
}
6363

64-
fn ensure_sqlite_ok(code: libc::c_int, raw_connection: *mut ffi::sqlite3) -> QueryResult<()> {
64+
pub(super) fn ensure_sqlite_ok(
65+
code: libc::c_int,
66+
raw_connection: *mut ffi::sqlite3,
67+
) -> QueryResult<()> {
6568
if code == ffi::SQLITE_OK {
6669
Ok(())
6770
} else {

0 commit comments

Comments
 (0)