sql_builder/backend/postgres/
query.rs1use super::*;
2use crate::ArrayType;
3use crate::extension::postgres::*;
4
5impl OperLeftAssocDecider for PostgresQueryBuilder {
6 fn well_known_left_associative(&self, op: &BinOper) -> bool {
7 let common_answer = common_well_known_left_associative(op);
8 let pg_specific_answer = matches!(op, BinOper::PgOperator(PgBinOper::Concatenate));
9 common_answer || pg_specific_answer
10 }
11}
12
13impl PrecedenceDecider for PostgresQueryBuilder {
14 fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
15 let common_answer = common_inner_expr_well_known_greater_precedence(inner, outer_oper);
16 let pg_specific_answer = match inner {
17 Expr::Binary(_, inner_bin_oper, _) => {
18 let inner_oper: Oper = (*inner_bin_oper).into();
19 if inner_oper.is_arithmetic() || inner_oper.is_shift() {
20 is_ilike(inner_bin_oper)
21 } else if is_pg_comparison(inner_bin_oper) {
22 outer_oper.is_logical()
23 } else {
24 false
25 }
26 }
27 _ => false,
28 };
29 common_answer || pg_specific_answer
30 }
31}
32
33impl QueryBuilder for PostgresQueryBuilder {
34 fn placeholder(&self) -> (&'static str, bool) {
35 ("$", true)
36 }
37
38 fn lexer_dialect(&self) -> crate::lexer::Dialect {
39 crate::lexer::Dialect::Postgres
40 }
41
42 fn prepare_expr(
43 &self,
44 simple_expr: &Expr,
45 sql: &mut impl SqlWriter,
46 ) -> Result<(), RenderError> {
47 match simple_expr {
48 Expr::AsEnum(type_name, expr) => {
49 sql.write_str("CAST(").unwrap();
50 expressions::prepare_expr_common(self, expr, sql)?;
51 let type_name = &type_name.0;
52 let (ty, sfx) = if let Some(base) = type_name.strip_suffix("[]") {
53 (base, "[]")
54 } else {
55 (type_name.as_ref(), "")
56 };
57 sql.write_str(" AS ").unwrap();
58 self.prepare_iden(&DynIden(Cow::Owned(ty.to_string())), sql);
59 sql.write_str(sfx).unwrap();
60 sql.write_char(')').unwrap();
61 }
62 _ => expressions::prepare_expr_common(self, simple_expr, sql)?,
63 }
64 Ok(())
65 }
66
67 fn write_value(&self, buf: &mut impl SqlWriter, value: &Value) -> Result<(), RenderError> {
68 match value {
69 Value::Enum(v) => match v {
70 OptionEnum::Some(v) => {
71 self.write_string_quoted(v.value.as_ref(), buf);
72 self.write_enum_type_hint(v.type_name.as_ref(), buf);
73 }
74 OptionEnum::None(_) => buf.write_str("NULL").unwrap(),
75 },
76 Value::Array(ArrayType::Enum(type_name), values) => {
77 match values {
78 None => buf.write_str("NULL").unwrap(),
79 Some(values) if values.is_empty() => buf.write_str("'{}'").unwrap(),
80 Some(values) => {
81 let elements = values
82 .iter()
83 .map(crate::value::postgres_array::enum_array_element)
84 .collect::<Result<Vec<_>, _>>()
85 .map_err(|_| {
86 RenderError::Unsupported(
87 "Enum array contains a NULL or non-enum element".into(),
88 )
89 })?;
90 buf.write_str("ARRAY [").unwrap();
91 for (index, element) in elements.iter().enumerate() {
92 if index > 0 {
93 buf.write_str(",").unwrap();
94 }
95 self.write_string_quoted(element.value.as_ref(), buf);
96 }
97 buf.write_str("]").unwrap();
98 }
99 }
100 self.write_enum_type_hint(type_name.as_ref(), buf);
101 }
102 _ => return values::write_value_common(self, buf, value),
103 }
104 Ok(())
105 }
106
107 fn prepare_select_distinct(
108 &self,
109 select_distinct: &SelectDistinct,
110 sql: &mut impl SqlWriter,
111 ) -> Result<(), RenderError> {
112 match select_distinct {
113 SelectDistinct::DistinctOn(cols) => {
114 sql.write_str("DISTINCT ON (").unwrap();
115
116 let mut cols = cols.iter();
117 join_io!(
118 cols,
119 col,
120 join {
121 sql.write_str(", ").unwrap();
122 },
123 do {
124 expressions::prepare_column_ref(self, col, sql)?;
125 }
126 );
127
128 sql.write_str(")").unwrap();
129 }
130 other => return expressions::prepare_select_distinct(self, other, sql),
131 };
132 Ok(())
133 }
134
135 fn prepare_cte_query(
137 &self,
138 query: &SubQueryStatement,
139 sql: &mut impl SqlWriter,
140 ) -> Result<(), RenderError> {
141 self.prepare_query_statement(query, sql)
142 }
143
144 fn prepare_select_into(
145 &self,
146 into_table: &SelectInto,
147 sql: &mut impl SqlWriter,
148 ) -> Result<(), RenderError> {
149 sql.write_str(" INTO ").unwrap();
150
151 if let Some(modifier) = &into_table.target_table_modifier {
152 sql.write_fmt(format_args!("{modifier} ")).unwrap();
153 }
154
155 sql.write_str("TABLE ").unwrap();
156 self.prepare_iden(&into_table.target_table, sql);
157 Ok(())
158 }
159
160 fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
161 if replace {
162 return Err(RenderError::Unsupported(
163 "PostgreSQL has no REPLACE; use ON CONFLICT .. DO UPDATE".into(),
164 ));
165 }
166 sql.write_str("INSERT").unwrap();
167 Ok(())
168 }
169
170 fn prepare_mutation_order_limit(
171 &self,
172 orders: &[OrderExpr],
173 limit: &Option<Value>,
174 _: &mut impl SqlWriter,
175 ) -> Result<(), RenderError> {
176 if orders.is_empty() && limit.is_none() {
177 return Ok(());
178 }
179 Err(RenderError::Unsupported(
180 "PostgreSQL has no ORDER BY or LIMIT in UPDATE or DELETE".into(),
181 ))
182 }
183
184 fn prepare_bin_oper(
185 &self,
186 bin_oper: &BinOper,
187 sql: &mut impl SqlWriter,
188 ) -> Result<(), RenderError> {
189 match bin_oper {
190 BinOper::PgOperator(oper) => sql.write_str(oper.sql()).unwrap(),
191 _ => expressions::prepare_bin_oper_common(self, bin_oper, sql)?,
192 }
193 Ok(())
194 }
195
196 fn prepare_function_name(
197 &self,
198 function: &Func,
199 sql: &mut impl SqlWriter,
200 ) -> Result<(), RenderError> {
201 match function {
202 Func::PgFunction(function) => sql
203 .write_str(match function {
204 PgFunc::ToTsquery => "TO_TSQUERY",
205 PgFunc::ToTsvector => "TO_TSVECTOR",
206 PgFunc::PhrasetoTsquery => "PHRASETO_TSQUERY",
207 PgFunc::PlaintoTsquery => "PLAINTO_TSQUERY",
208 PgFunc::WebsearchToTsquery => "WEBSEARCH_TO_TSQUERY",
209 PgFunc::TsRank => "TS_RANK",
210 PgFunc::TsRankCd => "TS_RANK_CD",
211 PgFunc::StartsWith => "STARTS_WITH",
212 PgFunc::GenRandomUUID => "GEN_RANDOM_UUID",
213 PgFunc::JsonBuildObject => "JSON_BUILD_OBJECT",
214 PgFunc::JsonAgg => "JSON_AGG",
215 PgFunc::ArrayAgg => "ARRAY_AGG",
216 PgFunc::DateTrunc => "DATE_TRUNC",
217 PgFunc::Any => "ANY",
218 PgFunc::Some => "SOME",
219 PgFunc::All => "ALL",
220 PgFunc::AdvisoryLock => "PG_ADVISORY_LOCK",
221 PgFunc::AdvisoryLockShared => "PG_ADVISORY_LOCK_SHARED",
222 PgFunc::TryAdvisoryLock => "PG_TRY_ADVISORY_LOCK",
223 PgFunc::TryAdvisoryLockShared => "PG_TRY_ADVISORY_LOCK_SHARED",
224 PgFunc::AdvisoryUnlock => "PG_ADVISORY_UNLOCK",
225 PgFunc::AdvisoryUnlockShared => "PG_ADVISORY_UNLOCK_SHARED",
226 PgFunc::AdvisoryUnlockAll => "PG_ADVISORY_UNLOCK_ALL",
227 PgFunc::AdvisoryXactLock => "PG_ADVISORY_XACT_LOCK",
228 PgFunc::AdvisoryXactLockShared => "PG_ADVISORY_XACT_LOCK_SHARED",
229 PgFunc::TryAdvisoryXactLock => "PG_TRY_ADVISORY_XACT_LOCK",
230 PgFunc::TryAdvisoryXactLockShared => "PG_TRY_ADVISORY_XACT_LOCK_SHARED",
231 })
232 .unwrap(),
233 _ => functions::prepare_function_name_common(self, function, sql)?,
234 }
235 Ok(())
236 }
237
238 fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
239 match value {
240 Value::Enum(value) => match value {
241 OptionEnum::Some(value) => {
242 let Enum { type_name, value } = *value;
243 sql.push_param(Value::String(Some(value.into_owned())), self as _)?;
244 self.write_enum_type_hint(type_name, sql);
245 }
246 OptionEnum::None(type_name) => {
247 sql.push_param(Value::String(None), self as _)?;
248 self.write_enum_type_hint(type_name, sql);
249 }
250 },
251 Value::Array(ArrayType::Enum(type_name), values) => {
252 let values = values
253 .map(|values| {
254 values
255 .iter()
256 .map(|value| {
257 crate::value::postgres_array::enum_array_element(value)
258 .map(|value| Value::String(Some(value.value.to_string())))
259 })
260 .collect::<Result<Vec<_>, _>>()
261 .map(Box::new)
262 })
263 .transpose();
264 let values = match values {
265 Ok(values) => values,
266 Err(_) => {
267 return Err(RenderError::Unsupported(
268 "Enum array contains a NULL or non-enum element".into(),
269 ));
270 }
271 };
272 sql.push_param(Value::Array(ArrayType::String, values), self as _)?;
273 self.write_enum_type_hint(type_name.as_ref(), sql);
274 sql.write_str("[]").unwrap();
275 }
276 _ => sql.push_param(value, self as _)?,
277 }
278 Ok(())
279 }
280
281 fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
282 if self.needs_escape(string) {
283 buffer.write_str("E'").unwrap();
284 } else {
285 buffer.write_str("'").unwrap();
286 }
287 self.write_escaped(buffer, string);
288 buffer.write_str("'").unwrap();
289 }
290
291 fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
292 buffer.write_str("'\\x").unwrap();
293 for b in bytes {
294 write!(buffer, "{b:02X}").unwrap();
295 }
296 buffer.write_str("'").unwrap();
297 }
298
299 fn if_null_function(&self) -> &str {
300 "COALESCE"
301 }
302}
303
304impl PostgresQueryBuilder {
305 fn write_enum_type_hint(&self, type_name: impl AsRef<str>, sql: &mut impl SqlWriter) {
306 sql.write_str("::").unwrap();
307 self.prepare_iden(&DynIden(Cow::Owned(type_name.as_ref().to_string())), sql);
308 }
309}
310
311fn is_pg_comparison(b: &BinOper) -> bool {
312 matches!(
313 b,
314 BinOper::PgOperator(PgBinOper::Contained)
315 | BinOper::PgOperator(PgBinOper::Contains)
316 | BinOper::PgOperator(PgBinOper::Similarity)
317 | BinOper::PgOperator(PgBinOper::WordSimilarity)
318 | BinOper::PgOperator(PgBinOper::StrictWordSimilarity)
319 | BinOper::PgOperator(PgBinOper::Matches)
320 )
321}
322
323fn is_ilike(b: &BinOper) -> bool {
324 matches!(
325 b,
326 BinOper::PgOperator(PgBinOper::ILike) | BinOper::PgOperator(PgBinOper::NotILike)
327 )
328}