wasi-pg-client 0.1.3

PostgreSQL client library for WASI Preview 2
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Transaction management: BEGIN, COMMIT, ROLLBACK, savepoints.
//!
//! This module provides the [`Transaction`] guard type and supporting types
//! ([`TransactionOptions`], [`IsolationLevel`], [`Savepoint`]).

use crate::connection::Connection;
use crate::error::Result;
use crate::query::result::{ExecuteResult, QueryResult};

#[cfg(feature = "tracing")]
use crate::tracing_ext::TARGET_TRANSACTION;

pub mod options;
pub mod savepoint;

pub use options::{IsolationLevel, TransactionOptions};
pub use savepoint::Savepoint;

// ---------------------------------------------------------------------------
// Transaction guard
// ---------------------------------------------------------------------------

/// An active transaction guard.
///
/// Created via [`Connection::transaction`] or [`Connection::transaction_with`].
/// The guard provides methods to execute queries within the transaction and
/// to [`commit`](Self::commit) or [`rollback`](Self::rollback) it.
///
/// # Drop behaviour
///
/// `Drop` cannot perform async I/O.  If the transaction is not explicitly
/// committed or rolled back before it goes out of scope, the connection may
/// be left in an idle-in-transaction state.  **Always** call `.commit().await`
/// or `.rollback().await` explicitly.
#[non_exhaustive]
pub struct Transaction<'a> {
    pub(crate) conn: &'a mut Connection,
    pub(crate) committed: bool,
    pub(crate) savepoint_depth: u32,
}

impl<'a> Transaction<'a> {
    pub(crate) fn new(conn: &'a mut Connection) -> Self {
        Self {
            conn,
            committed: false,
            savepoint_depth: 0,
        }
    }

    /// Commit the transaction.
    #[must_use = "commit errors should be checked"]
    pub async fn commit(mut self) -> Result<()> {
        #[cfg(feature = "tracing")]
        tracing::info!(target: TARGET_TRANSACTION, "COMMIT transaction");
        self.conn.execute("COMMIT").await?;
        self.committed = true;
        Ok(())
    }

    /// Roll back the transaction.
    #[must_use = "rollback errors should be checked"]
    pub async fn rollback(mut self) -> Result<()> {
        #[cfg(feature = "tracing")]
        tracing::warn!(target: TARGET_TRANSACTION, "ROLLBACK transaction");
        self.conn.execute("ROLLBACK").await?;
        self.committed = true;
        Ok(())
    }

    /// Returns `true` if the transaction is in a failed state.
    pub fn is_failed(&self) -> bool {
        self.conn.transaction_status() == crate::protocol::TransactionStatus::Failed
    }

    /// Execute a query that returns rows, within the transaction.
    #[must_use = "query errors should be checked"]
    pub async fn query(&mut self, sql: &str) -> Result<QueryResult> {
        self.conn.query(sql).await
    }

    /// Execute a statement that does not return rows.
    #[must_use = "execute errors should be checked"]
    pub async fn execute(&mut self, sql: &str) -> Result<ExecuteResult> {
        self.conn.execute(sql).await
    }

    /// Execute a query and return at most one row.
    #[must_use = "query errors should be checked"]
    pub async fn query_one(&mut self, sql: &str) -> Result<Option<crate::Row>> {
        self.conn.query_one(sql).await
    }

    /// Execute a parameterized query that returns rows.
    #[must_use = "query errors should be checked"]
    pub async fn query_params(
        &mut self,
        sql: &str,
        params: &[&dyn crate::types::ToSql],
    ) -> Result<QueryResult> {
        self.conn.query_params(sql, params).await
    }

    /// Execute a parameterized statement that does not return rows.
    #[must_use = "execute errors should be checked"]
    pub async fn execute_params(
        &mut self,
        sql: &str,
        params: &[&dyn crate::types::ToSql],
    ) -> Result<ExecuteResult> {
        self.conn.execute_params(sql, params).await
    }

    /// Prepare a statement within the transaction.
    #[must_use = "prepare errors should be checked"]
    pub async fn prepare(&mut self, sql: &str) -> Result<crate::query::PreparedStatement> {
        self.conn.prepare(sql).await
    }

    /// Create a savepoint (nested transaction scope).
    ///
    /// Only one `Savepoint` guard can be active at a time for a given
    /// `Transaction` because it holds a mutable borrow.
    #[must_use = "savepoint errors should be checked"]
    pub async fn savepoint(&mut self, name: &str) -> Result<Savepoint<'_, 'a>> {
        let sql = format!("SAVEPOINT {}", quote_identifier(name));
        self.conn.execute(&sql).await?;
        self.savepoint_depth += 1;
        Ok(Savepoint {
            transaction: self,
            name: name.to_string(),
            released: false,
        })
    }

