Skip to main content

TitoModel

Struct TitoModel 

Source
pub struct TitoModel<E: TitoEngine, T> {
    pub engine: E,
    pub partition_count: u32,
    /* private fields */
}

Fields§

§engine: E§partition_count: u32

Implementations§

Source§

impl<E: TitoEngine, T: TitoModelConstraints> TitoModel<E, T>

Source

pub fn new(engine: E, options: TitoModelOptions) -> Self

Source

pub fn relationships(&self) -> Vec<TitoRelationshipConfig>

Source

pub fn get_table(&self) -> String

Source

pub fn get_id_from_table(&self, key: String) -> String

Source

pub fn query_by_index( &self, index: impl Into<String>, ) -> IndexQueryBuilder<E, T>

Examples found in repository?
examples/blog.rs (line 161)
88async fn main() -> Result<(), TitoError> {
89    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
90
91    let post_model = tito_db.clone().model::<Post>(TitoModelOptions::default());
92    let tag_model = tito_db.clone().model::<Tag>(TitoModelOptions::default());
93
94    let tech_tag = tito_db
95        .transaction(|tx| {
96            let tag_model = tag_model.clone();
97            let tag = Tag {
98                id: DBUuid::new_v4().to_string(),
99                name: "Technology".to_string(),
100                description: "All about tech".to_string(),
101            };
102            let tag_clone = tag.clone();
103            async move {
104                tag_model.set(tag_clone).execute(&tx).await?;
105                Ok::<_, TitoError>(tag)
106            }
107        })
108        .await?;
109
110    let rust_tag = tito_db
111        .transaction(|tx| {
112            let tag_model = tag_model.clone();
113            let tag = Tag {
114                id: DBUuid::new_v4().to_string(),
115                name: "Rust".to_string(),
116                description: "Rust programming".to_string(),
117            };
118            let tag_clone = tag.clone();
119            async move {
120                tag_model.set(tag_clone).execute(&tx).await?;
121                Ok::<_, TitoError>(tag)
122            }
123        })
124        .await?;
125
126    println!("Created tags: {}, {}", tech_tag.name, rust_tag.name);
127
128    let post = tito_db
129        .transaction(|tx| {
130            let post_model = post_model.clone();
131            let post = Post {
132                id: DBUuid::new_v4().to_string(),
133                title: "Using Rust with TiKV".to_string(),
134                content: "Examples of using Rust with TiKV...".to_string(),
135                author: "Alice".to_string(),
136                tag_ids: vec![tech_tag.id.clone(), rust_tag.id.clone()],
137                tags: Vec::new(),
138            };
139            let post_clone = post.clone();
140            async move {
141                post_model.set(post_clone).execute(&tx).await?;
142                Ok::<_, TitoError>(post)
143            }
144        })
145        .await?;
146
147    println!("Created post: {}", post.title);
148
149    let post_with_tags = post_model
150        .get(&post.id)
151        .relationship("tags")
152        .execute(None)
153        .await?;
154
155    println!("Post: {}", post_with_tags.title);
156    println!("Tags:");
157    for tag in &post_with_tags.tags {
158        println!("- {}", tag.name);
159    }
160
161    let mut query = post_model.query_by_index("post-by-author");
162    let results = query
163        .value("Alice".to_string())
164        .relationship("tags")
165        .execute(None)
166        .await?;
167
168    println!("\nAlice's posts:");
169    for p in &results.items {
170        println!(
171            "- {} (tags: {})",
172            p.title,
173            p.tags
174                .iter()
175                .map(|t| t.name.clone())
176                .collect::<Vec<_>>()
177                .join(", ")
178        );
179    }
180
181    Ok(())
182}
Source

pub async fn tx<F, Fut, R, Err>(&self, f: F) -> Result<R, Err>
where F: FnOnce(E::Transaction) -> Fut + Clone + Send, Fut: Future<Output = Result<R, Err>> + Send, Err: From<TitoError> + Send + Sync + Debug, R: Send,

Source

pub async fn get_key( &self, key: &str, tx: &E::Transaction, ) -> Result<Value, TitoError>

Source

pub async fn delete( &self, key: String, tx: &E::Transaction, ) -> Result<bool, TitoError>

Source

pub fn to_paginated_items_with_cursor( &self, items: Vec<(String, Value)>, cursor: String, ) -> Result<TitoPaginated<T>, TitoError>

Source

pub fn to_paginated_items( &self, items: Vec<(String, Value)>, has_more: bool, ) -> Result<TitoPaginated<T>, TitoError>

Source

pub fn get_nested_values( &self, json: &Value, field_path: &str, ) -> Option<Vec<FieldValue>>

Source

pub fn set(&self, payload: T) -> SetBuilder<'_, E, T>

