qail-pg 0.27.6

Fastest async PostgreSQL driver - AST to wire protocol, optional io_uring on Linux
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
//! COPY protocol methods for PostgreSQL bulk operations.
//!

use super::{
    PgConnection, PgError, PgResult, is_ignorable_session_message, parse_affected_rows,
    unexpected_backend_message,
};
use crate::protocol::{AstEncoder, BackendMessage, PgEncoder};
use bytes::BytesMut;
use qail_core::ast::{Action, Qail};
use std::future::Future;

/// Quote a SQL identifier to prevent injection.
/// Wraps in double-quotes, escapes embedded double-quotes, and strips NUL bytes.
fn quote_ident(ident: &str) -> String {
    format!("\"{}\"", ident.replace('\0', "").replace('"', "\"\""))
}

fn parse_copy_text_row(line: &[u8]) -> Vec<String> {
    let line = if line.ends_with(b"\r") {
        &line[..line.len().saturating_sub(1)]
    } else {
        line
    };
    let text = String::from_utf8_lossy(line);
    text.split('\t').map(|s| s.to_string()).collect()
}

fn drain_copy_text_rows<F>(pending: &mut Vec<u8>, chunk: &[u8], on_row: &mut F) -> PgResult<()>
where
    F: FnMut(Vec<String>) -> PgResult<()>,
{
    pending.extend_from_slice(chunk);
    while let Some(pos) = pending.iter().position(|&b| b == b'\n') {
        let line = pending[..pos].to_vec();
        pending.drain(..=pos);
        on_row(parse_copy_text_row(&line))?;
    }
    Ok(())
}

fn flush_pending_copy_text_row<F>(pending: &mut Vec<u8>, on_row: &mut F) -> PgResult<()>
where
    F: FnMut(Vec<String>) -> PgResult<()>,
{
    if pending.is_empty() {
        return Ok(());
    }
    let line = std::mem::take(pending);
    on_row(parse_copy_text_row(&line))
}

impl PgConnection {
    /// **Fast** bulk insert using COPY protocol with zero-allocation encoding.
    /// Encodes all rows into a single buffer and writes with one syscall.
    /// ~2x faster than `copy_in_internal` due to batched I/O.
    pub(crate) async fn copy_in_fast(
        &mut self,
        table: &str,
        columns: &[String],
        rows: &[Vec<qail_core::ast::Value>],
    ) -> PgResult<u64> {
        use crate::protocol::encode_copy_batch;

        let cols: Vec<String> = columns.iter().map(|c| quote_ident(c)).collect();
        let sql = format!(
            "COPY {} ({}) FROM STDIN",
            quote_ident(table),
            cols.join(", ")
        );

        // Send COPY command
        let bytes = PgEncoder::try_encode_query_string(&sql)?;
        self.write_all_with_timeout(&bytes, "stream write").await?;

        // Wait for CopyInResponse
        let mut startup_error: Option<PgError> = None;
        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CopyInResponse { .. } => {
                    if let Some(err) = startup_error {
                        return Err(err);
                    }
                    break;
                }
                BackendMessage::ReadyForQuery(_) => {
                    return Err(startup_error.unwrap_or_else(|| {
                        PgError::Protocol(
                            "COPY IN failed before CopyInResponse (unexpected ReadyForQuery)"
                                .to_string(),
                        )
                    }));
                }
                BackendMessage::ErrorResponse(err) => {
                    if startup_error.is_none() {
                        startup_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => {
                    return Err(unexpected_backend_message("copy-in startup", &other));
                }
            }
        }

        // Encode ALL rows into a single buffer (zero-allocation per value)
        let batch_data = encode_copy_batch(rows);

        // Single write for entire batch!
        self.send_copy_data(&batch_data).await?;

        // Send CopyDone
        self.send_copy_done().await?;

        // Wait for CommandComplete
        let mut affected = 0u64;
        let mut final_error: Option<PgError> = None;
        let mut saw_command_complete = false;
        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CommandComplete(tag) => {
                    if saw_command_complete {
                        return Err(PgError::Protocol(
                            "COPY IN received duplicate CommandComplete".to_string(),
                        ));
                    }
                    saw_command_complete = true;
                    if final_error.is_none() {
                        affected = parse_affected_rows(&tag);
                    }
                }
                BackendMessage::ReadyForQuery(_) => {
                    if let Some(err) = final_error {
                        return Err(err);
                    }
                    if !saw_command_complete {
                        return Err(PgError::Protocol(
                            "COPY IN completion missing CommandComplete before ReadyForQuery"
                                .to_string(),
                        ));
                    }
                    return Ok(affected);
                }
                BackendMessage::ErrorResponse(err) => {
                    if final_error.is_none() {
                        final_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => {
                    return Err(unexpected_backend_message("copy-in completion", &other));
                }
            }
        }
    }

