-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcrud_vtab.rs
239 lines (209 loc) · 6.75 KB
/
crud_vtab.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
extern crate alloc;
use alloc::boxed::Box;
use alloc::string::String;
use core::ffi::{c_char, c_int, c_void};
use core::slice;
use const_format::formatcp;
use sqlite::{Connection, ResultCode, Value};
use sqlite_nostd as sqlite;
use sqlite_nostd::ManagedStmt;
use sqlite_nostd::ResultCode::NULL;
use crate::error::SQLiteError;
use crate::ext::SafeManagedStmt;
use crate::vtab_util::*;
// Structure:
// CREATE TABLE powersync_crud_(data TEXT, options INT HIDDEN);
//
// This is a insert-only virtual table. It generates transaction ids in ps_tx, and inserts data in
// ps_crud(tx_id, data).
//
// Using a virtual table like this allows us to hook into xBegin, xCommit and xRollback to automatically
// increment transaction ids. These are only called when powersync_crud_ is used as part of a transaction,
// meaning there is no transaction increment and no overhead when using local-only tables.
#[repr(C)]
struct VirtualTable {
base: sqlite::vtab,
db: *mut sqlite::sqlite3,
current_tx: Option<i64>,
insert_statement: Option<ManagedStmt>,
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct PowerSyncCrudFlags(pub u32);
extern "C" fn connect(
db: *mut sqlite::sqlite3,
_aux: *mut c_void,
_argc: c_int,
_argv: *const *const c_char,
vtab: *mut *mut sqlite::vtab,
_err: *mut *mut c_char,
) -> c_int {
if let Err(rc) = sqlite::declare_vtab(
db,
"CREATE TABLE powersync_crud_(data TEXT, options INT HIDDEN);",
) {
return rc as c_int;
}
unsafe {
let tab = Box::into_raw(Box::new(VirtualTable {
base: sqlite::vtab {
nRef: 0,
pModule: core::ptr::null(),
zErrMsg: core::ptr::null_mut(),
},
db,
current_tx: None,
insert_statement: None,
}));
*vtab = tab.cast::<sqlite::vtab>();
let _ = sqlite::vtab_config(db, 0);
}
ResultCode::OK as c_int
}
extern "C" fn disconnect(vtab: *mut sqlite::vtab) -> c_int {
unsafe {
drop(Box::from_raw(vtab));
}
ResultCode::OK as c_int
}
fn begin_impl(tab: &mut VirtualTable) -> Result<(), SQLiteError> {
let db = tab.db;
const SQL: &str = formatcp!("\
WITH insertion (tx_id, data) AS (VALUES (?1, ?2))
INSERT INTO ps_crud(tx_id, data)
SELECT * FROM insertion WHERE (?3 & {}) OR data->>'op' != 'PATCH' OR EXISTS (SELECT 1 FROM json_each(data->'data'));
", PowerSyncCrudFlags::FLAG_INCLUDE_EMPTY_UPDATE);
// language=SQLite
let insert_statement = db.prepare_v3(SQL, 0)?;
tab.insert_statement = Some(insert_statement);
// language=SQLite
let statement =
db.prepare_v2("UPDATE ps_tx SET next_tx = next_tx + 1 WHERE id = 1 RETURNING next_tx")?;
if statement.step()? == ResultCode::ROW {
let tx_id = statement.column_int64(0)? - 1;
tab.current_tx = Some(tx_id);
} else {
return Err(SQLiteError::from(ResultCode::ABORT));
}
Ok(())
}
extern "C" fn begin(vtab: *mut sqlite::vtab) -> c_int {
let tab = unsafe { &mut *(vtab.cast::<VirtualTable>()) };
let result = begin_impl(tab);
vtab_result(vtab, result)
}
extern "C" fn commit(vtab: *mut sqlite::vtab) -> c_int {
let tab = unsafe { &mut *(vtab.cast::<VirtualTable>()) };
tab.current_tx = None;
tab.insert_statement = None;
ResultCode::OK as c_int
}
extern "C" fn rollback(vtab: *mut sqlite::vtab) -> c_int {
let tab = unsafe { &mut *(vtab.cast::<VirtualTable>()) };
tab.current_tx = None;
tab.insert_statement = None;
// ps_tx will be rolled back automatically
ResultCode::OK as c_int
}
fn insert_operation(
vtab: *mut sqlite::vtab,
data: &str,
flags: PowerSyncCrudFlags,
) -> Result<(), SQLiteError> {
let tab = unsafe { &mut *(vtab.cast::<VirtualTable>()) };
if tab.current_tx.is_none() {
return Err(SQLiteError(
ResultCode::MISUSE,
Some(String::from("No tx_id")),
));
}
let current_tx = tab.current_tx.unwrap();
// language=SQLite
let statement = tab
.insert_statement
.as_ref()
.ok_or(SQLiteError::from(NULL))?;
statement.bind_int64(1, current_tx)?;
statement.bind_text(2, data, sqlite::Destructor::STATIC)?;
statement.bind_int(3, flags.0 as i32)?;
statement.exec()?;
Ok(())
}
extern "C" fn update(
vtab: *mut sqlite::vtab,
argc: c_int,
argv: *mut *mut sqlite::value,
_p_row_id: *mut sqlite::int64,
) -> c_int {
let args = sqlite::args!(argc, argv);
let rowid = args[0];
return if args.len() == 1 {
// DELETE
ResultCode::MISUSE as c_int
} else if rowid.value_type() == sqlite::ColumnType::Null {
// INSERT
let data = args[2].text();
let flags = match args[3].value_type() {
// We don't ignore empty updates by default.
sqlite_nostd::ColumnType::Null => PowerSyncCrudFlags::default(),
_ => PowerSyncCrudFlags(args[3].int() as u32),
};
let result = insert_operation(vtab, data, flags);
vtab_result(vtab, result)
} else {
// UPDATE - not supported
ResultCode::MISUSE as c_int
} as c_int;
}
// Insert-only virtual table.
// The primary functionality here is in begin, update, commit and rollback.
// connect and disconnect configures the table and allocates the required resources.
static MODULE: sqlite_nostd::module = sqlite_nostd::module {
iVersion: 0,
xCreate: None,
xConnect: Some(connect),
xBestIndex: Some(vtab_no_best_index),
xDisconnect: Some(disconnect),
xDestroy: None,
xOpen: Some(vtab_no_open),
xClose: Some(vtab_no_close),
xFilter: Some(vtab_no_filter),
xNext: Some(vtab_no_next),
xEof: Some(vtab_no_eof),
xColumn: Some(vtab_no_column),
xRowid: Some(vtab_no_rowid),
xUpdate: Some(update),
xBegin: Some(begin),
xSync: None,
xCommit: Some(commit),
xRollback: Some(rollback),
xFindFunction: None,
xRename: None,
xSavepoint: None,
xRelease: None,
xRollbackTo: None,
xShadowName: None,
};
pub fn register(db: *mut sqlite::sqlite3) -> Result<(), ResultCode> {
db.create_module_v2("powersync_crud_", &MODULE, None, None)?;
Ok(())
}
impl PowerSyncCrudFlags {
pub const FLAG_INCLUDE_EMPTY_UPDATE: u32 = 1 << 0;
pub fn set_include_empty_update(&mut self, value: bool) {
if value {
self.0 |= Self::FLAG_INCLUDE_EMPTY_UPDATE;
} else {
self.0 &= !Self::FLAG_INCLUDE_EMPTY_UPDATE;
}
}
pub fn has_include_empty_update(self) -> bool {
self.0 & Self::FLAG_INCLUDE_EMPTY_UPDATE != 0
}
}
impl Default for PowerSyncCrudFlags {
fn default() -> Self {
// For backwards-compatibility, we include empty updates by default.
return Self(Self::FLAG_INCLUDE_EMPTY_UPDATE);
}
}