rustango 0.60.7

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Postgres dialect: double-quoted identifiers, `$1`-style placeholders,
//! `BIGSERIAL` / `SERIAL` for `Auto<T>` PKs, native `BOOLEAN`,
//! `pg_advisory_lock` for migration coordination, full `RETURNING` /
//! `ON CONFLICT` / `ILIKE` / `IS DISTINCT FROM` / JSONB operator support.
//!
//! The IR-to-SQL helpers live in [`super::writers`]. This module is
//! the thin per-dialect shell: identity primitives, the
//! Postgres-specific NULL-cast table, the conflict-clause spelling,
//! and `compile_*` methods that hand off to the writers.

use crate::core::{
    AggregateQuery, BulkInsertQuery, BulkUpdateQuery, ConflictClause, CountQuery, DeleteQuery,
    FieldType, InsertQuery, ModelSchema, Op, SelectQuery, UpdateQuery,
};
#[cfg(feature = "postgres")]
use crate::core::{SearchClause, WhereExpr};

#[cfg(feature = "postgres")]
use super::writers;
use super::writers::{
    write_aggregate, write_bulk_insert, write_bulk_update_pg, write_count, write_delete,
    write_insert, write_select, write_update, Sql,
};
use super::{CompiledStatement, Dialect, SqlError};

/// The Postgres dialect.
///
/// Stateless; construct with `Postgres` and call [`Dialect::compile_select`].
#[derive(Debug, Default, Clone, Copy)]
pub struct Postgres;

/// `'static` reference to the singleton [`Postgres`] dialect, useful
/// where callers want a `&'static dyn Dialect` (e.g. [`crate::sql::Pool::dialect`]).
#[cfg(feature = "postgres")]
pub static DIALECT: &Postgres = &Postgres;

