Debian Codegraph @

third_party/rust/rusqlite/src/inner_connection.rs

raw
1 use std::ffi::CStr;
2 use std::os::raw::{c_char, c_int};
3 #[cfg(feature = "load_extension")]
4 use std::path::Path;
5 use std::ptr;
6 use std::str;
7 use std::sync::{Arc, Mutex};
8
9 use super::ffi;
10 use super::str_for_sqlite;
11 use super::{Connection, InterruptHandle, OpenFlags, PrepFlags, Result};
12 use crate::error::{decode_result_raw, error_from_handle, error_with_offset, Error};
13 use crate::raw_statement::RawStatement;
14 use crate::statement::Statement;
15 use crate::version_number;
16
17 pub struct InnerConnection {
18 pub db: *mut ffi::sqlite3,
19 // It's unsafe to call `sqlite3_close` while another thread is performing
20 // a `sqlite3_interrupt`, and vice versa, so we take this mutex during
21 // those functions. This protects a copy of the `db` pointer (which is
22 // cleared on closing), however the main copy, `db`, is unprotected.
23 // Otherwise, a long-running query would prevent calling interrupt, as
24 // interrupt would only acquire the lock after the query's completion.
25 interrupt_lock: Arc<Mutex<*mut ffi::sqlite3>>,
26 #[cfg(feature = "hooks")]
27 pub free_commit_hook: Option<unsafe fn(*mut std::os::raw::c_void)>,
28 #[cfg(feature = "hooks")]
29 pub free_rollback_hook: Option<unsafe fn(*mut std::os::raw::c_void)>,
30 #[cfg(feature = "hooks")]
31 pub free_update_hook: Option<unsafe fn(*mut std::os::raw::c_void)>,
32 #[cfg(feature = "hooks")]
33 pub progress_handler: Option<Box<dyn FnMut() -> bool + Send>>,
34 #[cfg(feature = "hooks")]
35 pub authorizer: Option<crate::hooks::BoxedAuthorizer>,
36 #[cfg(feature = "preupdate_hook")]
37 pub free_preupdate_hook: Option<unsafe fn(*mut std::os::raw::c_void)>,
38 owned: bool,
39 }
40
41 unsafe impl Send for InnerConnection {}
42
43 impl InnerConnection {
44 #[expect(clippy::mutex_atomic, clippy::arc_with_non_send_sync)] // See unsafe impl Send / Sync for InterruptHandle
45 #[inline]
46 pub unsafe fn new(db: *mut ffi::sqlite3, owned: bool) -> Self {
47 Self {
48 db,
49 interrupt_lock: Arc::new(Mutex::new(if owned { db } else { ptr::null_mut() })),
50 #[cfg(feature = "hooks")]
51 free_commit_hook: None,
52 #[cfg(feature = "hooks")]
53 free_rollback_hook: None,
54 #[cfg(feature = "hooks")]
55 free_update_hook: None,
56 #[cfg(feature = "hooks")]
57 progress_handler: None,
58 #[cfg(feature = "hooks")]
59 authorizer: None,
60 #[cfg(feature = "preupdate_hook")]
61 free_preupdate_hook: None,
62 owned,
63 }
64 }
65
66 pub fn open_with_flags(
67 c_path: &CStr,
68 mut flags: OpenFlags,
69 vfs: Option<&CStr>,
70 ) -> Result<Self> {
71 ensure_safe_sqlite_threading_mode()?;
72
73 let z_vfs = match vfs {
74 Some(c_vfs) => c_vfs.as_ptr(),
75 None => ptr::null(),
76 };
77
78 // turn on extended results code before opening database to have a better diagnostic if a failure happens
79 let exrescode = if version_number() >= 3_037_000 {
80 flags |= OpenFlags::SQLITE_OPEN_EXRESCODE;
81 true
82 } else {
83 false // flag SQLITE_OPEN_EXRESCODE is ignored by SQLite version < 3.37.0
84 };
85
86 unsafe {
87 let mut db: *mut ffi::sqlite3 = ptr::null_mut();
88 let r = ffi::sqlite3_open_v2(c_path.as_ptr(), &mut db, flags.bits(), z_vfs);
89 if r != ffi::SQLITE_OK {
90 let e = if db.is_null() {
91 err!(r, "{}", c_path.to_string_lossy())
92 } else {
93 let mut e = error_from_handle(db, r);
94 if let Error::SqliteFailure(
95 ffi::Error {
96 code: ffi::ErrorCode::CannotOpen,
97 ..
98 },
99 Some(msg),
100 ) = e
101 {
102 e = err!(r, "{msg}: {}", c_path.to_string_lossy());
103 }
104 ffi::sqlite3_close(db);
105 e
106 };
107
108 return Err(e);
109 }
110
111 // attempt to turn on extended results code; don't fail if we can't.
112 if !exrescode {
113 ffi::sqlite3_extended_result_codes(db, 1);
114 }
115
116 let r = ffi::sqlite3_busy_timeout(db, 5000);
117 if r != ffi::SQLITE_OK {
118 let e = error_from_handle(db, r);
119 ffi::sqlite3_close(db);
120 return Err(e);
121 }
122
123 Ok(Self::new(db, true))
124 }
125 }
126
127 #[inline]
128 pub fn db(&self) -> *mut ffi::sqlite3 {
129 self.db
130 }
131
132 #[inline]
133 pub fn decode_result(&self, code: c_int) -> Result<()> {
134 unsafe { decode_result_raw(self.db(), code) }
135 }
136
137 pub fn close(&mut self) -> Result<()> {
138 if self.db.is_null() {
139 return Ok(());
140 }
141 self.remove_hooks();
142 self.remove_preupdate_hook();
143 let mut shared_handle = self.interrupt_lock.lock().unwrap();
144 assert!(
145 !self.owned || !shared_handle.is_null(),
146 "Bug: Somehow interrupt_lock was cleared before the DB was closed"
147 );
148 if !self.owned {
149 self.db = ptr::null_mut();
150 return Ok(());
151 }
152 unsafe {
153 let r = ffi::sqlite3_close(self.db);
154 // Need to use _raw because _guard has a reference out, and
155 // decode_result takes &mut self.
156 let r = decode_result_raw(self.db, r);
157 if r.is_ok() {
158 *shared_handle = ptr::null_mut();
159 self.db = ptr::null_mut();
160 }
161 r
162 }
163 }
164
165 #[inline]
166 pub fn get_interrupt_handle(&self) -> InterruptHandle {
167 InterruptHandle {
168 db_lock: Arc::clone(&self.interrupt_lock),
169 }
170 }
171
172 #[inline]
173 #[cfg(feature = "load_extension")]
174 pub unsafe fn enable_load_extension(&mut self, onoff: c_int) -> Result<()> {
175 let r = ffi::sqlite3_enable_load_extension(self.db, onoff);
176 self.decode_result(r)
177 }
178
179 #[cfg(feature = "load_extension")]
180 pub unsafe fn load_extension(
181 &self,
182 dylib_path: &Path,
183 entry_point: Option<&str>,
184 ) -> Result<()> {
185 let dylib_str = super::path_to_cstring(dylib_path)?;
186 let mut errmsg: *mut c_char = ptr::null_mut();
187 let r = if let Some(entry_point) = entry_point {
188 let c_entry = crate::str_to_cstring(entry_point)?;
189 ffi::sqlite3_load_extension(self.db, dylib_str.as_ptr(), c_entry.as_ptr(), &mut errmsg)
190 } else {
191 ffi::sqlite3_load_extension(self.db, dylib_str.as_ptr(), ptr::null(), &mut errmsg)
192 };
193 if r == ffi::SQLITE_OK {
194 Ok(())
195 } else {
196 let message = super::errmsg_to_string(errmsg);
197 ffi::sqlite3_free(errmsg.cast::<std::os::raw::c_void>());
198 Err(crate::error::error_from_sqlite_code(r, Some(message)))
199 }
200 }
201
202 #[inline]
203 pub fn last_insert_rowid(&self) -> i64 {
204 unsafe { ffi::sqlite3_last_insert_rowid(self.db()) }
205 }
206
207 pub fn prepare<'a>(
208 &mut self,
209 conn: &'a Connection,
210 sql: &str,
211 flags: PrepFlags,
212 ) -> Result<Statement<'a>> {
213 let mut c_stmt: *mut ffi::sqlite3_stmt = ptr::null_mut();
214 let (c_sql, len, _) = str_for_sqlite(sql.as_bytes())?;
215 let mut c_tail: *const c_char = ptr::null();
216 #[cfg(not(feature = "unlock_notify"))]
217 let r = unsafe { self.prepare_(c_sql, len, flags, &mut c_stmt, &mut c_tail) };
218 #[cfg(feature = "unlock_notify")]
219 let r = unsafe {
220 use crate::unlock_notify;
221 let mut rc;
222 loop {
223 rc = self.prepare_(c_sql, len, flags, &mut c_stmt, &mut c_tail);
224 if !unlock_notify::is_locked(self.db, rc) {
225 break;
226 }
227 rc = unlock_notify::wait_for_unlock_notify(self.db);
228 if rc != ffi::SQLITE_OK {
229 break;
230 }
231 }
232 rc
233 };
234 // If there is an error, *ppStmt is set to NULL.
235 if r != ffi::SQLITE_OK {
236 return Err(unsafe { error_with_offset(self.db, r, sql) });
237 }
238 // If the input text contains no SQL (if the input is an empty string or a
239 // comment) then *ppStmt is set to NULL.
240 let tail = if c_tail.is_null() {
241 0
242 } else {
243 let n = (c_tail as isize) - (c_sql as isize);
244 if n <= 0 || n >= len as isize {
245 0
246 } else {
247 n as usize
248 }
249 };
250 Ok(Statement::new(conn, unsafe {
251 RawStatement::new(c_stmt, tail)
252 }))
253 }
254
255 #[inline]
256 #[cfg(not(feature = "modern_sqlite"))]
257 unsafe fn prepare_(
258 &self,
259 z_sql: *const c_char,
260 n_byte: c_int,
261 _: PrepFlags,
262 pp_stmt: *mut *mut ffi::sqlite3_stmt,
263 pz_tail: *mut *const c_char,
264 ) -> c_int {
265 ffi::sqlite3_prepare_v2(self.db(), z_sql, n_byte, pp_stmt, pz_tail)
266 }
267
268 #[inline]
269 #[cfg(feature = "modern_sqlite")]
270 unsafe fn prepare_(
271 &self,
272 z_sql: *const c_char,
273 n_byte: c_int,
274 flags: PrepFlags,
275 pp_stmt: *mut *mut ffi::sqlite3_stmt,
276 pz_tail: *mut *const c_char,
277 ) -> c_int {
278 ffi::sqlite3_prepare_v3(self.db(), z_sql, n_byte, flags.bits(), pp_stmt, pz_tail)
279 }
280
281 #[inline]
282 pub fn changes(&self) -> u64 {
283 #[cfg(not(feature = "modern_sqlite"))]
284 unsafe {
285 ffi::sqlite3_changes(self.db()) as u64
286 }
287 #[cfg(feature = "modern_sqlite")] // 3.37.0
288 unsafe {
289 ffi::sqlite3_changes64(self.db()) as u64
290 }
291 }
292
293 #[inline]
294 pub fn total_changes(&self) -> u64 {
295 #[cfg(not(feature = "modern_sqlite"))]
296 unsafe {
297 ffi::sqlite3_total_changes(self.db()) as u64
298 }
299 #[cfg(feature = "modern_sqlite")] // 3.37.0
300 unsafe {
301 ffi::sqlite3_total_changes64(self.db()) as u64
302 }
303 }
304
305 #[inline]
306 pub fn is_autocommit(&self) -> bool {
307 unsafe { get_autocommit(self.db()) }
308 }
309
310 pub fn is_busy(&self) -> bool {
311 let db = self.db();
312 unsafe {
313 let mut stmt = ffi::sqlite3_next_stmt(db, ptr::null_mut());
314 while !stmt.is_null() {
315 if ffi::sqlite3_stmt_busy(stmt) != 0 {
316 return true;
317 }
318 stmt = ffi::sqlite3_next_stmt(db, stmt);
319 }
320 }
321 false
322 }
323
324 pub fn cache_flush(&mut self) -> Result<()> {
325 crate::error::check(unsafe { ffi::sqlite3_db_cacheflush(self.db()) })
326 }
327
328 #[cfg(not(feature = "hooks"))]
329 #[inline]
330 fn remove_hooks(&mut self) {}
331
332 #[cfg(not(feature = "preupdate_hook"))]
333 #[inline]
334 fn remove_preupdate_hook(&mut self) {}
335
336 pub fn db_readonly(&self, db_name: super::DatabaseName<'_>) -> Result<bool> {
337 let name = db_name.as_cstr()?;
338 let r = unsafe { ffi::sqlite3_db_readonly(self.db, name.as_ptr()) };
339 match r {
340 0 => Ok(false),
341 1 => Ok(true),
342 -1 => Err(err!(
343 ffi::SQLITE_MISUSE,
344 "{db_name:?} is not the name of a database"
345 )),
346 _ => Err(err!(r, "Unexpected result")),
347 }
348 }
349
350 #[cfg(feature = "modern_sqlite")] // 3.37.0
351 pub fn txn_state(
352 &self,
353 db_name: Option<super::DatabaseName<'_>>,
354 ) -> Result<super::transaction::TransactionState> {
355 let r = if let Some(ref name) = db_name {
356 let name = name.as_cstr()?;
357 unsafe { ffi::sqlite3_txn_state(self.db, name.as_ptr()) }
358 } else {
359 unsafe { ffi::sqlite3_txn_state(self.db, ptr::null()) }
360 };
361 match r {
362 0 => Ok(super::transaction::TransactionState::None),
363 1 => Ok(super::transaction::TransactionState::Read),
364 2 => Ok(super::transaction::TransactionState::Write),
365 -1 => Err(err!(
366 ffi::SQLITE_MISUSE,
367 "{db_name:?} is not the name of a valid schema"
368 )),
369 _ => Err(err!(r, "Unexpected result")),
370 }
371 }
372
373 #[inline]
374 pub fn release_memory(&self) -> Result<()> {
375 self.decode_result(unsafe { ffi::sqlite3_db_release_memory(self.db) })
376 }
377
378 #[cfg(feature = "modern_sqlite")] // 3.41.0
379 pub fn is_interrupted(&self) -> bool {
380 unsafe { ffi::sqlite3_is_interrupted(self.db) == 1 }
381 }
382 }
383
384 #[inline]
385 pub(crate) unsafe fn get_autocommit(ptr: *mut ffi::sqlite3) -> bool {
386 ffi::sqlite3_get_autocommit(ptr) != 0
387 }
388
389 #[inline]
390 pub(crate) unsafe fn db_filename(
391 ptr: *mut ffi::sqlite3,
392 db_name: crate::DatabaseName<'_>,
393 ) -> Option<&str> {
394 let db_name = db_name.as_cstr().unwrap();
395 let db_filename = ffi::sqlite3_db_filename(ptr, db_name.as_ptr());
396 if db_filename.is_null() {
397 None
398 } else {
399 CStr::from_ptr(db_filename).to_str().ok()
400 }
401 }
402
403 impl Drop for InnerConnection {
404 #[expect(unused_must_use)]
405 #[inline]
406 fn drop(&mut self) {
407 self.close();
408 }
409 }
410
411 // threading mode checks are not necessary (and do not work) on target
412 // platforms that do not have threading (such as webassembly)
413 #[cfg(target_arch = "wasm32")]
414 fn ensure_safe_sqlite_threading_mode() -> Result<()> {
415 Ok(())
416 }
417
418 #[cfg(not(any(target_arch = "wasm32")))]
419 fn ensure_safe_sqlite_threading_mode() -> Result<()> {
420 // Ensure SQLite was compiled in threadsafe mode.
421 if unsafe { ffi::sqlite3_threadsafe() == 0 } {
422 return Err(Error::SqliteSingleThreadedMode);
423 }
424
425 // Now we know SQLite is _capable_ of being in Multi-thread of Serialized mode,
426 // but it's possible someone configured it to be in Single-thread mode
427 // before calling into us. That would mean we're exposing an unsafe API via
428 // a safe one (in Rust terminology).
429 //
430 // We can ask SQLite for a mutex and check for
431 // the magic value 8. This isn't documented, but it's what SQLite
432 // returns for its mutex allocation function in Single-thread mode.
433 const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
434 let is_singlethreaded = unsafe {
435 let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
436 let is_singlethreaded = mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC;
437 ffi::sqlite3_mutex_free(mutex_ptr);
438 is_singlethreaded
439 };
440 if is_singlethreaded {
441 Err(Error::SqliteSingleThreadedMode)
442 } else {
443 Ok(())
444 }
445 }