oxibase 0.5.4

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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// 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.

//! Python scripting backend for user-defined functions

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

#[cfg(feature = "python")]
use rustpython_vm::{
    compiler::Mode, convert::ToPyObject, AsObject, Interpreter, PyObjectRef, PyPayload, PyRef,
    Settings, VirtualMachine,
};

#[cfg(feature = "python")]
#[rustpython_vm::pymodule(name = "oxibase")]
mod oxibase_py_module {
    use rustpython_vm::{
        builtins::{PyIntRef, PyStrRef},
        PyResult, VirtualMachine,
    };

    #[pyfunction]
    fn execute(sql: PyStrRef, vm: &VirtualMachine) -> PyResult<PyIntRef> {
        match crate::functions::backends::execute_sql_query(sql.as_ref()) {
            Ok(res) => Ok(vm.ctx.new_int(res.rows_affected())),
            Err(e) => Err(vm.new_runtime_error(e.to_string())),
        }
    }

    #[pyfunction]
    fn commit(vm: &VirtualMachine) -> PyResult<()> {
        match crate::functions::backends::commit_transaction() {
            Ok(_) => Ok(()),
            Err(e) => Err(vm.new_runtime_error(e.to_string())),
        }
    }

    #[pyfunction]
    fn rollback(vm: &VirtualMachine) -> PyResult<()> {
        match crate::functions::backends::rollback_transaction() {
            Ok(_) => Ok(()),
            Err(e) => Err(vm.new_runtime_error(e.to_string())),
        }
    }

    #[pyfunction]
    fn begin(vm: &VirtualMachine) -> PyResult<()> {
        match crate::functions::backends::begin_transaction() {
            Ok(_) => Ok(()),
            Err(e) => Err(vm.new_runtime_error(e.to_string())),
        }
    }
}

/// Python scripting backend
#[cfg(feature = "python")]
pub struct PythonBackend {
    // Interpreter will be created per execution for isolation
}

#[cfg(feature = "python")]
impl PythonBackend {
    /// Indent each line of the code by 4 spaces for function wrapping
    fn indent_code(&self, code: &str) -> String {
        code.lines()
            .map(|line| format!("    {}", line))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

#[cfg(feature = "python")]
impl PythonBackend {
    /// Create a new Python backend
    pub fn new() -> Self {
        Self {}
    }
    fn build_new_row_dict(
        &self,
        vm: &VirtualMachine,
    ) -> Result<rustpython_vm::builtins::PyDictRef> {
        let dict = vm.ctx.new_dict();

        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                    if let Some(row_ptr) = *r.borrow() {
                        let row = unsafe { &*row_ptr };
                        for col in &schema.columns {
                            if let Some(val) = row.get(col.id) {
                                if let Ok(py_val) = self.convert_oxibase_to_python(val, vm) {
                                    let _ = dict.set_item(col.name.as_str(), py_val, vm);
                                }
                            }
                        }
                    }
                });
            }
        });

        Ok(dict)
    }

    fn build_old_row_dict(
        &self,
        vm: &VirtualMachine,
    ) -> Result<rustpython_vm::builtins::PyDictRef> {
        let dict = vm.ctx.new_dict();

        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                crate::functions::backends::triggers::CURRENT_OLD_ROW.with(|r| {
                    if let Some(row_ptr) = *r.borrow() {
                        let row = unsafe { &*row_ptr };
                        for col in &schema.columns {
                            if let Some(val) = row.get(col.id) {
                                if let Ok(py_val) = self.convert_oxibase_to_python(val, vm) {
                                    let _ = dict.set_item(col.name.as_str(), py_val, vm);
                                }
                            }
                        }
                    }
                });
            }
        });

        Ok(dict)
    }

    fn extract_new_row_dict(
        &self,
        dict: rustpython_vm::builtins::PyDictRef,
        vm: &VirtualMachine,
    ) -> Result<()> {
        let mut internal_err = None;
        crate::functions::backends::triggers::CURRENT_SCHEMA.with(|s| {
            if let Some(schema_ptr) = *s.borrow() {
                let schema = unsafe { &*schema_ptr };
                crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                    if let Some(row_ptr) = *r.borrow_mut() {
                        let row = unsafe { &mut *row_ptr };
                        for col in &schema.columns {
                            if let Ok(py_val) = dict.get_item(col.name.as_str(), vm) {
                                match self.convert_python_to_oxibase(&py_val, vm) {
                                    Ok(v) => {
                                        let _ =
                                            row.set(col.id, v.into_coerce_to_type(col.data_type));
                                    }
                                    Err(e) => internal_err = Some(e),
                                }
                            }
                        }
                    }
                });
            }
        });

        if let Some(e) = internal_err {
            return Err(e);
        }
        Ok(())
    }

    /// Convert Oxibase Value to Python object
    #[allow(dead_code)]
    fn convert_oxibase_to_python(&self, value: &Value, vm: &VirtualMachine) -> Result<PyObjectRef> {
        match value {
            Value::Null(_) => Ok(vm.ctx.none()),
            Value::Integer(i) => Ok(i.to_pyobject(vm)),
            Value::Float(f) => Ok(f.to_pyobject(vm)),
            Value::Text(s) => Ok(s.as_ref().to_pyobject(vm)),
            Value::Boolean(b) => Ok(b.to_pyobject(vm)),
            Value::Timestamp(ts) => {
                // Convert to Python datetime - simplified approach
                // For now, convert to ISO string and let Python handle it
                let iso_str = ts.to_rfc3339();
                Ok(iso_str.to_pyobject(vm))
            }
            Value::Json(j) => {
                // For now, just pass as string
                Ok(j.as_ref().to_pyobject(vm))
            }
        }
    }

    /// Convert Python object back to Oxibase Value
    fn convert_python_to_oxibase(
        &self,
        py_obj: &PyObjectRef,
        vm: &VirtualMachine,
    ) -> Result<Value> {
        if py_obj.is(&vm.ctx.none()) {
            return Ok(Value::null_unknown());
        }

        // Try to extract as different types using str() and parsing
        if let Ok(str_repr) = py_obj.str(vm) {
            // Convert PyStr to String
            let s = str_repr.to_string();
            // Try to parse as different types
            if let Ok(i) = s.parse::<i64>() {
                return Ok(Value::Integer(i));
            }
            if let Ok(f) = s.parse::<f64>() {
                return Ok(Value::Float(f));
            }
            if s == "True" {
                return Ok(Value::Boolean(true));
            }
            if s == "False" {
                return Ok(Value::Boolean(false));
            }
            // For strings and complex objects, return as text or JSON
            return Ok(Value::Text(s.into()));
        }

        // Fallback
        Err(Error::internal("Failed to convert Python object"))
    }

    /// Format Python error with basic error message
    fn format_python_error(
        &self,
        py_err: PyRef<rustpython_vm::builtins::PyBaseException>,
        vm: &VirtualMachine,
    ) -> String {
        // Format error consistently with other backends - try to get string representation
        match py_err.as_object().str(vm) {
            Ok(s) => s.to_string(),
            Err(_) => format!("{:?}", py_err),
        }
    }
}

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

