uqa-engine 0.4.0

Engine: schema-aware table store, catalog restore, transactions
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use super::{
    analyzer_registry, Arc, BTreeMap, DocId, Document, Engine, FieldName, FtsIndexStat, SQLError,
    TableState, Value,
};
use uqa_storage::InvertedIndex;

type TextIndexDocuments = Vec<(DocId, BTreeMap<FieldName, String>)>;

impl Engine {
    pub(crate) fn fts_fields_for_table(&self, name: &str) -> Result<Vec<FieldName>, SQLError> {
        Ok(self
            .try_query_table(name)
            .map_err(|err| SQLError::Internal(format!("resolve table `{name}`: {err}")))?
            .map_or_else(Vec::new, |table| table.fts_fields()))
    }

    /// Validate the physical text-search contract for one concrete field.
    /// A declared TEXT column is not searchable until it has been registered
    /// in a GIN/FTS index; treating that state as an empty posting list hides a
    /// schema/configuration error from both the public search API and the
    /// operator-tree executor.
    pub(crate) fn validate_text_search_field(
        &self,
        table: &str,
        field: &str,
    ) -> Result<(), SQLError> {
        let Some(table_state) = self
            .try_query_table(table)
            .map_err(|error| SQLError::Internal(format!("resolve text-search table: {error}")))?
        else {
            return Err(SQLError::UnknownTable(table.to_string()));
        };
        uqa_sql::semantics::text_indexes::require_physical_text_index(
            table,
            field,
            &table_state.fts_fields(),
            || table_state.columns.read().clone(),
        )
    }

    pub fn fts_index_stats(
        &self,
        table_filter: Option<&str>,
    ) -> Result<Vec<FtsIndexStat>, SQLError> {
        self.with_direct_read_snapshot(|engine| {
            engine.fts_index_stats_with_tables(table_filter, |name| {
                engine
                    .bind_query_table_read(name)
                    .map(|binding| binding.value)
            })
        })
    }

    pub(crate) fn fts_index_stats_in_execution(
        &self,
        table_filter: Option<&str>,
    ) -> Result<Vec<FtsIndexStat>, SQLError> {
        self.fts_index_stats_with_tables(table_filter, |name| self.require_query_table(name))
    }

    fn fts_index_stats_with_tables(
        &self,
        table_filter: Option<&str>,
        bind: impl Fn(&str) -> Result<Arc<TableState>, SQLError>,
    ) -> Result<Vec<FtsIndexStat>, SQLError> {
        let mut out = Vec::new();
        for table_name in self.fts_stats_table_names(table_filter)? {
            let table = bind(&table_name)?;
            let mut fields = table.fts_fields();
            fields.sort();
            let index = table.inverted_index.read();
            let index = uqa_execution::serializable::text::ObservedTextIndex::new(
                index.as_ref(),
                self.serializable_table_state_read(&table)?,
                table.columns.snapshot(),
            );
            for field in fields {
                let analyzer = self
                    .table_field_analyzer_in_execution(&table_name, &field)
                    .map_err(SQLError::Internal)?
                    .map_or_else(
                        || analyzer_registry::DEFAULT_ANALYZER_NAME.to_string(),
                        |(name, _)| name,
                    );
                let doc_length_count = index.doc_length_count(Some(&field)).map_err(|error| {
                    uqa_execution::storage_errors::storage_error(
                        "read FTS document-length count",
                        &error,
                    )
                })?;
                out.push(FtsIndexStat {
                    table_name: table_name.clone(),
                    field: field.clone(),
                    analyzer,
                    posting_count: index.posting_count(Some(&field)).map_err(|error| {
                        uqa_execution::storage_errors::storage_error(
                            "read FTS posting count",
                            &error,
                        )
                    })?,
                    doc_length_count,
                    indexed_doc_count: doc_length_count,
                    term_count: index.term_count(Some(&field)).map_err(|error| {
                        uqa_execution::storage_errors::storage_error("read FTS term count", &error)
                    })?,
                    total_field_length: index.total_field_length(&field).map_err(|error| {
                        uqa_execution::storage_errors::storage_error(
                            "read FTS field length",
                            &error,
                        )
                    })?,
                });
            }
        }
        Ok(out)
    }

    fn fts_stats_table_names(&self, table_filter: Option<&str>) -> Result<Vec<String>, SQLError> {
        self.synchronize_table_catalog()
            .map_err(|err| SQLError::Internal(format!("refresh table catalog: {err}")))?;
        let mut names = if let Some(name) = table_filter {
            vec![self
                .try_resolve_query_table_name(name)
                .map_err(|err| SQLError::Internal(format!("resolve table filter: {err}")))?
                .ok_or_else(|| SQLError::UnknownTable(name.to_string()))?]
        } else if let Some(tables) = self.query_table_snapshots.as_ref() {
            tables
                .keys()
                .map(uqa_core::RelationIdentity::qualified_name)
                .collect()
        } else {
            self.storage
                .tables
                .read()
                .keys()
                .map(uqa_core::RelationIdentity::qualified_name)
                .collect()
        };
        names.sort_unstable();
        Ok(names)
    }