    /// **Fastest** bulk insert using COPY protocol with pre-encoded data.
    /// Accepts raw COPY text format bytes, no encoding needed.
    /// Use when caller has already encoded rows to COPY format.
    /// # Format
    /// Data should be tab-separated rows with newlines:
    /// `1\thello\t3.14\n2\tworld\t2.71\n`
    pub async fn copy_in_raw(
        &mut self,
        table: &str,
        columns: &[String],
        data: &[u8],
    ) -> PgResult<u64> {
        let cols: Vec<String> = columns.iter().map(|c| quote_ident(c)).collect();
        let sql = format!(
            "COPY {} ({}) FROM STDIN",
            quote_ident(table),
            cols.join(", ")
        );

        // Send COPY command
        let bytes = PgEncoder::try_encode_query_string(&sql)?;
        self.write_all_with_timeout(&bytes, "stream write").await?;

        // Wait for CopyInResponse
        let mut startup_error: Option<PgError> = None;
        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CopyInResponse { .. } => {
                    if let Some(err) = startup_error {
                        return Err(err);
                    }
                    break;
                }
                BackendMessage::ReadyForQuery(_) => {
                    return Err(startup_error.unwrap_or_else(|| {
                        PgError::Protocol(
                            "COPY IN failed before CopyInResponse (unexpected ReadyForQuery)"
                                .to_string(),
                        )
                    }));
                }
                BackendMessage::ErrorResponse(err) => {
                    if startup_error.is_none() {
                        startup_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => {
                    return Err(unexpected_backend_message("copy-in raw startup", &other));
                }
            }
        }

        // Single write - data is already encoded!
        self.send_copy_data(data).await?;

        // Send CopyDone
        self.send_copy_done().await?;

        // Wait for CommandComplete
        let mut affected = 0u64;
        let mut final_error: Option<PgError> = None;
        let mut saw_command_complete = false;
        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CommandComplete(tag) => {
                    if saw_command_complete {
                        return Err(PgError::Protocol(
                            "COPY IN raw received duplicate CommandComplete".to_string(),
                        ));
                    }
                    saw_command_complete = true;
                    if final_error.is_none() {
                        affected = parse_affected_rows(&tag);
                    }
                }
                BackendMessage::ReadyForQuery(_) => {
                    if let Some(err) = final_error {
                        return Err(err);
                    }
                    if !saw_command_complete {
                        return Err(PgError::Protocol(
                            "COPY IN raw completion missing CommandComplete before ReadyForQuery"
                                .to_string(),
                        ));
                    }
                    return Ok(affected);
                }
                BackendMessage::ErrorResponse(err) => {
                    if final_error.is_none() {
                        final_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => {
                    return Err(unexpected_backend_message("copy-in raw completion", &other));
                }
            }
        }
    }

    /// Send CopyData message (raw bytes).
    pub(crate) async fn send_copy_data(&mut self, data: &[u8]) -> PgResult<()> {
        let total_len = data
            .len()
            .checked_add(4)
            .ok_or_else(|| PgError::Protocol("CopyData frame length overflow".to_string()))?;
        let len = i32::try_from(total_len)
            .map_err(|_| PgError::Protocol("CopyData frame exceeds i32::MAX".to_string()))?;

        // CopyData: 'd' + length + data
        let mut buf = BytesMut::with_capacity(1 + 4 + data.len());
        buf.extend_from_slice(b"d");
        buf.extend_from_slice(&len.to_be_bytes());
        buf.extend_from_slice(data);
        self.write_all_with_timeout(&buf, "stream write").await?;
        Ok(())
    }

    async fn send_copy_done(&mut self) -> PgResult<()> {
        // CopyDone: 'c' + length (4)
        self.write_all_with_timeout(&[b'c', 0, 0, 0, 4], "stream write")
            .await?;
        Ok(())
    }

