prax-postgres 0.12.1

PostgreSQL driver for the Prax ORM with connection pooling
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! PostgreSQL connection wrapper.

use std::sync::Arc;

use deadpool_postgres::Object;
use tokio_postgres::Row;
use tracing::{debug, trace};

use prax_query::sql::is_valid_sql_identifier;

use crate::error::{PgError, PgResult};
use crate::statement::PreparedStatementCache;

/// A wrapper around a PostgreSQL connection with statement caching.
pub struct PgConnection {
    client: Object,
    statement_cache: Arc<PreparedStatementCache>,
}

/// Whether a driver error is PostgreSQL's `0A000 "cached plan must not change
/// result type"`.
///
/// This is raised when a server-side prepared statement is executed after DDL
/// altered the result columns of a table it references (e.g. a pooled
/// connection that prepared the statement before an `ALTER TABLE … ADD
/// COLUMN`). It is transient: re-preparing against the current schema resolves
/// it. `0A000` is the shared `FEATURE_NOT_SUPPORTED` class, so the specific
/// message is required — other `0A000` conditions (genuinely unsupported
/// features) are terminal and must not trigger recovery.
fn is_stale_cached_plan(err: &tokio_postgres::Error) -> bool {
    // The human-readable message lives in the DbError, not in `Display`, which
    // renders a DB error as just "db error". Reading `to_string()` here would
    // never match the cached-plan text.
    match err.as_db_error() {
        Some(db) => {
            db.code() == &tokio_postgres::error::SqlState::FEATURE_NOT_SUPPORTED
                && is_stale_cached_plan_message(db.message())
        }
        None => false,
    }
}

/// The message half of [`is_stale_cached_plan`], split out so the gate can be
/// unit-tested without constructing a `tokio_postgres::Error` (which cannot be
/// built with a chosen SQLSTATE via the public API).
fn is_stale_cached_plan_message(msg: &str) -> bool {
    msg.contains("cached plan must not change result type")
}

impl PgConnection {
    /// Create a new connection wrapper.
    pub(crate) fn new(client: Object, statement_cache: Arc<PreparedStatementCache>) -> Self {
        Self {
            client,
            statement_cache,
        }
    }

