|
| 1 | +extern crate alloc; |
| 2 | + |
| 3 | +use alloc::format; |
| 4 | +use alloc::string::{String, ToString}; |
| 5 | +use core::ffi::c_int; |
| 6 | +use core::slice; |
| 7 | + |
| 8 | +use sqlite::ResultCode; |
| 9 | +use sqlite_nostd as sqlite; |
| 10 | +use sqlite_nostd::{Connection, Context}; |
| 11 | + |
| 12 | +use crate::create_sqlite_optional_text_fn; |
| 13 | +use crate::create_sqlite_text_fn; |
| 14 | +use crate::error::SQLiteError; |
| 15 | + |
| 16 | +fn powersync_client_id_impl( |
| 17 | + ctx: *mut sqlite::context, |
| 18 | + _args: &[*mut sqlite::value], |
| 19 | +) -> Result<String, SQLiteError> { |
| 20 | + let db = ctx.db_handle(); |
| 21 | + |
| 22 | + // language=SQLite |
| 23 | + let statement = db.prepare_v2("select value from ps_kv where key = 'client_id'")?; |
| 24 | + |
| 25 | + if statement.step()? == ResultCode::ROW { |
| 26 | + let client_id = statement.column_text(0)?; |
| 27 | + return Ok(client_id.to_string()); |
| 28 | + } else { |
| 29 | + return Err(SQLiteError( |
| 30 | + ResultCode::ABORT, |
| 31 | + Some(format!("No client_id found in ps_kv")), |
| 32 | + )); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +create_sqlite_text_fn!( |
| 37 | + powersync_client_id, |
| 38 | + powersync_client_id_impl, |
| 39 | + "powersync_last_synced_at" |
| 40 | +); |
| 41 | + |
| 42 | +fn powersync_last_synced_at_impl( |
| 43 | + ctx: *mut sqlite::context, |
| 44 | + _args: &[*mut sqlite::value], |
| 45 | +) -> Result<Option<String>, SQLiteError> { |
| 46 | + let db = ctx.db_handle(); |
| 47 | + |
| 48 | + // language=SQLite |
| 49 | + let statement = db.prepare_v2("select value from ps_kv where key = 'last_synced_at'")?; |
| 50 | + |
| 51 | + if statement.step()? == ResultCode::ROW { |
| 52 | + let client_id = statement.column_text(0)?; |
| 53 | + return Ok(Some(client_id.to_string())); |
| 54 | + } else { |
| 55 | + return Ok(None); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +create_sqlite_optional_text_fn!( |
| 60 | + powersync_last_synced_at, |
| 61 | + powersync_last_synced_at_impl, |
| 62 | + "powersync_last_synced_at" |
| 63 | +); |
| 64 | + |
| 65 | +pub fn register(db: *mut sqlite::sqlite3) -> Result<(), ResultCode> { |
| 66 | + db.create_function_v2( |
| 67 | + "powersync_client_id", |
| 68 | + 0, |
| 69 | + sqlite::UTF8 | sqlite::DETERMINISTIC, |
| 70 | + None, |
| 71 | + Some(powersync_client_id), |
| 72 | + None, |
| 73 | + None, |
| 74 | + None, |
| 75 | + )?; |
| 76 | + db.create_function_v2( |
| 77 | + "powersync_last_synced_at", |
| 78 | + 0, |
| 79 | + sqlite::UTF8 | sqlite::DETERMINISTIC, |
| 80 | + None, |
| 81 | + Some(powersync_last_synced_at), |
| 82 | + None, |
| 83 | + None, |
| 84 | + None, |
| 85 | + )?; |
| 86 | + |
| 87 | + Ok(()) |
| 88 | +} |
0 commit comments