mazzaroth_rs/external/
sql.rs

1//! Access to the query host functions
2
3#[cfg(not(feature = "host-mock"))]
4use super::externs::{_kq_json_insert, _kq_query_fetch, _kq_query_run};
5
6#[cfg(feature = "host-mock")]
7pub static mut QUERY_RESULT: Option<Vec<u8>> = None;
8
9#[cfg(feature = "host-mock")]
10pub static mut INSERT_RESULT: Result<u32, u32> = Ok(0);
11
12/// Execute a string query against the Mazzaroth leger.
13///
14/// # Arguments
15///
16/// * `query` - String query to be executed against the kvquery prefix
17///
18/// # Returns
19///
20///  Option<Vec<u8>>
21///  * `Some(Vec<u8>)` - xdr encoded result of the query execution
22///  * None - the query resulted in no results
23#[cfg(not(feature = "host-mock"))]
24pub fn exec(query: String) -> Option<Vec<u8>> {
25    let query_bytes: Vec<u8> = query.as_bytes().to_vec();
26    let mut hash = Vec::with_capacity(16); // 32 byte (256) hash
27    unsafe { hash.set_len(16) };
28    let len = unsafe { _kq_query_run(query_bytes.as_ptr(), query_bytes.len(), hash.as_ptr()) };
29    if len == 0 {
30        return None;
31    }
32    let mut result = Vec::with_capacity(len as usize);
33    unsafe {
34        result.set_len(len as usize);
35        _kq_query_fetch(result.as_ptr(), hash.as_ptr());
36    };
37    Some(result)
38}
39
40#[cfg(feature = "host-mock")]
41pub fn exec(_query: String) -> Option<Vec<u8>> {
42    unsafe { QUERY_RESULT.clone() }
43}
44
45/// Executes a query that will insert a JSON object into the specified table.
46///
47/// # Arguments
48///
49/// * `table_name` - String name of the table to insert into
50/// * `json` - String JSON string to insert into the table
51///
52/// # Returns
53///
54///  Result<u32, u32>
55///  * Ok(x) - resulting return code upon success
56///  * Err(x) - resulting return code upon error
57#[cfg(not(feature = "host-mock"))]
58pub fn insert(table_name: String, json: String) -> Result<u32, u32> {
59    let json_bytes: Vec<u8> = json.as_bytes().to_vec();
60    let table_bytes: Vec<u8> = table_name.as_bytes().to_vec();
61    match unsafe {
62        _kq_json_insert(
63            table_bytes.as_ptr(),
64            table_bytes.len(),
65            json_bytes.as_ptr(),
66            json_bytes.len(),
67        )
68    } {
69        0 => Ok(0),
70        x => Err(x),
71    }
72}
73
74#[cfg(feature = "host-mock")]
75pub fn insert(_table_name: String, _json: String) -> Result<u32, u32> {
76    unsafe { INSERT_RESULT.clone() }
77}