zero-postgres 0.9.0

A high-performance PostgreSQL client
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Extended query protocol state machine.

use crate::conversion::ToParams;
use crate::error::{Error, Result};
use crate::handler::ExtendedHandler;
use crate::protocol::backend::{
    BindComplete, CloseComplete, CommandComplete, DataRow, EmptyQueryResponse, ErrorResponse,
    NoData, ParameterDescription, ParseComplete, PortalSuspended, RawMessage, ReadyForQuery,
    RowDescription, msg_type,
};
use crate::protocol::frontend::{
    write_bind, write_close_statement, write_describe_portal, write_describe_statement,
    write_execute, write_parse, write_sync,
};
use crate::protocol::types::{Oid, TransactionStatus};

use super::StateMachine;
use super::action::{Action, AsyncMessage};
use crate::buffer_set::BufferSet;

/// Extended query state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    Initial,
    WaitingParse,
    WaitingBind,
    WaitingDescribe,
    WaitingRowDesc,
    ProcessingRows,
    WaitingReady,
    Finished,
}

/// Prepared statement information.
#[derive(Debug, Clone)]
pub struct PreparedStatement {
    /// Statement index (unique within connection)
    pub idx: u64,
    /// Parameter type OIDs
    pub param_oids: Vec<Oid>,
    /// Raw RowDescription payload (if the statement returns rows)
    pub(crate) row_desc_payload: Option<Vec<u8>>,
}

impl PreparedStatement {
    /// Get the wire protocol statement name.
    pub fn wire_name(&self) -> String {
        format!("_zero_s_{}", self.idx)
    }

    /// Parse column descriptions from stored RowDescription payload.
    ///
    /// Returns `None` if the statement doesn't return rows.
    pub fn parse_columns(&self) -> Option<Result<RowDescription<'_>>> {
        self.row_desc_payload
            .as_ref()
            .map(|bytes| RowDescription::parse(bytes))
    }

    /// Get the raw RowDescription payload.
    ///
    /// Returns `None` if the statement doesn't return rows.
    pub fn row_desc_payload(&self) -> Option<&[u8]> {
        self.row_desc_payload.as_deref()
    }
}

/// Operation type marker for tracking what operation is in progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Operation {
    /// Preparing a statement (Parse + Describe + Sync)
    Prepare,
    /// Executing a prepared statement (Bind + Describe + Execute + Sync)
    Execute,
    /// Executing raw SQL (Parse + Bind + Describe + Execute + Sync)
    ExecuteSql,
    /// Closing a statement (Close + Sync)
    CloseStatement,
}

/// Extended query protocol state machine.
pub struct ExtendedQueryStateMachine<'a, H> {
    state: State,
    handler: &'a mut H,
    operation: Operation,
    transaction_status: TransactionStatus,
    prepared_stmt: Option<PreparedStatement>,
    pending_error: Option<crate::error::ServerError>,
}

impl<'a, H: ExtendedHandler> ExtendedQueryStateMachine<'a, H> {
    /// Take the prepared statement (after prepare completes).
    pub fn take_prepared_statement(&mut self) -> Option<PreparedStatement> {
        self.prepared_stmt.take()
    }

    /// Prepare a statement.
    ///
    /// Writes Parse + DescribeStatement + Sync to `buffer_set.write_buffer`.
    pub fn prepare(
        handler: &'a mut H,
        buffer_set: &mut BufferSet,
        idx: u64,
        query: &str,
        param_oids: &[Oid],
    ) -> Self {
        let stmt_name = format!("_zero_s_{}", idx);
        buffer_set.write_buffer.clear();
        write_parse(&mut buffer_set.write_buffer, &stmt_name, query, param_oids);
        write_describe_statement(&mut buffer_set.write_buffer, &stmt_name);
        write_sync(&mut buffer_set.write_buffer);

        Self {
            state: State::Initial,
            handler,
            operation: Operation::Prepare,
            transaction_status: TransactionStatus::Idle,
            prepared_stmt: Some(PreparedStatement {
                idx,
                param_oids: Vec::new(),
                row_desc_payload: None,
            }),
            pending_error: None,
        }
    }

