sql_builder/extension/postgres/expr.rs
1use super::PgBinOper;
2use crate::{Expr, ExprTrait, IntoLikeExpr};
3
4/// Postgres-specific operator methods for building expressions.
5pub trait PgExpr: ExprTrait {
6 /// Express an postgres concatenate (`||`) expression.
7 ///
8 /// # Examples
9 ///
10 /// ```
11 /// use sql_builder::{extension::postgres::PgExpr, *};
12 ///
13 /// let query = Query::select().expr(Expr::val("a").concatenate("b")).take();
14 ///
15 /// assert_eq!(
16 /// query.to_string(PostgresQueryBuilder).unwrap(),
17 /// r#"SELECT 'a' || 'b'"#
18 /// );
19 ///
20 /// let query = Query::select()
21 /// .expr(Expr::val(vec!["a".to_owned()]).concatenate(vec!["b".to_owned()]))
22 /// .take();
23 ///
24 /// assert_eq!(
25 /// query.to_string(PostgresQueryBuilder).unwrap(),
26 /// r#"SELECT ARRAY ['a'] || ARRAY ['b']"#
27 /// );
28 /// ```
29 fn concatenate<T>(self, right: T) -> Expr
30 where
31 T: Into<Expr>,
32 {
33 self.binary(PgBinOper::Concatenate, right)
34 }
35
36 /// Alias of [`PgExpr::concatenate`]
37 fn concat<T>(self, right: T) -> Expr
38 where
39 T: Into<Expr>,
40 {
41 self.concatenate(right)
42 }
43
44 /// Express an postgres fulltext search matches (`@@`) expression.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use sql_builder::{*, extension::postgres::PgExpr};
50 ///
51 /// let query = Query::select()
52 /// .columns(["name", "variant", "language"])
53 /// .from("font")
54 /// .and_where(Expr::val("a & b").matches("a b"))
55 /// .and_where(Expr::col("name").matches("a b"))
56 /// .to_owned();
57 ///
58 /// assert_eq!(
59 /// query.to_string(PostgresQueryBuilder).unwrap(),
60 /// r#"SELECT "name", "variant", "language" FROM "font" WHERE 'a & b' @@ 'a b' AND "name" @@ 'a b'"#
61 /// );
62 /// ```
63 fn matches<T>(self, expr: T) -> Expr
64 where
65 T: Into<Expr>,
66 {
67 self.binary(PgBinOper::Matches, expr)
68 }
69
70 /// Express an postgres fulltext search contains (`@>`) expression.
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// use sql_builder::{*, extension::postgres::PgExpr};
76 ///
77 /// let query = Query::select()
78 /// .columns(["name", "variant", "language"])
79 /// .from("font")
80 /// .and_where(Expr::val("a & b").contains("a b"))
81 /// .and_where(Expr::col("name").contains("a b"))
82 /// .to_owned();
83 ///
84 /// assert_eq!(
85 /// query.to_string(PostgresQueryBuilder).unwrap(),
86 /// r#"SELECT "name", "variant", "language" FROM "font" WHERE 'a & b' @> 'a b' AND "name" @> 'a b'"#
87 /// );
88 /// ```
89 fn contains<T>(self, expr: T) -> Expr
90 where
91 T: Into<Expr>,
92 {
93 self.binary(PgBinOper::Contains, expr)
94 }
95
96 /// Express an postgres fulltext search contained (`<@`) expression.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// use sql_builder::{*, extension::postgres::PgExpr};
102 ///
103 /// let query = Query::select()
104 /// .columns(["name", "variant", "language"])
105 /// .from("font")
106 /// .and_where(Expr::val("a & b").contained("a b"))
107 /// .and_where(Expr::col("name").contained("a b"))
108 /// .to_owned();
109 ///
110 /// assert_eq!(
111 /// query.to_string(PostgresQueryBuilder).unwrap(),
112 /// r#"SELECT "name", "variant", "language" FROM "font" WHERE 'a & b' <@ 'a b' AND "name" <@ 'a b'"#
113 /// );
114 /// ```
115 fn contained<T>(self, expr: T) -> Expr
116 where
117 T: Into<Expr>,
118 {
119 self.binary(PgBinOper::Contained, expr)
120 }
121
122 /// Express a `ILIKE` expression.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use sql_builder::{*, extension::postgres::PgExpr};
128 ///
129 /// let query = Query::select()
130 /// .columns(["character", "size_w", "size_h"])
131 /// .from("character")
132 /// .and_where(Expr::col(("character", "character")).ilike("Ours'%"))
133 /// .to_owned();
134 ///
135 /// assert_eq!(
136 /// query.to_string(PostgresQueryBuilder).unwrap(),
137 /// r#"SELECT "character", "size_w", "size_h" FROM "character" WHERE "character"."character" ILIKE E'Ours\'%'"#
138 /// );
139 /// ```
140 fn ilike<L>(self, like: L) -> Expr
141 where
142 L: IntoLikeExpr,
143 {
144 self.binary(PgBinOper::ILike, like.into_like_expr())
145 }
146
147 /// Express a `NOT ILIKE` expression
148 fn not_ilike<L>(self, like: L) -> Expr
149 where
150 L: IntoLikeExpr,
151 {
152 self.binary(PgBinOper::NotILike, like.into_like_expr())
153 }
154
155 /// Express a postgres retrieves JSON field as JSON value (`->`).
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use sql_builder::{extension::postgres::PgExpr, *};
161 ///
162 /// let query = Query::select()
163 /// .column("variant")
164 /// .from("font")
165 /// .and_where(Expr::col("variant").get_json_field("a"))
166 /// .to_owned();
167 ///
168 /// assert_eq!(
169 /// query.to_string(PostgresQueryBuilder).unwrap(),
170 /// r#"SELECT "variant" FROM "font" WHERE "variant" -> 'a'"#
171 /// );
172 /// ```
173 fn get_json_field<T>(self, right: T) -> Expr
174 where
175 T: Into<Expr>,
176 {
177 self.binary(PgBinOper::GetJsonField, right)
178 }
179
180 /// Express a postgres retrieves JSON field and casts it to an appropriate SQL type (`->>`).
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use sql_builder::{extension::postgres::PgExpr, *};
186 ///
187 /// let query = Query::select()
188 /// .column("variant")
189 /// .from("font")
190 /// .and_where(Expr::col("variant").cast_json_field("a"))
191 /// .to_owned();
192 ///
193 /// assert_eq!(
194 /// query.to_string(PostgresQueryBuilder).unwrap(),
195 /// r#"SELECT "variant" FROM "font" WHERE "variant" ->> 'a'"#
196 /// );
197 /// ```
198 fn cast_json_field<T>(self, right: T) -> Expr
199 where
200 T: Into<Expr>,
201 {
202 self.binary(PgBinOper::CastJsonField, right)
203 }
204
205 /// Equivalent to `is_in` but bind parameters as array.
206 /// ```
207 /// use sql_builder::{extension::postgres::PgExpr, *};
208 ///
209 /// let query = Query::select()
210 /// .columns(["id"])
211 /// .from("character")
212 /// .and_where(
213 /// ("character", "size_w")
214 /// .into_column_ref()
215 /// .eq_any([1, 2, 3]),
216 /// )
217 /// .to_owned();
218 ///
219 /// assert_eq!(
220 /// query.to_string(PostgresQueryBuilder).unwrap(),
221 /// r#"SELECT "id" FROM "character" WHERE "character"."size_w" = ANY(ARRAY [1,2,3])"#
222 /// );
223 /// ```
224 fn eq_any<V, I>(self, v: I) -> Expr
225 where
226 V: Into<crate::Value> + crate::ValueType,
227 I: IntoIterator<Item = V>,
228 {
229 self.eq(super::PgFunc::any(crate::Value::Array(
230 V::array_type(),
231 Some(Box::new(v.into_iter().map(|v| v.into()).collect())),
232 )))
233 }
234
235 /// Equivalent to `is_not_in` but bind parameters as array.
236 /// ```
237 /// use sql_builder::{extension::postgres::PgExpr, *};
238 ///
239 /// let query = Query::select()
240 /// .columns(["id"])
241 /// .from("character")
242 /// .and_where(
243 /// ("character", "size_w")
244 /// .into_column_ref()
245 /// .ne_all([1, 2, 3]),
246 /// )
247 /// .to_owned();
248 ///
249 /// assert_eq!(
250 /// query.to_string(PostgresQueryBuilder).unwrap(),
251 /// r#"SELECT "id" FROM "character" WHERE "character"."size_w" <> ALL(ARRAY [1,2,3])"#
252 /// );
253 /// ```
254 fn ne_all<V, I>(self, v: I) -> Expr
255 where
256 V: Into<crate::Value> + crate::ValueType,
257 I: IntoIterator<Item = V>,
258 {
259 self.ne(super::PgFunc::all(crate::Value::Array(
260 V::array_type(),
261 Some(Box::new(v.into_iter().map(|v| v.into()).collect())),
262 )))
263 }
264}
265
266/// You should be able to use Postgres-specific operators with all types of expressions.
267impl<T> PgExpr for T where T: ExprTrait {}