oxibase 0.5.10

Autonomous relational database management system with MVCC, time-travel queries, and full ACID compliance
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// Copyright 2025 Oxibase Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Rhai scripting backend for user-defined functions

use super::ScriptingBackend;
use crate::core::{Error, Result, Value};
use rhai::{Engine, Scope};

/// Rhai scripting backend
pub struct RhaiBackend {
    engine: Engine,
}

impl RhaiBackend {
    /// Create a new Rhai backend
    pub fn new() -> Self {
        let mut engine = Engine::new();

        // Register custom functions for type conversions
        engine.register_fn("to_int", |v: i64| v);
        engine.register_fn("to_float", |v: f64| v);
        engine.register_fn("to_string", |v: String| v);

        engine.register_type_with_name::<NewRowProxy>("NewRowProxy");
        engine.register_indexer_get(|proxy: &mut NewRowProxy, prop: &str| proxy.get(prop));
        engine.register_indexer_set(|proxy: &mut NewRowProxy, prop: &str, val: rhai::Dynamic| {
            proxy.set(prop, val)
        });

        engine.register_type_with_name::<OldRowProxy>("OldRowProxy");
        engine.register_indexer_get(|proxy: &mut OldRowProxy, prop: &str| proxy.get(prop));

        engine.register_fn(
            "get_http_header",
            |header_name: String| -> std::result::Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
                let mut header_value = None;
                crate::functions::context::HTTP_HEADERS.with(|headers| {
                    if let Some(map) = headers.borrow().as_ref() {
                        let search_key = header_name.to_lowercase();
                        for (k, v) in map {
                            if k.to_lowercase() == search_key {
                                header_value = Some(v.clone());
                                break;
                            }
                        }
                    }
                });

                match header_value {
                    Some(v) => Ok(rhai::Dynamic::from(v)),
                    None => Ok(rhai::Dynamic::UNIT),
                }
            },
        );

        engine.register_fn(
            "commit",
            || -> std::result::Result<(), Box<rhai::EvalAltResult>> {
                match crate::functions::backends::commit_transaction() {
                    Ok(_) => Ok(()),
                    Err(e) => Err(e.to_string().into()),
                }
            },
        );

        engine.register_fn(
            "rollback",
            || -> std::result::Result<(), Box<rhai::EvalAltResult>> {
                match crate::functions::backends::rollback_transaction() {
                    Ok(_) => Ok(()),
                    Err(e) => Err(e.to_string().into()),
                }
            },
        );

        engine.register_fn(
            "begin",
            || -> std::result::Result<(), Box<rhai::EvalAltResult>> {
                match crate::functions::backends::begin_transaction() {
                    Ok(_) => Ok(()),
                    Err(e) => Err(e.to_string().into()),
                }
            },
        );

        // Register oxibase module
        let mut oxibase_module = rhai::Module::new();
        oxibase_module.set_native_fn(
            "execute",
            |sql: rhai::ImmutableString| -> std::result::Result<i64, Box<rhai::EvalAltResult>> {
                match crate::functions::backends::execute_sql_query(&sql) {
                    Ok(res) => Ok(res.rows_affected()),
                    Err(e) => Err(e.to_string().into()),
                }
            },
        );
        engine.register_static_module("oxibase", rhai::Shared::new(oxibase_module));

        #[cfg(debug_assertions)]
        #[allow(deprecated)]
        // since there is no standard debugging feature in our workspace, let's use debug build, or just remove the cfg
        engine.register_debugger(
            |_engine, debugger| debugger,
            |context: rhai::EvalContext,
             _event: rhai::debugger::DebuggerEvent,
             _node: rhai::ASTNode,
             _source: Option<&str>,
             pos: rhai::Position| {
                if let Some(line) = pos.line() {
                    if let Some(proc_name) = crate::functions::context::get_current_procedure_name()
                    {
                        if let Some(dc) = crate::functions::context::get_debug_controller() {
                            if dc.has_breakpoint(&proc_name, line) {
                                let mut local_map = serde_json::Map::new();
                                for (k, _, v) in context.scope().iter() {
                                    local_map.insert(
                                        k.to_string(),
                                        serde_json::Value::String(v.to_string()),
                                    );
                                }

                                let _ = dc.pause_execution(
                                    line,
                                    serde_json::Value::Object(local_map),
                                    serde_json::Value::Object(serde_json::Map::new()),
                                );
                            }
                        }
                    }
                }
                Ok(rhai::debugger::DebuggerCommand::Continue)
            },
        );

        Self { engine }
    }
}

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