    /// Execute a prepared statement.
    ///
    /// Writes Bind + DescribePortal + Execute + Sync to `buffer_set.write_buffer`.
    ///
    /// Uses the server-provided parameter OIDs to encode parameters, which allows
    /// flexible type conversion (e.g., i64 encoded as INT4 if server expects INT4).
    pub fn execute<P: ToParams>(
        handler: &'a mut H,
        buffer_set: &mut BufferSet,
        statement_name: &str,
        param_oids: &[Oid],
        params: &P,
    ) -> Result<Self> {
        buffer_set.write_buffer.clear();
        write_bind(
            &mut buffer_set.write_buffer,
            "",
            statement_name,
            params,
            param_oids,
        )?;
        write_describe_portal(&mut buffer_set.write_buffer, "");
        write_execute(&mut buffer_set.write_buffer, "", 0);
        write_sync(&mut buffer_set.write_buffer);

        Ok(Self {
            state: State::Initial,
            handler,
            operation: Operation::Execute,
            transaction_status: TransactionStatus::Idle,
            prepared_stmt: None,
            pending_error: None,
        })
    }

    /// Execute raw SQL (unnamed statement).
    ///
    /// Writes Parse + Bind + DescribePortal + Execute + Sync to `buffer_set.write_buffer`.
    ///
    /// Uses the natural OIDs from the parameters to inform the server about parameter types,
    /// which prevents "incorrect binary data format" errors when the server would otherwise
    /// infer a different type (e.g., INT4 vs INT8).
    pub fn execute_sql<P: ToParams>(
        handler: &'a mut H,
        buffer_set: &mut BufferSet,
        sql: &str,
        params: &P,
    ) -> Result<Self> {
        let param_oids = params.natural_oids();
        buffer_set.write_buffer.clear();
        write_parse(&mut buffer_set.write_buffer, "", sql, &param_oids);
        write_bind(&mut buffer_set.write_buffer, "", "", params, &param_oids)?;
        write_describe_portal(&mut buffer_set.write_buffer, "");
        write_execute(&mut buffer_set.write_buffer, "", 0);
        write_sync(&mut buffer_set.write_buffer);

        Ok(Self {
            state: State::Initial,
            handler,
            operation: Operation::ExecuteSql,
            transaction_status: TransactionStatus::Idle,
            prepared_stmt: None,
            pending_error: None,
        })
    }

    /// Close a prepared statement.
    ///
    /// Writes Close + Sync to `buffer_set.write_buffer`.
    pub fn close_statement(handler: &'a mut H, buffer_set: &mut BufferSet, name: &str) -> Self {
        buffer_set.write_buffer.clear();
        write_close_statement(&mut buffer_set.write_buffer, name);
        write_sync(&mut buffer_set.write_buffer);

        Self {
            state: State::Initial,
            handler,
            operation: Operation::CloseStatement,
            transaction_status: TransactionStatus::Idle,
            prepared_stmt: None,
            pending_error: None,
        }
    }

    fn handle_parse(&mut self, buffer_set: &BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;
        if type_byte != msg_type::PARSE_COMPLETE {
            return Err(Error::LibraryBug(format!(
                "Expected ParseComplete, got '{}'",
                type_byte as char
            )));
        }

        ParseComplete::parse(&buffer_set.read_buffer)?;
        // For SQL execute, next we get BindComplete
        // For prepare, go to WaitingDescribe to get ParameterDescription
        self.state = match self.operation {
            Operation::ExecuteSql => State::WaitingBind,
            Operation::Prepare => State::WaitingDescribe,
            _ => {
                return Err(Error::LibraryBug(
                    "handle_parse called for non-parse operation".into(),
                ));
            }
        };
        Ok(Action::ReadMessage)
    }

    fn handle_describe(&mut self, buffer_set: &BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;
        if type_byte != msg_type::PARAMETER_DESCRIPTION {
            return Err(Error::LibraryBug(format!(
                "Expected ParameterDescription, got '{}'",
                type_byte as char
            )));
        }

        let param_desc = ParameterDescription::parse(&buffer_set.read_buffer)?;
        if let Some(stmt) = &mut self.prepared_stmt {
            stmt.param_oids = param_desc.oids().to_vec();
        }

        self.state = State::WaitingRowDesc;
        Ok(Action::ReadMessage)
    }

