-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathraw_table.rs
More file actions
358 lines (317 loc) · 11.7 KB
/
raw_table.rs
File metadata and controls
358 lines (317 loc) · 11.7 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use core::{
cell::RefCell,
fmt::{self, Formatter, Write, from_fn},
};
use alloc::{
collections::btree_map::BTreeMap,
format,
rc::Rc,
string::{String, ToString},
vec,
vec::Vec,
};
use powersync_sqlite_nostd::{self as sqlite, Connection, Destructor, ResultCode};
use crate::{
error::PowerSyncError,
schema::{ColumnFilter, PendingStatement, PendingStatementValue, RawTable, SchemaTable},
utils::{InsertIntoCrud, SqlBuffer, WriteType},
views::table_columns_to_json_object,
};
pub struct InferredTableStructure {
pub name: String,
pub columns: Vec<String>,
}
impl InferredTableStructure {
pub fn read_from_database(
table_name: &str,
db: impl Connection,
synced_columns: &Option<ColumnFilter>,
) -> Result<Self, PowerSyncError> {
let stmt = db.prepare_v2("select name from pragma_table_info(?)")?;
stmt.bind_text(1, table_name, Destructor::STATIC)?;
let mut has_id_column = false;
let mut columns = vec![];
while let ResultCode::ROW = stmt.step()? {
let name = stmt.column_text(0)?;
if name == "id" {
has_id_column = true;
} else if let Some(filter) = synced_columns
&& !filter.matches(name)
{
// This column isn't part of the synced columns, skip.
} else {
columns.push(name.to_string());
}
}
if !has_id_column && columns.is_empty() {
Err(PowerSyncError::argument_error(format!(
"Could not find {table_name} in local schema."
)))
} else if !has_id_column {
Err(PowerSyncError::argument_error(format!(
"Table {table_name} has no id column."
)))
} else {
Ok(Self {
name: table_name.to_string(),
columns,
})
}
}
/// Generates a statement of the form `INSERT INTO $tbl ($cols) VALUES (?, ...) ON CONFLICT (id)
/// DO UPDATE SET ...` for the sync client.
pub fn infer_put_stmt(&self) -> PendingStatement {
let mut buffer = SqlBuffer::new();
let mut params = vec![];
buffer.push_str("INSERT INTO ");
let _ = buffer.identifier().write_str(&self.name);
buffer.push_str(" (id");
for column in &self.columns {
buffer.comma();
let _ = buffer.identifier().write_str(column);
}
buffer.push_str(") VALUES (?1");
params.push(PendingStatementValue::Id);
for (i, column) in self.columns.iter().enumerate() {
buffer.comma();
let _ = write!(&mut buffer, "?{}", i + 2);
params.push(PendingStatementValue::Column(column.clone()));
}
buffer.push_str(") ON CONFLICT (id) DO UPDATE SET ");
let mut do_update = buffer.comma_separated();
// Generated an "x" = ? for all synced columns to update them without affecting local-only
// columns.
for (i, column) in self.columns.iter().enumerate() {
let entry = do_update.element();
let _ = entry.identifier().write_str(column);
let _ = write!(entry, " = ?{}", i + 2);
}
PendingStatement {
sql: buffer.sql,
params,
named_parameters_index: None,
}
}
/// Generates a statement of the form `DELETE FROM $tbl WHERE id = ?` for the sync client.
pub fn infer_delete_stmt(&self) -> PendingStatement {
let mut buffer = SqlBuffer::new();
buffer.push_str("DELETE FROM ");
let _ = buffer.identifier().write_str(&self.name);
buffer.push_str(" WHERE id = ?");
PendingStatement {
sql: buffer.sql,
params: vec![PendingStatementValue::Id],
named_parameters_index: None,
}
}
}
/// A cache of inferred raw table schema and associated put and delete statements for `sync_local`.
///
/// This cache avoids having to re-generate statements on every (partial) checkpoint in the sync
/// client.
#[derive(Default)]
pub struct InferredSchemaCache {
entries: RefCell<BTreeMap<String, SchemaCacheEntry>>,
}
impl InferredSchemaCache {
pub fn current_schema_version(db: *mut sqlite::sqlite3) -> Result<usize, PowerSyncError> {
let version = db.prepare_v2("PRAGMA schema_version")?;
version.step()?;
let version = version.column_int64(0) as usize;
Ok(version)
}
pub fn infer_put_statement(
&self,
db: *mut sqlite::sqlite3,
schema_version: usize,
tbl: &RawTable,
) -> Result<Rc<PendingStatement>, PowerSyncError> {
self.with_entry(db, schema_version, tbl, SchemaCacheEntry::put)
}
pub fn infer_delete_statement(
&self,
db: *mut sqlite::sqlite3,
schema_version: usize,
tbl: &RawTable,
) -> Result<Rc<PendingStatement>, PowerSyncError> {
self.with_entry(db, schema_version, tbl, SchemaCacheEntry::delete)
}
fn with_entry(
&self,
db: *mut sqlite::sqlite3,
schema_version: usize,
tbl: &RawTable,
f: impl FnOnce(&mut SchemaCacheEntry) -> Rc<PendingStatement>,
) -> Result<Rc<PendingStatement>, PowerSyncError> {
let mut entries = self.entries.borrow_mut();
if let Some(value) = entries.get_mut(&tbl.name) {
if value.schema_version != schema_version {
// Values are outdated, refresh.
*value = SchemaCacheEntry::infer(db, schema_version, tbl)?;
}
Ok(f(value))
} else {
let mut entry = SchemaCacheEntry::infer(db, schema_version, tbl)?;
let stmt = f(&mut entry);
entries.insert(tbl.name.clone(), entry);
Ok(stmt)
}
}
}
pub struct SchemaCacheEntry {
schema_version: usize,
structure: InferredTableStructure,
put_stmt: Option<Rc<PendingStatement>>,
delete_stmt: Option<Rc<PendingStatement>>,
}
impl SchemaCacheEntry {
fn infer(
db: *mut sqlite::sqlite3,
schema_version: usize,
table: &RawTable,
) -> Result<Self, PowerSyncError> {
let local_table_name = table.require_table_name()?;
let structure = InferredTableStructure::read_from_database(
local_table_name,
db,
&table.schema.synced_columns,
)?;
Ok(Self {
schema_version,
structure,
put_stmt: None,
delete_stmt: None,
})
}
fn put(&mut self) -> Rc<PendingStatement> {
self.put_stmt
.get_or_insert_with(|| Rc::new(self.structure.infer_put_stmt()))
.clone()
}
fn delete(&mut self) -> Rc<PendingStatement> {
self.delete_stmt
.get_or_insert_with(|| Rc::new(self.structure.infer_delete_stmt()))
.clone()
}
}
/// Generates a `CREATE TRIGGER` statement to capture writes on raw tables and to forward them to
/// ps-crud.
pub fn generate_raw_table_trigger(
db: impl Connection,
table: &RawTable,
trigger_name: &str,
write: WriteType,
) -> Result<String, PowerSyncError> {
let local_table_name = table.require_table_name()?;
let synced_columns = &table.schema.synced_columns;
let resolved_table =
InferredTableStructure::read_from_database(local_table_name, db, synced_columns)?;
let as_schema_table = SchemaTable::Raw {
definition: table,
schema: &resolved_table,
};
let mut buffer = SqlBuffer::new();
buffer.create_trigger("", trigger_name);
buffer.trigger_after(write, local_table_name);
// Skip the trigger for writes during sync_local, these aren't crud writes.
buffer.push_str("WHEN NOT powersync_in_sync_operation()");
if write == WriteType::Update && synced_columns.is_some() {
buffer.push_str(" AND\n(");
// If we have a filter for synced columns (instead of syncing all of them), we want to add
// additional WHEN clauses to enesure the trigger runs for updates on those columns only.
for (i, name) in as_schema_table.column_names().enumerate() {
if i != 0 {
buffer.push_str(" OR ");
}
// Generate OLD."column" IS NOT NEW."column"
buffer.push_str("OLD.");
let _ = buffer.identifier().write_str(name);
buffer.push_str(" IS NOT NEW.");
let _ = buffer.identifier().write_str(name);
}
buffer.push_str(")");
}
buffer.push_str(" BEGIN\n");
if table.schema.options.flags.insert_only() {
if write != WriteType::Insert {
// Prevent illegal writes to a table marked as insert-only by raising errors here.
buffer.push_str("SELECT RAISE(FAIL, 'Unexpected update on insert-only table');\n");
} else {
// Write directly to powersync_crud_ to skip writing the $local bucket for insert-only
// tables.
let fragment = table_columns_to_json_object("NEW", &as_schema_table)?;
buffer.powersync_crud_manual_put(&table.name, &fragment);
}
} else {
if write == WriteType::Update {
// Updates must not change the id.
buffer.check_id_not_changed();
}
let json_fragment_new = table_columns_to_json_object("NEW", &as_schema_table)?;
let json_fragment_old = if write == WriteType::Update {
Some(table_columns_to_json_object("OLD", &as_schema_table)?)
} else {
None
};
let write_data = from_fn(|f: &mut Formatter| -> fmt::Result {
write!(f, "json(powersync_diff(")?;
if let Some(ref old) = json_fragment_old {
f.write_str(old)?;
} else {
// We don't have OLD values for inserts, we diff from an empty JSON object
// instead.
f.write_str("'{}'")?;
};
write!(f, ", {json_fragment_new}))")
});
buffer.insert_into_powersync_crud(InsertIntoCrud {
op: write,
table: &as_schema_table,
id_expr: if write == WriteType::Delete {
"OLD.id"
} else {
"NEW.id"
},
type_name: &table.name,
data: match write {
// There is no data for deleted rows.
WriteType::Delete => None,
_ => Some(&write_data),
},
metadata: None::<&'static str>,
})?;
}
buffer.trigger_end();
Ok(buffer.sql)
}
#[cfg(test)]
mod test {
use alloc::{string::ToString, vec};
use crate::schema::{PendingStatementValue, raw_table::InferredTableStructure};
#[test]
fn infer_sync_statements() {
let structure = InferredTableStructure {
name: "tbl".to_string(),
columns: vec!["foo".to_string(), "bar".to_string()],
};
let put = structure.infer_put_stmt();
assert_eq!(
put.sql,
r#"INSERT INTO "tbl" (id, "foo", "bar") VALUES (?1, ?2, ?3) ON CONFLICT (id) DO UPDATE SET "foo" = ?2, "bar" = ?3"#
);
assert_eq!(put.params.len(), 3);
assert!(matches!(put.params[0], PendingStatementValue::Id));
assert!(matches!(
put.params[1],
PendingStatementValue::Column(ref name) if name == "foo"
));
assert!(matches!(
put.params[2],
PendingStatementValue::Column(ref name) if name == "bar"
));
let delete = structure.infer_delete_stmt();
assert_eq!(delete.sql, r#"DELETE FROM "tbl" WHERE id = ?"#);
assert_eq!(delete.params.len(), 1);
assert!(matches!(delete.params[0], PendingStatementValue::Id));
}
}