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::All => sql.write_str("ALL").unwrap(),
114 SelectDistinct::Distinct => sql.write_str("DISTINCT").unwrap(),
115 SelectDistinct::DistinctOn(cols) => {
116 sql.write_str("DISTINCT ON (").unwrap();
117
118 let mut cols = cols.iter();
119 join_io!(
120 cols,
121 col,
122 join {
123 sql.write_str(", ").unwrap();
124 },
125 do {
126 expressions::prepare_column_ref(self, col, sql)?;
127 }
128 );
129
130 sql.write_str(")").unwrap();
131 }
132 _ => {}
133 };
134 Ok(())
135 }
136
137 fn prepare_select_into(
138 &self,
139 into_table: &SelectInto,
140 sql: &mut impl SqlWriter,
141 ) -> Result<(), RenderError> {
142 sql.write_str(" INTO ").unwrap();
143
144 if let Some(modifier) = &into_table.target_table_modifier {
145 sql.write_fmt(format_args!("{modifier} ")).unwrap();
146 }
147
148 sql.write_str("TABLE ").unwrap();
149 self.prepare_iden(&into_table.target_table, sql);
150 Ok(())
151 }
152
153 fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
154 if replace {
155 return Err(RenderError::Unsupported(
156 "PostgreSQL has no REPLACE; use ON CONFLICT .. DO UPDATE".into(),
157 ));
158 }
159 sql.write_str("INSERT").unwrap();
160 Ok(())
161 }
162
163 fn prepare_mutation_order_limit(
164 &self,
165 orders: &[OrderExpr],
166 limit: &Option<Value>,
167 _: &mut impl SqlWriter,
168 ) -> Result<(), RenderError> {
169 if orders.is_empty() && limit.is_none() {
170 return Ok(());
171 }
172 Err(RenderError::Unsupported(
173 "PostgreSQL has no ORDER BY or LIMIT in UPDATE or DELETE".into(),
174 ))
175 }
176
177 fn prepare_bin_oper(
178 &self,
179 bin_oper: &BinOper,
180 sql: &mut impl SqlWriter,
181 ) -> Result<(), RenderError> {
182 match bin_oper {
183 BinOper::PgOperator(oper) => sql.write_str(oper.sql()).unwrap(),
184 _ => expressions::prepare_bin_oper_common(self, bin_oper, sql)?,
185 }
186 Ok(())
187 }
188
189 fn prepare_function_name(
190 &self,
191 function: &Func,
192 sql: &mut impl SqlWriter,
193 ) -> Result<(), RenderError> {
194 match function {
195 Func::PgFunction(function) => sql
196 .write_str(match function {
197 PgFunc::ToTsquery => "TO_TSQUERY",
198 PgFunc::ToTsvector => "TO_TSVECTOR",
199 PgFunc::PhrasetoTsquery => "PHRASETO_TSQUERY",
200 PgFunc::PlaintoTsquery => "PLAINTO_TSQUERY",
201 PgFunc::WebsearchToTsquery => "WEBSEARCH_TO_TSQUERY",
202 PgFunc::TsRank => "TS_RANK",
203 PgFunc::TsRankCd => "TS_RANK_CD",
204 PgFunc::StartsWith => "STARTS_WITH",
205 PgFunc::GenRandomUUID => "GEN_RANDOM_UUID",
206 PgFunc::JsonBuildObject => "JSON_BUILD_OBJECT",
207 PgFunc::JsonAgg => "JSON_AGG",
208 PgFunc::ArrayAgg => "ARRAY_AGG",
209 PgFunc::DateTrunc => "DATE_TRUNC",
210 PgFunc::Any => "ANY",
211 PgFunc::Some => "SOME",
212 PgFunc::All => "ALL",
213 PgFunc::AdvisoryLock => "PG_ADVISORY_LOCK",
214 PgFunc::AdvisoryLockShared => "PG_ADVISORY_LOCK_SHARED",
215 PgFunc::TryAdvisoryLock => "PG_TRY_ADVISORY_LOCK",
216 PgFunc::TryAdvisoryLockShared => "PG_TRY_ADVISORY_LOCK_SHARED",
217 PgFunc::AdvisoryUnlock => "PG_ADVISORY_UNLOCK",
218 PgFunc::AdvisoryUnlockShared => "PG_ADVISORY_UNLOCK_SHARED",
219 PgFunc::AdvisoryUnlockAll => "PG_ADVISORY_UNLOCK_ALL",
220 PgFunc::AdvisoryXactLock => "PG_ADVISORY_XACT_LOCK",
221 PgFunc::AdvisoryXactLockShared => "PG_ADVISORY_XACT_LOCK_SHARED",
222 PgFunc::TryAdvisoryXactLock => "PG_TRY_ADVISORY_XACT_LOCK",
223 PgFunc::TryAdvisoryXactLockShared => "PG_TRY_ADVISORY_XACT_LOCK_SHARED",
224 })
225 .unwrap(),
226 _ => functions::prepare_function_name_common(self, function, sql)?,
227 }
228 Ok(())
229 }
230
231 fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
232 match value {
233 Value::Enum(value) => match value {
234 OptionEnum::Some(value) => {
235 let Enum { type_name, value } = *value;
236 sql.push_param(Value::String(Some(value.into_owned())), self as _)?;
237 self.write_enum_type_hint(type_name, sql);
238 }
239 OptionEnum::None(type_name) => {
240 sql.push_param(Value::String(None), self as _)?;
241 self.write_enum_type_hint(type_name, sql);
242 }
243 },
244 Value::Array(ArrayType::Enum(type_name), values) => {
245 let values = values
246 .map(|values| {
247 values
248 .iter()
249 .map(|value| {
250 crate::value::postgres_array::enum_array_element(value)
251 .map(|value| Value::String(Some(value.value.to_string())))
252 })
253 .collect::<Result<Vec<_>, _>>()
254 .map(Box::new)
255 })
256 .transpose();
257 let values = match values {
258 Ok(values) => values,
259 Err(_) => {
260 return Err(RenderError::Unsupported(
261 "Enum array contains a NULL or non-enum element".into(),
262 ));
263 }
264 };
265 sql.push_param(Value::Array(ArrayType::String, values), self as _)?;
266 self.write_enum_type_hint(type_name.as_ref(), sql);
267 sql.write_str("[]").unwrap();
268 }
269 _ => sql.push_param(value, self as _)?,
270 }
271 Ok(())
272 }
273
274 fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
275 if self.needs_escape(string) {
276 buffer.write_str("E'").unwrap();
277 } else {
278 buffer.write_str("'").unwrap();
279 }
280 self.write_escaped(buffer, string);
281 buffer.write_str("'").unwrap();
282 }
283
284 fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
285 buffer.write_str("'\\x").unwrap();
286 for b in bytes {
287 write!(buffer, "{b:02X}").unwrap();
288 }
289 buffer.write_str("'").unwrap();
290 }
291
292 fn if_null_function(&self) -> &str {
293 "COALESCE"
294 }
295}
296
297impl PostgresQueryBuilder {
298 fn write_enum_type_hint(&self, type_name: impl AsRef<str>, sql: &mut impl SqlWriter) {
299 sql.write_str("::").unwrap();
300 self.prepare_iden(&DynIden(Cow::Owned(type_name.as_ref().to_string())), sql);
301 }
302}
303
304fn is_pg_comparison(b: &BinOper) -> bool {
305 matches!(
306 b,
307 BinOper::PgOperator(PgBinOper::Contained)
308 | BinOper::PgOperator(PgBinOper::Contains)
309 | BinOper::PgOperator(PgBinOper::Similarity)
310 | BinOper::PgOperator(PgBinOper::WordSimilarity)
311 | BinOper::PgOperator(PgBinOper::StrictWordSimilarity)
312 | BinOper::PgOperator(PgBinOper::Matches)
313 )
314}
315
316fn is_ilike(b: &BinOper) -> bool {
317 matches!(
318 b,
319 BinOper::PgOperator(PgBinOper::ILike) | BinOper::PgOperator(PgBinOper::NotILike)
320 )
321}