impl ScriptingBackend for RhaiBackend {
    fn name(&self) -> &'static str {
        "rhai"
    }

    fn supported_languages(&self) -> &[&'static str] {
        &["rhai"]
    }

    fn execute(&self, code: &str, args: &[Value], param_names: &[&str]) -> Result<Value> {
        let mut scope = Scope::new();

        let mut ctx_map = rhai::Map::new();
        crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
            if r.borrow().is_some() {
                ctx_map.insert("new".into(), rhai::Dynamic::from(NewRowProxy));
            }
        });
        crate::functions::backends::triggers::CURRENT_OLD_ROW.with(|r| {
            if r.borrow().is_some() {
                ctx_map.insert("old".into(), rhai::Dynamic::from(OldRowProxy));
            }
        });
        let mut oxibase_map = rhai::Map::new();
        oxibase_map.insert("ctx".into(), rhai::Dynamic::from(ctx_map));
        scope.push("oxibase", oxibase_map);

        // Create arguments array for compatibility
        let mut args_array = rhai::Array::new();
        for arg in args {
            match arg {
                Value::Integer(i) => args_array.push(rhai::Dynamic::from(*i)),
                Value::Float(f) => args_array.push(rhai::Dynamic::from(*f)),
                Value::Text(s) => args_array.push(rhai::Dynamic::from(s.as_ref().to_string())),
                Value::Boolean(b) => args_array.push(rhai::Dynamic::from(*b)),
                _ => return Err(Error::internal("Unsupported argument type for Rhai")),
            };
        }
        scope.push("arguments", args_array);

        // Bind arguments to scope using parameter names
        for (i, arg) in args.iter().enumerate() {
            let var_name = param_names[i];
            match arg {
                Value::Integer(i) => scope.push(var_name, *i),
                Value::Float(f) => scope.push(var_name, *f),
                Value::Text(s) => scope.push(var_name, s.as_ref().to_string()),
                Value::Boolean(b) => scope.push(var_name, *b),
                _ => return Err(Error::internal("Unsupported argument type for Rhai")),
            };
        }

        // Execute the script
        match self
            .engine
            .eval_with_scope::<rhai::Dynamic>(&mut scope, code)
        {
            Ok(result) => {
                // Convert Rhai result back to Value
                if result.is::<i64>() {
                    Ok(Value::Integer(result.cast::<i64>()))
                } else if result.is::<f64>() {
                    Ok(Value::Float(result.cast::<f64>()))
                } else if result.is::<String>() {
                    Ok(Value::Text(result.cast::<String>().into()))
                } else if result.is::<bool>() {
                    Ok(Value::Boolean(result.cast::<bool>()))
                } else if result.is::<()>() {
                    Ok(Value::null_unknown())
                } else {
                    Err(Error::internal("Unsupported return type from Rhai script"))
                }
            }
            Err(e) => Err(Error::internal(format!("Rhai execution error: {}", e))),
        }
    }

    fn validate_code(&self, code: &str) -> Result<()> {
        match self.engine.compile(code) {
            Ok(_) => Ok(()),
            Err(e) => Err(Error::internal(format!("Rhai syntax error: {}", e))),
        }
    }

    fn execute_procedure(
        &self,
        code: &str,
        args: &mut [Value],
        param_names: &[&str],
        _modes: &[&str],
        _runner: Option<&dyn crate::functions::backends::SqlRunner>,
    ) -> Result<()> {
        let mut scope = Scope::new();

        let mut ctx_map = rhai::Map::new();
        crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
            if r.borrow().is_some() {
                ctx_map.insert("new".into(), rhai::Dynamic::from(NewRowProxy));
            }
        });
        crate::functions::backends::triggers::CURRENT_OLD_ROW.with(|r| {
            if r.borrow().is_some() {
                ctx_map.insert("old".into(), rhai::Dynamic::from(OldRowProxy));
            }
        });
        let mut oxibase_map = rhai::Map::new();
        oxibase_map.insert("ctx".into(), rhai::Dynamic::from(ctx_map));
        scope.push("oxibase", oxibase_map);

        // Bind arguments to scope using parameter names
        for (i, arg) in args.iter().enumerate() {
            let var_name = param_names[i];
            match arg {
                Value::Integer(i) => scope.push(var_name, *i),
                Value::Float(f) => scope.push(var_name, *f),
                Value::Text(s) => scope.push(var_name, s.as_ref().to_string()),
                Value::Boolean(b) => scope.push(var_name, *b),
                Value::Null(_) => scope.push(var_name, ()),
                _ => return Err(Error::internal("Unsupported argument type for Rhai")),
            };
        }

        // Execute the script
        match self
            .engine
            .eval_with_scope::<rhai::Dynamic>(&mut scope, code)
        {
            Ok(_) => {
                // Read modified values back from scope
                for (i, arg) in args.iter_mut().enumerate() {
                    let var_name = param_names[i];
                    if let Some(val) = scope.get_value::<rhai::Dynamic>(var_name) {
                        if val.is::<i64>() {
                            *arg = Value::Integer(val.cast::<i64>());
                        } else if val.is::<f64>() {
                            *arg = Value::Float(val.cast::<f64>());
                        } else if val.is::<String>() {
                            *arg = Value::Text(val.cast::<String>().into());
                        } else if val.is::<bool>() {
                            *arg = Value::Boolean(val.cast::<bool>());
                        } else if val.is::<()>() {
                            *arg = Value::null_unknown();
                        }
                    }
                }
                Ok(())
            }
            Err(e) => Err(Error::internal(format!("Rhai execution error: {}", e))),
        }
    }
}
// --- TRIGGER CONTEXT ---

