turingdb_helpers/document.rs
1use crate::commands::{from_op, TuringOp};
2use anyhow::Result;
3use serde::Serialize;
4
5/// ### Handles all queries releated to fields
6/// ```rust
7/// #[derive(Debug, Serialize, Clone)]
8/// pub struct DocumentQuery {
9/// db: String,
10/// document: Option<String>,
11/// }
12/// ```
13#[derive(Debug, Serialize, Clone, Default)]
14pub struct DocumentQuery {
15 db: String,
16 document: Option<String>,
17}
18
19impl DocumentQuery {
20 /// ### Initialize a new empty document
21 /// #### Usage
22 /// ```rust
23 /// use crate::DocumentQuery;
24 ///
25 /// Document::new()
26 /// ```
27 pub fn new() -> Self {
28 Self {
29 db: Default::default(),
30 document: Default::default(),
31 }
32 }
33 /// ### Add a database name
34 /// #### Usage
35 /// ```rust
36 /// use crate::DocumentQuery;
37 ///
38 /// let mut foo = DocumentQuery::new();
39 /// foo.db("db_name");
40 /// ```
41 pub fn db(&mut self, name: &str) -> &Self {
42 self.db = name.into();
43
44 self
45 }
46 /// ### Add a document name
47 /// #### Usage
48 /// ```rust
49 /// use crate::DocumentQuery;
50 ///
51 /// let mut foo = DocumentQuery::new();
52 /// foo
53 /// .db("db_name")
54 /// .document("document_name");
55 /// ```
56 pub fn document(&mut self, name: &str) -> &Self {
57 self.document = Some(name.into());
58
59 self
60 }
61 /// ### Creates a new document in a database
62 /// #### Usage
63 /// ```rust
64 /// use crate::DocumentQuery;
65 ///
66 /// let mut foo = DocumentQuery::new();
67 /// foo
68 /// .db("db_name")
69 /// .document("document_name")
70 /// .create()
71 /// ```
72 pub fn create(&self) -> Result<Vec<u8>> {
73 let mut packet = from_op(&TuringOp::DocumentCreate).to_vec();
74 packet.extend_from_slice(self.db.as_bytes());
75
76 let data = bincode::serialize::<Self>(self)?;
77 packet.extend_from_slice(&data);
78
79 Ok(packet)
80 }
81 /// ### List all documents in a database
82 /// #### Usage
83 /// ```rust
84 /// use crate::DocumentQuery;
85 ///
86 /// let mut foo = DocumentQuery::new();
87 /// foo
88 /// .db("db_name")
89 /// .list()
90 /// ```
91 pub fn list(&self) -> Result<Vec<u8>> {
92 let mut packet = from_op(&TuringOp::DocumentList).to_vec();
93 packet.extend_from_slice(self.db.as_bytes());
94
95 let data = bincode::serialize::<Self>(self)?;
96 packet.extend_from_slice(&data);
97
98 Ok(packet)
99 }
100 /// ### Drops document in a database
101 /// #### Usage
102 /// ```rust
103 /// use crate::DocumentQuery;
104 ///
105 /// let mut foo = DocumentQuery::new();
106 /// foo
107 /// .db("db_name")
108 /// .document("document_name")
109 /// .drop()
110 /// ```
111 pub fn drop(&self) -> Result<Vec<u8>> {
112 let mut packet = from_op(&TuringOp::DocumentDrop).to_vec();
113 packet.extend_from_slice(self.db.as_bytes());
114
115 let data = bincode::serialize::<Self>(self)?;
116 packet.extend_from_slice(&data);
117
118 Ok(packet)
119 }
120}