Examples found in repository?
examples/crud.rs (line 52)
38async fn main() -> Result<(), TitoError> {
39    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
40    let user_model = tito_db.clone().model::<User>(TitoModelOptions::default());
41
42    let user_id = DBUuid::new_v4().to_string();
43    let user = User {
44        id: user_id.clone(),
45        name: "John Doe".to_string(),
46        email: "john@example.com".to_string(),
47    };
48
49    let saved_user = tito_db
50        .transaction(|tx| {
51            let user_model = user_model.clone();
52            async move { user_model.set(user).execute(&tx).await }
53        })
54        .await?;
55
56    println!("Created user: {:?}", saved_user);
57
58    let found_user = user_model.get(&user_id).execute(None).await?;
59    println!("Found user: {:?}", found_user);
60
61    let updated_user = User {
62        id: user_id.clone(),
63        name: "John Updated".to_string(),
64        email: "john_updated@example.com".to_string(),
65    };
66
67    tito_db
68        .transaction(|tx| {
69            let user_model = user_model.clone();
70            async move { user_model.set(updated_user).execute(&tx).await }
71        })
72        .await?;
73
74    println!("User updated");
75
76    tito_db
77        .transaction(|tx| {
78            let user_model = user_model.clone();
79            async move { user_model.remove(&user_id, &tx).await }
80        })
81        .await?;
82
83    println!("User deleted");
84
85    Ok(())
86}
More examples
Hide additional examples
examples/blog.rs (line 104)
88async fn main() -> Result<(), TitoError> {
89    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
90
91    let post_model = tito_db.clone().model::<Post>(TitoModelOptions::default());
92    let tag_model = tito_db.clone().model::<Tag>(TitoModelOptions::default());
93
94    let tech_tag = tito_db
95        .transaction(|tx| {
96            let tag_model = tag_model.clone();
97            let tag = Tag {
98                id: DBUuid::new_v4().to_string(),
99                name: "Technology".to_string(),
100                description: "All about tech".to_string(),
101            };
102            let tag_clone = tag.clone();
103            async move {
104                tag_model.set(tag_clone).execute(&tx).await?;
105                Ok::<_, TitoError>(tag)
106            }
107        })
108        .await?;
109
110    let rust_tag = tito_db
111        .transaction(|tx| {
112            let tag_model = tag_model.clone();
113            let tag = Tag {
114                id: DBUuid::new_v4().to_string(),
115                name: "Rust".to_string(),
116                description: "Rust programming".to_string(),
117            };
118            let tag_clone = tag.clone();
119            async move {
120                tag_model.set(tag_clone).execute(&tx).await?;
121                Ok::<_, TitoError>(tag)
122            }
123        })
124        .await?;
125
126    println!("Created tags: {}, {}", tech_tag.name, rust_tag.name);
127
128    let post = tito_db
129        .transaction(|tx| {
130            let post_model = post_model.clone();
131            let post = Post {
132                id: DBUuid::new_v4().to_string(),
133                title: "Using Rust with TiKV".to_string(),
134                content: "Examples of using Rust with TiKV...".to_string(),
135                author: "Alice".to_string(),
136                tag_ids: vec![tech_tag.id.clone(), rust_tag.id.clone()],
137                tags: Vec::new(),
138            };
139            let post_clone = post.clone();
140            async move {
141                post_model.set(post_clone).execute(&tx).await?;
142                Ok::<_, TitoError>(post)
143            }
144        })
145        .await?;
146
147    println!("Created post: {}", post.title);
148
149    let post_with_tags = post_model
150        .get(&post.id)
151        .relationship("tags")
152        .execute(None)
153        .await?;
154
155    println!("Post: {}", post_with_tags.title);
156    println!("Tags:");
157    for tag in &post_with_tags.tags {
158        println!("- {}", tag.name);
159    }
160
161    let mut query = post_model.query_by_index("post-by-author");
162    let results = query
163        .value("Alice".to_string())
164        .relationship("tags")
165        .execute(None)
166        .await?;
167
168    println!("\nAlice's posts:");
169    for p in &results.items {
170        println!(
171            "- {} (tags: {})",
172            p.title,
173            p.tags
174                .iter()
175                .map(|t| t.name.clone())
176                .collect::<Vec<_>>()
177                .join(", ")
178        );
179    }
180
181    Ok(())
182}
Source

pub fn get(&self, id: &str) -> GetBuilder<'_, E, T>

