Compare commits
6 commits
master
...
fluffyemil
Author | SHA1 | Date | |
---|---|---|---|
|
48cd1aa3ed | ||
|
65e31ed09e | ||
|
a63b423aa9 | ||
|
ca412b3a8b | ||
|
23e7ff0585 | ||
|
3985c06927 |
7 changed files with 1017 additions and 37 deletions
|
@ -329,6 +329,78 @@ impl From<f64> for TypedValue {
|
|||
}
|
||||
}
|
||||
|
||||
impl TypedValue {
|
||||
pub fn into_entid(self) -> Option<Entid> {
|
||||
match self {
|
||||
TypedValue::Ref(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_kw(self) -> Option<Rc<NamespacedKeyword>> {
|
||||
match self {
|
||||
TypedValue::Keyword(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_boolean(self) -> Option<bool> {
|
||||
match self {
|
||||
TypedValue::Boolean(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_long(self) -> Option<i64> {
|
||||
match self {
|
||||
TypedValue::Long(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_double(self) -> Option<f64> {
|
||||
match self {
|
||||
TypedValue::Double(v) => Some(v.into_inner()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_instant(self) -> Option<DateTime<Utc>> {
|
||||
match self {
|
||||
TypedValue::Instant(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_timestamp(self) -> Option<i64> {
|
||||
match self {
|
||||
TypedValue::Instant(v) => Some(v.timestamp()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> Option<Rc<String>> {
|
||||
match self {
|
||||
TypedValue::String(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_uuid(self) -> Option<Uuid> {
|
||||
match self {
|
||||
TypedValue::Uuid(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_uuid_string(self) -> Option<String> {
|
||||
match self {
|
||||
TypedValue::Uuid(v) => Some(v.hyphenated().to_string()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Type safe representation of the possible return values from SQLite's `typeof`
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
|
||||
pub enum SQLTypeAffinity {
|
||||
|
|
|
@ -3,5 +3,8 @@ name = "mentat_ffi"
|
|||
version = "0.1.0"
|
||||
authors = ["Emily Toop <etoop@mozilla.com>"]
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dependencies.mentat]
|
||||
path = ".."
|
||||
|
|
535
ffi/src/lib.rs
535
ffi/src/lib.rs
|
@ -8,6 +8,7 @@
|
|||
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
// specific language governing permissions and limitations under the License.
|
||||
|
||||
extern crate libc;
|
||||
extern crate mentat;
|
||||
|
||||
use std::collections::{
|
||||
|
@ -16,23 +17,34 @@ use std::collections::{
|
|||
use std::os::raw::{
|
||||
c_char,
|
||||
c_int,
|
||||
c_void,
|
||||
};
|
||||
use std::slice;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
};
|
||||
use std::vec;
|
||||
|
||||
use libc::time_t;
|
||||
|
||||
pub use mentat::{
|
||||
Entid,
|
||||
FindSpec,
|
||||
HasSchema,
|
||||
KnownEntid,
|
||||
NamespacedKeyword,
|
||||
Queryable,
|
||||
QueryBuilder,
|
||||
QueryInputs,
|
||||
QueryOutput,
|
||||
QueryResults,
|
||||
Store,
|
||||
Syncable,
|
||||
TypedValue,
|
||||
TxObserver,
|
||||
};
|
||||
|
||||
pub use mentat::errors::{
|
||||
Result,
|
||||
Uuid,
|
||||
ValueType,
|
||||
Variable,
|
||||
};
|
||||
|
||||
pub mod android;
|
||||
|
@ -40,11 +52,13 @@ pub mod utils;
|
|||
|
||||
pub use utils::strings::{
|
||||
c_char_to_string,
|
||||
c_char_from_rc,
|
||||
kw_from_string,
|
||||
string_to_c_char,
|
||||
str_to_c_char,
|
||||
};
|
||||
|
||||
use utils::log;
|
||||
pub type TypedValueIterator = vec::IntoIter<TypedValue>;
|
||||
pub type TypedValueListIterator = vec::IntoIter<Vec<TypedValue>>;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone)]
|
||||
|
@ -62,21 +76,39 @@ pub struct ExternTxReportList {
|
|||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct ExternResult {
|
||||
pub error: *const c_char,
|
||||
#[derive(Debug)]
|
||||
pub struct ExternOption {
|
||||
pub value: *mut c_void,
|
||||
}
|
||||
|
||||
impl From<Result<()>> for ExternResult {
|
||||
fn from(result: Result<()>) -> Self {
|
||||
impl<T> From<Option<T>> for ExternOption {
|
||||
fn from(option: Option<T>) -> Self {
|
||||
ExternOption {
|
||||
value: option.map_or(std::ptr::null_mut(), |v| Box::into_raw(Box::new(v)) as *mut _ as *mut c_void)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct ExternResult {
|
||||
pub ok: *const c_void,
|
||||
pub err: *const c_char,
|
||||
}
|
||||
|
||||
impl<T, E> From<Result<T, E>> for ExternResult where E: std::error::Error {
|
||||
fn from(result: Result<T, E>) -> Self {
|
||||
match result {
|
||||
Ok(_) => {
|
||||
Ok(value) => {
|
||||
ExternResult {
|
||||
error: std::ptr::null(),
|
||||
err: std::ptr::null(),
|
||||
ok: Box::into_raw(Box::new(value)) as *const _ as *const c_void,
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
ExternResult {
|
||||
error: string_to_c_char(e.description().into())
|
||||
err: string_to_c_char(e.description()),
|
||||
ok: std::ptr::null(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -85,7 +117,7 @@ impl From<Result<()>> for ExternResult {
|
|||
|
||||
// A store cannot be opened twice to the same location.
|
||||
// Once created, the reference to the store is held by the caller and not Rust,
|
||||
// therefore the caller is responsible for calling `store_destroy` to release the memory
|
||||
// therefore the caller is responsible for calling `destroy` to release the memory
|
||||
// used by the Store in order to avoid a memory leak.
|
||||
// TODO: Start returning `ExternResult`s rather than crashing on error.
|
||||
#[no_mangle]
|
||||
|
@ -95,10 +127,364 @@ pub extern "C" fn store_open(uri: *const c_char) -> *mut Store {
|
|||
Box::into_raw(Box::new(store))
|
||||
}
|
||||
|
||||
// Reclaim the memory for the provided Store and drop, therefore releasing it.
|
||||
// TODO: open empty
|
||||
|
||||
// TODO: dismantle
|
||||
|
||||
// TODO: conn
|
||||
|
||||
// TODO: begin_read
|
||||
|
||||
// TODO: begin_transaction
|
||||
|
||||
// TODO: cache
|
||||
|
||||
// TODO: q_once
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_destroy(store: *mut Store) {
|
||||
let _ = Box::from_raw(store);
|
||||
pub unsafe extern "C" fn store_query<'a>(store: *mut Store, query: *const c_char) -> *mut QueryBuilder<'a> {
|
||||
let query = c_char_to_string(query);
|
||||
let store = &mut*store;
|
||||
let query_builder = QueryBuilder::new(store, query);
|
||||
Box::into_raw(Box::new(query_builder))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_int(query_builder: *mut QueryBuilder, var: *const c_char, value: c_int) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
let value = value as i32;
|
||||
query_builder.bind_value(&var, value);
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_long(query_builder: *mut QueryBuilder, var: *const c_char, value: i64) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_long(&var, value);
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_ref(query_builder: *mut QueryBuilder, var: *const c_char, value: i64) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_ref(&var, value);
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_ref_kw(query_builder: *mut QueryBuilder, var: *const c_char, value: *const c_char) {
|
||||
let var = c_char_to_string(var);
|
||||
let kw = kw_from_string(c_char_to_string(value));
|
||||
let query_builder = &mut*query_builder;
|
||||
if let Some(err) = query_builder.bind_ref_from_kw(&var, kw).err() {
|
||||
panic!(err);
|
||||
}
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_kw(query_builder: *mut QueryBuilder, var: *const c_char, value: *const c_char) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
let kw = kw_from_string(c_char_to_string(value));
|
||||
query_builder.bind_value(&var, kw);
|
||||
}
|
||||
|
||||
// boolean
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_boolean(query_builder: *mut QueryBuilder, var: *const c_char, value: bool) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_value(&var, value);
|
||||
}
|
||||
|
||||
// double
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_double(query_builder: *mut QueryBuilder, var: *const c_char, value: f64) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_value(&var, value);
|
||||
}
|
||||
|
||||
// instant
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_timestamp(query_builder: *mut QueryBuilder, var: *const c_char, value: time_t) {
|
||||
let var = c_char_to_string(var);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_instant(&var, value as i64);
|
||||
}
|
||||
|
||||
// string
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_string(query_builder: *mut QueryBuilder, var: *const c_char, value: *const c_char) {
|
||||
let var = c_char_to_string(var);
|
||||
let value = c_char_to_string(value);
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_value(&var, value);
|
||||
}
|
||||
|
||||
// uuid
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_bind_uuid(query_builder: *mut QueryBuilder, var: *const c_char, value: *const c_char) {
|
||||
let var = c_char_to_string(var);
|
||||
let value = Uuid::parse_str(&c_char_to_string(value)).expect("valid uuid");
|
||||
let query_builder = &mut*query_builder;
|
||||
query_builder.bind_value(&var, value);
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_execute_scalar(query_builder: *mut QueryBuilder) -> *mut ExternResult {
|
||||
let query_builder = &mut*query_builder;
|
||||
let results = query_builder.execute_scalar();
|
||||
Box::into_raw(Box::new(results.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_execute_coll(query_builder: *mut QueryBuilder) -> *mut ExternResult {
|
||||
let query_builder = &mut*query_builder;
|
||||
let results = query_builder.execute_coll();
|
||||
Box::into_raw(Box::new(results.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_execute_tuple(query_builder: *mut QueryBuilder) -> *mut ExternResult {
|
||||
let query_builder = &mut*query_builder;
|
||||
let results = query_builder.execute_tuple();
|
||||
Box::into_raw(Box::new(results.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn query_builder_execute(query_builder: *mut QueryBuilder) -> *mut ExternResult {
|
||||
let query_builder = &mut*query_builder;
|
||||
let results = query_builder.execute_rel();
|
||||
Box::into_raw(Box::new(results.into()))
|
||||
}
|
||||
|
||||
// as_long
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_long(typed_value: *mut TypedValue) -> i64 {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
typed_value.into_long().expect("Typed value cannot be coerced into a Long")
|
||||
}
|
||||
|
||||
// as_entid
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_entid(typed_value: *mut TypedValue) -> Entid {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
typed_value.into_entid().expect("Typed value cannot be coerced into an Entid")
|
||||
}
|
||||
|
||||
// kw
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_kw(typed_value: *mut TypedValue) -> *const c_char {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
string_to_c_char(typed_value.into_kw().expect("Typed value cannot be coerced into a Namespaced Keyword").to_string())
|
||||
}
|
||||
|
||||
//as_boolean
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_boolean(typed_value: *mut TypedValue) -> bool {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
typed_value.into_boolean().expect("Typed value cannot be coerced into a Boolean")
|
||||
}
|
||||
|
||||
//as_double
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_double(typed_value: *mut TypedValue) -> f64 {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
typed_value.into_double().expect("Typed value cannot be coerced into a Double")
|
||||
}
|
||||
|
||||
//as_timestamp
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_timestamp(typed_value: *mut TypedValue) -> i64 {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
let val = typed_value.into_timestamp().expect("Typed value cannot be coerced into a Timestamp");
|
||||
val
|
||||
}
|
||||
|
||||
//as_string
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_string(typed_value: *mut TypedValue) -> *const c_char {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
c_char_from_rc(typed_value.into_string().expect("Typed value cannot be coerced into a String"))
|
||||
}
|
||||
|
||||
//as_uuid
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn typed_value_as_uuid(typed_value: *mut TypedValue) -> *const c_char {
|
||||
let typed_value = Box::from_raw(typed_value);
|
||||
string_to_c_char(typed_value.into_uuid_string().expect("Typed value cannot be coerced into a Uuid"))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn row_at_index(rows: *mut Vec<Vec<TypedValue>>, index: c_int) -> *mut Vec<TypedValue> {
|
||||
let result = &*rows;
|
||||
result.get(index as usize).map_or(std::ptr::null_mut(), |v| Box::into_raw(Box::new(v.clone())))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn rows_iter(rows: *mut Vec<Vec<TypedValue>>) -> *mut TypedValueListIterator {
|
||||
let result = Box::from_raw(rows);
|
||||
Box::into_raw(Box::new(result.into_iter()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn rows_iter_next(iter: *mut TypedValueListIterator) -> *mut Vec<TypedValue> {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| Box::into_raw(Box::new(v)))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter(values: *mut Vec<TypedValue>) -> *mut TypedValueIterator {
|
||||
let result = Box::from_raw(values);
|
||||
Box::into_raw(Box::new(result.into_iter()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next(iter: *mut TypedValueIterator) -> *const TypedValue {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| &v as *const TypedValue)
|
||||
}
|
||||
|
||||
//as_long
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_long(iter: *mut TypedValueIterator) -> *const i64 {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| &v.into_long().expect("Typed value cannot be coerced into a Long") as *const i64)
|
||||
}
|
||||
// as ref
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_entid(iter: *mut TypedValueIterator) -> *const Entid {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| &v.into_entid().expect("Typed value cannot be coerced into am Entid") as *const Entid)
|
||||
}
|
||||
|
||||
// as kw
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_kw(iter: *mut TypedValueIterator) -> *const c_char {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| string_to_c_char(v.into_kw().expect("Typed value cannot be coerced into a Namespaced Keyword").to_string()))
|
||||
}
|
||||
|
||||
//as_boolean
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_boolean(iter: *mut TypedValueIterator) -> *const bool {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| &v.into_boolean().expect("Typed value cannot be coerced into a Boolean") as *const bool)
|
||||
}
|
||||
|
||||
//as_double
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_double(iter: *mut TypedValueIterator) -> *const f64 {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| &v.into_double().expect("Typed value cannot be coerced into a Double") as *const f64)
|
||||
}
|
||||
|
||||
//as_timestamp
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_timestamp(iter: *mut TypedValueIterator) -> *const i64 {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| v.into_timestamp().expect("Typed value cannot be coerced into a Timestamp") as *const i64)
|
||||
}
|
||||
|
||||
//as_string
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_string(iter: *mut TypedValueIterator) -> *const c_char {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| c_char_from_rc(v.into_string().expect("Typed value cannot be coerced into a String")))
|
||||
}
|
||||
|
||||
//as_uuid
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn values_iter_next_as_uuid(iter: *mut TypedValueIterator) -> *const c_char {
|
||||
let iter = &mut *iter;
|
||||
iter.next().map_or(std::ptr::null_mut(), |v| string_to_c_char(v.into_uuid_string().expect("Typed value cannot be coerced into a Uuid")))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index(values: *mut Vec<TypedValue>, index: c_int) -> *const TypedValue {
|
||||
let result = &*values;
|
||||
result.get(index as usize).expect("No value at index") as *const TypedValue
|
||||
}
|
||||
|
||||
//as_long
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_long(values: *mut Vec<TypedValue>, index: c_int) -> i64 {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
value.clone().into_long().expect("Typed value cannot be coerced into a Long")
|
||||
}
|
||||
// as ref
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_entid(values: *mut Vec<TypedValue>, index: c_int) -> Entid {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
value.clone().into_entid().expect("Typed value cannot be coerced into an Entid")
|
||||
}
|
||||
|
||||
// as kw
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_kw(values: *mut Vec<TypedValue>, index: c_int) -> *const c_char {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
string_to_c_char(value.clone().into_kw().expect("Typed value cannot be coerced into a Namespaced Keyword").to_string())
|
||||
}
|
||||
|
||||
//as_boolean
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_boolean(values: *mut Vec<TypedValue>, index: c_int) -> bool {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
value.clone().into_boolean().expect("Typed value cannot be coerced into a Boolean")
|
||||
}
|
||||
|
||||
//as_double
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_double(values: *mut Vec<TypedValue>, index: c_int) -> f64 {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
value.clone().into_double().expect("Typed value cannot be coerced into a Double")
|
||||
}
|
||||
|
||||
//as_timestamp
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_timestamp(values: *mut Vec<TypedValue>, index: c_int) -> i64 {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
value.clone().into_timestamp().expect("Typed value cannot be coerced into a timestamp")
|
||||
}
|
||||
|
||||
//as_string
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_string(values: *mut Vec<TypedValue>, index: c_int) -> *mut c_char {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
c_char_from_rc(value.clone().into_string().expect("Typed value cannot be coerced into a String"))
|
||||
}
|
||||
|
||||
//as_uuid
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn value_at_index_as_uuid(values: *mut Vec<TypedValue>, index: c_int) -> *mut c_char {
|
||||
let result = &*values;
|
||||
let value = result.get(index as usize).expect("No value at index");
|
||||
string_to_c_char(value.clone().into_uuid_string().expect("Typed value cannot be coerced into a Uuid"))
|
||||
}
|
||||
|
||||
// TODO: q_prepare
|
||||
|
||||
// TODO: q_explain
|
||||
|
||||
// TODO: lookup_values_for_attribute
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_value_for_attribute(store: *mut Store, entid: i64, attribute: *const c_char) -> *mut ExternResult {
|
||||
let store = &*store;
|
||||
let kw = kw_from_string(c_char_to_string(attribute));
|
||||
let value = match store.lookup_value_for_attribute(entid, &kw) {
|
||||
Ok(Some(v)) => ExternResult { ok: Box::into_raw(Box::new(v)) as *const _ as *const c_void, err: std::ptr::null() },
|
||||
Ok(None) => ExternResult { ok: std::ptr::null(), err: std::ptr::null() },
|
||||
Err(e) => ExternResult { ok: std::ptr::null(), err: string_to_c_char(e.description()) },
|
||||
};
|
||||
Box::into_raw(Box::new(value))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
|
@ -113,7 +499,6 @@ pub unsafe extern "C" fn store_register_observer(store: *mut Store,
|
|||
attribute_set.extend(slice.iter());
|
||||
let key = c_char_to_string(key);
|
||||
let tx_observer = Arc::new(TxObserver::new(attribute_set, move |obs_key, batch| {
|
||||
log::d(&format!("Calling observer registered for {:?}, batch: {:?}", obs_key, batch));
|
||||
let extern_reports: Vec<ExternTxReport> = batch.into_iter().map(|(tx_id, changes)| {
|
||||
let changes: Vec<Entid> = changes.into_iter().map(|i|*i).collect();
|
||||
let len = changes.len();
|
||||
|
@ -128,7 +513,7 @@ pub unsafe extern "C" fn store_register_observer(store: *mut Store,
|
|||
reports: extern_reports.into_boxed_slice(),
|
||||
len: len,
|
||||
};
|
||||
callback(str_to_c_char(obs_key), &reports);
|
||||
callback(string_to_c_char(obs_key), &reports);
|
||||
}));
|
||||
store.register_observer(key, tx_observer);
|
||||
}
|
||||
|
@ -137,22 +522,17 @@ pub unsafe extern "C" fn store_register_observer(store: *mut Store,
|
|||
pub unsafe extern "C" fn store_unregister_observer(store: *mut Store, key: *const c_char) {
|
||||
let store = &mut*store;
|
||||
let key = c_char_to_string(key);
|
||||
log::d(&format!("Unregistering observer for key: {:?}", key));
|
||||
store.unregister_observer(&key);
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_entid_for_attribute(store: *mut Store, attr: *const c_char) -> Entid {
|
||||
let store = &mut*store;
|
||||
let mut keyword_string = c_char_to_string(attr);
|
||||
let attr_name = keyword_string.split_off(1);
|
||||
let parts: Vec<&str> = attr_name.split("/").collect();
|
||||
let kw = NamespacedKeyword::new(parts[0], parts[1]);
|
||||
let keyword_string = c_char_to_string(attr);
|
||||
let kw = kw_from_string(keyword_string);
|
||||
let conn = store.conn();
|
||||
let current_schema = conn.current_schema();
|
||||
let got_entid = current_schema.get_entid(&kw);
|
||||
let entid = got_entid.unwrap();
|
||||
entid.into()
|
||||
current_schema.get_entid(&kw).expect("Unable to find entid for invalid attribute").into()
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
|
@ -178,3 +558,104 @@ pub unsafe extern "C" fn store_sync(store: *mut Store, user_uuid: *const c_char,
|
|||
let res = store.sync(&server_uri, &user_uuid);
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
fn assert_datom<E, V>(store: &mut Store, entid: E, attribute: String, value: V) -> *mut ExternResult
|
||||
where E: Into<KnownEntid>,
|
||||
V: Into<TypedValue> {
|
||||
let kw = kw_from_string(attribute);
|
||||
let res = store.assert_datom(entid.into(), kw, value.into());
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_long_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: i64) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
let kw = kw_from_string(c_char_to_string(attribute));
|
||||
let res = store.assert_datom(KnownEntid(entid), kw, TypedValue::Long(value));
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_entid_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: Entid) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
let kw = kw_from_string(c_char_to_string(attribute));
|
||||
let res = store.assert_datom(KnownEntid(entid), kw, TypedValue::Ref(value));
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_kw_ref_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: *const c_char) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
let kw = kw_from_string(c_char_to_string(attribute));
|
||||
let value = kw_from_string(c_char_to_string(value));
|
||||
let is_valid = store.conn().current_schema().get_entid(&value);
|
||||
if is_valid.is_none() {
|
||||
return Box::into_raw(Box::new(ExternResult { ok: std::ptr::null_mut(), err: string_to_c_char(format!("Unknown attribute {:?}", value)) }));
|
||||
}
|
||||
let kw_entid = is_valid.unwrap();
|
||||
let res = store.assert_datom(KnownEntid(entid), kw, TypedValue::Ref(kw_entid.into()));
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_boolean_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: bool) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
assert_datom(store, KnownEntid(entid), c_char_to_string(attribute), value)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_double_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: f64) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
assert_datom(store, KnownEntid(entid), c_char_to_string(attribute), value)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_timestamp_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: time_t) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
let kw = kw_from_string(c_char_to_string(attribute));
|
||||
let res = store.assert_datom(KnownEntid(entid), kw, TypedValue::instant(value as i64));
|
||||
Box::into_raw(Box::new(res.into()))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_string_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: *const c_char) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
assert_datom(store, KnownEntid(entid), c_char_to_string(attribute), c_char_to_string(value))
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn store_set_uuid_for_attribute_on_entid(store: *mut Store, entid: Entid, attribute: *const c_char, value: *const c_char) -> *mut ExternResult {
|
||||
let store = &mut*store;
|
||||
let uuid = Uuid::parse_str(&c_char_to_string(value)).expect("valid uuid");
|
||||
assert_datom(store, KnownEntid(entid), c_char_to_string(attribute), uuid)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn destroy(obj: *mut c_void) {
|
||||
if !obj.is_null() {
|
||||
let obj_to_release = Box::from_raw(obj);
|
||||
println!("object to release {:?}", obj_to_release);
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! define_destructor (
|
||||
($name:ident, $t:ty) => (
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn $name(obj: *mut $t) {
|
||||
if !obj.is_null() { let _ = Box::from_raw(obj); }
|
||||
}
|
||||
)
|
||||
);
|
||||
define_destructor!(query_builder_destroy, QueryBuilder);
|
||||
|
||||
define_destructor!(store_destroy, Store);
|
||||
|
||||
define_destructor!(typed_value_destroy, TypedValue);
|
||||
|
||||
define_destructor!(typed_value_list_destroy, Vec<TypedValue>);
|
||||
|
||||
define_destructor!(typed_value_list_iter_destroy, TypedValueIterator);
|
||||
|
||||
define_destructor!(typed_value_result_set_destroy, Vec<Vec<TypedValue>>);
|
||||
|
||||
define_destructor!(typed_value_result_set_iter_destroy, TypedValueListIterator);
|
||||
|
|
|
@ -9,27 +9,40 @@
|
|||
// specific language governing permissions and limitations under the License.
|
||||
|
||||
pub mod strings {
|
||||
use std::os::raw::c_char;
|
||||
use std;
|
||||
use std::ffi::{
|
||||
CString,
|
||||
CStr
|
||||
};
|
||||
use std::os::raw::c_char;
|
||||
use std::rc::Rc;
|
||||
|
||||
use mentat::{
|
||||
NamespacedKeyword,
|
||||
};
|
||||
|
||||
pub fn c_char_to_string(cchar: *const c_char) -> String {
|
||||
let c_str = unsafe { CStr::from_ptr(cchar) };
|
||||
let r_str = match c_str.to_str() {
|
||||
Err(_) => "",
|
||||
Ok(string) => string,
|
||||
};
|
||||
let r_str = c_str.to_str().unwrap_or("");
|
||||
r_str.to_string()
|
||||
}
|
||||
|
||||
pub fn string_to_c_char(r_string: String) -> *mut c_char {
|
||||
CString::new(r_string).unwrap().into_raw()
|
||||
pub fn string_to_c_char<T>(r_string: T) -> *mut c_char where T: Into<String> {
|
||||
CString::new(r_string.into()).unwrap().into_raw()
|
||||
}
|
||||
|
||||
pub fn str_to_c_char(r_string: &str) -> *mut c_char {
|
||||
string_to_c_char(r_string.to_string())
|
||||
pub fn kw_from_string(mut keyword_string: String) -> NamespacedKeyword {
|
||||
let attr_name = keyword_string.split_off(1);
|
||||
let parts: Vec<&str> = attr_name.split("/").collect();
|
||||
NamespacedKeyword::new(parts[0], parts[1])
|
||||
}
|
||||
|
||||
pub fn c_char_from_rc(rc_string: Rc<String>) -> *mut c_char {
|
||||
if let Some(str_ptr) = unsafe { Rc::into_raw(rc_string).as_ref() } {
|
||||
string_to_c_char(str_ptr.clone())
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -55,6 +68,6 @@ pub mod log {
|
|||
let message = message.as_ptr();
|
||||
let tag = CString::new("Mentat").unwrap();
|
||||
let tag = tag.as_ptr();
|
||||
unsafe { android::__android_log_write(android::ANDROID_LOG_DEBUG, tag, message) };
|
||||
unsafe { android::__android_log_write(android::LogLevel::Debug as i32, tag, message) };
|
||||
}
|
||||
}
|
||||
|
|
17
src/conn.rs
17
src/conn.rs
|
@ -81,6 +81,7 @@ use mentat_tolstoy::Syncer;
|
|||
use uuid::Uuid;
|
||||
|
||||
use entity_builder::{
|
||||
BuildTerms,
|
||||
InProgressBuilder,
|
||||
};
|
||||
|
||||
|
@ -578,6 +579,10 @@ impl Store {
|
|||
pub fn unregister_observer(&mut self, key: &String) {
|
||||
self.conn.unregister_observer(key);
|
||||
}
|
||||
|
||||
pub fn assert_datom<T>(&mut self, entid: T, attribute: NamespacedKeyword, value: TypedValue) -> Result<()> where T: Into<KnownEntid> {
|
||||
self.conn.assert_datom(&mut self.sqlite, entid, attribute, value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Queryable for Store {
|
||||
|
@ -865,6 +870,18 @@ impl Conn {
|
|||
pub fn unregister_observer(&mut self, key: &String) {
|
||||
self.tx_observer_service.lock().unwrap().deregister(key);
|
||||
}
|
||||
|
||||
// TODO: expose the entity builder over FFI and remove the need for this function entirely
|
||||
// It's really only here in order to keep the FFI layer as thin as possible.
|
||||
// Once the entity builder is exposed, we can perform all of these functions over FFI from the client.
|
||||
pub fn assert_datom<T>(&mut self, sqlite: &mut rusqlite::Connection, entid: T, attribute: NamespacedKeyword, value: TypedValue) -> Result<()> where T: Into<KnownEntid> {
|
||||
let in_progress = self.begin_transaction(sqlite)?;
|
||||
let mut builder = in_progress.builder().describe(entid.into());
|
||||
builder.add_kw(&attribute, value)?;
|
||||
builder.commit()
|
||||
.map_err(|e| e.into())
|
||||
.and(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
@ -97,6 +97,7 @@ pub mod vocabulary;
|
|||
pub mod conn;
|
||||
pub mod query;
|
||||
pub mod entity_builder;
|
||||
pub mod query_builder;
|
||||
|
||||
pub use query::{
|
||||
IntoResult,
|
||||
|
@ -111,6 +112,10 @@ pub use query::{
|
|||
q_once,
|
||||
};
|
||||
|
||||
pub use query_builder::{
|
||||
QueryBuilder,
|
||||
};
|
||||
|
||||
pub use conn::{
|
||||
CacheAction,
|
||||
CacheDirection,
|
||||
|
|
389
src/query_builder.rs
Normal file
389
src/query_builder.rs
Normal file
|
@ -0,0 +1,389 @@
|
|||
// Copyright 2018 Mozilla
|
||||
//
|
||||
// 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.
|
||||
|
||||
#![macro_use]
|
||||
use std::collections::{
|
||||
BTreeMap,
|
||||
};
|
||||
|
||||
use mentat_core::{
|
||||
Entid,
|
||||
NamespacedKeyword,
|
||||
TypedValue,
|
||||
ValueType,
|
||||
};
|
||||
|
||||
use ::{
|
||||
HasSchema,
|
||||
Queryable,
|
||||
QueryInputs,
|
||||
QueryOutput,
|
||||
Store,
|
||||
Variable,
|
||||
};
|
||||
|
||||
use errors::{
|
||||
ErrorKind,
|
||||
Result,
|
||||
};
|
||||
|
||||
pub struct QueryBuilder<'a> {
|
||||
sql: String,
|
||||
values: BTreeMap<Variable, TypedValue>,
|
||||
types: BTreeMap<Variable, ValueType>,
|
||||
store: &'a mut Store,
|
||||
}
|
||||
|
||||
impl<'a> QueryBuilder<'a> {
|
||||
pub fn new<T>(store: &'a mut Store, sql: T) -> QueryBuilder where T: Into<String> {
|
||||
QueryBuilder { sql: sql.into(), values: BTreeMap::new(), types: BTreeMap::new(), store }
|
||||
}
|
||||
|
||||
pub fn bind_value<T>(&mut self, var: &str, value: T) -> &mut Self where T: Into<TypedValue> {
|
||||
self.values.insert(Variable::from_valid_name(var), value.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn bind_ref_from_kw(&mut self, var: &str, value: NamespacedKeyword) -> Result<&mut Self> {
|
||||
let entid = self.store.conn().current_schema().get_entid(&value).ok_or(ErrorKind::UnknownAttribute(value.to_string()))?;
|
||||
self.values.insert(Variable::from_valid_name(var), TypedValue::Ref(entid.into()));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn bind_ref<T>(&mut self, var: &str, value: T) -> &mut Self where T: Into<Entid> {
|
||||
self.values.insert(Variable::from_valid_name(var), TypedValue::Ref(value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn bind_long(&mut self, var: &str, value: i64) -> &mut Self {
|
||||
self.values.insert(Variable::from_valid_name(var), TypedValue::Long(value));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn bind_instant(&mut self, var: &str, value: i64) -> &mut Self {
|
||||
self.values.insert(Variable::from_valid_name(var), TypedValue::instant(value));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn bind_type(&mut self, var: &str, value_type: ValueType) -> &mut Self {
|
||||
self.types.insert(Variable::from_valid_name(var), value_type);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn execute(&mut self) -> Result<QueryOutput> {
|
||||
let values = ::std::mem::replace(&mut self.values, Default::default());
|
||||
let types = ::std::mem::replace(&mut self.types, Default::default());
|
||||
let query_inputs = QueryInputs::new(types, values)?;
|
||||
let read = self.store.begin_read()?;
|
||||
read.q_once(&self.sql, query_inputs)
|
||||
}
|
||||
|
||||
pub fn execute_scalar(&mut self) -> Result<Option<TypedValue>> {
|
||||
let results = self.execute()?;
|
||||
results.into_scalar().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
pub fn execute_coll(&mut self) -> Result<Vec<TypedValue>> {
|
||||
let results = self.execute()?;
|
||||
results.into_coll().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
pub fn execute_tuple(&mut self) -> Result<Option<Vec<TypedValue>>> {
|
||||
let results = self.execute()?;
|
||||
results.into_tuple().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
pub fn execute_rel(&mut self) -> Result<Vec<Vec<TypedValue>>> {
|
||||
let results = self.execute()?;
|
||||
results.into_rel().map_err(|e| e.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::{
|
||||
QueryBuilder,
|
||||
TypedValue,
|
||||
Store,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_scalar_query() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "u" :foo/boolean true]
|
||||
[:db/add "p" :foo/boolean false]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let yes = report.tempids.get("u").expect("found it").clone();
|
||||
|
||||
let entid = QueryBuilder::new(&mut store, r#"[:find ?x .
|
||||
:in ?v
|
||||
:where [?x :foo/boolean ?v]]"#)
|
||||
.bind_value("?v", true)
|
||||
.execute_scalar().expect("ScalarResult")
|
||||
.map_or(None, |t| t.into_entid());
|
||||
assert_eq!(entid, Some(yes));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_coll_query() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
[:db/add "p" :foo/boolean false]
|
||||
[:db/add "p" :foo/long 24]
|
||||
[:db/add "u" :foo/boolean true]
|
||||
[:db/add "u" :foo/long 23]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let u_yes = report.tempids.get("u").expect("found it").clone();
|
||||
let l_yes = report.tempids.get("l").expect("found it").clone();
|
||||
let n_yes = report.tempids.get("n").expect("found it").clone();
|
||||
|
||||
let entids: Vec<i64> = QueryBuilder::new(&mut store, r#"[:find [?x ...]
|
||||
:in ?v
|
||||
:where [?x :foo/boolean ?v]]"#)
|
||||
.bind_value("?v", true)
|
||||
.execute_coll().expect("CollResult")
|
||||
.into_iter()
|
||||
.map(|v| v.into_entid().expect("val"))
|
||||
.collect();
|
||||
|
||||
assert_eq!(entids, vec![l_yes, n_yes, u_yes]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_coll_query_by_row() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
[:db/add "p" :foo/boolean false]
|
||||
[:db/add "p" :foo/long 24]
|
||||
[:db/add "u" :foo/boolean true]
|
||||
[:db/add "u" :foo/long 23]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let n_yes = report.tempids.get("n").expect("found it").clone();
|
||||
|
||||
let results = QueryBuilder::new(&mut store, r#"[:find [?x ...]
|
||||
:in ?v
|
||||
:where [?x :foo/boolean ?v]]"#)
|
||||
.bind_value("?v", true)
|
||||
.execute_coll().expect("CollResult");
|
||||
let entid = results.get(1).map_or(None, |t| t.to_owned().into_entid()).expect("entid");
|
||||
|
||||
assert_eq!(entid, n_yes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_query_result_by_column() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
[:db/add "p" :foo/boolean false]
|
||||
[:db/add "p" :foo/long 24]
|
||||
[:db/add "u" :foo/boolean true]
|
||||
[:db/add "u" :foo/long 23]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let n_yes = report.tempids.get("n").expect("found it").clone();
|
||||
|
||||
let results = QueryBuilder::new(&mut store, r#"[:find [?x, ?i]
|
||||
:in ?v ?i
|
||||
:where [?x :foo/boolean ?v]
|
||||
[?x :foo/long ?i]]"#)
|
||||
.bind_value("?v", true)
|
||||
.bind_long("?i", 27)
|
||||
.execute_tuple().expect("TupleResult").expect("Vec<TypedValue>");
|
||||
let entid = results.get(0).map_or(None, |t| t.to_owned().into_entid()).expect("entid");
|
||||
let long_val = results.get(1).map_or(None, |t| t.to_owned().into_long()).expect("long");
|
||||
|
||||
assert_eq!(entid, n_yes);
|
||||
assert_eq!(long_val, 27);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_query_result_by_iter() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
[:db/add "p" :foo/boolean false]
|
||||
[:db/add "p" :foo/long 24]
|
||||
[:db/add "u" :foo/boolean true]
|
||||
[:db/add "u" :foo/long 23]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let n_yes = report.tempids.get("n").expect("found it").clone();
|
||||
|
||||
let results: Vec<TypedValue> = QueryBuilder::new(&mut store, r#"[:find [?x, ?i]
|
||||
:in ?v ?i
|
||||
:where [?x :foo/boolean ?v]
|
||||
[?x :foo/long ?i]]"#)
|
||||
.bind_value("?v", true)
|
||||
.bind_long("?i", 27)
|
||||
.execute_tuple().expect("TupleResult").unwrap_or(vec![]);
|
||||
let entid = TypedValue::Ref(n_yes.clone());
|
||||
let long_val = TypedValue::Long(27);
|
||||
|
||||
assert_eq!(results, vec![entid, long_val]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rel_query_result() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let l_yes = report.tempids.get("l").expect("found it").clone();
|
||||
let m_yes = report.tempids.get("m").expect("found it").clone();
|
||||
let n_yes = report.tempids.get("n").expect("found it").clone();
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Res {
|
||||
entid: i64,
|
||||
boolean: bool,
|
||||
long_val: i64,
|
||||
};
|
||||
|
||||
let mut results: Vec<Res> = QueryBuilder::new(&mut store, r#"[:find ?x ?v ?i
|
||||
:where [?x :foo/boolean ?v]
|
||||
[?x :foo/long ?i]]"#)
|
||||
.execute_rel().expect("RelResult")
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
Res {
|
||||
entid: row.get(0).map_or(None, |t| t.to_owned().into_entid()).expect("entid"),
|
||||
boolean: row.get(1).map_or(None, |t| t.to_owned().into_boolean()).expect("boolean"),
|
||||
long_val: row.get(2).map_or(None, |t| t.to_owned().into_long()).expect("long"),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let res1 = results.pop().expect("res");
|
||||
assert_eq!(res1, Res { entid: n_yes, boolean: true, long_val: 27 });
|
||||
let res2 = results.pop().expect("res");
|
||||
assert_eq!(res2, Res { entid: m_yes, boolean: false, long_val: 26 });
|
||||
let res3 = results.pop().expect("res");
|
||||
assert_eq!(res3, Res { entid: l_yes, boolean: true, long_val: 25 });
|
||||
assert_eq!(results.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bind_ref() {
|
||||
let mut store = Store::open("").expect("store connection");
|
||||
store.transact(r#"[
|
||||
[:db/add "s" :db/ident :foo/boolean]
|
||||
[:db/add "s" :db/valueType :db.type/boolean]
|
||||
[:db/add "s" :db/cardinality :db.cardinality/one]
|
||||
[:db/add "t" :db/ident :foo/long]
|
||||
[:db/add "t" :db/valueType :db.type/long]
|
||||
[:db/add "t" :db/cardinality :db.cardinality/one]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let report = store.transact(r#"[
|
||||
[:db/add "l" :foo/boolean true]
|
||||
[:db/add "l" :foo/long 25]
|
||||
[:db/add "m" :foo/boolean false]
|
||||
[:db/add "m" :foo/long 26]
|
||||
[:db/add "n" :foo/boolean true]
|
||||
[:db/add "n" :foo/long 27]
|
||||
]"#).expect("successful transaction");
|
||||
|
||||
let l_yes = report.tempids.get("l").expect("found it").clone();
|
||||
|
||||
let results = QueryBuilder::new(&mut store, r#"[:find [?v ?i]
|
||||
:in ?x
|
||||
:where [?x :foo/boolean ?v]
|
||||
[?x :foo/long ?i]]"#)
|
||||
.bind_ref("?x", l_yes)
|
||||
.execute_tuple().expect("TupleResult")
|
||||
.unwrap_or(vec![]);
|
||||
assert_eq!(results.get(0).map_or(None, |t| t.to_owned().into_boolean()).expect("boolean"), true);
|
||||
assert_eq!(results.get(1).map_or(None, |t| t.to_owned().into_long()).expect("long"), 25);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue