Skip to main content

orbit_orm/
query.rs

1use std::marker::PhantomData;
2
3use crate::backend;
4use crate::driver::rows::DriverRows;
5use crate::transaction::Executor;
6use crate::{Driver, Error, Model, Value};
7
8/// A comparison for `where_op`.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Operator {
11    Lt,
12    Le,
13    Gt,
14    Ge,
15    Ne,
16    /// `LIKE`, case-insensitive on every database, as Laravel's `whereLike` is by default. The
17    /// value is the pattern, with `%` and `_` as wildcards. On PostgreSQL it is `ILIKE`.
18    Like,
19}
20
21impl Operator {
22    fn sql(self) -> &'static str {
23        match self {
24            Self::Lt => "<",
25            Self::Le => "<=",
26            Self::Gt => ">",
27            Self::Ge => ">=",
28            Self::Ne => "!=",
29            Self::Like => "LIKE",
30        }
31    }
32}
33
34/// The sort direction for `order_by`.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Direction {
37    Asc,
38    Desc,
39}
40
41/// How a condition joins the one before it. The first condition has no joiner.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43enum Joiner {
44    And,
45    Or,
46}
47
48/// A condition, with its names as given. They are quoted when the SQL is built, for the driver
49/// that runs it.
50#[derive(Debug, Clone)]
51enum Condition {
52    Compare {
53        column: String,
54        op: &'static str,
55        value: Value,
56    },
57    In {
58        column: String,
59        values: Vec<Value>,
60    },
61    Null {
62        column: String,
63        negated: bool,
64    },
65    /// A parenthesised group, built by `where_group`.
66    Group(Vec<Clause>),
67}
68
69#[derive(Debug, Clone)]
70struct Clause {
71    joiner: Joiner,
72    condition: Condition,
73}
74
75/// A query on one model's table. Start it with `Model::query()` or `Query::table()`, then
76/// finish it with a terminal method such as `get`, `first` or `insert`.
77pub struct Query<M: Model> {
78    table: String,
79    conditions: Vec<Clause>,
80    orders: Vec<(String, Direction)>,
81    columns: Option<Vec<String>>,
82    limit: Option<u64>,
83    offset: Option<u64>,
84    lock: bool,
85    error: Option<Error>,
86    model: PhantomData<M>,
87}
88
89/// The values bound to one statement, in placeholder order. Each call to `bind` adds one and
90/// returns the placeholder for it, in the driver's syntax.
91pub(crate) struct Params {
92    driver: Driver,
93    pub(crate) values: Vec<Value>,
94}
95
96impl Params {
97    pub(crate) fn new(driver: Driver) -> Self {
98        Self {
99            driver,
100            values: Vec::new(),
101        }
102    }
103
104    /// Adds `value` and returns its placeholder. A `NULL` is written as `NULL` on drivers that
105    /// inline it, and is not bound.
106    pub(crate) fn bind(&mut self, value: Value) -> String {
107        if matches!(value, Value::Null) && self.driver.inlines_null() {
108            return "NULL".to_owned();
109        }
110        self.values.push(value);
111        self.driver.placeholder(self.values.len())
112    }
113}
114
115/// Checks a table or column name. It must not be empty, and must not contain a backtick or a
116/// double quote, which are the quote characters of the supported databases.
117pub(crate) fn validate(name: &str) -> Result<(), Error> {
118    if name.is_empty() || name.contains(['`', '"']) {
119        return Err(Error::InvalidIdentifier(name.to_owned()));
120    }
121    Ok(())
122}
123
124/// Checks a name, or records the error and returns the name for the terminal to report.
125fn checked(name: &str, error: &mut Option<Error>) -> String {
126    if let Err(e) = validate(name) {
127        error.get_or_insert(e);
128    }
129    name.to_owned()
130}
131
132/// Checks a column that `insert` or `update` writes against `FILLABLE`.
133fn fillable<M: Model>(column: &str) -> Result<(), Error> {
134    if !M::FILLABLE.contains(&column) {
135        return Err(Error::NotFillable {
136            table: M::TABLE,
137            column: column.to_owned(),
138        });
139    }
140    validate(column)
141}
142
143impl<M: Model> Query<M> {
144    /// Starts a query on the model's table.
145    pub fn table() -> Self {
146        let mut error = None;
147        let table = checked(M::TABLE, &mut error);
148        Self {
149            table,
150            error,
151            ..Self::blank()
152        }
153    }
154
155    /// A query with no table, for the conditions of a group.
156    fn blank() -> Self {
157        Self {
158            table: String::new(),
159            conditions: Vec::new(),
160            orders: Vec::new(),
161            columns: None,
162            limit: None,
163            offset: None,
164            lock: false,
165            error: None,
166            model: PhantomData,
167        }
168    }
169
170    /// Adds `column = value`. A `NULL` value becomes `IS NULL`, as in Laravel.
171    pub fn where_eq(self, column: &str, value: impl Into<Value>) -> Self {
172        self.compare(Joiner::And, column, "=", value.into())
173    }
174
175    /// Adds `OR column = value`.
176    pub fn or_where_eq(self, column: &str, value: impl Into<Value>) -> Self {
177        self.compare(Joiner::Or, column, "=", value.into())
178    }
179
180    /// Adds `column <op> value`. `!=` with a `NULL` value becomes `IS NOT NULL`.
181    pub fn where_op(self, column: &str, op: Operator, value: impl Into<Value>) -> Self {
182        self.compare(Joiner::And, column, op.sql(), value.into())
183    }
184
185    /// Adds `OR column <op> value`. `!=` with a `NULL` value becomes `IS NOT NULL`.
186    pub fn or_where_op(self, column: &str, op: Operator, value: impl Into<Value>) -> Self {
187        self.compare(Joiner::Or, column, op.sql(), value.into())
188    }
189
190    fn compare(self, joiner: Joiner, column: &str, op: &'static str, value: Value) -> Self {
191        let mut this = self;
192        let column = checked(column, &mut this.error);
193        let condition = match (value, op) {
194            (Value::Null, "=") => Condition::Null {
195                column,
196                negated: false,
197            },
198            (Value::Null, "!=") => Condition::Null {
199                column,
200                negated: true,
201            },
202            (value, op) => Condition::Compare { column, op, value },
203        };
204        this.push(joiner, condition)
205    }
206
207    /// Adds `column IN (values)`. An empty list matches no rows, as in Laravel.
208    pub fn where_in<V: Into<Value>>(
209        self,
210        column: &str,
211        values: impl IntoIterator<Item = V>,
212    ) -> Self {
213        self.in_list(Joiner::And, column, values)
214    }
215
216    /// Adds `OR column IN (values)`. An empty list matches no rows.
217    pub fn or_where_in<V: Into<Value>>(
218        self,
219        column: &str,
220        values: impl IntoIterator<Item = V>,
221    ) -> Self {
222        self.in_list(Joiner::Or, column, values)
223    }
224
225    fn in_list<V: Into<Value>>(
226        mut self,
227        joiner: Joiner,
228        column: &str,
229        values: impl IntoIterator<Item = V>,
230    ) -> Self {
231        let column = checked(column, &mut self.error);
232        let values = values.into_iter().map(Into::into).collect();
233        self.push(joiner, Condition::In { column, values })
234    }
235
236    /// Adds `column IS NULL`.
237    pub fn where_null(self, column: &str) -> Self {
238        self.null(Joiner::And, column, false)
239    }
240
241    /// Adds `OR column IS NULL`.
242    pub fn or_where_null(self, column: &str) -> Self {
243        self.null(Joiner::Or, column, false)
244    }
245
246    /// Adds `column IS NOT NULL`.
247    pub fn where_not_null(self, column: &str) -> Self {
248        self.null(Joiner::And, column, true)
249    }
250
251    /// Adds `OR column IS NOT NULL`.
252    pub fn or_where_not_null(self, column: &str) -> Self {
253        self.null(Joiner::Or, column, true)
254    }
255
256    fn null(mut self, joiner: Joiner, column: &str, negated: bool) -> Self {
257        let column = checked(column, &mut self.error);
258        self.push(joiner, Condition::Null { column, negated })
259    }
260
261    /// Adds a group of conditions joined by `AND`, in parentheses. The closure gets an empty
262    /// query and adds its conditions to it, as Laravel's `where(fn)` does:
263    ///
264    /// ```ignore
265    /// .where_group(|q| q.where_eq("title", "a").or_where_eq("title", "b"))
266    /// ```
267    ///
268    /// Only where conditions are kept from the group; `order_by`, `limit` and the other
269    /// settings are ignored. An empty group adds nothing.
270    pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
271        self.group(Joiner::And, f)
272    }
273
274    /// Adds a group of conditions joined by `OR`, in parentheses. See `where_group`.
275    pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self {
276        self.group(Joiner::Or, f)
277    }
278
279    fn group(mut self, joiner: Joiner, f: impl FnOnce(Self) -> Self) -> Self {
280        let inner = f(Self::blank());
281        if let Some(error) = inner.error {
282            self.error.get_or_insert(error);
283        }
284        if inner.conditions.is_empty() {
285            return self;
286        }
287        self.push(joiner, Condition::Group(inner.conditions))
288    }
289
290    fn push(mut self, joiner: Joiner, condition: Condition) -> Self {
291        self.conditions.push(Clause { joiner, condition });
292        self
293    }
294
295    /// Adds a sort. Later calls sort within the earlier ones.
296    pub fn order_by(mut self, column: &str, direction: Direction) -> Self {
297        let column = checked(column, &mut self.error);
298        self.orders.push((column, direction));
299        self
300    }
301
302    /// Chooses the columns that `get` and `first` select. Without it, all columns are selected.
303    pub fn select(mut self, columns: &[&str]) -> Self {
304        if columns.is_empty() {
305            return self;
306        }
307        let names = columns
308            .iter()
309            .map(|column| checked(column, &mut self.error))
310            .collect();
311        self.columns = Some(names);
312        self
313    }
314
315    /// Returns at most `limit` rows.
316    pub fn limit(mut self, limit: u64) -> Self {
317        self.limit = Some(limit);
318        self
319    }
320
321    /// Skips the first `offset` rows.
322    pub fn offset(mut self, offset: u64) -> Self {
323        self.offset = Some(offset);
324        self
325    }
326
327    /// Locks the matching rows (`SELECT ... FOR UPDATE`). It applies to `get`, `first`, `find`,
328    /// `count` and `exists`. In a transaction the lock lasts until it ends. On the pool it lasts
329    /// only for the statement, in autocommit, as Laravel's `lockForUpdate()` does. SQLite has no
330    /// row locks, so the clause is left out there, as Laravel's SQLite grammar does.
331    pub fn for_update(mut self) -> Self {
332        self.lock = true;
333        self
334    }
335
336    /// Returns every row that matches.
337    pub async fn get<'a>(mut self, db: impl Executor<'a>) -> Result<Vec<M>, Error>
338    where
339        M: DriverRows,
340    {
341        self.take_error()?;
342        self.rows(db, self.limit).await
343    }
344
345    /// Returns every row that matches, decoded as `T` instead of the model. Use it with `select`
346    /// to read some columns into a tuple or a struct that implements `FromRow`. The clauses are
347    /// the same as `get`.
348    ///
349    /// ```ignore
350    /// let titles = Post::query()
351    ///     .select(&["id", "title"])
352    ///     .get_as::<(i64, String)>(&db)
353    ///     .await?;
354    /// ```
355    pub async fn get_as<'a, T>(mut self, db: impl Executor<'a>) -> Result<Vec<T>, Error>
356    where
357        T: DriverRows + Send + Unpin,
358    {
359        self.take_error()?;
360        self.rows::<T>(db, self.limit).await
361    }
362
363    /// Returns the first row decoded as `T`, in the order given by `order_by`. See `get_as`.
364    pub async fn first_as<'a, T>(mut self, db: impl Executor<'a>) -> Result<Option<T>, Error>
365    where
366        T: DriverRows + Send + Unpin,
367    {
368        self.take_error()?;
369        let rows = self.rows::<T>(db, Some(1)).await?;
370        Ok(rows.into_iter().next())
371    }
372
373    /// Returns the first row in the order given by `order_by`. Without `order_by` there is no
374    /// order, as with Laravel's `first`, so call `order_by` when the row matters.
375    pub async fn first<'a>(mut self, db: impl Executor<'a>) -> Result<Option<M>, Error>
376    where
377        M: DriverRows,
378    {
379        self.take_error()?;
380        let rows = self.rows::<M>(db, Some(1)).await?;
381        Ok(rows.into_iter().next())
382    }
383
384    /// Returns the first row, or an error when none matches.
385    pub async fn first_or_fail<'a>(self, db: impl Executor<'a>) -> Result<M, Error>
386    where
387        M: DriverRows,
388    {
389        self.first(db)
390            .await?
391            .ok_or(Error::NotFound { table: M::TABLE })
392    }
393
394    /// Returns the row with the given primary key, or `None` when there is none.
395    pub async fn find<'a>(
396        self,
397        db: impl Executor<'a>,
398        id: impl Into<Value>,
399    ) -> Result<Option<M>, Error>
400    where
401        M: DriverRows,
402    {
403        self.where_eq(M::PRIMARY_KEY, id).first(db).await
404    }
405
406    /// Returns the row with the given primary key, or an error when there is none.
407    pub async fn find_or_fail<'a>(
408        self,
409        db: impl Executor<'a>,
410        id: impl Into<Value>,
411    ) -> Result<M, Error>
412    where
413        M: DriverRows,
414    {
415        self.find(db, id)
416            .await?
417            .ok_or(Error::NotFound { table: M::TABLE })
418    }
419
420    /// Counts the rows that match.
421    pub async fn count<'a>(mut self, db: impl Executor<'a>) -> Result<i64, Error> {
422        self.take_error()?;
423        let target = db.target();
424        let driver = target.driver();
425        let mut params = Params::new(driver);
426        let sql = format!(
427            "SELECT COUNT(*) FROM {}{}{}",
428            self.table_sql(driver),
429            self.where_sql(driver, &mut params),
430            self.lock_sql(driver)
431        );
432        Ok(backend::scalar::<i64>(target, &sql, &params.values).await?)
433    }
434
435    /// Returns whether any row matches.
436    pub async fn exists<'a>(mut self, db: impl Executor<'a>) -> Result<bool, Error> {
437        self.take_error()?;
438        let target = db.target();
439        let driver = target.driver();
440        let mut params = Params::new(driver);
441        // The flag is cast to an integer so that every driver returns the same type.
442        let sql = format!(
443            "SELECT CAST(CASE WHEN EXISTS (SELECT 1 FROM {}{}{}) THEN 1 ELSE 0 END AS {})",
444            self.table_sql(driver),
445            self.where_sql(driver, &mut params),
446            self.lock_sql(driver),
447            driver.bigint()
448        );
449        let found = backend::scalar::<i64>(target, &sql, &params.values).await?;
450        Ok(found != 0)
451    }
452
453    /// Inserts one row and returns its auto-increment id, as Laravel's `insertGetId` does. The
454    /// columns must be in `FILLABLE`.
455    ///
456    /// On PostgreSQL the id comes from `RETURNING` on the primary key, in the key's own type, as
457    /// Laravel's PostgreSQL grammar does. When the key is not an integer (a text key, say), the
458    /// database generates no id, so `insert` returns 0, as MySQL's insert id is 0 for a table
459    /// with no auto-increment column. The key is stored as given; read it from your values.
460    pub async fn insert<'a>(
461        mut self,
462        db: impl Executor<'a>,
463        values: &[(&str, Value)],
464    ) -> Result<u64, Error> {
465        self.take_error()?;
466        let target = db.target();
467        let driver = target.driver();
468        let mut params = Params::new(driver);
469        let returning = driver
470            .insert_returns_id()
471            .then(|| format!(" RETURNING {}", driver.quote(M::PRIMARY_KEY)));
472        let sql = self.insert_sql(driver, "INSERT", &mut params, values, returning.as_deref())?;
473        if returning.is_some() {
474            let row: Option<ReturnedKey> =
475                backend::fetch_optional(target, &sql, &params.values).await?;
476            let ReturnedKey(id) = row.ok_or(Error::Database(sqlx::Error::RowNotFound))?;
477            return match id {
478                Some(id) => {
479                    u64::try_from(id).map_err(|_| Error::Database(sqlx::Error::RowNotFound))
480                }
481                None => Ok(0),
482            };
483        }
484        let outcome = backend::execute(target, &sql, &params.values).await?;
485        outcome.insert_id.ok_or(Error::Unsupported {
486            operation: "reading the insert id",
487            driver: driver.name(),
488        })
489    }
490
491    /// Replaces the row that has the same unique key or primary key as `values`, or inserts the
492    /// row when none has. Returns the rows affected, as the database reports them: MySQL gives 2
493    /// when a row was replaced, since it deletes the old row and inserts the new one, and SQLite
494    /// gives 1.
495    ///
496    /// This is Diesel's `replace_into`, which issues `REPLACE INTO` on MySQL and SQLite. It is not
497    /// Laravel's `upsert`, which is `INSERT ... ON DUPLICATE KEY UPDATE` or `ON CONFLICT`. The old
498    /// row is deleted, so its auto-increment id changes and columns not in `values` take their
499    /// defaults. The columns must be in `FILLABLE`.
500    ///
501    /// PostgreSQL has no `REPLACE`, and `INSERT ... ON CONFLICT` would keep the old row. So on
502    /// PostgreSQL this returns `Error::Unsupported`.
503    pub async fn replace<'a>(
504        mut self,
505        db: impl Executor<'a>,
506        values: &[(&str, Value)],
507    ) -> Result<u64, Error> {
508        self.take_error()?;
509        let target = db.target();
510        let driver = target.driver();
511        if !driver.supports_replace() {
512            return Err(Error::Unsupported {
513                operation: "replace",
514                driver: driver.name(),
515            });
516        }
517        let mut params = Params::new(driver);
518        let sql = self.insert_sql(driver, "REPLACE", &mut params, values, None)?;
519        let outcome = backend::execute(target, &sql, &params.values).await?;
520        Ok(outcome.rows_affected)
521    }
522
523    /// Builds `INSERT INTO table (columns) VALUES (...)`, with `returning` appended. The columns
524    /// must be in `FILLABLE`.
525    fn insert_sql(
526        &self,
527        driver: Driver,
528        keyword: &str,
529        params: &mut Params,
530        values: &[(&str, Value)],
531        returning: Option<&str>,
532    ) -> Result<String, Error> {
533        let mut columns = Vec::with_capacity(values.len());
534        let mut placeholders = Vec::with_capacity(values.len());
535        for (column, value) in values {
536            fillable::<M>(column)?;
537            columns.push(driver.quote(column));
538            placeholders.push(params.bind(value.clone()));
539        }
540        let table = self.table_sql(driver);
541        let returning = returning.unwrap_or("");
542        Ok(if columns.is_empty() {
543            format!(
544                "{keyword} INTO {table} {}{returning}",
545                driver.empty_insert()
546            )
547        } else {
548            format!(
549                "{keyword} INTO {table} ({}) VALUES ({}){returning}",
550                columns.join(", "),
551                placeholders.join(", ")
552            )
553        })
554    }
555
556    /// Sets the columns on every matching row and returns how many rows matched. The columns
557    /// must be in `FILLABLE`. Order and limit are ignored.
558    pub async fn update<'a>(
559        mut self,
560        db: impl Executor<'a>,
561        values: &[(&str, Value)],
562    ) -> Result<u64, Error> {
563        self.take_error()?;
564        if values.is_empty() {
565            return Ok(0);
566        }
567        let target = db.target();
568        let driver = target.driver();
569        let mut params = Params::new(driver);
570        let mut sets = Vec::with_capacity(values.len());
571        for (column, value) in values {
572            fillable::<M>(column)?;
573            let placeholder = params.bind(value.clone());
574            sets.push(format!("{} = {placeholder}", driver.quote(column)));
575        }
576        let mut sql = format!("UPDATE {} SET {}", self.table_sql(driver), sets.join(", "));
577        sql.push_str(&self.where_sql(driver, &mut params));
578        let outcome = backend::execute(target, &sql, &params.values).await?;
579        Ok(outcome.rows_affected)
580    }
581
582    /// Deletes every matching row and returns how many rows were deleted. Order and limit are
583    /// ignored.
584    pub async fn delete<'a>(mut self, db: impl Executor<'a>) -> Result<u64, Error> {
585        self.take_error()?;
586        let target = db.target();
587        let driver = target.driver();
588        let mut params = Params::new(driver);
589        let sql = format!(
590            "DELETE FROM {}{}",
591            self.table_sql(driver),
592            self.where_sql(driver, &mut params)
593        );
594        let outcome = backend::execute(target, &sql, &params.values).await?;
595        Ok(outcome.rows_affected)
596    }
597
598    /// Returns the first error recorded while building the query.
599    fn take_error(&mut self) -> Result<(), Error> {
600        match self.error.take() {
601            Some(e) => Err(e),
602            None => Ok(()),
603        }
604    }
605
606    /// The lock clause when `for_update` was asked for, or nothing.
607    fn lock_sql(&self, driver: Driver) -> &'static str {
608        if self.lock { driver.lock_clause() } else { "" }
609    }
610
611    /// The quoted table name.
612    fn table_sql(&self, driver: Driver) -> String {
613        driver.quote(&self.table)
614    }
615
616    async fn rows<'a, T>(&self, db: impl Executor<'a>, limit: Option<u64>) -> Result<Vec<T>, Error>
617    where
618        T: DriverRows + Send + Unpin,
619    {
620        let target = db.target();
621        let driver = target.driver();
622        let columns = match &self.columns {
623            Some(names) => names
624                .iter()
625                .map(|name| driver.quote(name))
626                .collect::<Vec<_>>()
627                .join(", "),
628            None => "*".to_owned(),
629        };
630        let mut params = Params::new(driver);
631        let sql = self.select_sql(driver, &columns, limit, &mut params);
632        Ok(backend::fetch_all::<T>(target, &sql, &params.values).await?)
633    }
634
635    /// Builds `SELECT` with the where clauses, order, limit, offset and lock.
636    fn select_sql(
637        &self,
638        driver: Driver,
639        columns: &str,
640        limit: Option<u64>,
641        params: &mut Params,
642    ) -> String {
643        let mut sql = format!("SELECT {columns} FROM {}", self.table_sql(driver));
644        sql.push_str(&self.where_sql(driver, params));
645        if !self.orders.is_empty() {
646            let terms: Vec<String> = self
647                .orders
648                .iter()
649                .map(|(column, direction)| match direction {
650                    Direction::Asc => format!("{} ASC", driver.quote(column)),
651                    Direction::Desc => format!("{} DESC", driver.quote(column)),
652                })
653                .collect();
654            sql.push_str(&format!(" ORDER BY {}", terms.join(", ")));
655        }
656        if let Some(limit) = limit {
657            sql.push_str(&format!(" LIMIT {}", params.bind(Value::UInt(limit))));
658        } else if let (true, Some(all)) = (self.offset.is_some(), driver.offset_only_limit()) {
659            // MySQL and SQLite need a LIMIT before OFFSET, so they get their largest value.
660            sql.push_str(&format!(" LIMIT {all}"));
661        }
662        if let Some(offset) = self.offset {
663            sql.push_str(&format!(" OFFSET {}", params.bind(Value::UInt(offset))));
664        }
665        sql.push_str(self.lock_sql(driver));
666        sql
667    }
668
669    /// Builds ` WHERE ...` from the conditions, or nothing.
670    fn where_sql(&self, driver: Driver, params: &mut Params) -> String {
671        if self.conditions.is_empty() {
672            return String::new();
673        }
674        format!(" WHERE {}", render(driver, &self.conditions, params))
675    }
676}
677
678/// The primary key that `INSERT ... RETURNING` gives back: its value when the key column is an
679/// integer, or `None` for any other type (a text key, say), which has no generated id.
680struct ReturnedKey(Option<i64>);
681
682impl<'r, R> sqlx::FromRow<'r, R> for ReturnedKey
683where
684    R: sqlx::Row,
685    usize: sqlx::ColumnIndex<R>,
686    i16: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
687    i32: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
688    i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
689{
690    fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
691        use sqlx::{TypeInfo, ValueRef};
692        let raw = row.try_get_raw(0)?;
693        if raw.is_null() {
694            return Ok(Self(None));
695        }
696        let name = raw.type_info().name().to_owned();
697        Ok(Self(match name.as_str() {
698            "INT2" => Some(i64::from(row.try_get::<i16, _>(0)?)),
699            "INT4" => Some(i64::from(row.try_get::<i32, _>(0)?)),
700            "INT8" => Some(row.try_get::<i64, _>(0)?),
701            _ => None,
702        }))
703    }
704}
705
706/// Joins the clauses with their `AND` or `OR`. Values are bound in the order they appear.
707fn render(driver: Driver, clauses: &[Clause], params: &mut Params) -> String {
708    let mut sql = String::new();
709    for (index, clause) in clauses.iter().enumerate() {
710        if index > 0 {
711            sql.push_str(match clause.joiner {
712                Joiner::And => " AND ",
713                Joiner::Or => " OR ",
714            });
715        }
716        match &clause.condition {
717            Condition::Compare { column, op, value } => {
718                let placeholder = params.bind(value.clone());
719                let compare = if *op == Operator::Like.sql() {
720                    driver.like(&driver.quote(column))
721                } else {
722                    format!("{} {op}", driver.quote(column))
723                };
724                sql.push_str(&format!("{compare} {placeholder}"));
725            }
726            Condition::In { values, .. } if values.is_empty() => sql.push_str("0 = 1"),
727            Condition::In { column, values } => {
728                let placeholders: Vec<String> =
729                    values.iter().map(|v| params.bind(v.clone())).collect();
730                sql.push_str(&format!(
731                    "{} IN ({})",
732                    driver.quote(column),
733                    placeholders.join(", ")
734                ));
735            }
736            Condition::Null { column, negated } => {
737                let not = if *negated { "NOT " } else { "" };
738                sql.push_str(&format!("{} IS {not}NULL", driver.quote(column)));
739            }
740            Condition::Group(inner) => {
741                sql.push_str(&format!("({})", render(driver, inner, params)));
742            }
743        }
744    }
745    sql
746}