Skip to main content

uqa_engine/table_storage/
truncate.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Clear table-owned storage state through the public Engine table API.
8
9use crate::table_storage::document_store_write_error;
10use crate::{DocId, Engine, SQLError};
11
12impl Engine {
13    pub fn truncate_table(&self, name: &str) -> Result<(), SQLError> {
14        self.truncate_tables(std::slice::from_ref(&name.to_string()))
15    }
16
17    pub(crate) fn truncate_tables(&self, names: &[String]) -> Result<(), SQLError> {
18        self.truncate_tables_with_identity(names, true)
19    }
20
21    pub(crate) fn truncate_tables_with_identity(
22        &self,
23        names: &[String],
24        restart_identity: bool,
25    ) -> Result<(), SQLError> {
26        if self.transaction_depth() != 0 {
27            return self.truncate_tables_inner(names, restart_identity);
28        }
29        if self.storage.backend.is_none() {
30            return self.truncate_tables_inner(names, restart_identity);
31        }
32        self.begin_implicit_statement_transaction(false)?;
33        match self.truncate_tables_inner(names, restart_identity) {
34            Ok(()) => self.run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit),
35            Err(error) => {
36                match self.run_transaction_statement(uqa_sql::ast::TransactionStmt::Rollback) {
37                    Ok(()) => Err(error),
38                    Err(rollback_error) => Err(SQLError::Internal(format!(
39                        "TRUNCATE failed: {error}; rollback also failed: {rollback_error}"
40                    ))),
41                }
42            }
43        }
44    }
45
46    fn truncate_tables_inner(
47        &self,
48        names: &[String],
49        restart_identity: bool,
50    ) -> Result<(), SQLError> {
51        self.prepare_serializable_transaction_snapshot()?;
52        let mut ordered = Vec::new();
53        let mut lock_order = std::collections::BTreeSet::new();
54        for name in names {
55            let Some((table_name, "table")) = self.try_resolve_visible_relation_kind(name)? else {
56                return Err(SQLError::UnknownTable(name.clone()));
57            };
58            if lock_order.insert(table_name.clone()) {
59                ordered.push(table_name);
60            }
61        }
62        for table_name in &lock_order {
63            self.lock_relation(
64                table_name,
65                crate::row_locks::RelationLockMode::AccessExclusive,
66            )?;
67        }
68        if !ordered.is_empty() {
69            self.prepare_explicit_transaction_writer()?;
70        }
71        for table_name in ordered {
72            self.truncate_locked_table(&table_name, restart_identity)?;
73        }
74        self.publish_catalog_constraint_tuples()
75    }
76
77    pub(crate) fn truncate_locked_table(
78        &self,
79        table_name: &str,
80        restart_identity: bool,
81    ) -> Result<(), SQLError> {
82        let t = self.require_table(table_name)?;
83        let allocator = self.table_identifier_allocator(&t).map_err(|error| {
84            uqa_execution::mutation::errors::identifier_storage_error(
85                "bind TRUNCATE document allocator",
86                &error,
87            )
88        })?;
89        if allocator.is_durable() {
90            allocator
91                .synchronize(&mut t.next_id.lock())
92                .map_err(|error| {
93                    uqa_execution::mutation::errors::identifier_storage_error(
94                        "retain TRUNCATE document watermark",
95                        &error,
96                    )
97                })?;
98        }
99        // Snapshot the doc id set before grabbing any write locks so
100        // we do not deadlock against the read guard inside the loop.
101        let ids: Vec<DocId> = t
102            .document_store
103            .read()
104            .doc_ids()
105            .map_err(|error| SQLError::Internal(format!("read document ids: {error}")))?;
106        let removed_count = (ids.len() as u64).max(1);
107        for doc_id in ids {
108            t.document_store
109                .write()
110                .delete(doc_id)
111                .map_err(|err| document_store_write_error(&err))?;
112            uqa_execution::serializable::text::remove_document(
113                self,
114                table_name,
115                t.columns.snapshot(),
116                t.inverted_index.write().as_mut(),
117                doc_id,
118            )?;
119            for idx in t
120                .vector_indexes
121                .write()
122                .live_mut()
123                .map_err(|error| {
124                    uqa_execution::storage_errors::storage_error(
125                        "write vector registrations",
126                        &error,
127                    )
128                })?
129                .values_mut()
130            {
131                idx.as_mut().delete(doc_id).map_err(|error| {
132                    SQLError::Internal(format!("delete indexed vector: {error}"))
133                })?;
134            }
135            self.note_row_deleted(table_name, doc_id)?;
136        }
137        uqa_execution::schema::indexes::diskann::replace_table_storage(
138            &self.index_registry_context(),
139            table_name,
140            || {
141                // Retire old rows under their original generation before selecting the new allocator namespace.
142                *t.storage_generation.write() = crate::new_table_storage_generation()?;
143                self.try_save_table_schema(table_name, &t)
144            },
145        )
146        .map_err(|error| {
147            uqa_execution::storage_errors::storage_error("replace TRUNCATE storage", &error)
148        })?;
149        if restart_identity {
150            *t.next_id.lock() = 1;
151            self.persist_next_id(table_name).map_err(|error| {
152                uqa_execution::mutation::errors::identifier_storage_error(
153                    "persist TRUNCATE identity",
154                    &error,
155                )
156            })?;
157            let owned_sequences = self
158                .sequence_names_owned_by_tables(&std::collections::BTreeSet::from([t.object_id()]))
159                .map_err(|error| SQLError::Internal(format!("load owned sequences: {error}")))?;
160            for sequence in owned_sequences {
161                self.restart_owned_sequence(&sequence).map_err(|error| {
162                    SQLError::Internal(format!("restart owned sequence `{sequence}`: {error}"))
163                })?;
164            }
165        } else if allocator.is_durable() {
166            self.persist_next_id(table_name).map_err(|error| {
167                uqa_execution::mutation::errors::identifier_storage_error(
168                    "persist TRUNCATE document watermark",
169                    &error,
170                )
171            })?;
172        }
173        self.value_indexes_truncate(table_name, &t)?;
174        self.mark_column_stats_dirty_by_count(table_name, &t, removed_count)
175            .map_err(|err| SQLError::Internal(format!("invalidate column stats: {err}")))?;
176        Ok(())
177    }
178}