    async fn start_copy_out(&mut self, sql: &str, context: &str) -> PgResult<()> {
        let bytes = PgEncoder::try_encode_query_string(sql)?;
        self.write_all_with_timeout(&bytes, "stream write").await?;

        let mut startup_error: Option<PgError> = None;
        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CopyOutResponse { .. } => {
                    if let Some(err) = startup_error {
                        return Err(err);
                    }
                    return Ok(());
                }
                BackendMessage::ReadyForQuery(_) => {
                    return Err(startup_error.unwrap_or_else(|| {
                        PgError::Protocol(format!(
                            "{} failed before CopyOutResponse (unexpected ReadyForQuery)",
                            context
                        ))
                    }));
                }
                BackendMessage::ErrorResponse(err) => {
                    if startup_error.is_none() {
                        startup_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => return Err(unexpected_backend_message(context, &other)),
            }
        }
    }

    async fn stream_copy_out_chunks<F, Fut>(
        &mut self,
        context: &str,
        mut on_chunk: F,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: Future<Output = PgResult<()>>,
    {
        let mut stream_error: Option<PgError> = None;
        let mut callback_error: Option<PgError> = None;
        let mut saw_copy_done = false;
        let mut saw_command_complete = false;

        loop {
            let msg = self.recv().await?;
            match msg {
                BackendMessage::CopyData(chunk) => {
                    if saw_copy_done {
                        return Err(PgError::Protocol(format!(
                            "{} received CopyData after CopyDone",
                            context
                        )));
                    }
                    if stream_error.is_none()
                        && callback_error.is_none()
                        && let Err(e) = on_chunk(chunk).await
                    {
                        callback_error = Some(e);
                    }
                }
                BackendMessage::CopyDone => {
                    if saw_copy_done {
                        return Err(PgError::Protocol(format!(
                            "{} received duplicate CopyDone",
                            context
                        )));
                    }
                    saw_copy_done = true;
                }
                BackendMessage::CommandComplete(_) => {
                    if saw_command_complete {
                        return Err(PgError::Protocol(format!(
                            "{} received duplicate CommandComplete",
                            context
                        )));
                    }
                    saw_command_complete = true;
                }
                BackendMessage::ReadyForQuery(_) => {
                    if let Some(err) = stream_error {
                        return Err(err);
                    }
                    if let Some(err) = callback_error {
                        return Err(err);
                    }
                    if !saw_copy_done {
                        return Err(PgError::Protocol(format!(
                            "{} missing CopyDone before ReadyForQuery",
                            context
                        )));
                    }
                    if !saw_command_complete {
                        return Err(PgError::Protocol(format!(
                            "{} missing CommandComplete before ReadyForQuery",
                            context
                        )));
                    }
                    return Ok(());
                }
                BackendMessage::ErrorResponse(err) => {
                    if stream_error.is_none() {
                        stream_error = Some(PgError::QueryServer(err.into()));
                    }
                }
                msg if is_ignorable_session_message(&msg) => {}
                other => return Err(unexpected_backend_message(context, &other)),
            }
        }
    }

    /// Export data using COPY TO STDOUT (AST-native).
    /// Takes a `Qail::Export` and returns rows as `Vec<Vec<String>>`.
    /// # Example
    /// ```ignore
    /// let cmd = Qail::export("users")
    ///     .columns(["id", "name"])
    ///     .filter("active", true);
    /// let rows = conn.copy_export(&cmd).await?;
    /// ```
    pub async fn copy_export(&mut self, cmd: &Qail) -> PgResult<Vec<Vec<String>>> {
        let mut rows = Vec::new();
        self.copy_export_stream_rows(cmd, |row| {
            rows.push(row);
            Ok(())
        })
        .await?;
        Ok(rows)
    }

    /// Stream COPY TO STDOUT chunks using an AST-native `Qail::Export` command.
    ///
    /// Chunks are forwarded as they arrive from PostgreSQL, so memory usage
    /// stays bounded by network frame size and callback processing.
    pub async fn copy_export_stream_raw<F, Fut>(&mut self, cmd: &Qail, on_chunk: F) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: Future<Output = PgResult<()>>,
    {
        if cmd.action != Action::Export {
            return Err(PgError::Query(
                "copy_export requires Qail::Export action".to_string(),
            ));
        }

        // Encode command to SQL using AST encoder
        let (sql, _params) =
            AstEncoder::encode_cmd_sql(cmd).map_err(|e| PgError::Encode(e.to_string()))?;

        self.copy_out_raw_stream(&sql, on_chunk).await
    }

    /// Stream COPY TO STDOUT rows using an AST-native `Qail::Export` command.
    ///
    /// Parses PostgreSQL COPY text lines into `Vec<String>` rows and invokes
    /// `on_row` for each row without buffering the full result.
    pub async fn copy_export_stream_rows<F>(&mut self, cmd: &Qail, mut on_row: F) -> PgResult<()>
    where
        F: FnMut(Vec<String>) -> PgResult<()>,
    {
        let mut pending = Vec::new();
        self.copy_export_stream_raw(cmd, |chunk| {
            let res = drain_copy_text_rows(&mut pending, &chunk, &mut on_row);
            std::future::ready(res)
        })
        .await?;
        flush_pending_copy_text_row(&mut pending, &mut on_row)
    }

    /// Export data using raw COPY TO STDOUT, returning raw bytes.
    /// Format: tab-separated values, newline-terminated rows.
    /// Suitable for direct re-import via copy_in_raw.
    ///
    /// # Safety
    /// `pub(crate)` — not exposed externally because callers pass raw SQL.
    /// External code should use `copy_export()` with the AST encoder instead.
    pub(crate) async fn copy_out_raw(&mut self, sql: &str) -> PgResult<Vec<u8>> {
        let mut data = Vec::new();
        self.copy_out_raw_stream(sql, |chunk| {
            data.extend_from_slice(&chunk);
            std::future::ready(Ok(()))
        })
        .await?;
        Ok(data)
    }

    /// Stream raw COPY TO STDOUT bytes with bounded memory usage.
    ///
    /// # Safety
    /// `pub(crate)` — callers pass raw SQL.
    pub(crate) async fn copy_out_raw_stream<F, Fut>(
        &mut self,
        sql: &str,
        on_chunk: F,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: Future<Output = PgResult<()>>,
    {
        self.start_copy_out(sql, "copy-out raw startup").await?;
        self.stream_copy_out_chunks("copy-out raw stream", on_chunk)
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::{drain_copy_text_rows, flush_pending_copy_text_row, parse_copy_text_row};
    use crate::driver::{PgError, PgResult};

    #[test]
    fn parse_copy_text_row_splits_tabs() {
        let row = parse_copy_text_row(b"a\tb\tc");
        assert_eq!(row, vec!["a", "b", "c"]);
    }

    #[test]
    fn parse_copy_text_row_trims_cr() {
        let row = parse_copy_text_row(b"a\tb\r");
        assert_eq!(row, vec!["a", "b"]);
    }

    #[test]
    fn drain_copy_text_rows_handles_chunk_boundaries() {
        let mut pending = Vec::new();
        let mut rows: Vec<Vec<String>> = Vec::new();

        drain_copy_text_rows(&mut pending, b"a\tb\nc", &mut |row: Vec<String>| {
            rows.push(row);
            Ok(())
        })
        .unwrap();
        assert_eq!(rows, vec![vec!["a".to_string(), "b".to_string()]]);
        assert_eq!(pending, b"c");

        drain_copy_text_rows(&mut pending, b"\td\n", &mut |row: Vec<String>| {
            rows.push(row);
            Ok(())
        })
        .unwrap();
        assert_eq!(
            rows,
            vec![
                vec!["a".to_string(), "b".to_string()],
                vec!["c".to_string(), "d".to_string()]
            ]
        );
        assert!(pending.is_empty());
    }

    #[test]
    fn flush_pending_copy_text_row_emits_final_partial_line() {
        let mut pending = b"x\ty".to_vec();
        let mut rows = Vec::new();
        let mut on_row = |row: Vec<String>| -> PgResult<()> {
            rows.push(row);
            Ok(())
        };

        flush_pending_copy_text_row(&mut pending, &mut on_row).unwrap();
        assert_eq!(rows, vec![vec!["x".to_string(), "y".to_string()]]);
        assert!(pending.is_empty());
    }

    #[test]
    fn callback_error_bubbles_from_row_drainer() {
        let mut pending = Vec::new();
        let mut on_row =
            |_row: Vec<String>| -> PgResult<()> { Err(PgError::Query("fail".to_string())) };

        let err = drain_copy_text_rows(&mut pending, b"a\tb\n", &mut on_row).unwrap_err();
        assert!(matches!(err, PgError::Query(msg) if msg == "fail"));
    }
}