Examples found in repository?
examples/crud.rs (line 58)
38async fn main() -> Result<(), TitoError> {
39    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
40    let user_model = tito_db.clone().model::<User>(TitoModelOptions::default());
41
42    let user_id = DBUuid::new_v4().to_string();
43    let user = User {
44        id: user_id.clone(),
45        name: "John Doe".to_string(),
46        email: "john@example.com".to_string(),
47    };
48
49    let saved_user = tito_db
50        .transaction(|tx| {
51            let user_model = user_model.clone();
52            async move { user_model.set(user).execute(&tx).await }
53        })
54        .await?;
55
56    println!("Created user: {:?}", saved_user);
57
58    let found_user = user_model.get(&user_id).execute(None).await?;
59    println!("Found user: {:?}", found_user);
60
61    let updated_user = User {
62        id: user_id.clone(),
63        name: "John Updated".to_string(),
64        email: "john_updated@example.com".to_string(),
65    };
66
67    tito_db
68        .transaction(|tx| {
69            let user_model = user_model.clone();
70            async move { user_model.set(updated_user).execute(&tx).await }
71        })
72        .await?;
73
74    println!("User updated");
75
76    tito_db
77        .transaction(|tx| {
78            let user_model = user_model.clone();
79            async move { user_model.remove(&user_id, &tx).await }
80        })
81        .await?;
82
83    println!("User deleted");
84
85    Ok(())
86}
More examples
Hide additional examples
examples/blog.rs (line 150)
88async fn main() -> Result<(), TitoError> {
89    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
90
91    let post_model = tito_db.clone().model::<Post>(TitoModelOptions::default());
92    let tag_model = tito_db.clone().model::<Tag>(TitoModelOptions::default());
93
94    let tech_tag = tito_db
95        .transaction(|tx| {
96            let tag_model = tag_model.clone();
97            let tag = Tag {
98                id: DBUuid::new_v4().to_string(),
99                name: "Technology".to_string(),
100                description: "All about tech".to_string(),
101            };
102            let tag_clone = tag.clone();
103            async move {
104                tag_model.set(tag_clone).execute(&tx).await?;
105                Ok::<_, TitoError>(tag)
106            }
107        })
108        .await?;
109
110    let rust_tag = tito_db
111        .transaction(|tx| {
112            let tag_model = tag_model.clone();
113            let tag = Tag {
114                id: DBUuid::new_v4().to_string(),
115                name: "Rust".to_string(),
116                description: "Rust programming".to_string(),
117            };
118            let tag_clone = tag.clone();
119            async move {
120                tag_model.set(tag_clone).execute(&tx).await?;
121                Ok::<_, TitoError>(tag)
122            }
123        })
124        .await?;
125
126    println!("Created tags: {}, {}", tech_tag.name, rust_tag.name);
127
128    let post = tito_db
129        .transaction(|tx| {
130            let post_model = post_model.clone();
131            let post = Post {
132                id: DBUuid::new_v4().to_string(),
133                title: "Using Rust with TiKV".to_string(),
134                content: "Examples of using Rust with TiKV...".to_string(),
135                author: "Alice".to_string(),
136                tag_ids: vec![tech_tag.id.clone(), rust_tag.id.clone()],
137                tags: Vec::new(),
138            };
139            let post_clone = post.clone();
140            async move {
141                post_model.set(post_clone).execute(&tx).await?;
142                Ok::<_, TitoError>(post)
143            }
144        })
145        .await?;
146
147    println!("Created post: {}", post.title);
148
149    let post_with_tags = post_model
150        .get(&post.id)
151        .relationship("tags")
152        .execute(None)
153        .await?;
154
155    println!("Post: {}", post_with_tags.title);
156    println!("Tags:");
157    for tag in &post_with_tags.tags {
158        println!("- {}", tag.name);
159    }
160
161    let mut query = post_model.query_by_index("post-by-author");
162    let results = query
163        .value("Alice".to_string())
164        .relationship("tags")
165        .execute(None)
166        .await?;
167
168    println!("\nAlice's posts:");
169    for p in &results.items {
170        println!(
171            "- {} (tags: {})",
172            p.title,
173            p.tags
174                .iter()
175                .map(|t| t.name.clone())
176                .collect::<Vec<_>>()
177                .join(", ")
178        );
179    }
180
181    Ok(())
182}
Source

pub async fn scan( &self, payload: TitoScanPayload, tx: &E::Transaction, ) -> Result<(Vec<(String, Value)>, bool), TitoError>

Source

pub async fn get_many_raw( &self, ids: Vec<String>, rels: Vec<String>, tx: &E::Transaction, ) -> Result<Vec<(String, Value)>, TitoError>

Source

pub fn get_many(&self, ids: Vec<String>) -> GetManyBuilder<'_, E, T>

Source

pub async fn scan_reverse( &self, payload: TitoScanPayload, tx: &E::Transaction, ) -> Result<(Vec<(String, Value)>, bool), TitoError>

Source

pub fn get_last_id(&self, key: String) -> Option<String>

Source

pub async fn batch_get( &self, keys: Vec<String>, tx: &E::Transaction, ) -> Result<Vec<(String, Value)>, TitoError>

Source

