orbis-plugin-api 1.0.0

Public API for developing Orbis plugins
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Database access for plugins.
//!
//! Provides type-safe database querying and mutation.
//!
//! # Example
//!
//! ```rust,ignore
//! use orbis_plugin_api::sdk::db;
//!
//! // Query with parameters
//! let users = db::query::<User>(
//!     "SELECT * FROM users WHERE active = ? LIMIT ?",
//!     &[&true, &10]
//! )?;
//!
//! // Execute a mutation
//! let rows_affected = db::execute(
//!     "UPDATE users SET last_login = ? WHERE id = ?",
//!     &[&now, &user_id]
//! )?;
//! ```

use super::error::{Error, Result};
use serde::{de::DeserializeOwned, Deserialize, Serialize};

/// A value that can be used as a database parameter
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DbValue {
    /// Null value
    Null,
    /// Boolean value
    Bool(bool),
    /// Integer value
    Int(i64),
    /// Float value
    Float(f64),
    /// String value
    String(String),
    /// Binary data
    Bytes(Vec<u8>),
    /// JSON value
    Json(serde_json::Value),
}

impl From<()> for DbValue {
    fn from(_: ()) -> Self {
        Self::Null
    }
}

impl From<bool> for DbValue {
    fn from(v: bool) -> Self {
        Self::Bool(v)
    }
}

impl From<i32> for DbValue {
    fn from(v: i32) -> Self {
        Self::Int(i64::from(v))
    }
}

impl From<i64> for DbValue {
    fn from(v: i64) -> Self {
        Self::Int(v)
    }
}

impl From<f64> for DbValue {
    fn from(v: f64) -> Self {
        Self::Float(v)
    }
}

impl From<&str> for DbValue {
    fn from(v: &str) -> Self {
        Self::String(v.to_string())
    }
}

impl From<String> for DbValue {
    fn from(v: String) -> Self {
        Self::String(v)
    }
}

impl From<Vec<u8>> for DbValue {
    fn from(v: Vec<u8>) -> Self {
        Self::Bytes(v)
    }
}

impl From<serde_json::Value> for DbValue {
    fn from(v: serde_json::Value) -> Self {
        Self::Json(v)
    }
}

/// Trait for types that can be converted to database parameters
pub trait ToDbParams {
    fn to_db_params(&self) -> Vec<DbValue>;
}

impl ToDbParams for () {
    fn to_db_params(&self) -> Vec<DbValue> {
        vec![]
    }
}

impl<T: Into<DbValue> + Clone> ToDbParams for &[T] {
    fn to_db_params(&self) -> Vec<DbValue> {
        self.iter().map(|v| v.clone().into()).collect()
    }
}

impl<T: Into<DbValue> + Clone, const N: usize> ToDbParams for [T; N] {
    fn to_db_params(&self) -> Vec<DbValue> {
        self.iter().map(|v| v.clone().into()).collect()
    }
}

impl ToDbParams for Vec<DbValue> {
    fn to_db_params(&self) -> Vec<DbValue> {
        self.clone()
    }
}

/// A row from a database query result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DbRow {
    /// Column values by name
    #[serde(flatten)]
    pub columns: std::collections::HashMap<String, serde_json::Value>,
}

impl DbRow {
    /// Get a column value by name
    #[inline]
    pub fn get(&self, name: &str) -> Option<&serde_json::Value> {
        self.columns.get(name)
    }

    /// Get a column value as a specific type
    pub fn get_as<T: DeserializeOwned>(&self, name: &str) -> Result<Option<T>> {
        match self.columns.get(name) {
            Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(Error::from),
            None => Ok(None),
        }
    }

    /// Get a required column value
    pub fn get_required<T: DeserializeOwned>(&self, name: &str) -> Result<T> {
        self.get_as(name)?
            .ok_or_else(|| Error::database(format!("Missing column: {}", name)))
    }

    /// Try to convert the row to a typed struct
    pub fn into_typed<T: DeserializeOwned>(self) -> Result<T> {
        let value = serde_json::to_value(self.columns)?;
        serde_json::from_value(value).map_err(Error::from)
    }
}

/// Database query request
#[derive(Debug, Serialize)]
#[allow(dead_code)]
struct QueryRequest<'a> {
    sql: &'a str,
    params: Vec<DbValue>,
}

/// Database query response
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct QueryResponse {
    rows: Vec<DbRow>,
    #[serde(default)]
    error: Option<String>,
}

/// Database execute response
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct ExecuteResponse {
    rows_affected: i64,
    #[serde(default)]
    last_insert_id: Option<i64>,
    #[serde(default)]
    error: Option<String>,
}

/// Execute a database query and return typed results.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Deserialize)]
/// struct User {
///     id: i64,
///     name: String,
///     email: String,
/// }
///
/// let users = db::query::<User>(
///     "SELECT id, name, email FROM users WHERE active = ?",
///     &[true]
/// )?;
/// ```
#[cfg(target_arch = "wasm32")]
pub fn query<T: DeserializeOwned>(sql: &str, params: impl ToDbParams) -> Result<Vec<T>> {
    let request = QueryRequest {
        sql,
        params: params.to_db_params(),
    };

    let request_json = serde_json::to_vec(&request)?;

    let result_ptr = unsafe {
        super::ffi::db_query(
            sql.as_ptr() as i32,
            sql.len() as i32,
            request_json.as_ptr() as i32,
            request_json.len() as i32,
        )
    };

    if result_ptr == 0 {
        return Err(Error::database("Database query failed"));
    }

    let result_bytes = unsafe { super::ffi::read_length_prefixed(result_ptr) };
    let response: QueryResponse = serde_json::from_slice(&result_bytes)?;

    if let Some(err) = response.error {
        return Err(Error::database(err));
    }

    response
        .rows
        .into_iter()
        .map(|row| row.into_typed())
        .collect()
}

