1use crate::bindings::vtx::api::sql::{self, DbValue};
2use crate::error::{VtxError, VtxResult};
3use serde::de::DeserializeOwned;
4
5pub trait ToDbValue {
9 fn to_db_value(&self) -> DbValue;
10}
11
12impl ToDbValue for String {
15 fn to_db_value(&self) -> DbValue {
16 DbValue::Text(self.clone())
17 }
18}
19
20impl ToDbValue for &str {
21 fn to_db_value(&self) -> DbValue {
22 DbValue::Text(self.to_string())
23 }
24}
25
26impl ToDbValue for i64 {
27 fn to_db_value(&self) -> DbValue {
28 DbValue::Integer(*self)
29 }
30}
31
32impl ToDbValue for i32 {
33 fn to_db_value(&self) -> DbValue {
34 DbValue::Integer(*self as i64)
35 }
36}
37
38impl ToDbValue for f64 {
39 fn to_db_value(&self) -> DbValue {
40 DbValue::Real(*self)
41 }
42}
43
44pub fn execute(sql: &str, params: &[&dyn ToDbValue]) -> VtxResult<u64> {
56 let wit_params: Vec<DbValue> = params.iter().map(|p| p.to_db_value()).collect();
57
58 sql::execute(sql, &wit_params).map_err(VtxError::DatabaseError)
59}
60
61pub fn query<T: DeserializeOwned>(sql: &str, params: &[&dyn ToDbValue]) -> VtxResult<Vec<T>> {
77 let wit_params: Vec<DbValue> = params.iter().map(|p| p.to_db_value()).collect();
78
79 let json_str = sql::query_json(sql, &wit_params).map_err(VtxError::DatabaseError)?;
80
81 serde_json::from_str(&json_str).map_err(|e| VtxError::SerializationError(e.to_string()))
82}