#[derive(Clone)]
pub struct NewRowProxy;

#[derive(Clone)]
pub struct OldRowProxy;

impl NewRowProxy {
    pub fn get(
        &mut self,
        prop: &str,
    ) -> std::result::Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
        let mut val = None;
        let mut found = false;

        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                if let Some(idx) = schema.get_column_index(prop) {
                    found = true;
                    crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                        if let Some(row_ptr) = *r.borrow() {
                            let row = unsafe { &*row_ptr };
                            if let Some(v) = row.get(idx) {
                                val = Some(crate::functions::backends::rhai::value_to_dynamic(v));
                            }
                        }
                    });
                }
            }
        });

        if !found {
            return Err(format!("Column not found: {}", prop).into());
        }

        Ok(val.unwrap_or(rhai::Dynamic::UNIT))
    }

    pub fn set(
        &mut self,
        prop: &str,
        new_val: rhai::Dynamic,
    ) -> std::result::Result<(), Box<rhai::EvalAltResult>> {
        let mut found = false;
        let mut success = false;
        let mut error = None;

        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                if let Some(idx) = schema.get_column_index(prop) {
                    found = true;
                    crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                        if let Some(row_ptr) = *r.borrow_mut() {
                            let row = unsafe { &mut *row_ptr };
                            if let Some(col) = schema.get_column(idx) {
                                match crate::functions::backends::rhai::dynamic_to_value(
                                    new_val.clone(),
                                    col.data_type,
                                ) {
                                    Ok(v) => {
                                        let _ = row.set(idx, v);
                                        success = true;
                                    }
                                    Err(e) => error = Some(e.to_string()),
                                }
                            }
                        }
                    });
                }
            }
        });

        if !found {
            return Err(format!("Column not found: {}", prop).into());
        }
        if let Some(err) = error {
            return Err(err.into());
        }

        Ok(())
    }
}

impl OldRowProxy {
    pub fn get(
        &mut self,
        prop: &str,
    ) -> std::result::Result<rhai::Dynamic, Box<rhai::EvalAltResult>> {
        let mut val = None;
        let mut found = false;

        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                if let Some(idx) = schema.get_column_index(prop) {
                    found = true;
                    crate::functions::backends::triggers::CURRENT_OLD_ROW.with(|r| {
                        if let Some(row_ptr) = *r.borrow() {
                            let row = unsafe { &*row_ptr };
                            if let Some(v) = row.get(idx) {
                                val = Some(crate::functions::backends::rhai::value_to_dynamic(v));
                            }
                        }
                    });
                }
            }
        });

        if !found {
            return Err(format!("Column not found: {}", prop).into());
        }

        Ok(val.unwrap_or(rhai::Dynamic::UNIT))
    }
}

pub(crate) fn value_to_dynamic(val: &crate::core::Value) -> rhai::Dynamic {
    match val {
        crate::core::Value::Integer(i) => rhai::Dynamic::from(*i),
        crate::core::Value::Float(f) => rhai::Dynamic::from(*f),
        crate::core::Value::Text(s) => rhai::Dynamic::from(s.as_ref().to_string()),
        crate::core::Value::Boolean(b) => rhai::Dynamic::from(*b),
        crate::core::Value::Null(_) => rhai::Dynamic::UNIT,
        _ => rhai::Dynamic::from(val.to_string()),
    }
}

pub(crate) fn dynamic_to_value(
    val: rhai::Dynamic,
    dt: crate::core::DataType,
) -> std::result::Result<crate::core::Value, crate::core::Error> {
    if val.is_unit() {
        return Ok(crate::core::Value::Null(dt));
    }

    match dt {
        crate::core::DataType::Integer => {
            if val.is::<i64>() {
                Ok(crate::core::Value::Integer(val.cast::<i64>()))
            } else if val.is::<i32>() {
                Ok(crate::core::Value::Integer(val.cast::<i32>() as i64))
            } else {
                Ok(crate::core::Value::Integer(val.as_int().map_err(|_| {
                    crate::core::Error::internal("Cannot cast to integer")
                })?))
            }
        }
        crate::core::DataType::Float => {
            if val.is::<f64>() {
                Ok(crate::core::Value::Float(val.cast::<f64>()))
            } else if val.is::<f32>() {
                Ok(crate::core::Value::Float(val.cast::<f32>() as f64))
            } else {
                Ok(crate::core::Value::Float(val.as_float().map_err(|_| {
                    crate::core::Error::internal("Cannot cast to float")
                })?))
            }
        }
        crate::core::DataType::Text => Ok(crate::core::Value::text(val.to_string())),
        crate::core::DataType::Boolean => {
            if val.is::<bool>() {
                Ok(crate::core::Value::Boolean(val.cast::<bool>()))
            } else {
                Ok(crate::core::Value::Boolean(val.as_bool().map_err(
                    |_| crate::core::Error::internal("Cannot cast to bool"),
                )?))
            }
        }
        _ => Ok(crate::core::Value::text(val.to_string())),
    }
}