    fn handle_row_desc(&mut self, buffer_set: &BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;

        match type_byte {
            msg_type::ROW_DESCRIPTION => {
                if let Some(stmt) = &mut self.prepared_stmt {
                    stmt.row_desc_payload = Some(buffer_set.read_buffer.clone());
                }
                self.state = State::WaitingReady;
                Ok(Action::ReadMessage)
            }
            msg_type::NO_DATA => {
                let payload = &buffer_set.read_buffer;
                NoData::parse(payload)?;
                // Statement doesn't return rows
                self.state = State::WaitingReady;
                Ok(Action::ReadMessage)
            }
            _ => Err(Error::LibraryBug(format!(
                "Expected RowDescription or NoData, got '{}'",
                type_byte as char
            ))),
        }
    }

    fn handle_bind(&mut self, buffer_set: &mut BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;

        match type_byte {
            msg_type::BIND_COMPLETE => {
                BindComplete::parse(&buffer_set.read_buffer)?;
                self.state = State::ProcessingRows;
                Ok(Action::ReadMessage)
            }
            msg_type::ROW_DESCRIPTION => {
                // Store column buffer for later use in row callbacks
                buffer_set.column_buffer.clear();
                buffer_set
                    .column_buffer
                    .extend_from_slice(&buffer_set.read_buffer);
                let cols = RowDescription::parse(&buffer_set.column_buffer)?;
                self.handler.result_start(cols)?;
                self.state = State::ProcessingRows;
                Ok(Action::ReadMessage)
            }
            _ => Err(Error::LibraryBug(format!(
                "Expected BindComplete, got '{}'",
                type_byte as char
            ))),
        }
    }

    fn handle_rows(&mut self, buffer_set: &mut BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;
        let payload = &buffer_set.read_buffer;

        match type_byte {
            msg_type::ROW_DESCRIPTION => {
                // Store column buffer for later use in row callbacks
                buffer_set.column_buffer.clear();
                buffer_set.column_buffer.extend_from_slice(payload);
                let cols = RowDescription::parse(&buffer_set.column_buffer)?;
                self.handler.result_start(cols)?;
                Ok(Action::ReadMessage)
            }
            msg_type::NO_DATA => {
                // Statement doesn't return rows (e.g., INSERT without RETURNING)
                NoData::parse(payload)?;
                Ok(Action::ReadMessage)
            }
            msg_type::DATA_ROW => {
                let cols = RowDescription::parse(&buffer_set.column_buffer)?;
                let row = DataRow::parse(payload)?;
                self.handler.row(cols, row)?;
                Ok(Action::ReadMessage)
            }
            msg_type::COMMAND_COMPLETE => {
                let complete = CommandComplete::parse(payload)?;
                self.handler.result_end(complete)?;
                self.state = State::WaitingReady;
                Ok(Action::ReadMessage)
            }
            msg_type::EMPTY_QUERY_RESPONSE => {
                EmptyQueryResponse::parse(payload)?;
                // Portal was created from an empty query string
                self.state = State::WaitingReady;
                Ok(Action::ReadMessage)
            }
            msg_type::PORTAL_SUSPENDED => {
                PortalSuspended::parse(payload)?;
                // Row limit reached, need to Execute again to get more
                self.state = State::WaitingReady;
                Ok(Action::ReadMessage)
            }
            msg_type::READY_FOR_QUERY => {
                let ready = ReadyForQuery::parse(payload)?;
                self.transaction_status = ready.transaction_status().unwrap_or_default();
                self.state = State::Finished;
                Ok(Action::Finished)
            }
            _ => Err(Error::LibraryBug(format!(
                "Unexpected message in rows: '{}'",
                type_byte as char
            ))),
        }
    }