    /// Start a COPY IN operation within this transaction.
    #[must_use = "copy errors should be checked"]
    pub async fn copy_in(&mut self, sql: &str) -> Result<crate::CopyIn<'_>> {
        self.conn.copy_in(sql).await
    }

    /// Start a COPY OUT operation within this transaction.
    #[must_use = "copy errors should be checked"]
    pub async fn copy_out(&mut self, sql: &str) -> Result<crate::CopyOut<'_>> {
        self.conn.copy_out(sql).await
    }
}

impl<'a> Drop for Transaction<'a> {
    #[allow(clippy::needless_return)]
    fn drop(&mut self) {
        if self.committed || std::thread::panicking() {
            return;
        }
        #[cfg(feature = "tracing")]
        tracing::warn!(target: TARGET_TRANSACTION, "Transaction dropped without explicit commit/rollback");
        // Drop cannot be async.  We cannot send ROLLBACK here.
        // Users must call .commit().await or .rollback().await explicitly.
    }
}

// ---------------------------------------------------------------------------
// Utility
// ---------------------------------------------------------------------------

/// Quote a PostgreSQL identifier to prevent SQL injection.
pub(crate) fn quote_identifier(name: &str) -> String {
    format!("\"{}\"", name.replace('"', "\"\""))
}

// ---------------------------------------------------------------------------
// Connection extensions
// ---------------------------------------------------------------------------