impl Dialect for Postgres {
    fn name(&self) -> &'static str {
        "postgres"
    }

    // Postgres uses ANSI-style double-quoted identifiers — same as the
    // trait default, no override needed for `quote_ident`.

    fn placeholder(&self, n: usize) -> String {
        format!("${n}")
    }

    // PostgreSQL drops any constraint — CHECK, FOREIGN KEY, UNIQUE —
    // through the one ANSI spelling, and supports `IF EXISTS` on it, so
    // both of these are idempotent and identical. MySQL needs
    // `DROP CHECK` / `DROP FOREIGN KEY` and rejects `IF EXISTS` there;
    // SQLite has no `ALTER TABLE … DROP CONSTRAINT` at all and returns
    // `None`. These were the trait's default body until it became clear
    // that defaulting to the PG form is what shipped #559 to MySQL.
    fn drop_check_constraint_sql(&self, table: &str, name: &str) -> Option<String> {
        Some(format!(
            "ALTER TABLE {} DROP CONSTRAINT IF EXISTS {}",
            self.quote_ident(table),
            self.quote_ident(name)
        ))
    }

    fn reset_sequence_sql(&self, table: &str, column: &str) -> Option<String> {
        let (t, c) = (self.quote_ident(table), self.quote_ident(column));
        Some(format!(
            "SELECT setval(pg_get_serial_sequence({}, {}), COALESCE(MAX({c}), 1), \
             MAX({c}) IS NOT NULL) FROM {t}",
            self.placeholder(1),
            self.placeholder(2),
        ))
    }

    fn defer_foreign_keys_sql(&self) -> Option<&'static str> {
        None
    }

    fn clear_tables_sql(&self, tables: &[&str]) -> Vec<String> {
        let quoted: Vec<String> = tables.iter().map(|t| self.quote_ident(t)).collect();
        vec![format!(
            "TRUNCATE TABLE {} RESTART IDENTITY CASCADE",
            quoted.join(", ")
        )]
    }

    fn drop_foreign_key_sql(&self, table: &str, name: &str) -> Option<String> {
        Some(format!(
            "ALTER TABLE {} DROP CONSTRAINT IF EXISTS {}",
            self.quote_ident(table),
            self.quote_ident(name)
        ))
    }

    /// `to_regclass` resolves the table through `search_path`, as the DDL does.
    fn foreign_key_names_sql(&self) -> Option<&'static str> {
        Some(
            "SELECT c.conname::text FROM pg_constraint c \
             JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey) \
             WHERE c.contype = 'f' AND c.conrelid = to_regclass(quote_ident($1)) \
             AND a.attname = $2 AND cardinality(c.conkey) = 1",
        )
    }

    /// A renamed column keeps its UNIQUE constraint's old name (#2133).
    fn unique_index_names_sql(&self) -> Option<&'static str> {
        Some(
            "SELECT c.conname::text FROM pg_constraint c \
             JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey) \
             WHERE c.contype = 'u' AND c.conrelid = to_regclass(quote_ident($1)) \
             AND a.attname = $2 AND cardinality(c.conkey) = 1",
        )
    }

    fn drop_unique_index_sql(&self, table: &str, name: &str) -> Option<String> {
        Some(format!(
            "ALTER TABLE {} DROP CONSTRAINT {}",
            self.quote_ident(table),
            self.quote_ident(name)
        ))
    }

    fn column_comment_statement(&self, table: &str, column: &str, comment: &str) -> Option<String> {
        Some(format!(
            "COMMENT ON COLUMN {}.{} IS {}",
            self.quote_ident(table),
            self.quote_ident(column),
            self.quote_literal(comment),
        ))
    }

    fn table_comment_statement(&self, table: &str, comment: &str) -> Option<String> {
        Some(format!(
            "COMMENT ON TABLE {} IS {}",
            self.quote_ident(table),
            self.quote_literal(comment),
        ))
    }

    fn serial_type(&self, field_type: FieldType) -> &'static str {
        match field_type {
            FieldType::I32 => "SERIAL",
            _ => "BIGSERIAL",
        }
    }

    // #344 — CITextField. Postgres ships the `citext` extension that
    // provides a case-insensitive text type; once the extension is
    // installed, a `CITEXT` column compares case-insensitively. Migrations
    // run `ci_text_extension_sql` before the first CITEXT column (#2240).
    // In `public`, so every tenant's `search_path` finds it (#2269).
    fn ci_text_type(&self, _max_length: Option<u32>) -> String {
        // CITEXT has no length parameter; `max_length` is advisory.
        "CITEXT".to_owned()
    }

    fn ci_text_extension_sql(&self) -> Option<&'static str> {
        Some("CREATE EXTENSION IF NOT EXISTS citext SCHEMA public;")
    }

    // Postgres has a native `BOOLEAN` type with `TRUE` / `FALSE`
    // literals — same as the trait default, no override.

    fn supports_concurrent_index(&self) -> bool {
        true
    }

    fn supports_returning(&self) -> bool {
        true
    }

    fn supports(&self, token: &str) -> bool {
        // Postgres-specific capability tokens that aren't reachable via
        // the default impl's whitelist. Extends the default; the
        // generic `window_functions` / `cte` / etc. fall through to
        // `super::Dialect::supports` via the `||`.
        matches!(
            token,
            "array_type"
                | "range_type"
                | "hstore"
                | "citext"
                | "listen_notify"
                | "notify"
                | "row_security"
                | "gin_index"
                | "gist_index"
                | "spgist_index"
                | "brin_index"
                | "unique_constraint_deferred"
                | "exclusion_constraint"
                | "tablespaces"
                | "json_path"
                | "json_query"
                // pgvector similarity search (#824). Requires the
                // `vector` extension to be installed/enabled.
                | "pgvector"
                | "vector"
                // PostGIS geometry columns (#443). Requires the
                // `postgis` extension to be installed/enabled.
                | "postgis"
                | "geometry"
        ) || self.default_supports(token)
    }

    fn cast_aggregate_to_int(&self, expr: &str) -> String {
        // PostgreSQL accepts the shorter `<expr>::bigint` form.
        format!("{expr}::bigint")
    }

    fn cast_aggregate_to_float(&self, expr: &str) -> String {
        format!("{expr}::double precision")
    }

    fn null_cast(&self, ty: FieldType) -> Option<&'static str> {
        // #562 — the PG `null_cast` table was character-identical to
        // the trait-default `cast_type` table 14 variants long.
        // Delegate so the canonical token table lives in one place
        // (`Dialect::cast_type` default impl); divergence between
        // the two would silently change which `NULL::T` token PG
        // sees.
        self.cast_type(ty)
    }

    /// Postgres supports every `Op` the IR carries — `ILIKE`,
    /// `IS DISTINCT FROM`, JSONB operators, etc. (Trait default
    /// `true` is correct; the explicit override documents intent.)
    fn supports_op(&self, _op: Op) -> bool {
        true
    }

    /// `bigint LIKE text` has no operator, so a non-text column is
    /// cast first (#2229, #2263).
    fn like_operand(&self, qualified_col: &str, ty: Option<FieldType>) -> String {
        match ty {
            Some(ty) if ty != FieldType::String => format!("CAST({qualified_col} AS TEXT)"),
            _ => qualified_col.to_owned(),
        }
    }

    fn write_conflict_clause(
        &self,
        sql: &mut String,
        _model: &ModelSchema,
        conflict: &ConflictClause,
    ) -> Result<(), SqlError> {
        match conflict {
            ConflictClause::DoNothing => {
                sql.push_str(" ON CONFLICT DO NOTHING");
            }
            ConflictClause::DoUpdate {
                target,
                update_columns,
            } => {
                sql.push_str(" ON CONFLICT (");
                let mut first = true;
                for col in target {
                    if !first {
                        sql.push_str(", ");
                    }
                    first = false;
                    write_pg_ident(sql, col);
                }
                sql.push_str(") DO UPDATE SET ");
                let mut first = true;
                for col in update_columns {
                    if !first {
                        sql.push_str(", ");
                    }
                    first = false;
                    write_pg_ident(sql, col);
                    sql.push_str(" = EXCLUDED.");
                    write_pg_ident(sql, col);
                }
            }
        }
        Ok(())
    }

    fn acquire_session_lock_sql(&self) -> Option<String> {
        Some(format!(
            "SELECT pg_try_advisory_lock({})",
            self.placeholder(1)
        ))
    }

    fn release_session_lock_sql(&self) -> Option<String> {
        Some(format!(
            "SELECT pg_advisory_unlock({})",
            self.placeholder(1)
        ))
    }

    fn acquire_xact_lock_sql(&self) -> Option<String> {
        Some(format!(
            "SELECT pg_advisory_xact_lock({})",
            self.placeholder(1)
        ))
    }

    // ---- compilation: thin shells over `writers::*` ----

    fn compile_select(&self, query: &SelectQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_select(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_count(&self, query: &CountQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_count(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_aggregate(&self, query: &AggregateQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_aggregate(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_insert(&self, query: &InsertQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::with_capacity(self, query.values.len());
        write_insert(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_bulk_insert(&self, query: &BulkInsertQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::with_capacity(self, query.columns.len() * query.rows.len());
        write_bulk_insert(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_update(&self, query: &UpdateQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_update(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_delete(&self, query: &DeleteQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_delete(&mut b, query)?;
        Ok(b.finish())
    }

    fn compile_bulk_update(&self, query: &BulkUpdateQuery) -> Result<CompiledStatement, SqlError> {
        let mut b = Sql::new(self);
        write_bulk_update_pg(&mut b, query)?;
        Ok(b.finish())
    }
}

/// Direct Postgres-quoted identifier writer used by
/// [`Postgres::write_conflict_clause`]. The conflict clause writes
/// directly into a `&mut String` (it's part of the `Dialect` trait
/// surface, not a `Sql<'_>` builder), so we need a small helper that
/// doesn't go through the builder.
fn write_pg_ident(sql: &mut String, name: &str) {
    sql.push('"');
    for ch in name.chars() {
        if ch == '"' {
            sql.push_str("\"\"");
        } else {
            sql.push(ch);
        }
    }
    sql.push('"');
}

/// Compile the WHERE / ORDER BY / LIMIT / OFFSET tail of a `SelectQuery`
/// into a `CompiledStatement`. The `sql` field starts at the first `WHERE`
/// keyword (or is empty when there are no filters/search/ordering). `params`
/// carries the bound values for the WHERE clause in order.
///
/// Used by `annotate_count_children_on` to forward the parent queryset's
/// WHERE / ORDER / LIMIT constraints into the hand-rolled aggregate SQL.
///
/// This is the Postgres-typed shim — the underlying writer is dialect-
/// agnostic, so [`super::writers::compile_where_order_tail`] takes a
/// `&dyn Dialect` and is reusable from a `MySql` executor when batch 5
/// migrates `annotate_count_children` to `&Pool`.
///
/// # Errors
/// As [`super::writers::compile_where_order_tail`].
#[cfg(feature = "postgres")]
pub(crate) fn compile_where_order_tail(
    where_clause: &WhereExpr,
    search: Option<&SearchClause>,
    order_by: &[crate::core::OrderItem],
    limit: Option<i64>,
    offset: Option<i64>,
    qualify_with: Option<&'static str>,
    model: Option<&'static ModelSchema>,
) -> Result<CompiledStatement, SqlError> {
    writers::compile_where_order_tail(
        DIALECT,
        where_clause,
        search,
        order_by,
        limit,
        offset,
        qualify_with,
        model,
    )
}