    fn handle_ready(&mut self, buffer_set: &BufferSet) -> Result<Action> {
        let type_byte = buffer_set.type_byte;
        let payload = &buffer_set.read_buffer;

        match type_byte {
            msg_type::READY_FOR_QUERY => {
                let ready = ReadyForQuery::parse(payload)?;
                self.transaction_status = ready.transaction_status().unwrap_or_default();
                self.state = State::Finished;
                if let Some(err) = self.pending_error.take() {
                    Ok(Action::Error(err))
                } else {
                    Ok(Action::Finished)
                }
            }
            msg_type::CLOSE_COMPLETE => {
                CloseComplete::parse(payload)?;
                // Continue waiting for ReadyForQuery
                Ok(Action::ReadMessage)
            }
            _ => Err(Error::LibraryBug(format!(
                "Expected ReadyForQuery, got '{}'",
                type_byte as char
            ))),
        }
    }

    fn handle_async_message(&self, msg: &RawMessage<'_>) -> Result<Action> {
        match msg.type_byte {
            msg_type::NOTICE_RESPONSE => {
                let notice = crate::protocol::backend::NoticeResponse::parse(msg.payload)?;
                Ok(Action::HandleAsyncMessageAndReadMessage(
                    AsyncMessage::Notice(notice.0),
                ))
            }
            msg_type::PARAMETER_STATUS => {
                let param = crate::protocol::backend::auth::ParameterStatus::parse(msg.payload)?;
                Ok(Action::HandleAsyncMessageAndReadMessage(
                    AsyncMessage::ParameterChanged {
                        name: param.name.to_string(),
                        value: param.value.to_string(),
                    },
                ))
            }
            msg_type::NOTIFICATION_RESPONSE => {
                let notification =
                    crate::protocol::backend::auth::NotificationResponse::parse(msg.payload)?;
                Ok(Action::HandleAsyncMessageAndReadMessage(
                    AsyncMessage::Notification {
                        pid: notification.pid,
                        channel: notification.channel.to_string(),
                        payload: notification.payload.to_string(),
                    },
                ))
            }
            _ => Err(Error::LibraryBug(format!(
                "Unknown async message type: '{}'",
                msg.type_byte as char
            ))),
        }
    }
}

impl<H: ExtendedHandler> StateMachine for ExtendedQueryStateMachine<'_, H> {
    fn step(&mut self, buffer_set: &mut BufferSet) -> Result<Action> {
        // Initial state: write buffer was pre-filled by constructor
        if self.state == State::Initial {
            // Determine initial waiting state based on operation
            self.state = match self.operation {
                Operation::Prepare => State::WaitingParse,
                Operation::Execute => State::WaitingBind, // First we get BindComplete
                Operation::ExecuteSql => State::WaitingParse,
                Operation::CloseStatement => State::WaitingReady,
            };
            return Ok(Action::WriteAndReadMessage);
        }

        let type_byte = buffer_set.type_byte;

        // Handle async messages
        if RawMessage::is_async_type(type_byte) {
            let msg = RawMessage::new(type_byte, &buffer_set.read_buffer);
            return self.handle_async_message(&msg);
        }
        // Handle error response
        if type_byte == msg_type::ERROR_RESPONSE {
            let error = ErrorResponse::parse(&buffer_set.read_buffer)?;
            self.pending_error = Some(error.0);
            self.state = State::WaitingReady;
            return Ok(Action::ReadMessage);
        }

        match self.state {
            State::WaitingParse => self.handle_parse(buffer_set),
            State::WaitingDescribe => self.handle_describe(buffer_set),
            State::WaitingRowDesc => self.handle_row_desc(buffer_set),
            State::WaitingBind => self.handle_bind(buffer_set),
            State::ProcessingRows => self.handle_rows(buffer_set),
            State::WaitingReady => self.handle_ready(buffer_set),
            _ => Err(Error::LibraryBug(format!(
                "Unexpected state {:?}",
                self.state
            ))),
        }
    }

    fn transaction_status(&self) -> TransactionStatus {
        self.transaction_status
    }
}

// === Bind Portal State Machine ===
// Used by exec_iter to create a portal without executing it.

use crate::protocol::frontend::write_flush;

