bicycle_core/models/
example.rs

1/*
2Bicycle is a framework for managing data.
3
4Copyright (C) 2024 Ordinary Labs
5
6This program is free software: you can redistribute it and/or modify
7it under the terms of the GNU Affero General Public License as
8published by the Free Software Foundation, either version 3 of the
9License, or (at your option) any later version.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License
17along with this program.  If not, see <http://www.gnu.org/licenses/>.
18*/
19
20use std::error::Error;
21
22use prost::Message;
23
24use bicycle_proto::{index_query::Expression, IndexQuery};
25
26use engine::{
27    batch_put, delete_begins_with, delete_eq, delete_gte, delete_lte, get_begins_with, get_eq,
28    get_gte, get_lte, put,
29};
30
31const MODEL_NAME: &'static str = "EXAMPLE";
32
33pub fn get_examples_by_pk(
34    query: IndexQuery,
35) -> Result<Vec<bicycle_proto::Example>, Box<dyn Error>> {
36    if let Some(expression) = query.expression {
37        match expression {
38            Expression::Eq(val) => get_eq::<bicycle_proto::Example>(MODEL_NAME, &val),
39            Expression::Gte(val) => get_gte::<bicycle_proto::Example>(MODEL_NAME, &val),
40            Expression::Lte(val) => get_lte::<bicycle_proto::Example>(MODEL_NAME, &val),
41            Expression::BeginsWith(val) => {
42                get_begins_with::<bicycle_proto::Example>(MODEL_NAME, &val)
43            }
44        }
45    } else {
46        Err("no expression provided".into())
47    }
48}
49
50pub fn delete_examples_by_pk(query: IndexQuery) -> Result<(), Box<dyn Error>> {
51    if let Some(expression) = query.expression {
52        match expression {
53            Expression::Eq(val) => delete_eq(MODEL_NAME, &val),
54            Expression::Gte(val) => delete_gte(MODEL_NAME, &val),
55            Expression::Lte(val) => delete_lte(MODEL_NAME, &val),
56            Expression::BeginsWith(val) => delete_begins_with(MODEL_NAME, &val),
57        }
58    } else {
59        Err("no expression provided".into())
60    }
61}
62
63#[inline(always)]
64pub fn put_example(example: bicycle_proto::Example) -> Result<(), Box<dyn Error>> {
65    put(MODEL_NAME, example.pk.clone(), example.encode_to_vec())
66}
67
68#[inline]
69pub fn batch_put_examples(examples: bicycle_proto::Examples) -> Result<(), Box<dyn Error>> {
70    let mut params = vec![];
71
72    for example in examples.examples {
73        params.push((example.pk.clone(), example.encode_to_vec()));
74    }
75
76    batch_put(MODEL_NAME, params)
77}