Skip to content

Commit 99931bd

Browse files
committed
moving VariableContext from Python to Rust
1 parent f98c231 commit 99931bd

File tree

1 file changed

+43
-25
lines changed

1 file changed

+43
-25
lines changed

src/lib.rs

Lines changed: 43 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::{
88
use itertools::Itertools;
99
use parking_lot::{ArcMutexGuard, Mutex, RawMutex, RwLock};
1010
use pyo3::{
11-
exceptions::{PyKeyError, PyRuntimeError, PyValueError},
11+
exceptions::{PyKeyError, PyRuntimeError, PyTypeError, PyValueError},
1212
prelude::*,
1313
types::{PyBytes, PyType},
1414
};
@@ -561,30 +561,48 @@ impl PyVariable {
561561
}
562562
}
563563

564-
//class VariableContext:
565-
//def __init__(self):
566-
//self.variables = []
567-
//
568-
//def new(self, name=None):
569-
//i = len(self.variables)
570-
//assert i < 128
571-
//v = Variable(i, name)
572-
//self.variables.append(v)
573-
//return v
574-
//
575-
//def check_schemas(self):
576-
//for v in self.variables:
577-
// if not v.schema:
578-
// if v.name:
579-
// name = "'" + v.name + "'"
580-
// else:
581-
// name = "_"
582-
// raise TypeError(
583-
// "missing schema for variable "
584-
// + name
585-
// + "/"
586-
// + str(v.index)
587-
// )
564+
pub struct InnerVariableContext {
565+
variables: Vec<Py<PyVariable>>,
566+
}
567+
568+
#[pyclass(frozen, name = "VariableContext")]
569+
pub struct PyVariableContext(RwLock<InnerVariableContext>);
570+
571+
#[pymethods]
572+
impl PyVariableContext {
573+
#[new]
574+
pub fn new() -> Self {
575+
PyVariableContext(RwLock::new(InnerVariableContext {
576+
variables: Vec::new(),
577+
}))
578+
}
579+
580+
#[pyo3(signature = (name))]
581+
pub fn fresh_variable(&self, py: Python<'_>, name: String) -> Py<PyVariable> {
582+
let mut variable_context = self.0.write();
583+
584+
let next_index = variable_context.variables.len();
585+
586+
let variable = Py::new(py, PyVariable::new(next_index, name)).unwrap();
587+
variable_context.variables.push(variable.clone_ref(py));
588+
589+
return variable;
590+
}
591+
592+
pub fn check_schemas(&self) -> PyResult<()> {
593+
let variable_context = self.0.read();
594+
for v in &variable_context.variables {
595+
let variable = v.get().0.read();
596+
597+
if variable._value_schema.is_none() {
598+
let name = &variable.name;
599+
let msg = format!("missing value schema for variable {name}");
600+
return Err(PyTypeError::new_err(msg));
601+
}
602+
}
603+
Ok(())
604+
}
605+
}
588606

589607
#[pyclass(frozen, name = "Query")]
590608
pub struct PyQuery {

0 commit comments

Comments
 (0)