impl Connection {
    /// Begin a new transaction.
    ///
    /// # Example
    /// ```ignore
    /// let mut txn = conn.transaction().await?;
    /// txn.execute("INSERT INTO users (name) VALUES ('alice')").await?;
    /// txn.commit().await?;
    /// ```
    #[must_use = "transaction errors should be checked"]
    pub async fn transaction(&mut self) -> Result<Transaction<'_>> {
        self.execute("BEGIN").await?;
        #[cfg(feature = "tracing")]
        tracing::info!(target: TARGET_TRANSACTION, "BEGIN transaction");
        Ok(Transaction::new(self))
    }

    /// Begin a new transaction with the given options.
    ///
    /// # Example
    /// ```ignore
    /// let mut txn = conn.transaction_with(
    ///     TransactionOptions::new()
    ///         .isolation_level(IsolationLevel::Serializable)
    ///         .read_only(true)
    /// ).await?;
    /// ```
    #[must_use = "transaction errors should be checked"]
    pub async fn transaction_with(
        &mut self,
        options: &TransactionOptions,
    ) -> Result<Transaction<'_>> {
        let sql = options.to_begin_sql();
        self.execute(&sql).await?;
        Ok(Transaction::new(self))
    }

    /// Execute an async closure within a transaction.
    ///
    /// Commits on `Ok`, rolls back on `Err`. This requires Rust 1.85+ (async
    /// closures are stable).
    ///
    /// # Example
    /// ```ignore
    /// let rows: Vec<i32> = conn.with_transaction(async |txn| {
    ///     txn.execute("INSERT INTO nums (v) VALUES (1)").await?;
    ///     let result = txn.query("SELECT v FROM nums").await?;
    ///     let vals: Vec<i32> = result.iter().map(|r| r.get(0).unwrap()).collect();
    ///     Ok(vals)
    /// }).await?;
    /// ```
    #[must_use = "transaction errors should be checked"]
    pub async fn with_transaction<T, F>(&mut self, f: F) -> Result<T>
    where
        F: AsyncFnOnce(&mut Transaction<'_>) -> Result<T>,
    {
        let mut txn = self.transaction().await?;
        match f(&mut txn).await {
            Ok(val) => {
                txn.commit().await?;
                Ok(val)
            }
            Err(e) => {
                let _ = txn.rollback().await;
                Err(e)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{Codec, ServerParams};
    use crate::config::Config;
    use crate::connection::ConnectionState;
    use crate::error::Error;
    use crate::protocol::TransactionStatus;
    use crate::transport::{BufferedTransport, ClientTransport, MockTransport, PgTransport};
    use std::collections::VecDeque;

    fn make_connection(read_data: Vec<u8>) -> Connection {
        let transport = PgTransport::Plain(BufferedTransport::new(ClientTransport::Mock(
            MockTransport::new(read_data),
        )));
        Connection {
            transport,
            codec: Codec::new(),
            server_params: ServerParams::default(),
            state: ConnectionState::Idle,
            config: Config::new(),
            transaction_status: TransactionStatus::Idle,
            notification_queue: VecDeque::new(),
            notice_handler: None,
            statement_counter: 0,
            needs_recovery: false,
            health: crate::reconnect::session::ConnectionHealth::new(),
            session_state: crate::reconnect::session::SessionState::new(),
        }
    }

    fn build_command_complete_msg(tag: &str) -> Vec<u8> {
        let mut buf = vec![b'C'];
        let mut body = Vec::new();
        body.extend_from_slice(tag.as_bytes());
        body.push(0);
        let len = (body.len() + 4) as i32;
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(&body);
        buf
    }

    fn build_ready_for_query(status: u8) -> Vec<u8> {
        vec![b'Z', 0, 0, 0, 5, status]
    }

    fn build_error_response(msg: &str) -> Vec<u8> {
        let mut buf = vec![b'E'];
        let mut body = Vec::new();
        body.push(b'S');
        body.extend_from_slice(b"ERROR\0");
        body.push(b'M');
        body.extend_from_slice(msg.as_bytes());
        body.push(0);
        body.push(0);
        let len = (body.len() + 4) as i32;
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(&body);
        buf
    }

    fn build_row_description_msg(fields: &[(&str, u32)]) -> Vec<u8> {
        let mut buf = vec![b'T'];
        let mut body = Vec::new();
        body.extend_from_slice(&(fields.len() as i16).to_be_bytes());
        for (name, type_oid) in fields {
            body.extend_from_slice(name.as_bytes());
            body.push(0);
            body.extend_from_slice(&0u32.to_be_bytes()); // table_oid
            body.extend_from_slice(&0i16.to_be_bytes()); // column_id
            body.extend_from_slice(&type_oid.to_be_bytes()); // type_oid
            body.extend_from_slice(&(-1i16).to_be_bytes()); // type_size
            body.extend_from_slice(&(-1i32).to_be_bytes()); // type_modifier
            body.extend_from_slice(&0i16.to_be_bytes()); // format
        }
        let len = (body.len() + 4) as i32;
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(&body);
        buf
    }

    fn build_data_row_msg(values: &[Option<&str>]) -> Vec<u8> {
        let mut buf = vec![b'D'];
        let mut body = Vec::new();
        body.extend_from_slice(&(values.len() as i16).to_be_bytes());
        for val in values {
            match val {
                Some(v) => {
                    let bytes = v.as_bytes();
                    body.extend_from_slice(&(bytes.len() as i32).to_be_bytes());
                    body.extend_from_slice(bytes);
                }
                None => {
                    body.extend_from_slice(&(-1i32).to_be_bytes());
                }
            }
        }
        let len = (body.len() + 4) as i32;
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(&body);
        buf
    }

    // -----------------------------------------------------------------------
    // Identifier quoting
    // -----------------------------------------------------------------------

    #[test]
    fn test_quote_identifier_basic() {
        assert_eq!(quote_identifier("foo"), "\"foo\"");
    }

    #[test]
    fn test_quote_identifier_with_quotes() {
        assert_eq!(quote_identifier("foo\"bar"), "\"foo\"\"bar\"");
    }

    #[test]
    fn test_quote_identifier_empty() {
        assert_eq!(quote_identifier(""), "\"\"");
    }

    // -----------------------------------------------------------------------
    // Transaction options
    // -----------------------------------------------------------------------

    #[test]
    fn test_transaction_options_default() {
        let opts = TransactionOptions::new();
        assert_eq!(opts.to_begin_sql(), "BEGIN");
    }

    #[test]
    fn test_transaction_options_isolation() {
        let opts = TransactionOptions::new().isolation_level(IsolationLevel::Serializable);
        assert_eq!(opts.to_begin_sql(), "BEGIN ISOLATION LEVEL SERIALIZABLE");
    }

    #[test]
    fn test_transaction_options_all() {
        let opts = TransactionOptions::new()
            .isolation_level(IsolationLevel::RepeatableRead)
            .read_only(true)
            .deferrable(true);
        assert_eq!(
            opts.to_begin_sql(),
            "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY DEFERRABLE"
        );
    }

    #[test]
    fn test_transaction_options_read_write() {
        let opts = TransactionOptions::new().read_only(false);
        assert_eq!(opts.to_begin_sql(), "BEGIN READ WRITE");
    }

    // -----------------------------------------------------------------------
    // Transaction lifecycle (mock transport)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_transaction_commit_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("COMMIT"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let txn = conn.transaction().await.unwrap();
        assert!(!txn.committed);
        txn.commit().await.unwrap();
        // After commit txn is consumed; verify connection state
        assert_eq!(conn.transaction_status(), TransactionStatus::Idle);
    }

    #[tokio::test]
    async fn test_transaction_rollback_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("ROLLBACK"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let txn = conn.transaction().await.unwrap();
        assert!(!txn.committed);
        txn.rollback().await.unwrap();
        assert_eq!(conn.transaction_status(), TransactionStatus::Idle);
    }

    #[tokio::test]
    async fn test_transaction_is_failed_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_error_response("syntax error"));
        data.extend_from_slice(&build_ready_for_query(b'E'));
        data.extend_from_slice(&build_command_complete_msg("ROLLBACK"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let mut txn = conn.transaction().await.unwrap();
        assert!(!txn.is_failed());

        // Bad query puts the transaction in failed state
        let err = txn.execute("BAD SQL").await;
        assert!(err.is_err());
        assert!(txn.is_failed());

        // Rolling back should clear the failed state
        txn.rollback().await.unwrap();
        assert_eq!(conn.transaction_status(), TransactionStatus::Idle);
    }

    #[tokio::test]
    async fn test_transaction_query_delegation_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        // RowDescription + DataRow + CommandComplete + ReadyForQuery for SELECT
        data.extend_from_slice(&build_row_description_msg(&[(
            "val",
            crate::types::INT4_OID,
        )]));
        data.extend_from_slice(&build_data_row_msg(&[Some("42")]));
        data.extend_from_slice(&build_command_complete_msg("SELECT 1"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("COMMIT"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let mut txn = conn.transaction().await.unwrap();
        let result = txn.query("SELECT 42").await.unwrap();
        assert_eq!(result.len(), 1);
        let v: i32 = result.rows()[0].get(0).unwrap();
        assert_eq!(v, 42);
        txn.commit().await.unwrap();
    }

    #[tokio::test]
    async fn test_with_transaction_success_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_row_description_msg(&[(
            "val",
            crate::types::INT4_OID,
        )]));
        data.extend_from_slice(&build_data_row_msg(&[Some("42")]));
        data.extend_from_slice(&build_command_complete_msg("SELECT 1"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("COMMIT"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let result = conn
            .with_transaction(async |txn| {
                let qr = txn.query("SELECT 42").await?;
                let v: i32 = qr.rows()[0].get(0)?;
                Ok(v)
            })
            .await
            .unwrap();
        assert_eq!(result, 42);
        assert_eq!(conn.transaction_status(), TransactionStatus::Idle);
    }

    #[tokio::test]
    async fn test_with_transaction_error_rolls_back_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_row_description_msg(&[(
            "val",
            crate::types::INT4_OID,
        )]));
        data.extend_from_slice(&build_data_row_msg(&[Some("42")]));
        data.extend_from_slice(&build_command_complete_msg("SELECT 1"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("ROLLBACK"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let result = conn
            .with_transaction(async |txn| {
                let qr = txn.query("SELECT 42").await?;
                let _v: i32 = qr.rows()[0].get(0)?;
                // Force an error to trigger rollback
                Err::<i32, Error>(Error::Config("intentional failure".into()))
            })
            .await;
        assert!(result.is_err());
        assert_eq!(conn.transaction_status(), TransactionStatus::Idle);
    }

    #[tokio::test]
    async fn test_transaction_savepoint_mock() {
        let mut data = Vec::new();
        data.extend_from_slice(&build_command_complete_msg("BEGIN"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("SAVEPOINT sp1"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("RELEASE SAVEPOINT sp1"));
        data.extend_from_slice(&build_ready_for_query(b'T'));
        data.extend_from_slice(&build_command_complete_msg("COMMIT"));
        data.extend_from_slice(&build_ready_for_query(b'I'));

        let mut conn = make_connection(data);
        let mut txn = conn.transaction().await.unwrap();
        assert_eq!(txn.savepoint_depth, 0);
        let sp = txn.savepoint("sp1").await.unwrap();
        sp.release().await.unwrap();
        assert_eq!(txn.savepoint_depth, 0);
        txn.commit().await.unwrap();
    }

    #[test]
    fn test_transaction_drop_without_commit_does_not_panic() {
        let mut conn = make_connection(Vec::new());
        let txn = Transaction::new(&mut conn);
        assert!(!txn.committed);
        drop(txn); // must not panic
    }

    #[test]
    fn test_transaction_drop_after_commit_is_noop() {
        let mut conn = make_connection(Vec::new());
        let txn = Transaction::new(&mut conn);
        // Simulate committed state (normally set by commit())
        let mut txn = txn;
        txn.committed = true;
        drop(txn); // must not panic
    }
}