| 1 |
//! [Session Extension](https://sqlite.org/sessionintro.html) |
| 2 |
#![expect(non_camel_case_types)] |
| 3 |
|
| 4 |
use std::ffi::CStr; |
| 5 |
use std::io::{Read, Write}; |
| 6 |
use std::marker::PhantomData; |
| 7 |
use std::os::raw::{c_char, c_int, c_uchar, c_void}; |
| 8 |
use std::panic::catch_unwind; |
| 9 |
use std::ptr; |
| 10 |
use std::slice::{from_raw_parts, from_raw_parts_mut}; |
| 11 |
|
| 12 |
use fallible_streaming_iterator::FallibleStreamingIterator; |
| 13 |
|
| 14 |
use crate::error::{check, error_from_sqlite_code, Error}; |
| 15 |
use crate::ffi; |
| 16 |
use crate::hooks::Action; |
| 17 |
use crate::types::ValueRef; |
| 18 |
use crate::{errmsg_to_string, str_to_cstring, Connection, DatabaseName, Result}; |
| 19 |
|
| 20 |
// https://sqlite.org/session.html |
| 21 |
|
| 22 |
type Filter = Option<Box<dyn Fn(&str) -> bool>>; |
| 23 |
|
| 24 |
/// An instance of this object is a session that can be |
| 25 |
/// used to record changes to a database. |
| 26 |
pub struct Session<'conn> { |
| 27 |
phantom: PhantomData<&'conn Connection>, |
| 28 |
s: *mut ffi::sqlite3_session, |
| 29 |
filter: Filter, |
| 30 |
} |
| 31 |
|
| 32 |
impl Session<'_> { |
| 33 |
/// Create a new session object |
| 34 |
#[inline] |
| 35 |
pub fn new(db: &Connection) -> Result<Session<'_>> { |
| 36 |
Session::new_with_name(db, DatabaseName::Main) |
| 37 |
} |
| 38 |
|
| 39 |
/// Create a new session object |
| 40 |
#[inline] |
| 41 |
pub fn new_with_name<'conn>( |
| 42 |
db: &'conn Connection, |
| 43 |
name: DatabaseName<'_>, |
| 44 |
) -> Result<Session<'conn>> { |
| 45 |
let name = name.as_cstr()?; |
| 46 |
|
| 47 |
let db = db.db.borrow_mut().db; |
| 48 |
|
| 49 |
let mut s: *mut ffi::sqlite3_session = ptr::null_mut(); |
| 50 |
check(unsafe { ffi::sqlite3session_create(db, name.as_ptr(), &mut s) })?; |
| 51 |
|
| 52 |
Ok(Session { |
| 53 |
phantom: PhantomData, |
| 54 |
s, |
| 55 |
filter: None, |
| 56 |
}) |
| 57 |
} |
| 58 |
|
| 59 |
/// Set a table filter |
| 60 |
pub fn table_filter<F>(&mut self, filter: Option<F>) |
| 61 |
where |
| 62 |
F: Fn(&str) -> bool + Send + 'static, |
| 63 |
{ |
| 64 |
unsafe extern "C" fn call_boxed_closure<F>( |
| 65 |
p_arg: *mut c_void, |
| 66 |
tbl_str: *const c_char, |
| 67 |
) -> c_int |
| 68 |
where |
| 69 |
F: Fn(&str) -> bool, |
| 70 |
{ |
| 71 |
let tbl_name = CStr::from_ptr(tbl_str).to_str(); |
| 72 |
c_int::from( |
| 73 |
catch_unwind(|| { |
| 74 |
let boxed_filter: *mut F = p_arg.cast::<F>(); |
| 75 |
(*boxed_filter)(tbl_name.expect("non-utf8 table name")) |
| 76 |
}) |
| 77 |
.unwrap_or_default(), |
| 78 |
) |
| 79 |
} |
| 80 |
|
| 81 |
match filter { |
| 82 |
Some(filter) => { |
| 83 |
let boxed_filter = Box::new(filter); |
| 84 |
unsafe { |
| 85 |
ffi::sqlite3session_table_filter( |
| 86 |
self.s, |
| 87 |
Some(call_boxed_closure::<F>), |
| 88 |
&*boxed_filter as *const F as *mut _, |
| 89 |
); |
| 90 |
} |
| 91 |
self.filter = Some(boxed_filter); |
| 92 |
} |
| 93 |
_ => { |
| 94 |
unsafe { ffi::sqlite3session_table_filter(self.s, None, ptr::null_mut()) } |
| 95 |
self.filter = None; |
| 96 |
} |
| 97 |
}; |
| 98 |
} |
| 99 |
|
| 100 |
/// Attach a table. `None` means all tables. |
| 101 |
pub fn attach(&mut self, table: Option<&str>) -> Result<()> { |
| 102 |
let table = if let Some(table) = table { |
| 103 |
Some(str_to_cstring(table)?) |
| 104 |
} else { |
| 105 |
None |
| 106 |
}; |
| 107 |
let table = table.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); |
| 108 |
check(unsafe { ffi::sqlite3session_attach(self.s, table) }) |
| 109 |
} |
| 110 |
|
| 111 |
/// Generate a Changeset |
| 112 |
pub fn changeset(&mut self) -> Result<Changeset> { |
| 113 |
let mut n = 0; |
| 114 |
let mut cs: *mut c_void = ptr::null_mut(); |
| 115 |
check(unsafe { ffi::sqlite3session_changeset(self.s, &mut n, &mut cs) })?; |
| 116 |
Ok(Changeset { cs, n }) |
| 117 |
} |
| 118 |
|
| 119 |
/// Write the set of changes represented by this session to `output`. |
| 120 |
#[inline] |
| 121 |
pub fn changeset_strm(&mut self, output: &mut dyn Write) -> Result<()> { |
| 122 |
let output_ref = &output; |
| 123 |
check(unsafe { |
| 124 |
ffi::sqlite3session_changeset_strm( |
| 125 |
self.s, |
| 126 |
Some(x_output), |
| 127 |
output_ref as *const &mut dyn Write as *mut c_void, |
| 128 |
) |
| 129 |
}) |
| 130 |
} |
| 131 |
|
| 132 |
/// Generate a Patchset |
| 133 |
#[inline] |
| 134 |
pub fn patchset(&mut self) -> Result<Changeset> { |
| 135 |
let mut n = 0; |
| 136 |
let mut ps: *mut c_void = ptr::null_mut(); |
| 137 |
check(unsafe { ffi::sqlite3session_patchset(self.s, &mut n, &mut ps) })?; |
| 138 |
// TODO Validate: same struct |
| 139 |
Ok(Changeset { cs: ps, n }) |
| 140 |
} |
| 141 |
|
| 142 |
/// Write the set of patches represented by this session to `output`. |
| 143 |
#[inline] |
| 144 |
pub fn patchset_strm(&mut self, output: &mut dyn Write) -> Result<()> { |
| 145 |
let output_ref = &output; |
| 146 |
check(unsafe { |
| 147 |
ffi::sqlite3session_patchset_strm( |
| 148 |
self.s, |
| 149 |
Some(x_output), |
| 150 |
output_ref as *const &mut dyn Write as *mut c_void, |
| 151 |
) |
| 152 |
}) |
| 153 |
} |
| 154 |
|
| 155 |
/// Load the difference between tables. |
| 156 |
pub fn diff(&mut self, from: DatabaseName<'_>, table: &str) -> Result<()> { |
| 157 |
let from = from.as_cstr()?; |
| 158 |
let table = str_to_cstring(table)?; |
| 159 |
let table = table.as_ptr(); |
| 160 |
unsafe { |
| 161 |
let mut errmsg = ptr::null_mut(); |
| 162 |
let r = |
| 163 |
ffi::sqlite3session_diff(self.s, from.as_ptr(), table, &mut errmsg as *mut *mut _); |
| 164 |
if r != ffi::SQLITE_OK { |
| 165 |
let errmsg: *mut c_char = errmsg; |
| 166 |
let message = errmsg_to_string(&*errmsg); |
| 167 |
ffi::sqlite3_free(errmsg as *mut c_void); |
| 168 |
return Err(error_from_sqlite_code(r, Some(message))); |
| 169 |
} |
| 170 |
} |
| 171 |
Ok(()) |
| 172 |
} |
| 173 |
|
| 174 |
/// Test if a changeset has recorded any changes |
| 175 |
#[inline] |
| 176 |
pub fn is_empty(&self) -> bool { |
| 177 |
unsafe { ffi::sqlite3session_isempty(self.s) != 0 } |
| 178 |
} |
| 179 |
|
| 180 |
/// Query the current state of the session |
| 181 |
#[inline] |
| 182 |
pub fn is_enabled(&self) -> bool { |
| 183 |
unsafe { ffi::sqlite3session_enable(self.s, -1) != 0 } |
| 184 |
} |
| 185 |
|
| 186 |
/// Enable or disable the recording of changes |
| 187 |
#[inline] |
| 188 |
pub fn set_enabled(&mut self, enabled: bool) { |
| 189 |
unsafe { |
| 190 |
ffi::sqlite3session_enable(self.s, c_int::from(enabled)); |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
/// Query the current state of the indirect flag |
| 195 |
#[inline] |
| 196 |
pub fn is_indirect(&self) -> bool { |
| 197 |
unsafe { ffi::sqlite3session_indirect(self.s, -1) != 0 } |
| 198 |
} |
| 199 |
|
| 200 |
/// Set or clear the indirect change flag |
| 201 |
#[inline] |
| 202 |
pub fn set_indirect(&mut self, indirect: bool) { |
| 203 |
unsafe { |
| 204 |
ffi::sqlite3session_indirect(self.s, c_int::from(indirect)); |
| 205 |
} |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
impl Drop for Session<'_> { |
| 210 |
#[inline] |
| 211 |
fn drop(&mut self) { |
| 212 |
if self.filter.is_some() { |
| 213 |
self.table_filter(None::<fn(&str) -> bool>); |
| 214 |
} |
| 215 |
unsafe { ffi::sqlite3session_delete(self.s) }; |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// Invert a changeset |
| 220 |
#[inline] |
| 221 |
pub fn invert_strm(input: &mut dyn Read, output: &mut dyn Write) -> Result<()> { |
| 222 |
let input_ref = &input; |
| 223 |
let output_ref = &output; |
| 224 |
check(unsafe { |
| 225 |
ffi::sqlite3changeset_invert_strm( |
| 226 |
Some(x_input), |
| 227 |
input_ref as *const &mut dyn Read as *mut c_void, |
| 228 |
Some(x_output), |
| 229 |
output_ref as *const &mut dyn Write as *mut c_void, |
| 230 |
) |
| 231 |
}) |
| 232 |
} |
| 233 |
|
| 234 |
/// Combine two changesets |
| 235 |
#[inline] |
| 236 |
pub fn concat_strm( |
| 237 |
input_a: &mut dyn Read, |
| 238 |
input_b: &mut dyn Read, |
| 239 |
output: &mut dyn Write, |
| 240 |
) -> Result<()> { |
| 241 |
let input_a_ref = &input_a; |
| 242 |
let input_b_ref = &input_b; |
| 243 |
let output_ref = &output; |
| 244 |
check(unsafe { |
| 245 |
ffi::sqlite3changeset_concat_strm( |
| 246 |
Some(x_input), |
| 247 |
input_a_ref as *const &mut dyn Read as *mut c_void, |
| 248 |
Some(x_input), |
| 249 |
input_b_ref as *const &mut dyn Read as *mut c_void, |
| 250 |
Some(x_output), |
| 251 |
output_ref as *const &mut dyn Write as *mut c_void, |
| 252 |
) |
| 253 |
}) |
| 254 |
} |
| 255 |
|
| 256 |
/// Changeset or Patchset |
| 257 |
pub struct Changeset { |
| 258 |
cs: *mut c_void, |
| 259 |
n: c_int, |
| 260 |
} |
| 261 |
|
| 262 |
impl Changeset { |
| 263 |
/// Invert a changeset |
| 264 |
#[inline] |
| 265 |
pub fn invert(&self) -> Result<Changeset> { |
| 266 |
let mut n = 0; |
| 267 |
let mut cs = ptr::null_mut(); |
| 268 |
check(unsafe { |
| 269 |
ffi::sqlite3changeset_invert(self.n, self.cs, &mut n, &mut cs as *mut *mut _) |
| 270 |
})?; |
| 271 |
Ok(Changeset { cs, n }) |
| 272 |
} |
| 273 |
|
| 274 |
/// Create an iterator to traverse a changeset |
| 275 |
#[inline] |
| 276 |
pub fn iter(&self) -> Result<ChangesetIter<'_>> { |
| 277 |
let mut it = ptr::null_mut(); |
| 278 |
check(unsafe { ffi::sqlite3changeset_start(&mut it as *mut *mut _, self.n, self.cs) })?; |
| 279 |
Ok(ChangesetIter { |
| 280 |
phantom: PhantomData, |
| 281 |
it, |
| 282 |
item: None, |
| 283 |
}) |
| 284 |
} |
| 285 |
|
| 286 |
/// Concatenate two changeset objects |
| 287 |
#[inline] |
| 288 |
pub fn concat(a: &Changeset, b: &Changeset) -> Result<Changeset> { |
| 289 |
let mut n = 0; |
| 290 |
let mut cs = ptr::null_mut(); |
| 291 |
check(unsafe { |
| 292 |
ffi::sqlite3changeset_concat(a.n, a.cs, b.n, b.cs, &mut n, &mut cs as *mut *mut _) |
| 293 |
})?; |
| 294 |
Ok(Changeset { cs, n }) |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
impl Drop for Changeset { |
| 299 |
#[inline] |
| 300 |
fn drop(&mut self) { |
| 301 |
unsafe { |
| 302 |
ffi::sqlite3_free(self.cs); |
| 303 |
} |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
/// Cursor for iterating over the elements of a changeset |
| 308 |
/// or patchset. |
| 309 |
pub struct ChangesetIter<'changeset> { |
| 310 |
phantom: PhantomData<&'changeset Changeset>, |
| 311 |
it: *mut ffi::sqlite3_changeset_iter, |
| 312 |
item: Option<ChangesetItem>, |
| 313 |
} |
| 314 |
|
| 315 |
impl ChangesetIter<'_> { |
| 316 |
/// Create an iterator on `input` |
| 317 |
#[inline] |
| 318 |
pub fn start_strm<'input>(input: &&'input mut dyn Read) -> Result<ChangesetIter<'input>> { |
| 319 |
let mut it = ptr::null_mut(); |
| 320 |
check(unsafe { |
| 321 |
ffi::sqlite3changeset_start_strm( |
| 322 |
&mut it as *mut *mut _, |
| 323 |
Some(x_input), |
| 324 |
input as *const &mut dyn Read as *mut c_void, |
| 325 |
) |
| 326 |
})?; |
| 327 |
Ok(ChangesetIter { |
| 328 |
phantom: PhantomData, |
| 329 |
it, |
| 330 |
item: None, |
| 331 |
}) |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
impl FallibleStreamingIterator for ChangesetIter<'_> { |
| 336 |
type Error = Error; |
| 337 |
type Item = ChangesetItem; |
| 338 |
|
| 339 |
#[inline] |
| 340 |
fn advance(&mut self) -> Result<()> { |
| 341 |
let rc = unsafe { ffi::sqlite3changeset_next(self.it) }; |
| 342 |
match rc { |
| 343 |
ffi::SQLITE_ROW => { |
| 344 |
self.item = Some(ChangesetItem { it: self.it }); |
| 345 |
Ok(()) |
| 346 |
} |
| 347 |
ffi::SQLITE_DONE => { |
| 348 |
self.item = None; |
| 349 |
Ok(()) |
| 350 |
} |
| 351 |
code => Err(error_from_sqlite_code(code, None)), |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
#[inline] |
| 356 |
fn get(&self) -> Option<&ChangesetItem> { |
| 357 |
self.item.as_ref() |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
/// Operation |
| 362 |
pub struct Operation<'item> { |
| 363 |
table_name: &'item str, |
| 364 |
number_of_columns: i32, |
| 365 |
code: Action, |
| 366 |
indirect: bool, |
| 367 |
} |
| 368 |
|
| 369 |
impl Operation<'_> { |
| 370 |
/// Returns the table name. |
| 371 |
#[inline] |
| 372 |
pub fn table_name(&self) -> &str { |
| 373 |
self.table_name |
| 374 |
} |
| 375 |
|
| 376 |
/// Returns the number of columns in table |
| 377 |
#[inline] |
| 378 |
pub fn number_of_columns(&self) -> i32 { |
| 379 |
self.number_of_columns |
| 380 |
} |
| 381 |
|
| 382 |
/// Returns the action code. |
| 383 |
#[inline] |
| 384 |
pub fn code(&self) -> Action { |
| 385 |
self.code |
| 386 |
} |
| 387 |
|
| 388 |
/// Returns `true` for an 'indirect' change. |
| 389 |
#[inline] |
| 390 |
pub fn indirect(&self) -> bool { |
| 391 |
self.indirect |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
impl Drop for ChangesetIter<'_> { |
| 396 |
#[inline] |
| 397 |
fn drop(&mut self) { |
| 398 |
unsafe { |
| 399 |
ffi::sqlite3changeset_finalize(self.it); |
| 400 |
} |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
/// An item passed to a conflict-handler by |
| 405 |
/// [`Connection::apply`](Connection::apply), or an item generated by |
| 406 |
/// [`ChangesetIter::next`](ChangesetIter::next). |
| 407 |
// TODO enum ? Delete, Insert, Update, ... |
| 408 |
pub struct ChangesetItem { |
| 409 |
it: *mut ffi::sqlite3_changeset_iter, |
| 410 |
} |
| 411 |
|
| 412 |
impl ChangesetItem { |
| 413 |
/// Obtain conflicting row values |
| 414 |
/// |
| 415 |
/// May only be called with an `SQLITE_CHANGESET_DATA` or |
| 416 |
/// `SQLITE_CHANGESET_CONFLICT` conflict handler callback. |
| 417 |
#[inline] |
| 418 |
pub fn conflict(&self, col: usize) -> Result<ValueRef<'_>> { |
| 419 |
unsafe { |
| 420 |
let mut p_value: *mut ffi::sqlite3_value = ptr::null_mut(); |
| 421 |
check(ffi::sqlite3changeset_conflict( |
| 422 |
self.it, |
| 423 |
col as i32, |
| 424 |
&mut p_value, |
| 425 |
))?; |
| 426 |
if p_value.is_null() { |
| 427 |
Err(Error::InvalidColumnIndex(col)) |
| 428 |
} else { |
| 429 |
Ok(ValueRef::from_value(p_value)) |
| 430 |
} |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
/// Determine the number of foreign key constraint violations |
| 435 |
/// |
| 436 |
/// May only be called with an `SQLITE_CHANGESET_FOREIGN_KEY` conflict |
| 437 |
/// handler callback. |
| 438 |
#[inline] |
| 439 |
pub fn fk_conflicts(&self) -> Result<i32> { |
| 440 |
unsafe { |
| 441 |
let mut p_out = 0; |
| 442 |
check(ffi::sqlite3changeset_fk_conflicts(self.it, &mut p_out))?; |
| 443 |
Ok(p_out) |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
/// Obtain new.* Values |
| 448 |
/// |
| 449 |
/// May only be called if the type of change is either `SQLITE_UPDATE` or |
| 450 |
/// `SQLITE_INSERT`. |
| 451 |
#[inline] |
| 452 |
pub fn new_value(&self, col: usize) -> Result<ValueRef<'_>> { |
| 453 |
unsafe { |
| 454 |
let mut p_value: *mut ffi::sqlite3_value = ptr::null_mut(); |
| 455 |
check(ffi::sqlite3changeset_new(self.it, col as i32, &mut p_value))?; |
| 456 |
if p_value.is_null() { |
| 457 |
Err(Error::InvalidColumnIndex(col)) |
| 458 |
} else { |
| 459 |
Ok(ValueRef::from_value(p_value)) |
| 460 |
} |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
/// Obtain old.* Values |
| 465 |
/// |
| 466 |
/// May only be called if the type of change is either `SQLITE_DELETE` or |
| 467 |
/// `SQLITE_UPDATE`. |
| 468 |
#[inline] |
| 469 |
pub fn old_value(&self, col: usize) -> Result<ValueRef<'_>> { |
| 470 |
unsafe { |
| 471 |
let mut p_value: *mut ffi::sqlite3_value = ptr::null_mut(); |
| 472 |
check(ffi::sqlite3changeset_old(self.it, col as i32, &mut p_value))?; |
| 473 |
if p_value.is_null() { |
| 474 |
Err(Error::InvalidColumnIndex(col)) |
| 475 |
} else { |
| 476 |
Ok(ValueRef::from_value(p_value)) |
| 477 |
} |
| 478 |
} |
| 479 |
} |
| 480 |
|
| 481 |
/// Obtain the current operation |
| 482 |
#[inline] |
| 483 |
pub fn op(&self) -> Result<Operation<'_>> { |
| 484 |
let mut number_of_columns = 0; |
| 485 |
let mut code = 0; |
| 486 |
let mut indirect = 0; |
| 487 |
let tab = unsafe { |
| 488 |
let mut pz_tab: *const c_char = ptr::null(); |
| 489 |
check(ffi::sqlite3changeset_op( |
| 490 |
self.it, |
| 491 |
&mut pz_tab, |
| 492 |
&mut number_of_columns, |
| 493 |
&mut code, |
| 494 |
&mut indirect, |
| 495 |
))?; |
| 496 |
CStr::from_ptr(pz_tab) |
| 497 |
}; |
| 498 |
let table_name = tab.to_str()?; |
| 499 |
Ok(Operation { |
| 500 |
table_name, |
| 501 |
number_of_columns, |
| 502 |
code: Action::from(code), |
| 503 |
indirect: indirect != 0, |
| 504 |
}) |
| 505 |
} |
| 506 |
|
| 507 |
/// Obtain the primary key definition of a table |
| 508 |
#[inline] |
| 509 |
pub fn pk(&self) -> Result<&[u8]> { |
| 510 |
let mut number_of_columns = 0; |
| 511 |
unsafe { |
| 512 |
let mut pks: *mut c_uchar = ptr::null_mut(); |
| 513 |
check(ffi::sqlite3changeset_pk( |
| 514 |
self.it, |
| 515 |
&mut pks, |
| 516 |
&mut number_of_columns, |
| 517 |
))?; |
| 518 |
Ok(from_raw_parts(pks, number_of_columns as usize)) |
| 519 |
} |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
/// Used to combine two or more changesets or |
| 524 |
/// patchsets |
| 525 |
pub struct Changegroup { |
| 526 |
cg: *mut ffi::sqlite3_changegroup, |
| 527 |
} |
| 528 |
|
| 529 |
impl Changegroup { |
| 530 |
/// Create a new change group. |
| 531 |
#[inline] |
| 532 |
pub fn new() -> Result<Self> { |
| 533 |
let mut cg = ptr::null_mut(); |
| 534 |
check(unsafe { ffi::sqlite3changegroup_new(&mut cg) })?; |
| 535 |
Ok(Changegroup { cg }) |
| 536 |
} |
| 537 |
|
| 538 |
/// Add a changeset |
| 539 |
#[inline] |
| 540 |
pub fn add(&mut self, cs: &Changeset) -> Result<()> { |
| 541 |
check(unsafe { ffi::sqlite3changegroup_add(self.cg, cs.n, cs.cs) }) |
| 542 |
} |
| 543 |
|
| 544 |
/// Add a changeset read from `input` to this change group. |
| 545 |
#[inline] |
| 546 |
pub fn add_stream(&mut self, input: &mut dyn Read) -> Result<()> { |
| 547 |
let input_ref = &input; |
| 548 |
check(unsafe { |
| 549 |
ffi::sqlite3changegroup_add_strm( |
| 550 |
self.cg, |
| 551 |
Some(x_input), |
| 552 |
input_ref as *const &mut dyn Read as *mut c_void, |
| 553 |
) |
| 554 |
}) |
| 555 |
} |
| 556 |
|
| 557 |
/// Obtain a composite Changeset |
| 558 |
#[inline] |
| 559 |
pub fn output(&mut self) -> Result<Changeset> { |
| 560 |
let mut n = 0; |
| 561 |
let mut output: *mut c_void = ptr::null_mut(); |
| 562 |
check(unsafe { ffi::sqlite3changegroup_output(self.cg, &mut n, &mut output) })?; |
| 563 |
Ok(Changeset { cs: output, n }) |
| 564 |
} |
| 565 |
|
| 566 |
/// Write the combined set of changes to `output`. |
| 567 |
#[inline] |
| 568 |
pub fn output_strm(&mut self, output: &mut dyn Write) -> Result<()> { |
| 569 |
let output_ref = &output; |
| 570 |
check(unsafe { |
| 571 |
ffi::sqlite3changegroup_output_strm( |
| 572 |
self.cg, |
| 573 |
Some(x_output), |
| 574 |
output_ref as *const &mut dyn Write as *mut c_void, |
| 575 |
) |
| 576 |
}) |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
impl Drop for Changegroup { |
| 581 |
#[inline] |
| 582 |
fn drop(&mut self) { |
| 583 |
unsafe { |
| 584 |
ffi::sqlite3changegroup_delete(self.cg); |
| 585 |
} |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
impl Connection { |
| 590 |
/// Apply a changeset to a database |
| 591 |
pub fn apply<F, C>(&self, cs: &Changeset, filter: Option<F>, conflict: C) -> Result<()> |
| 592 |
where |
| 593 |
F: Fn(&str) -> bool + Send + 'static, |
| 594 |
C: Fn(ConflictType, ChangesetItem) -> ConflictAction + Send + 'static, |
| 595 |
{ |
| 596 |
let db = self.db.borrow_mut().db; |
| 597 |
|
| 598 |
let filtered = filter.is_some(); |
| 599 |
let tuple = &mut (filter, conflict); |
| 600 |
check(unsafe { |
| 601 |
if filtered { |
| 602 |
ffi::sqlite3changeset_apply( |
| 603 |
db, |
| 604 |
cs.n, |
| 605 |
cs.cs, |
| 606 |
Some(call_filter::<F, C>), |
| 607 |
Some(call_conflict::<F, C>), |
| 608 |
tuple as *mut (Option<F>, C) as *mut c_void, |
| 609 |
) |
| 610 |
} else { |
| 611 |
ffi::sqlite3changeset_apply( |
| 612 |
db, |
| 613 |
cs.n, |
| 614 |
cs.cs, |
| 615 |
None, |
| 616 |
Some(call_conflict::<F, C>), |
| 617 |
tuple as *mut (Option<F>, C) as *mut c_void, |
| 618 |
) |
| 619 |
} |
| 620 |
}) |
| 621 |
} |
| 622 |
|
| 623 |
/// Apply a changeset to a database |
| 624 |
pub fn apply_strm<F, C>( |
| 625 |
&self, |
| 626 |
input: &mut dyn Read, |
| 627 |
filter: Option<F>, |
| 628 |
conflict: C, |
| 629 |
) -> Result<()> |
| 630 |
where |
| 631 |
F: Fn(&str) -> bool + Send + 'static, |
| 632 |
C: Fn(ConflictType, ChangesetItem) -> ConflictAction + Send + 'static, |
| 633 |
{ |
| 634 |
let input_ref = &input; |
| 635 |
let db = self.db.borrow_mut().db; |
| 636 |
|
| 637 |
let filtered = filter.is_some(); |
| 638 |
let tuple = &mut (filter, conflict); |
| 639 |
check(unsafe { |
| 640 |
if filtered { |
| 641 |
ffi::sqlite3changeset_apply_strm( |
| 642 |
db, |
| 643 |
Some(x_input), |
| 644 |
input_ref as *const &mut dyn Read as *mut c_void, |
| 645 |
Some(call_filter::<F, C>), |
| 646 |
Some(call_conflict::<F, C>), |
| 647 |
tuple as *mut (Option<F>, C) as *mut c_void, |
| 648 |
) |
| 649 |
} else { |
| 650 |
ffi::sqlite3changeset_apply_strm( |
| 651 |
db, |
| 652 |
Some(x_input), |
| 653 |
input_ref as *const &mut dyn Read as *mut c_void, |
| 654 |
None, |
| 655 |
Some(call_conflict::<F, C>), |
| 656 |
tuple as *mut (Option<F>, C) as *mut c_void, |
| 657 |
) |
| 658 |
} |
| 659 |
}) |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
/// Constants passed to the conflict handler |
| 664 |
/// See [here](https://sqlite.org/session.html#SQLITE_CHANGESET_CONFLICT) for details. |
| 665 |
#[allow(missing_docs)] |
| 666 |
#[repr(i32)] |
| 667 |
#[derive(Debug, PartialEq, Eq)] |
| 668 |
#[non_exhaustive] |
| 669 |
pub enum ConflictType { |
| 670 |
UNKNOWN = -1, |
| 671 |
SQLITE_CHANGESET_DATA = ffi::SQLITE_CHANGESET_DATA, |
| 672 |
SQLITE_CHANGESET_NOTFOUND = ffi::SQLITE_CHANGESET_NOTFOUND, |
| 673 |
SQLITE_CHANGESET_CONFLICT = ffi::SQLITE_CHANGESET_CONFLICT, |
| 674 |
SQLITE_CHANGESET_CONSTRAINT = ffi::SQLITE_CHANGESET_CONSTRAINT, |
| 675 |
SQLITE_CHANGESET_FOREIGN_KEY = ffi::SQLITE_CHANGESET_FOREIGN_KEY, |
| 676 |
} |
| 677 |
impl From<i32> for ConflictType { |
| 678 |
fn from(code: i32) -> ConflictType { |
| 679 |
match code { |
| 680 |
ffi::SQLITE_CHANGESET_DATA => ConflictType::SQLITE_CHANGESET_DATA, |
| 681 |
ffi::SQLITE_CHANGESET_NOTFOUND => ConflictType::SQLITE_CHANGESET_NOTFOUND, |
| 682 |
ffi::SQLITE_CHANGESET_CONFLICT => ConflictType::SQLITE_CHANGESET_CONFLICT, |
| 683 |
ffi::SQLITE_CHANGESET_CONSTRAINT => ConflictType::SQLITE_CHANGESET_CONSTRAINT, |
| 684 |
ffi::SQLITE_CHANGESET_FOREIGN_KEY => ConflictType::SQLITE_CHANGESET_FOREIGN_KEY, |
| 685 |
_ => ConflictType::UNKNOWN, |
| 686 |
} |
| 687 |
} |
| 688 |
} |
| 689 |
|
| 690 |
/// Constants returned by the conflict handler |
| 691 |
/// See [here](https://sqlite.org/session.html#SQLITE_CHANGESET_ABORT) for details. |
| 692 |
#[allow(missing_docs)] |
| 693 |
#[repr(i32)] |
| 694 |
#[derive(Debug, PartialEq, Eq)] |
| 695 |
#[non_exhaustive] |
| 696 |
pub enum ConflictAction { |
| 697 |
SQLITE_CHANGESET_OMIT = ffi::SQLITE_CHANGESET_OMIT, |
| 698 |
SQLITE_CHANGESET_REPLACE = ffi::SQLITE_CHANGESET_REPLACE, |
| 699 |
SQLITE_CHANGESET_ABORT = ffi::SQLITE_CHANGESET_ABORT, |
| 700 |
} |
| 701 |
|
| 702 |
unsafe extern "C" fn call_filter<F, C>(p_ctx: *mut c_void, tbl_str: *const c_char) -> c_int |
| 703 |
where |
| 704 |
F: Fn(&str) -> bool + Send + 'static, |
| 705 |
C: Fn(ConflictType, ChangesetItem) -> ConflictAction + Send + 'static, |
| 706 |
{ |
| 707 |
let tbl_name = CStr::from_ptr(tbl_str).to_str(); |
| 708 |
c_int::from( |
| 709 |
catch_unwind(|| { |
| 710 |
let tuple: *mut (Option<F>, C) = p_ctx.cast::<(Option<F>, C)>(); |
| 711 |
if let Some(ref filter) = (*tuple).0 { |
| 712 |
filter(tbl_name.expect("illegal table name")) |
| 713 |
} else { |
| 714 |
true |
| 715 |
} |
| 716 |
}) |
| 717 |
.unwrap_or_default(), |
| 718 |
) |
| 719 |
} |
| 720 |
|
| 721 |
unsafe extern "C" fn call_conflict<F, C>( |
| 722 |
p_ctx: *mut c_void, |
| 723 |
e_conflict: c_int, |
| 724 |
p: *mut ffi::sqlite3_changeset_iter, |
| 725 |
) -> c_int |
| 726 |
where |
| 727 |
F: Fn(&str) -> bool + Send + 'static, |
| 728 |
C: Fn(ConflictType, ChangesetItem) -> ConflictAction + Send + 'static, |
| 729 |
{ |
| 730 |
let conflict_type = ConflictType::from(e_conflict); |
| 731 |
let item = ChangesetItem { it: p }; |
| 732 |
if let Ok(action) = catch_unwind(|| { |
| 733 |
let tuple: *mut (Option<F>, C) = p_ctx.cast::<(Option<F>, C)>(); |
| 734 |
(*tuple).1(conflict_type, item) |
| 735 |
}) { |
| 736 |
action as c_int |
| 737 |
} else { |
| 738 |
ffi::SQLITE_CHANGESET_ABORT |
| 739 |
} |
| 740 |
} |
| 741 |
|
| 742 |
unsafe extern "C" fn x_input(p_in: *mut c_void, data: *mut c_void, len: *mut c_int) -> c_int { |
| 743 |
if p_in.is_null() { |
| 744 |
return ffi::SQLITE_MISUSE; |
| 745 |
} |
| 746 |
let bytes: &mut [u8] = from_raw_parts_mut(data as *mut u8, *len as usize); |
| 747 |
let input = p_in as *mut &mut dyn Read; |
| 748 |
match (*input).read(bytes) { |
| 749 |
Ok(n) => { |
| 750 |
*len = n as i32; // TODO Validate: n = 0 may not mean the reader will always no longer be able to |
| 751 |
// produce bytes. |
| 752 |
ffi::SQLITE_OK |
| 753 |
} |
| 754 |
Err(_) => ffi::SQLITE_IOERR_READ, // TODO check if err is a (ru)sqlite Error => propagate |
| 755 |
} |
| 756 |
} |
| 757 |
|
| 758 |
unsafe extern "C" fn x_output(p_out: *mut c_void, data: *const c_void, len: c_int) -> c_int { |
| 759 |
if p_out.is_null() { |
| 760 |
return ffi::SQLITE_MISUSE; |
| 761 |
} |
| 762 |
// The sessions module never invokes an xOutput callback with the third |
| 763 |
// parameter set to a value less than or equal to zero. |
| 764 |
let bytes: &[u8] = from_raw_parts(data as *const u8, len as usize); |
| 765 |
let output = p_out as *mut &mut dyn Write; |
| 766 |
match (*output).write_all(bytes) { |
| 767 |
Ok(_) => ffi::SQLITE_OK, |
| 768 |
Err(_) => ffi::SQLITE_IOERR_WRITE, // TODO check if err is a (ru)sqlite Error => propagate |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
#[cfg(test)] |
| 773 |
mod test { |
| 774 |
use fallible_streaming_iterator::FallibleStreamingIterator; |
| 775 |
use std::io::Read; |
| 776 |
use std::sync::atomic::{AtomicBool, Ordering}; |
| 777 |
|
| 778 |
use super::{Changeset, ChangesetIter, ConflictAction, ConflictType, Session}; |
| 779 |
use crate::hooks::Action; |
| 780 |
use crate::{Connection, Result}; |
| 781 |
|
| 782 |
fn one_changeset_insert() -> Result<Changeset> { |
| 783 |
let db = Connection::open_in_memory()?; |
| 784 |
db.execute_batch("CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL);")?; |
| 785 |
|
| 786 |
let mut session = Session::new(&db)?; |
| 787 |
assert!(session.is_empty()); |
| 788 |
|
| 789 |
session.attach(None)?; |
| 790 |
db.execute("INSERT INTO foo (t) VALUES (?1);", ["bar"])?; |
| 791 |
|
| 792 |
session.changeset() |
| 793 |
} |
| 794 |
|
| 795 |
fn one_changeset_update() -> Result<Changeset> { |
| 796 |
let db = Connection::open_in_memory()?; |
| 797 |
db.execute_batch( |
| 798 |
"CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL, i INTEGER NOT NULL DEFAULT 0);", |
| 799 |
)?; |
| 800 |
db.execute_batch("INSERT INTO foo (t) VALUES ('bar');")?; |
| 801 |
|
| 802 |
let mut session = Session::new(&db)?; |
| 803 |
session.attach(None)?; |
| 804 |
db.execute("UPDATE foo SET i=100 WHERE t='bar';", [])?; |
| 805 |
|
| 806 |
session.changeset() |
| 807 |
} |
| 808 |
|
| 809 |
fn one_changeset_strm() -> Result<Vec<u8>> { |
| 810 |
let db = Connection::open_in_memory()?; |
| 811 |
db.execute_batch("CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL);")?; |
| 812 |
|
| 813 |
let mut session = Session::new(&db)?; |
| 814 |
assert!(session.is_empty()); |
| 815 |
|
| 816 |
session.attach(None)?; |
| 817 |
db.execute("INSERT INTO foo (t) VALUES (?1);", ["bar"])?; |
| 818 |
|
| 819 |
let mut output = Vec::new(); |
| 820 |
session.changeset_strm(&mut output)?; |
| 821 |
Ok(output) |
| 822 |
} |
| 823 |
|
| 824 |
#[test] |
| 825 |
fn test_changeset() -> Result<()> { |
| 826 |
let changeset = one_changeset_insert()?; |
| 827 |
let mut iter = changeset.iter()?; |
| 828 |
let item = iter.next()?; |
| 829 |
assert!(item.is_some()); |
| 830 |
|
| 831 |
let item = item.unwrap(); |
| 832 |
let op = item.op()?; |
| 833 |
assert_eq!("foo", op.table_name()); |
| 834 |
assert_eq!(1, op.number_of_columns()); |
| 835 |
assert_eq!(Action::SQLITE_INSERT, op.code()); |
| 836 |
assert!(!op.indirect()); |
| 837 |
|
| 838 |
let pk = item.pk()?; |
| 839 |
assert_eq!(&[1], pk); |
| 840 |
|
| 841 |
let new_value = item.new_value(0)?; |
| 842 |
assert_eq!(Ok("bar"), new_value.as_str()); |
| 843 |
Ok(()) |
| 844 |
} |
| 845 |
|
| 846 |
#[test] |
| 847 |
fn test_changeset_strm() -> Result<()> { |
| 848 |
let output = one_changeset_strm()?; |
| 849 |
assert!(!output.is_empty()); |
| 850 |
assert_eq!(14, output.len()); |
| 851 |
|
| 852 |
let input: &mut dyn Read = &mut output.as_slice(); |
| 853 |
let mut iter = ChangesetIter::start_strm(&input)?; |
| 854 |
let item = iter.next()?; |
| 855 |
assert!(item.is_some()); |
| 856 |
Ok(()) |
| 857 |
} |
| 858 |
|
| 859 |
#[test] |
| 860 |
fn test_changeset_values() -> Result<()> { |
| 861 |
let changeset = one_changeset_update()?; |
| 862 |
let mut iter = changeset.iter()?; |
| 863 |
let item = iter.next()?.unwrap(); |
| 864 |
|
| 865 |
let new_value = item.new_value(0); // unchanged |
| 866 |
assert_eq!(Err(crate::Error::InvalidColumnIndex(0)), new_value); |
| 867 |
let new_value = item.new_value(1)?; // updated |
| 868 |
assert_eq!(Ok(100), new_value.as_i64()); |
| 869 |
Ok(()) |
| 870 |
} |
| 871 |
|
| 872 |
#[test] |
| 873 |
fn test_changeset_apply() -> Result<()> { |
| 874 |
let changeset = one_changeset_insert()?; |
| 875 |
|
| 876 |
let db = Connection::open_in_memory()?; |
| 877 |
db.execute_batch("CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL);")?; |
| 878 |
|
| 879 |
static CALLED: AtomicBool = AtomicBool::new(false); |
| 880 |
db.apply( |
| 881 |
&changeset, |
| 882 |
None::<fn(&str) -> bool>, |
| 883 |
|_conflict_type, _item| { |
| 884 |
CALLED.store(true, Ordering::Relaxed); |
| 885 |
ConflictAction::SQLITE_CHANGESET_OMIT |
| 886 |
}, |
| 887 |
)?; |
| 888 |
|
| 889 |
assert!(!CALLED.load(Ordering::Relaxed)); |
| 890 |
let check = db.query_row("SELECT 1 FROM foo WHERE t = ?1", ["bar"], |row| { |
| 891 |
row.get::<_, i32>(0) |
| 892 |
})?; |
| 893 |
assert_eq!(1, check); |
| 894 |
|
| 895 |
// conflict expected when same changeset applied again on the same db |
| 896 |
db.apply( |
| 897 |
&changeset, |
| 898 |
None::<fn(&str) -> bool>, |
| 899 |
|conflict_type, item| { |
| 900 |
CALLED.store(true, Ordering::Relaxed); |
| 901 |
assert_eq!(ConflictType::SQLITE_CHANGESET_CONFLICT, conflict_type); |
| 902 |
let conflict = item.conflict(0).unwrap(); |
| 903 |
assert_eq!(Ok("bar"), conflict.as_str()); |
| 904 |
ConflictAction::SQLITE_CHANGESET_OMIT |
| 905 |
}, |
| 906 |
)?; |
| 907 |
assert!(CALLED.load(Ordering::Relaxed)); |
| 908 |
Ok(()) |
| 909 |
} |
| 910 |
|
| 911 |
#[test] |
| 912 |
fn test_changeset_apply_strm() -> Result<()> { |
| 913 |
let output = one_changeset_strm()?; |
| 914 |
|
| 915 |
let db = Connection::open_in_memory()?; |
| 916 |
db.execute_batch("CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL);")?; |
| 917 |
|
| 918 |
let mut input = output.as_slice(); |
| 919 |
db.apply_strm( |
| 920 |
&mut input, |
| 921 |
None::<fn(&str) -> bool>, |
| 922 |
|_conflict_type, _item| ConflictAction::SQLITE_CHANGESET_OMIT, |
| 923 |
)?; |
| 924 |
|
| 925 |
let check = db.query_row("SELECT 1 FROM foo WHERE t = ?1", ["bar"], |row| { |
| 926 |
row.get::<_, i32>(0) |
| 927 |
})?; |
| 928 |
assert_eq!(1, check); |
| 929 |
Ok(()) |
| 930 |
} |
| 931 |
|
| 932 |
#[test] |
| 933 |
fn test_session_empty() -> Result<()> { |
| 934 |
let db = Connection::open_in_memory()?; |
| 935 |
db.execute_batch("CREATE TABLE foo(t TEXT PRIMARY KEY NOT NULL);")?; |
| 936 |
|
| 937 |
let mut session = Session::new(&db)?; |
| 938 |
assert!(session.is_empty()); |
| 939 |
|
| 940 |
session.attach(None)?; |
| 941 |
db.execute("INSERT INTO foo (t) VALUES (?1);", ["bar"])?; |
| 942 |
|
| 943 |
assert!(!session.is_empty()); |
| 944 |
Ok(()) |
| 945 |
} |
| 946 |
|
| 947 |
#[test] |
| 948 |
fn test_session_set_enabled() -> Result<()> { |
| 949 |
let db = Connection::open_in_memory()?; |
| 950 |
|
| 951 |
let mut session = Session::new(&db)?; |
| 952 |
assert!(session.is_enabled()); |
| 953 |
session.set_enabled(false); |
| 954 |
assert!(!session.is_enabled()); |
| 955 |
Ok(()) |
| 956 |
} |
| 957 |
|
| 958 |
#[test] |
| 959 |
fn test_session_set_indirect() -> Result<()> { |
| 960 |
let db = Connection::open_in_memory()?; |
| 961 |
|
| 962 |
let mut session = Session::new(&db)?; |
| 963 |
assert!(!session.is_indirect()); |
| 964 |
session.set_indirect(true); |
| 965 |
assert!(session.is_indirect()); |
| 966 |
Ok(()) |
| 967 |
} |
| 968 |
} |