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 _thread = self.statement_thread_context().enter();
18        let result = self.synchronize_for_copy().and_then(|()| {
19            uqa_execution::copy::copy_from(&self.copy_execution_context(), statement, &mut input)
20        });
21        result.map_err(|error| self.abort_sql_transaction_after_error(error))
22    }
23
24    /// Write a `PostgreSQL` text or CSV `COPY ... TO STDOUT` stream and return the number of emitted rows.
25    pub fn copy_to(&self, statement: &str, mut output: impl Write) -> Result<u64, SQLError> {
26        let _statement = self.lock_statement_gate();
27        let _thread = self.statement_thread_context().enter();
28        let result = self.synchronize_for_copy().and_then(|()| {
29            uqa_execution::copy::copy_to(&self.copy_execution_context(), statement, &mut output)
30        });
31        result.map_err(|error| self.abort_sql_transaction_after_error(error))
32    }
33
34    fn synchronize_for_copy(&self) -> Result<(), SQLError> {
35        self.synchronize_table_catalog()
36            .map_err(|error| SQLError::Internal(format!("refresh table catalog: {error}")))?;
37        self.synchronize_table_data().map_err(|error| {
38            SQLError::Internal(format!("refresh committed table data: {error}"))
39        })?;
40        self.synchronize_catalog_registries().map_err(|error| {
41            SQLError::Internal(format!("refresh durable catalog registries: {error}"))
42        })
43    }
44}