Skip to main content

uqa_engine/
copy.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Public COPY stream entry points and session synchronization.
8use crate::Engine;
9use std::io::{Read, Write};
10use uqa_sql::SQLError;
11impl Engine {
12    /// Consume a `PostgreSQL` text or CSV `COPY relation FROM STDIN` stream.
13    ///
14    /// The complete input is decoded before the single underlying multi-row insert starts. Row routing, defaults, identity allocation, generated columns, checks, foreign keys, and statement rollback consequently use exactly the same implementation as `INSERT`.
15    pub fn copy_from(&self, statement: &str, mut input: impl Read) -> Result<u64, SQLError> {
16        let _statement = self.lock_statement_gate();
17        let result = self.synchronize_for_copy().and_then(|()| {
18            uqa_execution::copy::copy_from(&self.copy_execution_context(), statement, &mut input)
19        });
20        result.map_err(|error| self.abort_sql_transaction_after_error(error))
21    }
22
23    /// Write a `PostgreSQL` text or CSV `COPY ... TO STDOUT` stream and return the number of emitted rows.
24    pub fn copy_to(&self, statement: &str, mut output: impl Write) -> Result<u64, SQLError> {
25        let _statement = self.lock_statement_gate();
26        let _thread = self.statement_thread_context().enter();
27        let result = self.synchronize_for_copy().and_then(|()| {
28            uqa_execution::copy::copy_to(&self.copy_execution_context(), statement, &mut output)
29        });
30        result.map_err(|error| self.abort_sql_transaction_after_error(error))
31    }
32
33    fn synchronize_for_copy(&self) -> Result<(), SQLError> {
34        self.synchronize_table_catalog()
35            .map_err(|error| SQLError::Internal(format!("refresh table catalog: {error}")))?;
36        self.synchronize_table_data().map_err(|error| {
37            SQLError::Internal(format!("refresh committed table data: {error}"))
38        })?;
39        self.synchronize_catalog_registries().map_err(|error| {
40            SQLError::Internal(format!("refresh durable catalog registries: {error}"))
41        })
42    }
43}