    pub(crate) fn project_fts_sources(t: &Arc<TableState>) -> Result<TextIndexDocuments, String> {
        Self::project_fts_sources_inner(t, None)
    }

    pub(crate) fn project_fts_sources_cancellable(
        t: &Arc<TableState>,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<TextIndexDocuments, String> {
        Self::project_fts_sources_inner(t, Some(cancellation))
    }

    fn project_fts_sources_inner(
        t: &Arc<TableState>,
        cancellation: Option<&uqa_core::CancellationToken>,
    ) -> Result<TextIndexDocuments, String> {
        if let Some(cancellation) = cancellation {
            cancellation.check().map_err(|error| error.to_string())?;
        }
        let fts_fields = t.fts_fields();
        let indexed_docs = {
            let store = t.document_store.read();
            let doc_ids = store.doc_ids().map_err(|error| error.to_string())?;
            let fields: Vec<&str> = fts_fields.iter().map(String::as_str).collect();
            let mut indexed_docs = Vec::with_capacity(doc_ids.len());
            store
                .for_each_fields_multi_ref(&doc_ids, &fields, &mut |doc_id, projected_values| {
                    if cancellation.is_some_and(uqa_core::CancellationToken::is_cancelled) {
                        return false;
                    }
                    let mut text_fields: BTreeMap<FieldName, String> = BTreeMap::new();
                    for (field, value) in fts_fields.iter().zip(projected_values) {
                        if let Value::Str(text) = value {
                            text_fields.insert(field.clone(), text.clone());
                        }
                    }
                    if !text_fields.is_empty() {
                        indexed_docs.push((doc_id, text_fields));
                    }
                    true
                })
                .map_err(|error| error.to_string())?;
            if let Some(cancellation) = cancellation {
                cancellation.check().map_err(|error| error.to_string())?;
            }
            indexed_docs
        };
        Ok(indexed_docs)
    }

    pub(crate) fn rebuild_fts_index(t: &Arc<TableState>) -> Result<(), String> {
        let documents = Self::project_fts_sources(t)?;
        t.inverted_index
            .write()
            .try_rebuild_documents(documents)
            .map_err(|error| error.to_string())
    }

    pub(crate) fn rebuild_fts_index_cancellable(
        t: &Arc<TableState>,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<(), String> {
        let documents = Self::project_fts_sources_cancellable(t, cancellation)?;
        t.inverted_index
            .write()
            .try_rebuild_documents_cancellable(documents, cancellation)
            .map_err(|error| error.to_string())
    }

    pub fn add_document(
        &self,
        table: &str,
        doc_id: DocId,
        document: Document,
    ) -> Result<(), SQLError> {
        self.with_implicit_row_write_transaction(
            table,
            doc_id,
            uqa_sql::ast::LockStrength::ForUpdate,
            |engine| engine.add_document_impl(table, doc_id, document, false),
        )
    }

    pub(crate) fn add_document_impl(
        &self,
        table: &str,
        doc_id: DocId,
        mut document: Document,
        known_new: bool,
    ) -> Result<(), SQLError> {
        uqa_execution::mutation::assignment::refresh_stored_generated_columns(
            self.mutation_assignment_context(),
            table,
            &mut document,
        )?;
        uqa_execution::serializable::observe_row_write(self, table, doc_id)?;
        self.add_prepared_document_impl(table, doc_id, document, known_new)
    }

    pub(crate) fn add_prepared_document_impl(
        &self,
        table: &str,
        doc_id: DocId,
        document: Document,
        known_new: bool,
    ) -> Result<(), SQLError> {
        self.add_prepared_document_impl_with_fts(table, doc_id, document, known_new, true, None)
    }

    pub(crate) fn add_prepared_document_without_fts_impl(
        &self,
        table: &str,
        doc_id: DocId,
        document: Document,
        known_new: bool,
    ) -> Result<(), SQLError> {
        self.add_prepared_document_impl_with_fts(table, doc_id, document, known_new, false, None)
    }

    pub(crate) fn add_prepared_stored_document_impl(
        &self,
        table: &str,
        doc_id: DocId,
        document: uqa_storage::StoredDocument,
        known_new: bool,
    ) -> Result<(), SQLError> {
        let (fields, metadata) = document.into_parts();
        self.add_prepared_document_impl_with_fts(
            table,
            doc_id,
            fields,
            known_new,
            true,
            Some(metadata),
        )
    }

    pub(crate) fn prepared_document_text_fields(
        &self,
        table: &str,
        document: &Document,
    ) -> Result<BTreeMap<FieldName, String>, SQLError> {
        let Some(t) = self
            .try_table(table)
            .map_err(|err| SQLError::Internal(format!("resolve table `{table}`: {err}")))?
        else {
            return Err(SQLError::UnknownTable(table.to_string()));
        };
        let mut text_fields = BTreeMap::new();
        for name in &t.fts_fields() {
            if let Some(Value::Str(value)) = document.get(name) {
                text_fields.insert(name.clone(), value.clone());
            }
        }
        Ok(text_fields)
    }

    pub(crate) fn add_prepared_fts_documents(
        &self,
        table: &str,
        documents: Vec<(DocId, BTreeMap<FieldName, String>)>,
    ) -> Result<(), SQLError> {
        let Some(t) = self
            .try_table(table)
            .map_err(|err| SQLError::Internal(format!("resolve table `{table}`: {err}")))?
        else {
            return Err(SQLError::UnknownTable(table.to_string()));
        };
        let result = uqa_execution::serializable::text::add_documents(
            self,
            table,
            t.columns.snapshot(),
            t.inverted_index.write().as_mut(),
            documents,
        );
        result
    }

    fn add_prepared_document_impl_with_fts(
        &self,
        table: &str,
        doc_id: DocId,
        mut document: Document,
        known_new: bool,
        index_fts: bool,
        metadata: Option<uqa_storage::DocumentMetadata>,
    ) -> Result<(), SQLError> {
        let Some(table_name) = self
            .try_resolve_table_name(table)
            .map_err(|err| SQLError::Internal(format!("resolve table `{table}`: {err}")))?
        else {
            return Err(SQLError::UnknownTable(table.to_string()));
        };
        let Some(t) = self
            .try_table(table)
            .map_err(|err| SQLError::Internal(format!("resolve table `{table}`: {err}")))?
        else {
            return Err(SQLError::UnknownTable(table.to_string()));
        };
        let existed = if known_new {
            false
        } else {
            t.document_store
                .read()
                .get(doc_id)
                .map_err(|error| SQLError::Internal(format!("read existing document: {error}")))?
                .is_some()
        };
        // Value-index maintenance: unindex the previous field values
        // (put may replace an existing document), index the new ones.
        // `old_indexed` is `None` exactly when no index is built, so
        // the common path costs one read-lock check. A failed put must
        // leave the value indexes untouched. A known-new document has
        // no previous values to unindex, so its writes skip the per-row
        // storage lookup entirely and only insert the new values.
        let (old_indexed, indexed_fields) = if known_new {
            (None, Self::value_indexes_built_fields(&t))
        } else {
            let old = Self::value_indexes_old_values(&t, doc_id);
            let fields = old.as_ref().map(|old| {
                old.keys()
                    .cloned()
                    .collect::<Vec<uqa_storage::ValueIndexKey>>()
            });
            (old, fields)
        };
        let persistent_indexed =
            self.persistent_value_index_document_values(&table_name, &document)?;
        let new_indexed = indexed_fields
            .map(|fields| {
                if let Some(values) = &persistent_indexed {
                    return Ok(values.clone());
                }
                self.value_index_document_values(&table_name, &fields, &document)
            })
            .transpose()?;
        self.observe_value_index_write(
            &table_name,
            &t,
            doc_id,
            existed,
            old_indexed.as_ref(),
            persistent_indexed.as_ref().or(new_indexed.as_ref()),
        )?;
        if index_fts {
            let text_fields = self.prepared_document_text_fields(table, &document)?;
            // Replacement is one atomic inverted-index operation even when the new document has no indexed text. Skipping an empty field map would leave stale postings from the previous version; remove-then-add would expose a destructive failure window when analysis fails.
            uqa_execution::serializable::text::add_document(
                self,
                &table_name,
                t.columns.snapshot(),
                t.inverted_index.write().as_mut(),
                doc_id,
                text_fields,
            )?;
        }
        let columns = t.columns.read().clone();
        crate::generated::strip_virtual_generated_columns(&columns, &mut document);
        let metadata = match metadata {
            Some(metadata) => metadata,
            None => uqa_storage::DocumentMetadata::with_tuple_xmin(self.tuple_version_xid()?),
        };
        self.advance_next_id(&table_name, doc_id).map_err(|error| {
            uqa_execution::mutation::errors::identifier_storage_error(
                "observe inserted document identity",
                &error,
            )
        })?;
        let mut store = t.document_store.write();
        store
            .put_stored(
                doc_id,
                uqa_storage::StoredDocument::with_metadata(document, metadata),
            )
            .map_err(|err| crate::table_storage::document_store_write_error(&err))?;
        if let Some(new) = persistent_indexed.as_ref() {
            self.persist_value_indexes_apply_write(&table_name, doc_id, Some(new))?;
        }
        if let Some(new) = new_indexed.as_ref() {
            Self::value_indexes_apply_write(&t, doc_id, old_indexed.as_ref(), Some(new));
        }
        drop(store);
        self.mark_column_stats_dirty(&table_name, &t)
            .map_err(|err| SQLError::Internal(format!("invalidate column stats: {err}")))?;
        if existed {
            self.note_row_changed(&table_name, doc_id)?;
        } else {
            self.note_row_inserted(&table_name, doc_id)?;
        }
        Ok(())
    }
}