Skip to content

Commit a73b332

Browse files
committed
WIP feat(sqlite): add position information to DB errors
1 parent 3df64c9 commit a73b332

File tree

6 files changed

+132
-58
lines changed

6 files changed

+132
-58
lines changed

sqlx-sqlite/src/connection/execute.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::sync::Arc;
12
use crate::connection::{ConnectionHandle, ConnectionState};
23
use crate::error::Error;
34
use crate::logger::QueryLogger;
@@ -20,14 +21,14 @@ pub struct ExecuteIter<'a> {
2021

2122
pub(crate) fn iter<'a>(
2223
conn: &'a mut ConnectionState,
23-
query: &'a str,
24+
query: &'a Arc<str>,
2425
args: Option<SqliteArguments<'a>>,
2526
persistent: bool,
2627
) -> Result<ExecuteIter<'a>, Error> {
2728
// fetch the cached statement or allocate a new one
28-
let statement = conn.statements.get(query, persistent)?;
29+
let statement = conn.statements.get(query.clone(), persistent)?;
2930

30-
let logger = QueryLogger::new(query, conn.log_settings.clone());
31+
let logger = QueryLogger::new(&query, conn.log_settings.clone());
3132

3233
Ok(ExecuteIter {
3334
handle: &mut conn.handle,

sqlx-sqlite/src/connection/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::os::raw::{c_int, c_void};
66
use std::panic::catch_unwind;
77
use std::ptr;
88
use std::ptr::NonNull;
9-
9+
use std::sync::Arc;
1010
use futures_core::future::BoxFuture;
1111
use futures_intrusive::sync::MutexGuard;
1212
use futures_util::future;
@@ -395,12 +395,12 @@ impl Statements {
395395
}
396396
}
397397

398-
fn get(&mut self, query: &str, persistent: bool) -> Result<&mut VirtualStatement, Error> {
398+
fn get(&mut self, query: Arc<str>, persistent: bool) -> Result<&mut VirtualStatement, Error> {
399399
if !persistent || !self.cached.is_enabled() {
400400
return Ok(self.temp.insert(VirtualStatement::new(query, false)?));
401401
}
402402

403-
let exists = self.cached.contains_key(query);
403+
let exists = self.cached.contains_key(&query);
404404

405405
if !exists {
406406
let statement = VirtualStatement::new(query, true)?;

sqlx-sqlite/src/connection/worker.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,15 @@ pub(crate) struct WorkerSharedState {
4040

4141
enum Command {
4242
Prepare {
43-
query: Box<str>,
43+
query: Arc<str>,
4444
tx: oneshot::Sender<Result<SqliteStatement<'static>, Error>>,
4545
},
4646
Describe {
47-
query: Box<str>,
47+
query: Arc<str>,
4848
tx: oneshot::Sender<Result<Describe<Sqlite>, Error>>,
4949
},
5050
Execute {
51-
query: Box<str>,
51+
query: Arc<str>,
5252
arguments: Option<SqliteArguments<'static>>,
5353
persistent: bool,
5454
tx: flume::Sender<Result<Either<SqliteQueryResult, SqliteRow>, Error>>,
@@ -119,7 +119,7 @@ impl ConnectionWorker {
119119
let _guard = span.enter();
120120
match cmd {
121121
Command::Prepare { query, tx } => {
122-
tx.send(prepare(&mut conn, &query).map(|prepared| {
122+
tx.send(prepare(&mut conn, query).map(|prepared| {
123123
update_cached_statements_size(
124124
&conn,
125125
&shared.cached_statements_size,
@@ -394,7 +394,7 @@ impl ConnectionWorker {
394394
}
395395
}
396396

397-
fn prepare(conn: &mut ConnectionState, query: &str) -> Result<SqliteStatement<'static>, Error> {
397+
fn prepare(conn: &mut ConnectionState, query: Arc<str>) -> Result<SqliteStatement<'static>, Error> {
398398
// prepare statement object (or checkout from cache)
399399
let statement = conn.statements.get(query, true)?;
400400

sqlx-sqlite/src/error.rs

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use std::os::raw::c_int;
55
use std::{borrow::Cow, str::from_utf8_unchecked};
66

77
use libsqlite3_sys::{
8-
sqlite3, sqlite3_errmsg, sqlite3_extended_errcode, SQLITE_CONSTRAINT_CHECK,
9-
SQLITE_CONSTRAINT_FOREIGNKEY, SQLITE_CONSTRAINT_NOTNULL, SQLITE_CONSTRAINT_PRIMARYKEY,
10-
SQLITE_CONSTRAINT_UNIQUE,
8+
sqlite3, sqlite3_errmsg, sqlite3_error_offset, sqlite3_extended_errcode,
9+
SQLITE_CONSTRAINT_CHECK, SQLITE_CONSTRAINT_FOREIGNKEY, SQLITE_CONSTRAINT_NOTNULL,
10+
SQLITE_CONSTRAINT_PRIMARYKEY, SQLITE_CONSTRAINT_UNIQUE,
1111
};
1212

1313
pub(crate) use sqlx_core::error::*;
@@ -19,6 +19,8 @@ pub(crate) use sqlx_core::error::*;
1919
pub struct SqliteError {
2020
code: c_int,
2121
message: String,
22+
offset: Option<usize>,
23+
error_pos: Option<ErrorPosition>,
2224
}
2325

2426
impl SqliteError {
@@ -34,9 +36,26 @@ impl SqliteError {
3436
from_utf8_unchecked(CStr::from_ptr(msg).to_bytes())
3537
};
3638

39+
// returns `-1` if not applicable
40+
let offset = unsafe { sqlite3_error_offset(handle) }.try_into().ok();
41+
3742
Self {
3843
code,
3944
message: message.to_owned(),
45+
offset,
46+
error_pos,
47+
}
48+
}
49+
50+
pub(crate) fn add_offset(&mut self, offset: usize) {
51+
if let Some(prev_offset) = self.offset {
52+
self.offset = prev_offset.checked_add(offset);
53+
}
54+
}
55+
56+
pub(crate) fn find_error_pos(&mut self, query: &str) {
57+
if let Some(offset) = self.offset {
58+
self.error_pos = ErrorPosition::find(query, PositionBasis::ByteOffset(offset));
4059
}
4160
}
4261

@@ -72,6 +91,10 @@ impl DatabaseError for SqliteError {
7291
Some(format!("{}", self.code).into())
7392
}
7493

94+
fn position(&self) -> Option<ErrorPosition> {
95+
self.error_pos
96+
}
97+
7598
#[doc(hidden)]
7699
fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {
77100
self

sqlx-sqlite/src/statement/virtual.rs

Lines changed: 72 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,11 @@ pub struct VirtualStatement {
3131
/// there are no more statements to execute and `reset()` must be called
3232
index: Option<usize>,
3333

34-
/// tail of the most recently prepared SQL statement within this container
35-
tail: Bytes,
34+
/// The full input SQL.
35+
sql: Arc<str>,
36+
37+
/// The byte offset of the next statement to prepare in `sql`.
38+
tail_offset: usize,
3639

3740
/// underlying sqlite handles for each inner statement
3841
/// a SQL query string in SQLite is broken up into N statements
@@ -44,6 +47,9 @@ pub struct VirtualStatement {
4447

4548
// each set of column names
4649
pub(crate) column_names: SmallVec<[Arc<HashMap<UStr, usize>>; 1]>,
50+
51+
/// Offsets into `sql` for each statement.
52+
pub(crate) sql_offsets: SmallVec<[usize; 1]>,
4753
}
4854

4955
pub struct PreparedStatement<'a> {
@@ -53,9 +59,7 @@ pub struct PreparedStatement<'a> {
5359
}
5460

5561
impl VirtualStatement {
56-
pub(crate) fn new(mut query: &str, persistent: bool) -> Result<Self, Error> {
57-
query = query.trim();
58-
62+
pub(crate) fn new(query: Arc<str>, persistent: bool) -> Result<Self, Error> {
5963
if query.len() > i32::max_value() as usize {
6064
return Err(err_protocol!(
6165
"query string must be smaller than {} bytes",
@@ -65,11 +69,13 @@ impl VirtualStatement {
6569

6670
Ok(Self {
6771
persistent,
68-
tail: Bytes::from(String::from(query)),
72+
sql: query,
73+
tail_offset: 0,
6974
handles: SmallVec::with_capacity(1),
7075
index: None,
7176
columns: SmallVec::with_capacity(1),
7277
column_names: SmallVec::with_capacity(1),
78+
sql_offsets: SmallVec::with_capacity(1),
7379
})
7480
}
7581

@@ -84,11 +90,33 @@ impl VirtualStatement {
8490
.or(Some(0));
8591

8692
while self.handles.len() <= self.index.unwrap_or(0) {
87-
if self.tail.is_empty() {
93+
let sql_offset = self.tail_offset;
94+
95+
let query = self.sql.get(sql_offset..).unwrap_or("");
96+
97+
if query.is_empty() {
8898
return Ok(None);
8999
}
90100

91-
if let Some(statement) = prepare(conn.as_ptr(), &mut self.tail, self.persistent)? {
101+
let (consumed, maybe_statement) = try_prepare(
102+
conn.as_ptr(),
103+
query,
104+
self.persistent,
105+
).map_err(|mut e| {
106+
// `sqlite3_offset()` returns the offset into the passed string,
107+
// but we want the offset into the original SQL string.
108+
e.add_offset(sql_offset);
109+
e.find_error_pos(&self.sql);
110+
e
111+
})?;
112+
113+
self.tail_offset = self.tail_offset
114+
.checked_add(consumed)
115+
// Highly unlikely, but since we're dealing with `unsafe` here
116+
// it's best not to fool around.
117+
.ok_or_else(|| Error::Protocol(format!("overflow adding {n:?} bytes to tail_offset {tail_offset:?}")))?;
118+
119+
if let Some(statement) = maybe_statement {
92120
let num = statement.column_count();
93121

94122
let mut columns = Vec::with_capacity(num);
@@ -112,6 +140,7 @@ impl VirtualStatement {
112140
self.handles.push(statement);
113141
self.columns.push(Arc::new(columns));
114142
self.column_names.push(Arc::new(column_names));
143+
self.sql_offsets.push(sql_offset);
115144
}
116145
}
117146

@@ -140,11 +169,13 @@ impl VirtualStatement {
140169
}
141170
}
142171

143-
fn prepare(
172+
/// Attempt to prepare one statement, returning the number of bytes consumed from `sql`,
173+
/// and the statement handle if successful.
174+
fn try_prepare(
144175
conn: *mut sqlite3,
145-
query: &mut Bytes,
176+
query: &str,
146177
persistent: bool,
147-
) -> Result<Option<StatementHandle>, Error> {
178+
) -> Result<(usize, Option<StatementHandle>), SqliteError> {
148179
let mut flags = 0;
149180

150181
// For some reason, when building with the `sqlcipher` feature enabled
@@ -158,40 +189,37 @@ fn prepare(
158189
flags |= SQLITE_PREPARE_PERSISTENT as u32;
159190
}
160191

161-
while !query.is_empty() {
162-
let mut statement_handle: *mut sqlite3_stmt = null_mut();
163-
let mut tail: *const c_char = null();
164-
165-
let query_ptr = query.as_ptr() as *const c_char;
166-
let query_len = query.len() as i32;
167-
168-
// <https://www.sqlite.org/c3ref/prepare.html>
169-
let status = unsafe {
170-
sqlite3_prepare_v3(
171-
conn,
172-
query_ptr,
173-
query_len,
174-
flags,
175-
&mut statement_handle,
176-
&mut tail,
177-
)
178-
};
179-
180-
if status != SQLITE_OK {
181-
return Err(SqliteError::new(conn).into());
182-
}
183-
184-
// tail should point to the first byte past the end of the first SQL
185-
// statement in zSql. these routines only compile the first statement,
186-
// so tail is left pointing to what remains un-compiled.
192+
let mut statement_handle: *mut sqlite3_stmt = null_mut();
193+
let mut tail_ptr: *const c_char = null();
194+
195+
let query_ptr = query.as_ptr() as *const c_char;
196+
let query_len = query.len() as i32;
197+
198+
// <https://www.sqlite.org/c3ref/prepare.html>
199+
let status = unsafe {
200+
sqlite3_prepare_v3(
201+
conn,
202+
query_ptr,
203+
query_len,
204+
flags,
205+
&mut statement_handle,
206+
&mut tail_ptr,
207+
)
208+
};
209+
210+
if status != SQLITE_OK {
211+
// Note: `offset` and `error_pos` will be updated in `VirtualStatement::prepare_next()`.
212+
return Err(SqliteError::new(conn));
213+
}
187214

188-
let n = (tail as usize) - (query_ptr as usize);
189-
query.advance(n);
215+
// tail should point to the first byte past the end of the first SQL
216+
// statement in zSql. these routines only compile the first statement,
217+
// so tail is left pointing to what remains un-compiled.
190218

191-
if let Some(handle) = NonNull::new(statement_handle) {
192-
return Ok(Some(StatementHandle::new(handle)));
193-
}
194-
}
219+
let consumed = (tail_ptr as usize) - (query_ptr as usize);
195220

196-
Ok(None)
221+
Ok((
222+
consumed,
223+
NonNull::new(statement_handle).map(StatementHandle::new),
224+
))
197225
}

tests/sqlite/error.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use sqlx::{error::ErrorKind, sqlite::Sqlite, Connection, Executor};
2+
use sqlx_sqlite::{SqliteConnection, SqliteError};
23
use sqlx_test::new;
34

45
#[sqlx_macros::test]
@@ -70,3 +71,24 @@ async fn it_fails_with_check_violation() -> anyhow::Result<()> {
7071

7172
Ok(())
7273
}
74+
75+
#[sqlx_macros::test]
76+
async fn it_fails_with_useful_information() -> anyhow::Result<()> {
77+
let mut conn = SqliteConnection::connect(":memory:").await?;
78+
79+
let err: sqlx::Error = sqlx::query("SELECT foo FORM bar")
80+
.execute(&mut conn)
81+
.await
82+
.unwrap_err();
83+
84+
let sqlx::Error::Database(dbe) = err else {
85+
panic!("unexpected error kind: {err:?}")
86+
};
87+
88+
let dbe= dbe.downcast::<SqliteError>();
89+
90+
eprintln!("{dbe}");
91+
eprintln!("{dbe:?}");
92+
93+
Ok(())
94+
}

0 commit comments

Comments
 (0)