/// Execute a database query (non-WASM stub)
#[cfg(not(target_arch = "wasm32"))]
pub fn query<T: DeserializeOwned>(_sql: &str, _params: impl ToDbParams) -> Result<Vec<T>> {
    Ok(vec![])
}

/// Execute a query and return raw rows (for dynamic queries)
#[cfg(target_arch = "wasm32")]
pub fn query_raw(sql: &str, params: impl ToDbParams) -> Result<Vec<DbRow>> {
    let request = QueryRequest {
        sql,
        params: params.to_db_params(),
    };

    let request_json = serde_json::to_vec(&request)?;

    let result_ptr = unsafe {
        super::ffi::db_query(
            sql.as_ptr() as i32,
            sql.len() as i32,
            request_json.as_ptr() as i32,
            request_json.len() as i32,
        )
    };

    if result_ptr == 0 {
        return Err(Error::database("Database query failed"));
    }

    let result_bytes = unsafe { super::ffi::read_length_prefixed(result_ptr) };
    let response: QueryResponse = serde_json::from_slice(&result_bytes)?;

    if let Some(err) = response.error {
        return Err(Error::database(err));
    }

    Ok(response.rows)
}

/// Execute a query and return raw rows (non-WASM stub)
#[cfg(not(target_arch = "wasm32"))]
pub fn query_raw(_sql: &str, _params: impl ToDbParams) -> Result<Vec<DbRow>> {
    Ok(vec![])
}

/// Query for a single row
pub fn query_one<T: DeserializeOwned>(sql: &str, params: impl ToDbParams) -> Result<Option<T>> {
    let results = query::<T>(sql, params)?;
    Ok(results.into_iter().next())
}

/// Query for a single required row
pub fn query_one_required<T: DeserializeOwned>(sql: &str, params: impl ToDbParams) -> Result<T> {
    query_one::<T>(sql, params)?.ok_or_else(|| Error::not_found("No rows found"))
}

/// Query for a single scalar value
pub fn query_scalar<T: DeserializeOwned>(sql: &str, params: impl ToDbParams) -> Result<Option<T>> {
    let rows = query_raw(sql, params)?;
    if let Some(row) = rows.into_iter().next() {
        if let Some((_, value)) = row.columns.into_iter().next() {
            return Ok(Some(serde_json::from_value(value)?));
        }
    }
    Ok(None)
}

/// Execute a database mutation (INSERT, UPDATE, DELETE).
///
/// Returns the number of affected rows.
///
/// # Example
///
/// ```rust,ignore
/// let rows = db::execute(
///     "UPDATE users SET last_login = NOW() WHERE id = ?",
///     &[&user_id]
/// )?;
/// ```
#[cfg(target_arch = "wasm32")]
pub fn execute(sql: &str, params: impl ToDbParams) -> Result<i64> {
    let params_json = serde_json::to_vec(&params.to_db_params())?;

    let result = unsafe {
        super::ffi::db_execute(
            sql.as_ptr() as i32,
            sql.len() as i32,
            params_json.as_ptr() as i32,
            params_json.len() as i32,
        )
    };

    if result < 0 {
        return Err(Error::database("Database execute failed"));
    }

    Ok(i64::from(result))
}

/// Execute a database mutation (non-WASM stub)
#[cfg(not(target_arch = "wasm32"))]
pub fn execute(_sql: &str, _params: impl ToDbParams) -> Result<i64> {
    Ok(0)
}

/// Insert a row and return the last insert ID
#[cfg(target_arch = "wasm32")]
pub fn insert_returning_id(sql: &str, params: impl ToDbParams) -> Result<i64> {
    // For PostgreSQL, append RETURNING id
    let returning_sql = if sql.to_uppercase().contains("RETURNING") {
        sql.to_string()
    } else {
        format!("{} RETURNING id", sql)
    };

    query_scalar::<i64>(&returning_sql, params)?
        .ok_or_else(|| Error::database("Insert did not return an ID"))
}

/// Insert a row and return the last insert ID (non-WASM stub)
#[cfg(not(target_arch = "wasm32"))]
pub fn insert_returning_id(_sql: &str, _params: impl ToDbParams) -> Result<i64> {
    Ok(0)
}

/// Transaction builder for multiple operations
pub struct Transaction {
    operations: Vec<(String, Vec<DbValue>)>,
}

impl Transaction {
    /// Create a new transaction builder
    #[must_use]
    pub const fn new() -> Self {
        Self {
            operations: Vec::new(),
        }
    }

    /// Add an operation to the transaction
    pub fn add(&mut self, sql: impl Into<String>, params: impl ToDbParams) -> &mut Self {
        self.operations.push((sql.into(), params.to_db_params()));
        self
    }

    /// Execute all operations in a transaction
    ///
    /// Note: Actual transaction support depends on host implementation
    pub fn commit(self) -> Result<()> {
        for (sql, params) in self.operations {
            execute(&sql, params.as_slice())?;
        }
        Ok(())
    }
}

impl Default for Transaction {
    fn default() -> Self {
        Self::new()
    }
}

/// Start building a transaction
#[inline]
#[must_use]
pub const fn transaction() -> Transaction {
    Transaction::new()
}