/// State for bind portal flow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BindState {
    Initial,
    WaitingParse,
    WaitingBind,
    Finished,
}

/// State machine for binding a portal (Parse + Bind, no Execute/Sync).
///
/// Used by `exec_iter` to create a portal that can be executed multiple times.
pub struct BindStateMachine {
    state: BindState,
    needs_parse: bool,
}

impl BindStateMachine {
    /// Bind a prepared statement to a portal.
    ///
    /// Writes Bind + Flush to `buffer_set.write_buffer`.
    ///
    /// Uses the server-provided parameter OIDs to encode parameters.
    ///
    /// # Arguments
    /// - `portal_name`: Portal name (empty string "" for unnamed portal)
    pub fn bind_prepared<P: ToParams>(
        buffer_set: &mut BufferSet,
        portal_name: &str,
        statement_name: &str,
        param_oids: &[Oid],
        params: &P,
    ) -> Result<Self> {
        buffer_set.write_buffer.clear();
        write_bind(
            &mut buffer_set.write_buffer,
            portal_name,
            statement_name,
            params,
            param_oids,
        )?;
        write_flush(&mut buffer_set.write_buffer);

        Ok(Self {
            state: BindState::Initial,
            needs_parse: false,
        })
    }

    /// Parse raw SQL and bind to a portal.
    ///
    /// Writes Parse + Bind + Flush to `buffer_set.write_buffer`.
    ///
    /// Uses the natural OIDs from the parameters to inform the server about parameter types.
    ///
    /// # Arguments
    /// - `portal_name`: Portal name (empty string "" for unnamed portal)
    pub fn bind_sql<P: ToParams>(
        buffer_set: &mut BufferSet,
        portal_name: &str,
        sql: &str,
        params: &P,
    ) -> Result<Self> {
        let param_oids = params.natural_oids();
        buffer_set.write_buffer.clear();
        write_parse(&mut buffer_set.write_buffer, "", sql, &param_oids);
        write_bind(
            &mut buffer_set.write_buffer,
            portal_name,
            "",
            params,
            &param_oids,
        )?;
        write_flush(&mut buffer_set.write_buffer);

        Ok(Self {
            state: BindState::Initial,
            needs_parse: true,
        })
    }

    /// Process input and return the next action.
    pub fn step(&mut self, buffer_set: &mut BufferSet) -> Result<Action> {
        // Initial state: write buffer was pre-filled by constructor
        if self.state == BindState::Initial {
            self.state = if self.needs_parse {
                BindState::WaitingParse
            } else {
                BindState::WaitingBind
            };
            return Ok(Action::WriteAndReadMessage);
        }

        let type_byte = buffer_set.type_byte;

        // Handle async messages - need to keep reading
        if RawMessage::is_async_type(type_byte) {
            return Ok(Action::ReadMessage);
        }

        // Handle error response
        if type_byte == msg_type::ERROR_RESPONSE {
            let error = ErrorResponse::parse(&buffer_set.read_buffer)?;
            return Err(error.into_error());
        }

        match self.state {
            BindState::WaitingParse => {
                if type_byte != msg_type::PARSE_COMPLETE {
                    return Err(Error::LibraryBug(format!(
                        "Expected ParseComplete, got '{}'",
                        type_byte as char
                    )));
                }
                ParseComplete::parse(&buffer_set.read_buffer)?;
                self.state = BindState::WaitingBind;
                Ok(Action::ReadMessage)
            }
            BindState::WaitingBind => {
                if type_byte != msg_type::BIND_COMPLETE {
                    return Err(Error::LibraryBug(format!(
                        "Expected BindComplete, got '{}'",
                        type_byte as char
                    )));
                }
                BindComplete::parse(&buffer_set.read_buffer)?;
                self.state = BindState::Finished;
                Ok(Action::Finished)
            }
            _ => Err(Error::LibraryBug(format!(
                "Unexpected state {:?}",
                self.state
            ))),
        }
    }
}

// === Batch Execution State Machine ===
// Used by exec_batch to execute multiple parameter sets efficiently.

/// State for batch execution flow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BatchState {
    Initial,
    WaitingParse,
    Processing,
    Finished,
}

