edgedb_query/models/edge_query.rs
1use edgedb_protocol::common::Cardinality;
2use crate::ToEdgeQl;
3use crate::ToEdgeValue;
4use edgedb_protocol::value::Value;
5
6/// EgdeQuery represents a edgeDB query.
7///
8/// It combines the string query and its query arguments
9///
10/// __query__ : the string query
11///
12/// __args__ : the query arguments
13///
14/// __cardinality__ : the query cardinality, MANY by default
15///
16///<br>
17///
18/// ## Examples
19///
20///``` rust
21/// use edgedb_protocol::codec::ObjectShape;
22/// use edgedb_protocol::descriptors::{ShapeElement, TypePos};
23/// use edgedb_protocol::value::Value;
24/// use edgedb_protocol::common::Cardinality;
25/// use edgedb_query::models::edge_query::EdgeQuery;
26///
27/// let shape: &[ShapeElement] = &[ShapeElement {
28/// flag_implicit: false,
29/// flag_link_property: false,
30/// flag_link: false,
31/// cardinality: Some(Cardinality::One),
32/// name: "var".to_string(),
33/// type_pos: TypePos(0),
34/// }];
35///
36/// let args = Some(Value::Object {
37/// shape: ObjectShape::from(shape),
38/// fields: vec![Some(Value::Str(String::from("Rust")))],
39/// });
40///
41/// let query = "Select 'I love ' ++ <str>$var".to_owned();
42///
43/// let edge_query = EdgeQuery { query, args, cardinality: Cardinality:: One };
44///
45/// ```
46///
47#[derive(Debug)]
48pub struct EdgeQuery {
49 pub query: String,
50 pub args: Option<Value>,
51 pub cardinality: Cardinality
52}
53
54impl EdgeQuery {
55 fn with_cardinality(self, cardinality: Cardinality) -> Self {
56 let query = match cardinality {
57 Cardinality::AtMostOne | Cardinality::One => {
58 format!("SELECT ({}) limit 1", self.query)
59 }
60 _ => {
61 self.query
62 }
63 };
64
65 Self {
66 query,
67 args: self.args,
68 cardinality
69 }
70 }
71}
72
73
74/// ToEdgeQuery trait
75pub trait ToEdgeQuery: ToEdgeQl + ToEdgeValue {
76
77 /// Convert a given struct into a EdgeQuery struct
78 fn to_edge_query(&self) -> EdgeQuery {
79 EdgeQuery {
80 query: self.to_edgeql().to_string(),
81 args: Some(self.to_edge_value()),
82 cardinality: Cardinality::Many
83 }
84 }
85
86 fn to_edge_query_with_cardinality(&self, cardinality: Cardinality) -> EdgeQuery {
87 self.to_edge_query().with_cardinality(cardinality)
88 }
89}