Skip to main content

sql_builder/backend/postgres/
query.rs

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