pub async fn remove_by_index( &self, index: &str, value: &str, batch_size: u32, tx: &E::Transaction, ) -> Result<Vec<String>, TitoError>

Source

pub async fn remove( &self, raw_id: &str, tx: &E::Transaction, ) -> Result<bool, TitoError>

Examples found in repository?
examples/crud.rs (line 79)
38async fn main() -> Result<(), TitoError> {
39    let tito_db = TiKV::connect(vec!["127.0.0.1:2379"]).await?;
40    let user_model = tito_db.clone().model::<User>(TitoModelOptions::default());
41
42    let user_id = DBUuid::new_v4().to_string();
43    let user = User {
44        id: user_id.clone(),
45        name: "John Doe".to_string(),
46        email: "john@example.com".to_string(),
47    };
48
49    let saved_user = tito_db
50        .transaction(|tx| {
51            let user_model = user_model.clone();
52            async move { user_model.set(user).execute(&tx).await }
53        })
54        .await?;
55
56    println!("Created user: {:?}", saved_user);
57
58    let found_user = user_model.get(&user_id).execute(None).await?;
59    println!("Found user: {:?}", found_user);
60
61    let updated_user = User {
62        id: user_id.clone(),
63        name: "John Updated".to_string(),
64        email: "john_updated@example.com".to_string(),
65    };
66
67    tito_db
68        .transaction(|tx| {
69            let user_model = user_model.clone();
70            async move { user_model.set(updated_user).execute(&tx).await }
71        })
72        .await?;
73
74    println!("User updated");
75
76    tito_db
77        .transaction(|tx| {
78            let user_model = user_model.clone();
79            async move { user_model.remove(&user_id, &tx).await }
80        })
81        .await?;
82
83    println!("User deleted");
84
85    Ok(())
86}
Source

pub async fn find( &self, payload: TitoFindPayload, ) -> Result<TitoPaginated<T>, TitoError>

Source§

impl<E: TitoEngine, T: Default + Clone + Serialize + DeserializeOwned + Unpin + Send + Sync + TitoModelTrait> TitoModel<E, T>

Source

pub fn get_index_keys( &self, id: String, value: &T, json: &Value, ) -> Result<Vec<(String, Value)>, TitoError>

Source

pub async fn find_by_index_raw( &self, payload: TitoFindByIndexPayload, tx: &E::Transaction, ) -> Result<(Vec<(String, Value)>, bool), TitoError>

Source

pub async fn find_by_index_reverse_raw( &self, payload: TitoFindByIndexPayload, tx: &E::Transaction, ) -> Result<(Vec<(String, Value)>, bool), TitoError>

Source

pub async fn find_by_index( &self, payload: TitoFindByIndexPayload, tx: Option<&E::Transaction>, ) -> Result<TitoPaginated<T>, TitoError>

Source

pub async fn find_by_index_reverse( &self, payload: TitoFindByIndexPayload, tx: Option<&E::Transaction>, ) -> Result<TitoPaginated<T>, TitoError>

Source

pub async fn find_one_by_index( &self, payload: TitoFindOneByIndexPayload, tx: Option<&E::Transaction>, ) -> Result<T, TitoError>

Source§

impl<E: TitoEngine, T: Default + Clone + Serialize + DeserializeOwned + Unpin + Send + Sync + TitoModelTrait> TitoModel<E, T>

Source

pub fn stitch_relationship( &self, item: &mut Value, rel_map: &HashMap<String, Value>, config: &TitoRelationshipConfig, )

Source

pub fn get_relationship_data( &self, items: &Vec<(String, Value)>, rels_config: &[TitoRelationshipConfig], rels: &Vec<String>, ) -> Vec<(TitoRelationshipConfig, String)>

Source

pub async fn fetch_and_stitch_relationships( &self, items: Vec<(String, Value)>, rels: Vec<String>, tx: &E::Transaction, ) -> Result<Vec<(String, Value)>, TitoError>

Source

pub fn extract_relationship(&self, input: &str) -> Option<String>

Trait Implementations§

Source§

impl<E: Clone + TitoEngine, T: Clone> Clone for TitoModel<E, T>

Source§

fn clone(&self) -> TitoModel<E, T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<E, T> Freeze for TitoModel<E, T>
where E: Freeze,

§

impl<E, T> RefUnwindSafe for TitoModel<E, T>

§

impl<E, T> Send for TitoModel<E, T>
where T: Send,

§

impl<E, T> Sync for TitoModel<E, T>
where T: Sync,

§

impl<E, T> Unpin for TitoModel<E, T>
where E: Unpin, T: Unpin,

§

impl<E, T> UnsafeUnpin for TitoModel<E, T>
where E: UnsafeUnpin,

§

impl<E, T> UnwindSafe for TitoModel<E, T>
where E: UnwindSafe, T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,