#[cfg(feature = "python")]
impl ScriptingBackend for PythonBackend {
    fn name(&self) -> &'static str {
        "python"
    }

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

    fn execute(&self, code: &str, args: &[Value], param_names: &[&str]) -> Result<Value> {
        // Create a new interpreter for each execution (isolation)
        let interpreter = Interpreter::with_init(Settings::default(), |_| ());

        interpreter
            .enter(|vm| {
                let scope = vm.new_scope_with_builtins();

                // Create arguments list for compatibility
                let mut args_vec = Vec::new();
                for arg in args {
                    let py_value = self.convert_oxibase_to_python(arg, vm)?;
                    args_vec.push(py_value);
                }
                let args_list = vm.ctx.new_list(args_vec);
                scope.globals.set_item("arguments", args_list.into(), vm).map_err(|e| {
                    Error::internal(format!("Failed to set arguments list: {:?}", e))
                })?;

                // Convert arguments to Python variables using parameter names
                for (i, arg) in args.iter().enumerate() {
                    let param_name = param_names[i];
                    let py_value = self.convert_oxibase_to_python(arg, vm)?;
                    scope
                        .globals
                        .set_item(param_name, py_value, vm)
                        .map_err(|e| Error::internal(format!("Failed to set argument {}: {:?}", param_name, e)))?;
                }

                // Wrap user code in a function to support 'return' statements
                let indented_code = self.indent_code(code);
                let wrapper_code = format!(
                    "def __user_function():\n{}\nresult = __user_function()",
                    indented_code
                );

                // Execute the wrapper
                match vm.run_string(scope.clone(), &wrapper_code, "<user_function>".to_string()) {
                    Ok(_) => {
                        // Check for 'result' (set by the wrapper)
                        match scope.globals.get_item("result", vm) {
                            Ok(result) => self.convert_python_to_oxibase(&result, vm),
                            Err(_) => Err(Error::internal(
                                "Python function did not return a value (use 'return' or set 'result')",
                            )),
                        }
                    }
                    Err(py_err) => {
                        // Convert Python exception to detailed error message
                        let error_msg = self.format_python_error(py_err, vm);
                        Err(Error::internal(format!(
                            "Python execution error: {}",
                            error_msg
                        )))
                    }
                }
            })
            .map_err(|e| Error::internal(format!("Interpreter 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 builder = Interpreter::builder(Settings::default());
        let def = oxibase_py_module::module_def(&builder.ctx);
        let interpreter = builder.add_native_module(def).build();

        interpreter
            .enter(|vm| {
                let scope = vm.new_scope_with_builtins();

                let mut oxibase_mod_opt = None;
                if let Ok(m) = vm.import("oxibase", 0) {
                    oxibase_mod_opt = Some(m);
                }

                if let Some(oxibase_mod) = oxibase_mod_opt {
                    let ctx_ns = rustpython_vm::builtins::PyNamespace {}.into_ref(&vm.ctx);
                    crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                        if r.borrow().is_some() {
                            if let Ok(dict) = self.build_new_row_dict(vm) {
                                use rustpython_vm::AsObject;
                                let _ = ctx_ns.as_object().set_attr("new", vm.new_pyobj(dict), vm);
                            }
                        }
                    });
                    crate::functions::backends::triggers::CURRENT_OLD_ROW.with(|r| {
                        if r.borrow().is_some() {
                            if let Ok(dict) = self.build_old_row_dict(vm) {
                                use rustpython_vm::AsObject;
                                let _ = ctx_ns.as_object().set_attr("old", vm.new_pyobj(dict), vm);
                            }
                        }
                    });
                    let _ = oxibase_mod.set_attr("ctx", vm.new_pyobj(ctx_ns), vm);
                }

                for (i, arg) in args.iter().enumerate() {
                    let param_name = param_names[i];
                    let py_value = self.convert_oxibase_to_python(arg, vm)?;
                    scope
                        .globals
                        .set_item(param_name, py_value, vm)
                        .map_err(|e| {
                            Error::internal(format!(
                                "Failed to set parameter {}: {:?}",
                                param_name, e
                            ))
                        })?;
                }

                match vm.compile(code, Mode::Exec, "<procedure>".to_string()) {
                    Ok(code_obj) => {
                        match vm.run_code_obj(code_obj, scope.clone()) {
                            Ok(_) => {
                                // Extract updated variables
                                for (i, arg) in args.iter_mut().enumerate() {
                                    let param_name = param_names[i];
                                    if let Ok(Some(py_val)) =
                                        scope.globals.get_item_opt(param_name, vm)
                                    {
                                        if let Ok(new_val) =
                                            self.convert_python_to_oxibase(&py_val, vm)
                                        {
                                            *arg = new_val;
                                        }
                                    }
                                }

                                crate::functions::backends::triggers::CURRENT_NEW_ROW.with(|r| {
                                    if r.borrow().is_some() {
                                        let mut new_row_extracted = false;
                                        if let Ok(oxibase_mod) = vm.import("oxibase", 0) {
                                            if let Ok(ctx_obj) = oxibase_mod.get_attr("ctx", vm) {
                                                if let Ok(new_obj) = ctx_obj.get_attr("new", vm) {
                                                    if let Ok(dict) = new_obj.downcast::<rustpython_vm::builtins::PyDict>() {
                                                        let _ = self.extract_new_row_dict(dict, vm);
                                                        new_row_extracted = true;
                                                    }
                                                }
                                            }
                                        }
                                        if !new_row_extracted {
                                            // Fallback for scope extraction if needed?
                                            // Actually, FR-005 mandates reading from the nested path.
                                        }
                                    }
                                });

                                Ok(())
                            }
                            Err(py_err) => {
                                let error_msg = self.format_python_error(py_err, vm);
                                Err(Error::internal(format!(
                                    "Python execution error: {}",
                                    error_msg
                                )))
                            }
                        }
                    }
                    Err(py_err) => {
                        let error_msg = py_err.to_string();
                        Err(Error::internal(format!(
                            "Python compilation error: {}",
                            error_msg
                        )))
                    }
                }
            })
            .map_err(|e| Error::internal(format!("Interpreter error: {:?}", e)))?;
        Ok(())
    }

    fn validate_code(&self, code: &str) -> Result<()> {
        // Basic syntax validation using rustpython parsing with wrapper
        let interpreter = Interpreter::with_init(Settings::default(), |_| ());
        interpreter
            .enter(|vm| {
                // Wrap code in function for validation
                let indented_code = self.indent_code(code);
                let wrapper_code = format!(
                    "def __user_function():\n{}\nresult = __user_function()",
                    indented_code
                );

                // Try to compile the wrapped code to check for syntax errors
                match vm.compile(&wrapper_code, Mode::Exec, "<validation>".to_string()) {
                    Ok(_) => Ok(()),
                    Err(e) => Err(Error::internal(format!("Python syntax error: {}", e))),
                }
            })
            .map_err(|e| Error::internal(format!("Validation error: {:?}", e)))
    }
}

/// Stub implementation when Python feature is not enabled
#[cfg(not(feature = "python"))]
pub struct PythonBackend;

#[cfg(not(feature = "python"))]
impl PythonBackend {
    pub fn new() -> Self {
        Self
    }
}

#[cfg(not(feature = "python"))]
impl ScriptingBackend for PythonBackend {
    fn name(&self) -> &'static str {
        "python"
    }

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

    fn execute(&self, _code: &str, _args: &[Value], _param_names: &[&str]) -> Result<Value> {
        Err(Error::internal(
            "Python backend not enabled. Use --features python to enable Python support",
        ))
    }

    fn validate_code(&self, _code: &str) -> Result<()> {
        Err(Error::internal(
            "Python backend not enabled. Use --features python to enable Python support",
        ))
    }
}