    /// Execute a query and return all rows.
    pub async fn query(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Vec<Row>> {
        trace!(sql = %sql, "Executing query");

        // Try to get a cached prepared statement
        let stmt = self
            .statement_cache
            .get_or_prepare(&self.client, sql)
            .await?;

        match self.client.query(&stmt, params).await {
            Ok(rows) => Ok(rows),
            Err(e) if is_stale_cached_plan(&e) => {
                let stmt = self.reprepare_after_stale_plan(sql).await?;
                let rows = self.client.query(&stmt, params).await?;
                Ok(rows)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Execute a query and return exactly one row.
    pub async fn query_one(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Row> {
        trace!(sql = %sql, "Executing query_one");

        let stmt = self
            .statement_cache
            .get_or_prepare(&self.client, sql)
            .await?;

        match self.client.query_one(&stmt, params).await {
            Ok(row) => Ok(row),
            Err(e) if is_stale_cached_plan(&e) => {
                let stmt = self.reprepare_after_stale_plan(sql).await?;
                let row = self.client.query_one(&stmt, params).await?;
                Ok(row)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Execute a query and return zero or one row.
    pub async fn query_opt(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Option<Row>> {
        trace!(sql = %sql, "Executing query_opt");

        let stmt = self
            .statement_cache
            .get_or_prepare(&self.client, sql)
            .await?;

        match self.client.query_opt(&stmt, params).await {
            Ok(row) => Ok(row),
            Err(e) if is_stale_cached_plan(&e) => {
                let stmt = self.reprepare_after_stale_plan(sql).await?;
                let row = self.client.query_opt(&stmt, params).await?;
                Ok(row)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Execute a statement and return the number of affected rows.
    pub async fn execute(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<u64> {
        trace!(sql = %sql, "Executing statement");

        let stmt = self
            .statement_cache
            .get_or_prepare(&self.client, sql)
            .await?;

        match self.client.execute(&stmt, params).await {
            Ok(count) => Ok(count),
            Err(e) if is_stale_cached_plan(&e) => {
                let stmt = self.reprepare_after_stale_plan(sql).await?;
                let count = self.client.execute(&stmt, params).await?;
                Ok(count)
            }
            Err(e) => Err(e.into()),
        }
    }

    /// Recover from a stale cached plan (`0A000`): drop the SQL from the
    /// statement cache and prepare it afresh, bypassing deadpool's per-
    /// connection cache so the new plan is built against the current schema.
    ///
    /// `prepare_cached` would hand back the same invalidated statement, so the
    /// retry must use the uncached `prepare`. The freshly prepared statement is
    /// what the caller re-executes; the cache is left empty for this SQL so the
    /// next ordinary call re-primes it via `get_or_prepare`.
    async fn reprepare_after_stale_plan(&self, sql: &str) -> PgResult<tokio_postgres::Statement> {
        debug!(
            sql = %sql,
            "Recovering from stale cached plan (0A000): re-preparing statement"
        );
        self.statement_cache.evict(sql);
        let stmt = self.client.prepare(sql).await?;
        Ok(stmt)
    }

    /// Execute a batch of statements in a single round-trip.
    pub async fn batch_execute(&self, sql: &str) -> PgResult<()> {
        trace!(sql = %sql, "Executing batch");
        self.client.batch_execute(sql).await?;
        Ok(())
    }

    /// Begin a transaction.
    pub async fn transaction(&mut self) -> PgResult<PgTransaction<'_>> {
        debug!("Beginning transaction");
        let txn = self.client.transaction().await?;
        Ok(PgTransaction {
            txn,
            statement_cache: self.statement_cache.clone(),
        })
    }

    /// Get the underlying tokio-postgres client.
    ///
    /// This is useful for advanced operations not covered by this wrapper.
    pub fn inner(&self) -> &Object {
        &self.client
    }

    /// Execute a query using the prepared statement cache.
    ///
    /// This is an alias for `query` that makes it explicit that statement caching
    /// is being used. All query methods already use prepared statement caching,
    /// but this method name makes it more explicit for benchmark comparisons.
    #[inline]
    pub async fn query_cached(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Vec<Row>> {
        self.query(sql, params).await
    }

    /// Execute a raw query without using the prepared statement cache.
    ///
    /// This is useful for one-off queries where the overhead of preparing
    /// a statement isn't worth it.
    pub async fn query_raw(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Vec<Row>> {
        trace!(sql = %sql, "Executing raw query (no statement cache)");
        let rows = self.client.query(sql, params).await?;
        Ok(rows)
    }

    /// Execute a raw query and return zero or one row without using statement cache.
    pub async fn query_opt_raw(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Option<Row>> {
        trace!(sql = %sql, "Executing raw query_opt (no statement cache)");
        let row = self.client.query_opt(sql, params).await?;
        Ok(row)
    }
}

/// Maximum allowed savepoint name length (matches PostgreSQL's `NAMEDATALEN - 1`).
const MAX_SAVEPOINT_NAME_LEN: usize = 63;

/// Validate a savepoint name before it is interpolated into SQL.
///
/// Savepoint identifiers cannot be parameterized, so they must match the
/// whitelist pattern `^[A-Za-z_][A-Za-z0-9_]*$` to prevent SQL injection.
fn validate_savepoint_name(name: &str) -> PgResult<()> {
    let valid = name.len() <= MAX_SAVEPOINT_NAME_LEN && is_valid_sql_identifier(name);
    if !valid {
        return Err(PgError::query(format!("invalid savepoint name: {name:?}")));
    }
    Ok(())
}

/// A PostgreSQL transaction.
pub struct PgTransaction<'a> {
    txn: deadpool_postgres::Transaction<'a>,
    statement_cache: Arc<PreparedStatementCache>,
}

impl<'a> PgTransaction<'a> {
    // A stale cached plan (`0A000`) is NOT transparently retried inside a
    // transaction: the error aborts the transaction, so any subsequent
    // statement on it fails with `25P02 in_failed_sql_transaction`. Re-running
    // the one statement cannot succeed here. The error is still classified
    // retryable (via `classify_sqlstate`), so a caller that retries the whole
    // transaction recovers on a fresh statement. Only the non-transactional
    // `PgConnection` methods above self-heal in place.

    /// Execute a query and return all rows.
    pub async fn query(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Vec<Row>> {
        trace!(sql = %sql, "Executing query in transaction");

        let stmt = self
            .statement_cache
            .get_or_prepare_in_txn(&self.txn, sql)
            .await?;

        let rows = self.txn.query(&stmt, params).await?;
        Ok(rows)
    }

    /// Execute a query and return exactly one row.
    pub async fn query_one(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Row> {
        let stmt = self
            .statement_cache
            .get_or_prepare_in_txn(&self.txn, sql)
            .await?;

        let row = self.txn.query_one(&stmt, params).await?;
        Ok(row)
    }

    /// Execute a query and return zero or one row.
    pub async fn query_opt(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<Option<Row>> {
        let stmt = self
            .statement_cache
            .get_or_prepare_in_txn(&self.txn, sql)
            .await?;

        let row = self.txn.query_opt(&stmt, params).await?;
        Ok(row)
    }

    /// Execute a statement and return the number of affected rows.
    pub async fn execute(
        &self,
        sql: &str,
        params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
    ) -> PgResult<u64> {
        let stmt = self
            .statement_cache
            .get_or_prepare_in_txn(&self.txn, sql)
            .await?;

        let count = self.txn.execute(&stmt, params).await?;
        Ok(count)
    }

    /// Create a savepoint.
    pub async fn savepoint(&mut self, name: &str) -> PgResult<()> {
        validate_savepoint_name(name)?;
        debug!(name = %name, "Creating savepoint");
        self.txn
            .batch_execute(&format!("SAVEPOINT {}", name))
            .await?;
        Ok(())
    }

    /// Rollback to a savepoint.
    pub async fn rollback_to(&mut self, name: &str) -> PgResult<()> {
        validate_savepoint_name(name)?;
        debug!(name = %name, "Rolling back to savepoint");
        self.txn
            .batch_execute(&format!("ROLLBACK TO SAVEPOINT {}", name))
            .await?;
        Ok(())
    }

    /// Release a savepoint.
    pub async fn release_savepoint(&mut self, name: &str) -> PgResult<()> {
        validate_savepoint_name(name)?;
        debug!(name = %name, "Releasing savepoint");
        self.txn
            .batch_execute(&format!("RELEASE SAVEPOINT {}", name))
            .await?;
        Ok(())
    }

    /// Commit the transaction.
    pub async fn commit(self) -> PgResult<()> {
        debug!("Committing transaction");
        self.txn.commit().await?;
        Ok(())
    }

    /// Rollback the transaction.
    pub async fn rollback(self) -> PgResult<()> {
        debug!("Rolling back transaction");
        self.txn.rollback().await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Integration tests would require a real PostgreSQL connection
    // Unit tests for connection wrapper are limited without mocking

    #[test]
    fn test_stale_cached_plan_message_gate() {
        // The exact PostgreSQL wording is recognized.
        assert!(is_stale_cached_plan_message(
            "db error: ERROR: cached plan must not change result type"
        ));
        // Other 0A000 (FEATURE_NOT_SUPPORTED) messages are not the stale-plan
        // case and must not trigger recovery.
        assert!(!is_stale_cached_plan_message(
            "ERROR: cannot insert into view \"v\""
        ));
        assert!(!is_stale_cached_plan_message("some unrelated error"));
    }

    #[test]
    fn test_validate_savepoint_name_accepts_valid_names() {
        assert!(validate_savepoint_name("sp1").is_ok());
        assert!(validate_savepoint_name("my_savepoint").is_ok());
        assert!(validate_savepoint_name("_private").is_ok());
        assert!(validate_savepoint_name("SP_2").is_ok());
        assert!(validate_savepoint_name("a").is_ok());
        // 63 chars (the max) is accepted
        let max_name = "a".repeat(MAX_SAVEPOINT_NAME_LEN);
        assert!(validate_savepoint_name(&max_name).is_ok());
    }

    #[test]
    fn test_validate_savepoint_name_rejects_invalid_names() {
        assert!(validate_savepoint_name("sp1; DROP TABLE").is_err());
        assert!(validate_savepoint_name("my savepoint").is_err());
        assert!(validate_savepoint_name("\"quoted\"").is_err());
        assert!(validate_savepoint_name("").is_err());
        assert!(validate_savepoint_name("1leading_digit").is_err());
        assert!(validate_savepoint_name("has-dash").is_err());
        assert!(validate_savepoint_name("has.dot").is_err());
        // 64 chars exceeds the limit
        let too_long = "a".repeat(MAX_SAVEPOINT_NAME_LEN + 1);
        assert!(validate_savepoint_name(&too_long).is_err());
    }
}