/// State machine for batch execution (Parse? + (Bind + Execute)* + Sync).
///
/// Used by `exec_batch` to execute a statement with multiple parameter sets.
pub struct BatchStateMachine {
    state: BatchState,
    needs_parse: bool,
    transaction_status: TransactionStatus,
    pending_error: Option<crate::error::ServerError>,
}

impl BatchStateMachine {
    /// Create a new batch state machine.
    ///
    /// The caller is responsible for populating `buffer_set.write_buffer` with:
    /// - Parse (optional, if needs_parse is true)
    /// - Bind + Execute for each parameter set
    /// - Sync
    pub fn new(needs_parse: bool) -> Self {
        Self {
            state: BatchState::Initial,
            needs_parse,
            transaction_status: TransactionStatus::Idle,
            pending_error: None,
        }
    }

    /// Get the transaction status after completion.
    pub fn transaction_status(&self) -> TransactionStatus {
        self.transaction_status
    }

    /// Process input and return the next action.
    pub fn step(&mut self, buffer_set: &mut BufferSet) -> Result<Action> {
        // Initial state: write buffer was pre-filled by caller
        if self.state == BatchState::Initial {
            self.state = if self.needs_parse {
                BatchState::WaitingParse
            } else {
                BatchState::Processing
            };
            return Ok(Action::WriteAndReadMessage);
        }

        let type_byte = buffer_set.type_byte;

        // Handle async messages - need to keep reading
        if RawMessage::is_async_type(type_byte) {
            return Ok(Action::ReadMessage);
        }
        // Handle error response - continue reading until ReadyForQuery
        if type_byte == msg_type::ERROR_RESPONSE {
            let error = ErrorResponse::parse(&buffer_set.read_buffer)?;
            self.pending_error = Some(error.0);
            self.state = BatchState::Processing;
            return Ok(Action::ReadMessage);
        }

        match self.state {
            BatchState::WaitingParse => {
                if type_byte != msg_type::PARSE_COMPLETE {
                    return Err(Error::LibraryBug(format!(
                        "Expected ParseComplete, got '{}'",
                        type_byte as char
                    )));
                }
                ParseComplete::parse(&buffer_set.read_buffer)?;
                self.state = BatchState::Processing;
                Ok(Action::ReadMessage)
            }
            BatchState::Processing => {
                match type_byte {
                    msg_type::BIND_COMPLETE => {
                        BindComplete::parse(&buffer_set.read_buffer)?;
                        Ok(Action::ReadMessage)
                    }
                    msg_type::NO_DATA => {
                        NoData::parse(&buffer_set.read_buffer)?;
                        Ok(Action::ReadMessage)
                    }
                    msg_type::ROW_DESCRIPTION => {
                        // Discard row description - we don't process rows in batch
                        RowDescription::parse(&buffer_set.read_buffer)?;
                        Ok(Action::ReadMessage)
                    }
                    msg_type::DATA_ROW => {
                        // Discard data rows - batch doesn't return data
                        Ok(Action::ReadMessage)
                    }
                    msg_type::COMMAND_COMPLETE => {
                        CommandComplete::parse(&buffer_set.read_buffer)?;
                        Ok(Action::ReadMessage)
                    }
                    msg_type::EMPTY_QUERY_RESPONSE => {
                        EmptyQueryResponse::parse(&buffer_set.read_buffer)?;
                        Ok(Action::ReadMessage)
                    }
                    msg_type::READY_FOR_QUERY => {
                        let ready = ReadyForQuery::parse(&buffer_set.read_buffer)?;
                        self.transaction_status = ready.transaction_status().unwrap_or_default();
                        self.state = BatchState::Finished;
                        if let Some(err) = self.pending_error.take() {
                            Ok(Action::Error(err))
                        } else {
                            Ok(Action::Finished)
                        }
                    }
                    _ => Err(Error::LibraryBug(format!(
                        "Unexpected message in batch: '{}'",
                        type_byte as char
                    ))),
                }
            }
            _ => Err(Error::LibraryBug(format!(
                "Unexpected state {:?}",
                self.state
            ))),
        }
    }
}