-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathview_admin.rs
More file actions
272 lines (230 loc) · 7.72 KB
/
view_admin.rs
File metadata and controls
272 lines (230 loc) · 7.72 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
extern crate alloc;
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::ffi::{c_int, c_void};
use powersync_sqlite_nostd as sqlite;
use powersync_sqlite_nostd::{Connection, Context};
use sqlite::{ResultCode, Value};
use crate::error::{PSResult, PowerSyncError};
use crate::migrations::{LATEST_VERSION, powersync_migrate};
use crate::schema::inspection::ExistingView;
use crate::state::DatabaseState;
use crate::utils::SqlBuffer;
use crate::{create_auto_tx_function, create_sqlite_text_fn};
// Used in old down migrations, do not remove.
extern "C" fn powersync_drop_view(
ctx: *mut sqlite::context,
argc: c_int,
argv: *mut *mut sqlite::value,
) {
let args = sqlite::args!(argc, argv);
let name = args[0].text();
if let Err(e) = ExistingView::drop_by_name(ctx.db_handle(), name) {
e.apply_to_ctx("powersync_drop_view", ctx);
}
}
fn powersync_init_impl(
ctx: *mut sqlite::context,
_args: &[*mut sqlite::value],
) -> Result<String, PowerSyncError> {
powersync_migrate(ctx, LATEST_VERSION)?;
Ok(String::from(""))
}
create_auto_tx_function!(powersync_init_tx, powersync_init_impl);
create_sqlite_text_fn!(powersync_init, powersync_init_tx, "powersync_init");
fn powersync_test_migration_impl(
ctx: *mut sqlite::context,
args: &[*mut sqlite::value],
) -> Result<String, PowerSyncError> {
let target_version = args[0].int();
powersync_migrate(ctx, target_version)?;
Ok(String::from(""))
}
create_auto_tx_function!(powersync_test_migration_tx, powersync_test_migration_impl);
create_sqlite_text_fn!(
powersync_test_migration,
powersync_test_migration_tx,
"powersync_test_migration"
);
fn powersync_clear_impl(
ctx: *mut sqlite::context,
args: &[*mut sqlite::value],
) -> Result<String, PowerSyncError> {
let local_db = ctx.db_handle();
let state = unsafe { DatabaseState::from_context(&ctx) };
let flags = PowerSyncClearFlags(args[0].int());
if !flags.soft_clear() {
// With a soft clear, we want to delete public data while keeping internal data around. When
// connect() is called with compatible JWTs yielding a large overlap of buckets, this can
// speed up the next sync.
local_db.exec_safe("DELETE FROM ps_oplog; DELETE FROM ps_buckets")?;
} else {
trigger_resync(local_db, state)?;
local_db.exec_safe("DELETE FROM ps_buckets WHERE name = '$local'")?;
}
// language=SQLite
local_db.exec_safe(
"\
DELETE FROM ps_crud;
DELETE FROM ps_untyped;
DELETE FROM ps_updated_rows;
DELETE FROM ps_kv WHERE key != 'client_id';
DELETE FROM ps_stream_subscriptions;
",
)?;
clear_has_synced(local_db)?;
let table_glob = if flags.clear_local() {
"ps_data_*"
} else {
"ps_data__*"
};
let tables_stmt = local_db
.prepare_v2("SELECT name FROM sqlite_master WHERE type='table' AND name GLOB ?1")?;
tables_stmt.bind_text(1, table_glob, sqlite::Destructor::STATIC)?;
let mut tables: Vec<String> = alloc::vec![];
while tables_stmt.step()? == ResultCode::ROW {
let name = tables_stmt.column_text(0)?;
tables.push(name.to_string());
}
for name in tables {
let quoted = SqlBuffer::quote_identifier(&name);
// The first delete statement deletes a single row, to trigger an update notification for the table.
// The second delete statement uses the truncate optimization to delete the remainder of the data.
let delete_sql = format!(
"\
DELETE FROM {table} WHERE rowid IN (SELECT rowid FROM {table} LIMIT 1);
DELETE FROM {table};",
table = quoted
);
local_db.exec_safe(&delete_sql)?;
}
if let Some(schema) = state.view_schema() {
// Pretend to be in a sync_local step when clearing raw tables. Similar to the case above
// where we delete from the underlying table to sidestep the CRUD trigger, we don't want
// triggers on raw tables to record this delete in ps_crud.
let _skip_crud = state.sync_local_guard();
for raw_table in &schema.raw_tables {
if let Some(stmt) = &raw_table.clear {
local_db.exec_safe(&stmt).map_err(|e| {
PowerSyncError::from_sqlite(
local_db,
e,
format!("Clearing raw table {}", raw_table.name),
)
})?;
}
}
}
Ok(String::from(""))
}
fn trigger_resync(db: *mut sqlite::sqlite3, state: &DatabaseState) -> Result<(), PowerSyncError> {
{
let client = state.sync_client.borrow();
if let Some(client) = client.as_ref()
&& client.has_sync_iteration()
{
return Err(PowerSyncError::argument_error(
"Cannot clear or trigger resync while a sync iteration is active.",
));
}
}
db.exec_safe("UPDATE ps_buckets SET last_applied_op = 0 WHERE name != '$local'")
.into_db_result(db)?;
Ok(Default::default())
}
fn clear_has_synced(db: *mut sqlite::sqlite3) -> Result<(), PowerSyncError> {
db.exec_safe("DELETE FROM ps_sync_state;")?;
db.exec_safe("UPDATE ps_stream_subscriptions SET last_synced_at = NULL")?;
Ok(())
}
fn powersync_trigger_resync_impl(
ctx: *mut sqlite::context,
args: &[*mut sqlite::value],
) -> Result<String, PowerSyncError> {
let local_db = ctx.db_handle();
let state = unsafe { DatabaseState::from_context(&ctx) };
trigger_resync(local_db, state)?;
let clear_progress = args[0].int() != 0;
if clear_progress {
clear_has_synced(local_db)?;
}
Ok(Default::default())
}
create_auto_tx_function!(powersync_trigger_resync_tx, powersync_trigger_resync_impl);
create_sqlite_text_fn!(
powersync_trigger_resync,
powersync_trigger_resync_tx,
"powersync_trigger_resync"
);
#[derive(Clone, Copy)]
struct PowerSyncClearFlags(i32);
impl PowerSyncClearFlags {
const MASK_CLEAR_LOCAL: i32 = 0x01;
const MASK_SOFT_CLEAR: i32 = 0x02;
fn clear_local(self) -> bool {
self.0 & Self::MASK_CLEAR_LOCAL != 0
}
fn soft_clear(self) -> bool {
self.0 & Self::MASK_SOFT_CLEAR != 0
}
}
create_auto_tx_function!(powersync_clear_tx, powersync_clear_impl);
create_sqlite_text_fn!(powersync_clear, powersync_clear_tx, "powersync_clear");
pub fn register(db: *mut sqlite::sqlite3, state: Rc<DatabaseState>) -> Result<(), ResultCode> {
// This entire module is just making it easier to edit sqlite_master using queries.
// Internal function, used exclusively in existing migrations.
db.create_function_v2(
"powersync_drop_view",
1,
sqlite::UTF8,
None,
Some(powersync_drop_view),
None,
None,
None,
)?;
// Initialize the extension internal tables, and start a migration.
db.create_function_v2(
"powersync_init",
0,
sqlite::UTF8,
None,
Some(powersync_init),
None,
None,
None,
)?;
db.create_function_v2(
"powersync_test_migration",
1,
sqlite::UTF8,
None,
Some(powersync_test_migration),
None,
None,
None,
)?;
db.create_function_v2(
"powersync_clear",
1,
sqlite::UTF8,
Some(Rc::into_raw(state.clone()) as *mut c_void),
Some(powersync_clear),
None,
None,
Some(DatabaseState::destroy_rc),
)?;
db.create_function_v2(
"powersync_trigger_resync",
1,
sqlite::UTF8,
Some(Rc::into_raw(state) as *mut c_void),
Some(powersync_trigger_resync),
None,
None,
Some(DatabaseState::destroy_rc),
)?;
Ok(())
}