Skip to main content

hawdb_system_sql/
lib.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Virtual `system`, `information_schema`, and `pg_catalog` query execution.
16//!
17//! This crate owns the bounded, storage-backed system-catalog query engine.
18//! The embedded facade supplies a snapshot of its live state and retains all
19//! database lifecycle and transaction coordination.
20
21use hawdb_core::time::{SystemTime, UNIX_EPOCH};
22use hawdb_core::{
23    Catalog, ConstraintKind, ConstraintSubject, GraphStatistics, HawDBError, IndexKind,
24    IndexStatisticsSample, LabelId, PropertyType, RelTypeId, Result, RuntimeCapabilities,
25    SchemaObjectState, TableKind, Value,
26};
27use hawdb_executor::{
28    binding::map_payload_bytes, QueryOutput, QueryRows, QuerySchema, Row, VectorExecutionReport,
29};
30use hawdb_plan_cache::PlanCacheStats;
31use hawdb_query::QueryIdentity;
32use hawdb_sql::{Expr, ExprKind};
33use hawdb_sql::{
34    SelectProjection, SelectStatement, SqlBound, SqlColumnRef, SqlComparisonOp, SqlOrderDirection,
35    SqlOrderItem, SqlPredicate, SqlStatement, SqlValue,
36};
37use hawdb_storage::{
38    append_table::{AppendOrderMode, AppendState, AppendStorageResidencyReport},
39    config::{RelationalIndexMode, StorageResidencyMode},
40    projection::{ProjectedGraphStatus, SearchProjectionChangefeedStatus},
41    relational::{
42        RelationalColumnDefault, RelationalScalarType, RelationalState, RelationalTableSchema,
43        RelationalValue,
44    },
45};
46use std::cmp::Ordering;
47use std::collections::{BTreeMap, VecDeque};
48
49#[doc(hidden)]
50pub const DEFAULT_SLOW_QUERY_LOG_CAPACITY: usize = 256;
51#[doc(hidden)]
52pub const DEFAULT_SLOW_QUERY_LOG_THRESHOLD_MICROS: u128 = 300_000;
53#[doc(hidden)]
54pub const DEFAULT_STATEMENT_SUMMARY_CAPACITY: usize = 256;
55pub const SLOW_QUERY_LOG_EVENT_PROTOCOL: &str = "hawdb-slow-query-log-event-v1";
56const MAX_SLOW_QUERY_TEXT_BYTES: usize = 4096;
57const MAX_STATEMENT_TEXT_BYTES: usize = 4096;
58const MAX_STATEMENT_ERROR_BYTES: usize = 1024;
59
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct SlowQueryLogExportOptions {
62    pub include_query_text: bool,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct SlowQueryLogRecordSummary {
67    pub sequence: u64,
68    pub query_language: String,
69    pub statement_kind: String,
70    pub query_digest: String,
71    pub started_unix_micros: i64,
72    pub elapsed_micros: i64,
73    pub row_count: i64,
74    pub success: bool,
75    pub slow_log_candidate: bool,
76    pub access_control_policy_epoch: Option<u64>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
80#[doc(hidden)]
81pub struct SlowQueryRecord {
82    pub sequence: u64,
83    pub query_language: String,
84    pub statement_kind: String,
85    pub query_digest: String,
86    pub query_text_hash: String,
87    pub query_text: String,
88    pub started_unix_micros: i64,
89    pub elapsed_micros: i64,
90    pub row_count: i64,
91    pub success: bool,
92    pub error: Option<String>,
93    pub slow_log_candidate: bool,
94    pub access_control_policy_epoch: Option<u64>,
95    pub vector_execution_reports: Vec<VectorExecutionReport>,
96}
97
98#[doc(hidden)]
99pub struct SlowQueryCompletion<'a> {
100    pub query_language: &'a str,
101    pub statement_kind: &'a str,
102    pub query_text: &'a str,
103    pub query_identity: &'a QueryIdentity,
104    pub elapsed_micros: u128,
105    pub row_count: usize,
106    pub success: bool,
107    pub error: Option<String>,
108    pub slow_log_candidate: bool,
109    pub access_control_policy_epoch: Option<u64>,
110    pub vector_execution_reports: Vec<VectorExecutionReport>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
114#[doc(hidden)]
115pub struct SlowQueryLog {
116    capacity: usize,
117    next_sequence: u64,
118    records: VecDeque<SlowQueryRecord>,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122#[doc(hidden)]
123pub struct StatementExecution {
124    pub query_language: String,
125    pub query_text: String,
126    pub statement_kind: String,
127    pub query_digest: String,
128    pub query_text_hash: String,
129    pub elapsed_micros: i64,
130    pub row_count: i64,
131    pub success: bool,
132    pub error: Option<String>,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
136#[doc(hidden)]
137pub struct StatementSummaryRecord {
138    pub digest: String,
139    pub query_language: String,
140    pub query_text: String,
141    pub sample_query_text_hash: String,
142    pub statement_kind: String,
143    pub execution_count: i64,
144    pub success_count: i64,
145    pub error_count: i64,
146    pub total_elapsed_micros: i64,
147    pub max_elapsed_micros: i64,
148    pub total_row_count: i64,
149    pub last_seen_unix_micros: i64,
150    pub last_elapsed_micros: i64,
151    pub last_row_count: i64,
152    pub last_success: bool,
153    pub last_error: Option<String>,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157#[doc(hidden)]
158pub struct StatementSummary {
159    capacity: usize,
160    records: BTreeMap<String, StatementSummaryRecord>,
161    insertion_order: VecDeque<String>,
162}
163
164/// Supplies the storage state needed by bounded virtual catalog queries.
165///
166/// The embedded facade owns the concrete store and adapts it at this boundary.
167#[doc(hidden)]
168pub trait SystemSqlStore {
169    fn commit_epoch(&self) -> u64;
170    fn append_storage_residency_report(&self) -> AppendStorageResidencyReport;
171    fn statistics(&self, catalog: &Catalog) -> GraphStatistics;
172    fn projected_graph_statuses(&self) -> Vec<ProjectedGraphStatus>;
173    fn search_projection_changefeed_status(&self) -> SearchProjectionChangefeedStatus;
174}
175
176#[doc(hidden)]
177pub struct SystemSqlContext<'a, Store: SystemSqlStore> {
178    pub catalog: &'a Catalog,
179    pub store: &'a Store,
180    pub relational_state: &'a RelationalState,
181    pub append_state: &'a AppendState,
182    pub runtime: SystemRuntimeSnapshot,
183    pub plan_cache_stats: &'a PlanCacheStats,
184    pub slow_queries: &'a [SlowQueryRecord],
185    pub statement_summaries: &'a [StatementSummaryRecord],
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189#[doc(hidden)]
190pub struct SystemRuntimeSnapshot {
191    read_only: bool,
192    max_read_result_rows: Option<usize>,
193    max_read_result_payload_bytes: Option<usize>,
194    storage_residency_mode: StorageResidencyMode,
195    relational_index_mode: RelationalIndexMode,
196    runtime_capabilities: RuntimeCapabilities,
197}
198
199impl SystemRuntimeSnapshot {
200    pub fn new(
201        read_only: bool,
202        max_read_result_rows: Option<usize>,
203        max_read_result_payload_bytes: Option<usize>,
204        storage_residency_mode: StorageResidencyMode,
205        relational_index_mode: RelationalIndexMode,
206        runtime_capabilities: RuntimeCapabilities,
207    ) -> Self {
208        Self {
209            read_only,
210            max_read_result_rows,
211            max_read_result_payload_bytes,
212            storage_residency_mode,
213            relational_index_mode,
214            runtime_capabilities,
215        }
216    }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub(crate) enum SqlLogicalPlan {
221    SystemTableScan(SystemTableScan),
222}
223
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub(crate) enum SqlPhysicalPlan {
226    SystemTableScanExec(SystemTableScan),
227}
228
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub(crate) struct SystemTableScan {
231    table: SystemTable,
232    projection: Vec<(String, String)>,
233    predicate: Option<SqlPredicate>,
234    order_by: Vec<SqlOrderItem>,
235    offset: Option<u64>,
236    limit: Option<u64>,
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240enum SystemTable {
241    Tables,
242    VectorColumns,
243    Properties,
244    Indexes,
245    Constraints,
246    AppendTables,
247    AppendStorage,
248    RuntimeStatus,
249    RuntimeCapabilities,
250    GraphStatistics,
251    ProjectedGraphs,
252    SearchProjectionChangefeed,
253    PlanCache,
254    SlowQueries,
255    StatementSummary,
256    InformationSchemaTables,
257    InformationSchemaColumns,
258    PgTables,
259    PgIndexes,
260}
261
262#[doc(hidden)]
263pub fn is_virtual_catalog_select(select: &SelectStatement) -> bool {
264    let Some(from) = &select.from else {
265        return false;
266    };
267    matches!(
268        (from.schema.as_deref(), from.name.as_str()),
269        (Some("system" | "information_schema" | "pg_catalog"), _)
270            | (None, "pg_tables" | "pg_indexes")
271    )
272}
273
274impl SlowQueryRecord {
275    pub fn completed(completion: SlowQueryCompletion<'_>) -> Self {
276        Self {
277            sequence: 0,
278            query_language: completion.query_language.to_string(),
279            statement_kind: completion.statement_kind.to_string(),
280            query_digest: completion.query_identity.query_digest().to_string(),
281            query_text_hash: completion.query_identity.query_text_hash().to_string(),
282            query_text: truncate_utf8(completion.query_text, MAX_SLOW_QUERY_TEXT_BYTES),
283            started_unix_micros: unix_now_micros(),
284            elapsed_micros: saturating_i64_from_u128(completion.elapsed_micros),
285            row_count: i64::try_from(completion.row_count).unwrap_or(i64::MAX),
286            success: completion.success,
287            error: completion.error,
288            slow_log_candidate: completion.slow_log_candidate,
289            access_control_policy_epoch: completion.access_control_policy_epoch,
290            vector_execution_reports: completion.vector_execution_reports,
291        }
292    }
293}
294
295impl SlowQueryLog {
296    pub fn new(capacity: usize) -> Self {
297        Self {
298            capacity,
299            next_sequence: 1,
300            records: VecDeque::with_capacity(capacity),
301        }
302    }
303
304    pub fn push(&mut self, mut record: SlowQueryRecord) {
305        if self.capacity == 0 {
306            return;
307        }
308        record.sequence = self.next_sequence;
309        self.next_sequence = self.next_sequence.saturating_add(1);
310        while self.records.len() >= self.capacity {
311            self.records.pop_front();
312        }
313        self.records.push_back(record);
314    }
315
316    pub fn snapshot(&self) -> Vec<SlowQueryRecord> {
317        self.records.iter().cloned().collect()
318    }
319}
320
321pub fn slow_query_log_jsonl(
322    records: &[SlowQueryRecord],
323    include_query_text: bool,
324) -> Result<String> {
325    let mut jsonl = String::new();
326    for record in records {
327        let line = serde_json::to_string(&slow_query_record_json(record, include_query_text))
328            .map_err(|error| {
329                HawDBError::or_stop(&error, || {
330                    HawDBError::Execution(format!("slow query log JSON error: {error}"))
331                })
332            })?;
333        jsonl.push_str(&line);
334        jsonl.push('\n');
335    }
336    Ok(jsonl)
337}
338
339pub fn slow_query_record_summary(record: &SlowQueryRecord) -> SlowQueryLogRecordSummary {
340    SlowQueryLogRecordSummary {
341        sequence: record.sequence,
342        query_language: record.query_language.clone(),
343        statement_kind: record.statement_kind.clone(),
344        query_digest: record.query_digest.clone(),
345        started_unix_micros: record.started_unix_micros,
346        elapsed_micros: record.elapsed_micros,
347        row_count: record.row_count,
348        success: record.success,
349        slow_log_candidate: record.slow_log_candidate,
350        access_control_policy_epoch: record.access_control_policy_epoch,
351    }
352}
353
354fn slow_query_record_json(record: &SlowQueryRecord, include_query_text: bool) -> serde_json::Value {
355    let mut object = serde_json::json!({
356        "protocol": SLOW_QUERY_LOG_EVENT_PROTOCOL,
357        "protocol_version": 1,
358        "sequence": record.sequence,
359        "query_language": record.query_language,
360        "statement_kind": record.statement_kind,
361        "query_digest": record.query_digest,
362        "started_unix_micros": record.started_unix_micros,
363        "elapsed_micros": record.elapsed_micros,
364        "row_count": record.row_count,
365        "success": record.success,
366        "slow_log_candidate": record.slow_log_candidate,
367        "access_control_policy_epoch": record.access_control_policy_epoch,
368        "redaction": {
369            "query_text_copied": include_query_text,
370            "parameters_copied": false,
371            "access_control_policy_inputs_copied": false
372        }
373    });
374    if include_query_text {
375        object["query_text"] = serde_json::Value::String(record.query_text.clone());
376    }
377    if let Some(error) = &record.error {
378        object["error"] =
379            serde_json::Value::String(truncate_utf8(error, MAX_STATEMENT_ERROR_BYTES));
380    }
381    object["vector_execution_report_count"] =
382        serde_json::json!(record.vector_execution_reports.len());
383    object["vector_execution_reports"] = serde_json::Value::Array(
384        record
385            .vector_execution_reports
386            .iter()
387            .map(vector_execution_report_json)
388            .collect(),
389    );
390    object
391}
392
393fn vector_execution_report_json(report: &VectorExecutionReport) -> serde_json::Value {
394    serde_json::json!({
395        "backend": report.backend.as_str(),
396        "compression_mode": report.compression_mode.as_str(),
397        "candidate_source": report.candidate_source.as_str(),
398        "backend_selection_reason": report.backend_selection_reason.map(|reason| reason.as_str()),
399        "estimated_raw_vector_bytes": report.estimated_raw_vector_bytes,
400        "filter_selectivity_per_million": report.filter_selectivity_per_million,
401        "candidate_score_source": report.candidate_score_source.as_str(),
402        "final_score_source": report.final_score_source.as_str(),
403        "generated_candidate_count": report.generated_candidate_count,
404        "descriptor_pruned_count": report.descriptor_pruned_count,
405        "scalar_filtered_count": report.scalar_filtered_count,
406        "residual_filtered_count": report.residual_filtered_count,
407        "candidate_scan_rounds": report.candidate_scan_rounds,
408        "reranked_candidate_count": report.reranked_candidate_count,
409        "returned_count": report.returned_count,
410        "raw_vector_bytes_read": report.raw_vector_bytes_read,
411        "candidate_scan": report.candidate_scan_metrics.as_ref().map(|metrics| serde_json::json!({
412            "kernel": metrics.kernel,
413            "worker_count": metrics.worker_count,
414            "segment_count": metrics.segment_count,
415            "scanned_segment_count": metrics.scanned_segment_count,
416            "scored_document_count": metrics.scored_document_count,
417            "filtered_document_count": metrics.filtered_document_count,
418            "scanned_block_count": metrics.scanned_block_count,
419            "skipped_block_count": metrics.skipped_block_count,
420            "payload_bytes_read": metrics.payload_bytes_read,
421            "admitted_working_bytes": metrics.admitted_working_bytes,
422        })),
423        "index_covered_document_count": report.index_covered_document_count,
424        "index_candidate_document_count": report.index_candidate_document_count,
425        "index_coverage_complete": report.index_coverage_complete,
426        "fallback_reason_codes": report.fallback_reason_codes.iter().map(|code| code.as_str()).collect::<Vec<_>>(),
427    })
428}
429
430impl StatementExecution {
431    pub fn completed(
432        query_language: &str,
433        query_text: &str,
434        statement_kind: &str,
435        query_identity: &QueryIdentity,
436        elapsed_micros: u128,
437        row_count: usize,
438    ) -> Self {
439        Self {
440            query_language: query_language.to_string(),
441            query_text: truncate_utf8(query_text, MAX_STATEMENT_TEXT_BYTES),
442            statement_kind: statement_kind.to_string(),
443            query_digest: query_identity.query_digest().to_string(),
444            query_text_hash: query_identity.query_text_hash().to_string(),
445            elapsed_micros: saturating_i64_from_u128(elapsed_micros),
446            row_count: i64::try_from(row_count).unwrap_or(i64::MAX),
447            success: true,
448            error: None,
449        }
450    }
451
452    pub fn failed(
453        query_language: &str,
454        query_text: &str,
455        statement_kind: &str,
456        query_identity: &QueryIdentity,
457        elapsed_micros: u128,
458        error: String,
459    ) -> Self {
460        Self {
461            query_language: query_language.to_string(),
462            query_text: truncate_utf8(query_text, MAX_STATEMENT_TEXT_BYTES),
463            statement_kind: statement_kind.to_string(),
464            query_digest: query_identity.query_digest().to_string(),
465            query_text_hash: query_identity.query_text_hash().to_string(),
466            elapsed_micros: saturating_i64_from_u128(elapsed_micros),
467            row_count: 0,
468            success: false,
469            error: Some(truncate_utf8(&error, MAX_STATEMENT_ERROR_BYTES)),
470        }
471    }
472}
473
474impl StatementSummary {
475    pub fn new(capacity: usize) -> Self {
476        Self {
477            capacity,
478            records: BTreeMap::new(),
479            insertion_order: VecDeque::with_capacity(capacity),
480        }
481    }
482
483    pub fn record(&mut self, execution: StatementExecution) {
484        if self.capacity == 0 {
485            return;
486        }
487
488        if let Some(record) = self.records.get_mut(execution.query_digest.as_str()) {
489            record.apply(execution);
490            return;
491        }
492        self.insert_execution(execution);
493    }
494
495    /// Updates a successful execution without owning metadata already retained
496    /// by the first sample for this digest.
497    pub fn record_completed(
498        &mut self,
499        query_language: &str,
500        query_text: &str,
501        statement_kind: &str,
502        query_identity: &QueryIdentity,
503        elapsed_micros: u128,
504        row_count: usize,
505    ) {
506        if self.capacity == 0 {
507            return;
508        }
509        if let Some(record) = self.records.get_mut(query_identity.query_digest()) {
510            record.apply_metrics(
511                saturating_i64_from_u128(elapsed_micros),
512                i64::try_from(row_count).unwrap_or(i64::MAX),
513                true,
514                None,
515            );
516            return;
517        }
518        self.insert_execution(StatementExecution::completed(
519            query_language,
520            query_text,
521            statement_kind,
522            query_identity,
523            elapsed_micros,
524            row_count,
525        ));
526    }
527
528    fn insert_execution(&mut self, execution: StatementExecution) {
529        let digest = execution.query_digest.clone();
530        while self.records.len() >= self.capacity {
531            let Some(evicted) = self.insertion_order.pop_front() else {
532                break;
533            };
534            self.records.remove(&evicted);
535        }
536
537        self.insertion_order.push_back(digest.clone());
538        self.records.insert(
539            digest.clone(),
540            StatementSummaryRecord::from_execution(digest, execution),
541        );
542    }
543
544    pub fn snapshot(&self) -> Vec<StatementSummaryRecord> {
545        self.insertion_order
546            .iter()
547            .filter_map(|digest| self.records.get(digest).cloned())
548            .collect()
549    }
550}
551
552impl StatementSummaryRecord {
553    fn from_execution(digest: String, execution: StatementExecution) -> Self {
554        let now = unix_now_micros();
555        let success_count = i64::from(execution.success);
556        let error_count = i64::from(!execution.success);
557        Self {
558            digest,
559            query_language: execution.query_language,
560            query_text: execution.query_text,
561            sample_query_text_hash: execution.query_text_hash,
562            statement_kind: execution.statement_kind,
563            execution_count: 1,
564            success_count,
565            error_count,
566            total_elapsed_micros: execution.elapsed_micros,
567            max_elapsed_micros: execution.elapsed_micros,
568            total_row_count: execution.row_count,
569            last_seen_unix_micros: now,
570            last_elapsed_micros: execution.elapsed_micros,
571            last_row_count: execution.row_count,
572            last_success: execution.success,
573            last_error: execution.error,
574        }
575    }
576
577    fn apply(&mut self, execution: StatementExecution) {
578        self.apply_metrics(
579            execution.elapsed_micros,
580            execution.row_count,
581            execution.success,
582            execution.error,
583        );
584    }
585
586    fn apply_metrics(
587        &mut self,
588        elapsed_micros: i64,
589        row_count: i64,
590        success: bool,
591        error: Option<String>,
592    ) {
593        self.execution_count = self.execution_count.saturating_add(1);
594        if success {
595            self.success_count = self.success_count.saturating_add(1);
596        } else {
597            self.error_count = self.error_count.saturating_add(1);
598        }
599        self.total_elapsed_micros = self.total_elapsed_micros.saturating_add(elapsed_micros);
600        self.max_elapsed_micros = self.max_elapsed_micros.max(elapsed_micros);
601        self.total_row_count = self.total_row_count.saturating_add(row_count);
602        self.last_seen_unix_micros = unix_now_micros();
603        self.last_elapsed_micros = elapsed_micros;
604        self.last_row_count = row_count;
605        self.last_success = success;
606        self.last_error = error;
607    }
608}
609
610#[cfg(test)]
611pub fn query_sql<Store: SystemSqlStore>(
612    sql_text: &str,
613    max_rows: Option<usize>,
614    max_payload_bytes: Option<usize>,
615    context: &SystemSqlContext<'_, Store>,
616) -> Result<QueryOutput> {
617    query_sql_with_params(sql_text, &[], max_rows, max_payload_bytes, context)
618}
619
620pub fn query_sql_with_params<Store: SystemSqlStore>(
621    sql_text: &str,
622    parameters: &[Value],
623    max_rows: Option<usize>,
624    max_payload_bytes: Option<usize>,
625    context: &SystemSqlContext<'_, Store>,
626) -> Result<QueryOutput> {
627    let logical = plan_sql(sql_text, parameters)?;
628    let physical = optimize_sql(logical);
629    let SqlPhysicalPlan::SystemTableScanExec(scan) = &physical;
630    let schema = QuerySchema::try_new(scan.projection.iter().map(|(_, name)| name.clone()))?;
631    let rows = execute_sql(physical, context, max_rows)?;
632    let payload_bytes = rows.iter().fold(0usize, |total, row| {
633        total.saturating_add(map_payload_bytes(row))
634    });
635    if let Some(limit) = max_payload_bytes
636        && payload_bytes > limit
637    {
638        return Err(HawDBError::read_budget_exceeded(
639            hawdb_core::ReadBudgetResource::PayloadBytes,
640            limit,
641            format!(
642                "SQL query payload uses {payload_bytes} bytes, exceeding max_read_result_payload_bytes {limit}"
643            ),
644        ));
645    }
646    Ok(QueryOutput {
647        rows: QueryRows::try_from_named_rows(schema, rows)?,
648    })
649}
650
651fn plan_sql(sql_text: &str, parameters: &[Value]) -> Result<SqlLogicalPlan> {
652    let prepared = hawdb_sql::prepare_postgres_sql(sql_text)?;
653    if prepared.parameters.len() != parameters.len() {
654        return Err(HawDBError::Semantic(format!(
655            "PostgreSQL statement requires {} parameters, but {} parameters were supplied",
656            prepared.parameters.len(),
657            parameters.len()
658        )));
659    }
660    let SqlStatement::Select(select) = prepared.statement else {
661        return Err(HawDBError::Semantic(
662            "system SQL only supports SELECT statements".to_string(),
663        ));
664    };
665    validate_system_select_shape(&select)?;
666    let table = system_table(&select)?;
667    validate_projection(table, &select.projection)?;
668    validate_predicate_columns(table, select.selection.as_ref())?;
669    validate_order_columns(table, &select.order_by)?;
670    Ok(SqlLogicalPlan::SystemTableScan(SystemTableScan {
671        table,
672        projection: projection_columns(table, &select.projection),
673        predicate: select
674            .selection
675            .map(|predicate| bind_predicate(predicate, parameters))
676            .transpose()?,
677        order_by: select.order_by,
678        offset: select
679            .offset
680            .map(|bound| bind_bound(bound, parameters, "OFFSET"))
681            .transpose()?,
682        limit: select
683            .limit
684            .map(|bound| bind_bound(bound, parameters, "LIMIT"))
685            .transpose()?,
686    }))
687}
688
689fn validate_system_select_shape(select: &SelectStatement) -> Result<()> {
690    if select.having.is_some() {
691        return Err(HawDBError::Semantic(
692            "system SQL does not support HAVING".into(),
693        ));
694    }
695    if select.distinct
696        || select.from_alias.is_some()
697        || !select.joins.is_empty()
698        || !select.group_by.is_empty()
699        || select.lock_strength.is_some()
700    {
701        return Err(HawDBError::Semantic(
702            "system SQL does not support DISTINCT, table aliases, joins, GROUP BY, or locking clauses"
703                .to_string(),
704        ));
705    }
706    if select
707        .order_by
708        .iter()
709        .any(|item| item.nulls != hawdb_sql::SqlNullOrder::DialectDefault)
710    {
711        return Err(HawDBError::Semantic(
712            "system SQL does not support explicit NULLS FIRST/LAST".to_string(),
713        ));
714    }
715    Ok(())
716}
717
718fn bind_predicate(mut predicate: SqlPredicate, parameters: &[Value]) -> Result<SqlPredicate> {
719    predicate.try_visit_mut(&mut |expression| {
720        if let ExprKind::Value(value) = &mut expression.kind {
721            let unbound = std::mem::replace(value, SqlValue::Literal(Value::Null));
722            *value = SqlValue::Literal(bind_value(unbound, parameters)?);
723        }
724        if let ExprKind::Like {
725            pattern,
726            escape,
727            case_insensitive,
728            ..
729        } = &expression.kind
730            && let SqlValue::Literal(Value::String(pattern)) = pattern.require_value()?
731        {
732            hawdb_sql::sql_like_matches("", pattern, *escape, *case_insensitive)?;
733        }
734        Ok::<_, HawDBError>(())
735    })?;
736    Ok(predicate)
737}
738
739fn bind_value(value: SqlValue, parameters: &[Value]) -> Result<Value> {
740    hawdb_sql::bind_sql_value(&value, parameters)
741}
742
743fn bind_bound(bound: SqlBound, parameters: &[Value], name: &str) -> Result<u64> {
744    match bound {
745        SqlBound::Literal(value) => Ok(value),
746        SqlBound::Parameter(position) => match parameters.get(position - 1) {
747            Some(Value::Int(value)) if *value >= 0 => Ok(*value as u64),
748            Some(_) => Err(HawDBError::Semantic(format!(
749                "PostgreSQL {name} parameter ${position} must be a non-negative integer"
750            ))),
751            None => Err(HawDBError::Semantic(format!(
752                "missing PostgreSQL parameter ${position}"
753            ))),
754        },
755    }
756}
757
758fn optimize_sql(logical: SqlLogicalPlan) -> SqlPhysicalPlan {
759    match logical {
760        SqlLogicalPlan::SystemTableScan(scan) => SqlPhysicalPlan::SystemTableScanExec(scan),
761    }
762}
763
764fn execute_sql<Store: SystemSqlStore>(
765    physical: SqlPhysicalPlan,
766    context: &SystemSqlContext<'_, Store>,
767    max_rows: Option<usize>,
768) -> Result<Vec<Row>> {
769    match physical {
770        SqlPhysicalPlan::SystemTableScanExec(scan) => {
771            execute_system_table_scan(scan, context, max_rows)
772        }
773    }
774}
775
776fn execute_system_table_scan<Store: SystemSqlStore>(
777    scan: SystemTableScan,
778    context: &SystemSqlContext<'_, Store>,
779    max_rows: Option<usize>,
780) -> Result<Vec<Row>> {
781    let mut rows = match scan.table {
782        SystemTable::Tables => table_rows(context.catalog),
783        SystemTable::VectorColumns => vector_column_rows(context.relational_state),
784        SystemTable::Properties => property_rows(context.catalog),
785        SystemTable::Indexes => index_rows(context.catalog),
786        SystemTable::Constraints => constraint_rows(context.catalog),
787        SystemTable::AppendTables => append_table_rows(context.append_state),
788        SystemTable::AppendStorage => append_storage_rows(context.store, context.append_state),
789        SystemTable::RuntimeStatus => runtime_status_rows(context),
790        SystemTable::RuntimeCapabilities => runtime_capability_rows(context.runtime),
791        SystemTable::GraphStatistics => {
792            graph_statistics_rows(context.catalog, &context.store.statistics(context.catalog))
793        }
794        SystemTable::ProjectedGraphs => {
795            projected_graph_rows(context.store.projected_graph_statuses())
796        }
797        SystemTable::SearchProjectionChangefeed => {
798            search_projection_changefeed_rows(context.store.search_projection_changefeed_status())
799        }
800        SystemTable::PlanCache => plan_cache_rows(context.plan_cache_stats),
801        SystemTable::SlowQueries => slow_query_rows(context.slow_queries),
802        SystemTable::StatementSummary => statement_summary_rows(context.statement_summaries),
803        SystemTable::InformationSchemaTables => {
804            information_schema_table_rows(context.relational_state)
805        }
806        SystemTable::InformationSchemaColumns => {
807            information_schema_column_rows(context.relational_state)
808        }
809        SystemTable::PgTables => pg_table_rows(context.relational_state),
810        SystemTable::PgIndexes => pg_index_rows(context.relational_state),
811    };
812
813    if let Some(predicate) = &scan.predicate {
814        let mut retained = 0;
815        for index in 0..rows.len() {
816            if predicate_matches(predicate, &rows[index])? {
817                rows.swap(retained, index);
818                retained += 1;
819            }
820        }
821        rows.truncate(retained);
822    }
823
824    if !scan.order_by.is_empty() {
825        rows.sort_by(|left, right| compare_ordered_rows(left, right, &scan.order_by));
826    }
827
828    let offset = scan.offset.unwrap_or(0);
829    let limit = effective_limit(scan.limit, max_rows)?;
830    rows = rows
831        .into_iter()
832        .skip(usize::try_from(offset).unwrap_or(usize::MAX))
833        .take(limit.unwrap_or(usize::MAX))
834        .collect();
835
836    if let Some(max_rows) = max_rows
837        && rows.len() > max_rows
838    {
839        return Err(HawDBError::read_budget_exceeded(
840            hawdb_core::ReadBudgetResource::Rows,
841            max_rows,
842            format!(
843                "SQL query returned more than {max_rows} rows, exceeding max_read_result_rows {max_rows}"
844            ),
845        ));
846    }
847
848    Ok(project_rows(rows, &scan.projection))
849}
850
851fn effective_limit(query_limit: Option<u64>, max_rows: Option<usize>) -> Result<Option<usize>> {
852    let query_limit = query_limit
853        .map(|limit| {
854            usize::try_from(limit)
855                .map_err(|_| HawDBError::Semantic("SQL LIMIT is too large".to_string()))
856        })
857        .transpose()?;
858    Ok(match (query_limit, max_rows) {
859        (Some(query_limit), Some(max_rows)) => Some(query_limit.min(max_rows.saturating_add(1))),
860        (Some(query_limit), None) => Some(query_limit),
861        (None, Some(max_rows)) => Some(max_rows.saturating_add(1)),
862        (None, None) => None,
863    })
864}
865
866fn projection_columns(
867    table: SystemTable,
868    projection: &[SelectProjection],
869) -> Vec<(String, String)> {
870    let mut columns = Vec::new();
871    for item in projection {
872        match item {
873            SelectProjection::Wildcard => columns.extend(
874                table_columns(table)
875                    .iter()
876                    .map(|name| (name.to_string(), name.to_string())),
877            ),
878            SelectProjection::Expression {
879                expression:
880                    Expr {
881                        kind: ExprKind::Column(column),
882                        ..
883                    },
884                alias,
885                ..
886            } => columns.push((
887                column.name.clone(),
888                alias.clone().unwrap_or_else(|| column.name.clone()),
889            )),
890            _ => unreachable!("catalog projections were validated during planning"),
891        }
892    }
893    columns
894}
895
896fn project_rows(rows: Vec<Row>, projection: &[(String, String)]) -> Vec<Row> {
897    rows.into_iter()
898        .map(|row| {
899            projection
900                .iter()
901                .map(|(source, name)| {
902                    let value = row.get(source).cloned().unwrap_or(Value::Null);
903                    (name.clone(), value)
904                })
905                .collect()
906        })
907        .collect()
908}
909
910fn table_rows(catalog: &Catalog) -> Vec<Row> {
911    catalog
912        .table_descriptors()
913        .map(|table| {
914            BTreeMap::from([
915                ("table_id".to_string(), u32_value(table.id.0)),
916                ("table_name".to_string(), Value::String(table.name.clone())),
917                (
918                    "table_kind".to_string(),
919                    Value::String(table_kind_name(table.kind).to_string()),
920                ),
921                (
922                    "state".to_string(),
923                    Value::String(schema_object_state_name(table.state).to_string()),
924                ),
925            ])
926        })
927        .collect()
928}
929
930fn information_schema_table_rows(state: &RelationalState) -> Vec<Row> {
931    state
932        .table_schemas()
933        // Search index postings are an index, not a relation.
934        .filter(|schema| schema.search_index().is_none())
935        .map(|schema| {
936            BTreeMap::from([
937                (
938                    "table_catalog".to_string(),
939                    Value::String("hawdb".to_string()),
940                ),
941                (
942                    "table_schema".to_string(),
943                    Value::String("public".to_string()),
944                ),
945                ("table_name".to_string(), Value::String(schema.name.clone())),
946                (
947                    "table_type".to_string(),
948                    Value::String(
949                        if schema.materialized_view.is_some() {
950                            "MATERIALIZED VIEW"
951                        } else {
952                            "BASE TABLE"
953                        }
954                        .to_string(),
955                    ),
956                ),
957                ("self_referencing_column_name".to_string(), Value::Null),
958                ("reference_generation".to_string(), Value::Null),
959                ("user_defined_type_catalog".to_string(), Value::Null),
960                ("user_defined_type_schema".to_string(), Value::Null),
961                ("user_defined_type_name".to_string(), Value::Null),
962                (
963                    "is_insertable_into".to_string(),
964                    Value::String(
965                        if schema.materialized_view.is_some() {
966                            "NO"
967                        } else {
968                            "YES"
969                        }
970                        .to_string(),
971                    ),
972                ),
973                ("is_typed".to_string(), Value::String("NO".to_string())),
974                ("commit_action".to_string(), Value::Null),
975            ])
976        })
977        .collect()
978}
979
980fn vector_column_rows(state: &RelationalState) -> Vec<Row> {
981    state
982        .table_schemas()
983        .flat_map(|schema| {
984            schema.columns.iter().filter_map(move |column| {
985                let RelationalScalarType::Vector(dimension) = column.scalar_type else {
986                    return None;
987                };
988                Some(BTreeMap::from([
989                    ("table_schema".into(), Value::String("public".into())),
990                    ("table_name".into(), Value::String(schema.name.clone())),
991                    ("column_name".into(), Value::String(column.name.clone())),
992                    ("dimensions".into(), Value::Int(i64::from(dimension.get()))),
993                    ("element_type".into(), Value::String("float32".into())),
994                    ("nullable".into(), Value::Bool(column.nullable)),
995                ]))
996            })
997        })
998        .collect()
999}
1000
1001fn information_schema_column_rows(state: &RelationalState) -> Vec<Row> {
1002    state
1003        .table_schemas()
1004        .flat_map(|schema| {
1005            schema
1006                .visible_columns()
1007                .iter()
1008                .enumerate()
1009                .map(move |(position, column)| {
1010                    let type_info = information_schema_type(column.scalar_type);
1011                    let ordinal_position = position.saturating_add(1);
1012                    BTreeMap::from([
1013                        (
1014                            "table_catalog".to_string(),
1015                            Value::String("hawdb".to_string()),
1016                        ),
1017                        (
1018                            "table_schema".to_string(),
1019                            Value::String("public".to_string()),
1020                        ),
1021                        ("table_name".to_string(), Value::String(schema.name.clone())),
1022                        (
1023                            "column_name".to_string(),
1024                            Value::String(column.name.clone()),
1025                        ),
1026                        (
1027                            "ordinal_position".to_string(),
1028                            usize_value(ordinal_position),
1029                        ),
1030                        (
1031                            "column_default".to_string(),
1032                            relational_default_value(column.default.as_ref()),
1033                        ),
1034                        (
1035                            "is_nullable".to_string(),
1036                            Value::String(if column.nullable { "YES" } else { "NO" }.to_string()),
1037                        ),
1038                        (
1039                            "data_type".to_string(),
1040                            Value::String(type_info.data_type.to_string()),
1041                        ),
1042                        (
1043                            "character_maximum_length".to_string(),
1044                            option_i64_value(type_info.character_maximum_length),
1045                        ),
1046                        (
1047                            "character_octet_length".to_string(),
1048                            option_i64_value(type_info.character_octet_length),
1049                        ),
1050                        (
1051                            "numeric_precision".to_string(),
1052                            option_i64_value(type_info.numeric_precision),
1053                        ),
1054                        (
1055                            "numeric_precision_radix".to_string(),
1056                            option_i64_value(type_info.numeric_precision_radix),
1057                        ),
1058                        (
1059                            "numeric_scale".to_string(),
1060                            option_i64_value(type_info.numeric_scale),
1061                        ),
1062                        (
1063                            "datetime_precision".to_string(),
1064                            option_i64_value(type_info.datetime_precision),
1065                        ),
1066                        ("interval_type".to_string(), Value::Null),
1067                        ("interval_precision".to_string(), Value::Null),
1068                        ("character_set_catalog".to_string(), Value::Null),
1069                        ("character_set_schema".to_string(), Value::Null),
1070                        ("character_set_name".to_string(), Value::Null),
1071                        ("collation_catalog".to_string(), Value::Null),
1072                        ("collation_schema".to_string(), Value::Null),
1073                        ("collation_name".to_string(), Value::Null),
1074                        ("domain_catalog".to_string(), Value::Null),
1075                        ("domain_schema".to_string(), Value::Null),
1076                        ("domain_name".to_string(), Value::Null),
1077                        (
1078                            "udt_catalog".to_string(),
1079                            Value::String("hawdb".to_string()),
1080                        ),
1081                        (
1082                            "udt_schema".to_string(),
1083                            Value::String(
1084                                if matches!(column.scalar_type, RelationalScalarType::Vector(_)) {
1085                                    "public"
1086                                } else {
1087                                    "pg_catalog"
1088                                }
1089                                .to_string(),
1090                            ),
1091                        ),
1092                        (
1093                            "udt_name".to_string(),
1094                            Value::String(type_info.udt_name.to_string()),
1095                        ),
1096                        ("scope_catalog".to_string(), Value::Null),
1097                        ("scope_schema".to_string(), Value::Null),
1098                        ("scope_name".to_string(), Value::Null),
1099                        ("maximum_cardinality".to_string(), Value::Null),
1100                        (
1101                            "dtd_identifier".to_string(),
1102                            Value::String(ordinal_position.to_string()),
1103                        ),
1104                        (
1105                            "is_self_referencing".to_string(),
1106                            Value::String("NO".to_string()),
1107                        ),
1108                        ("is_identity".to_string(), Value::String("NO".to_string())),
1109                        ("identity_generation".to_string(), Value::Null),
1110                        ("identity_start".to_string(), Value::Null),
1111                        ("identity_increment".to_string(), Value::Null),
1112                        ("identity_maximum".to_string(), Value::Null),
1113                        ("identity_minimum".to_string(), Value::Null),
1114                        ("identity_cycle".to_string(), Value::Null),
1115                        (
1116                            "is_generated".to_string(),
1117                            Value::String("NEVER".to_string()),
1118                        ),
1119                        ("generation_expression".to_string(), Value::Null),
1120                        ("is_updatable".to_string(), Value::String("YES".to_string())),
1121                    ])
1122                })
1123        })
1124        .collect()
1125}
1126
1127#[derive(Debug, Clone, Copy)]
1128struct InformationSchemaType {
1129    data_type: &'static str,
1130    udt_name: &'static str,
1131    character_maximum_length: Option<i64>,
1132    character_octet_length: Option<i64>,
1133    numeric_precision: Option<i64>,
1134    numeric_precision_radix: Option<i64>,
1135    numeric_scale: Option<i64>,
1136    datetime_precision: Option<i64>,
1137}
1138
1139fn information_schema_type(scalar_type: RelationalScalarType) -> InformationSchemaType {
1140    match scalar_type {
1141        RelationalScalarType::Decimal(kind) => InformationSchemaType {
1142            data_type: "numeric",
1143            udt_name: "numeric",
1144            character_maximum_length: None,
1145            character_octet_length: None,
1146            numeric_precision: Some(i64::from(kind.precision())),
1147            numeric_precision_radix: Some(10),
1148            numeric_scale: Some(i64::from(kind.scale())),
1149            datetime_precision: None,
1150        },
1151        RelationalScalarType::Boolean => InformationSchemaType {
1152            data_type: "boolean",
1153            udt_name: "bool",
1154            character_maximum_length: None,
1155            character_octet_length: None,
1156            numeric_precision: None,
1157            numeric_precision_radix: None,
1158            numeric_scale: None,
1159            datetime_precision: None,
1160        },
1161        RelationalScalarType::BigInt => InformationSchemaType {
1162            data_type: "bigint",
1163            udt_name: "int8",
1164            character_maximum_length: None,
1165            character_octet_length: None,
1166            numeric_precision: Some(64),
1167            numeric_precision_radix: Some(2),
1168            numeric_scale: Some(0),
1169            datetime_precision: None,
1170        },
1171        RelationalScalarType::DoublePrecision => InformationSchemaType {
1172            data_type: "double precision",
1173            udt_name: "float8",
1174            character_maximum_length: None,
1175            character_octet_length: None,
1176            numeric_precision: Some(53),
1177            numeric_precision_radix: Some(2),
1178            numeric_scale: None,
1179            datetime_precision: None,
1180        },
1181        RelationalScalarType::Text => InformationSchemaType {
1182            data_type: "text",
1183            udt_name: "text",
1184            character_maximum_length: None,
1185            character_octet_length: None,
1186            numeric_precision: None,
1187            numeric_precision_radix: None,
1188            numeric_scale: None,
1189            datetime_precision: None,
1190        },
1191        RelationalScalarType::Bytea => InformationSchemaType {
1192            data_type: "bytea",
1193            udt_name: "bytea",
1194            character_maximum_length: None,
1195            character_octet_length: None,
1196            numeric_precision: None,
1197            numeric_precision_radix: None,
1198            numeric_scale: None,
1199            datetime_precision: None,
1200        },
1201        RelationalScalarType::Uuid => InformationSchemaType {
1202            data_type: "uuid",
1203            udt_name: "uuid",
1204            character_maximum_length: None,
1205            character_octet_length: None,
1206            numeric_precision: None,
1207            numeric_precision_radix: None,
1208            numeric_scale: None,
1209            datetime_precision: None,
1210        },
1211        RelationalScalarType::Timestamp(precision)
1212        | RelationalScalarType::TimestampTz(precision) => {
1213            let zoned = matches!(scalar_type, RelationalScalarType::TimestampTz(_));
1214            InformationSchemaType {
1215                data_type: if zoned {
1216                    "timestamp with time zone"
1217                } else {
1218                    "timestamp without time zone"
1219                },
1220                udt_name: if zoned { "timestamptz" } else { "timestamp" },
1221                character_maximum_length: None,
1222                character_octet_length: None,
1223                numeric_precision: None,
1224                numeric_precision_radix: None,
1225                numeric_scale: None,
1226                datetime_precision: Some(i64::from(precision.get())),
1227            }
1228        }
1229        RelationalScalarType::Vector(_) => InformationSchemaType {
1230            data_type: "USER-DEFINED",
1231            udt_name: "vector",
1232            character_maximum_length: None,
1233            character_octet_length: None,
1234            numeric_precision: None,
1235            numeric_precision_radix: None,
1236            numeric_scale: None,
1237            datetime_precision: None,
1238        },
1239    }
1240}
1241
1242fn relational_default_value(default: Option<&RelationalColumnDefault>) -> Value {
1243    match default {
1244        None | Some(RelationalColumnDefault::Literal(RelationalValue::Overflow(_))) => Value::Null,
1245        Some(RelationalColumnDefault::Literal(RelationalValue::Null)) => {
1246            Value::String("NULL".to_string())
1247        }
1248        Some(RelationalColumnDefault::Literal(RelationalValue::Boolean(value))) => {
1249            Value::String(value.to_string())
1250        }
1251        Some(RelationalColumnDefault::Literal(RelationalValue::BigInt(value))) => {
1252            Value::String(value.to_string())
1253        }
1254        Some(RelationalColumnDefault::Literal(RelationalValue::Decimal(value))) => {
1255            Value::String(value.to_string())
1256        }
1257        Some(RelationalColumnDefault::Literal(RelationalValue::DoublePrecision(value))) => {
1258            Value::String(value.to_string())
1259        }
1260        Some(RelationalColumnDefault::Literal(RelationalValue::Text(value))) => {
1261            Value::String(format!("'{}'::text", value.replace('\'', "''")))
1262        }
1263        Some(RelationalColumnDefault::Literal(RelationalValue::Bytea(value))) => {
1264            Value::String(format!("'\\x{}'::bytea", encode_hex(value)))
1265        }
1266        Some(RelationalColumnDefault::Literal(RelationalValue::Uuid(value))) => {
1267            Value::String(format!("'{value}'::uuid"))
1268        }
1269        Some(RelationalColumnDefault::Literal(RelationalValue::Vector(value))) => {
1270            Value::String(Value::Vector(value.clone()).to_string())
1271        }
1272        Some(RelationalColumnDefault::Literal(RelationalValue::Timestamp(value))) => {
1273            hawdb_core::sql_timestamp::format_timestamp(value.get()).map_or(Value::Null, |text| {
1274                Value::String(format!("'{text}'::timestamp without time zone"))
1275            })
1276        }
1277        Some(RelationalColumnDefault::Literal(RelationalValue::TimestampTz(value))) => {
1278            hawdb_core::sql_timestamp::format_timestamptz(value.get()).map_or(Value::Null, |text| {
1279                Value::String(format!("'{text}'::timestamp with time zone"))
1280            })
1281        }
1282        Some(RelationalColumnDefault::UuidV7) => Value::String("uuidv7()".to_string()),
1283        Some(RelationalColumnDefault::CurrentTimestamp(kind)) => {
1284            let name = if kind.zoned {
1285                "CURRENT_TIMESTAMP"
1286            } else {
1287                "LOCALTIMESTAMP"
1288            };
1289            Value::String(
1290                if kind.precision == hawdb_core::TimestampPrecision::DEFAULT {
1291                    name.to_string()
1292                } else {
1293                    format!("{name}({})", kind.precision.get())
1294                },
1295            )
1296        }
1297    }
1298}
1299
1300fn encode_hex(bytes: &[u8]) -> String {
1301    const HEX: &[u8; 16] = b"0123456789abcdef";
1302    let mut encoded = String::with_capacity(bytes.len().saturating_mul(2));
1303    for byte in bytes {
1304        encoded.push(HEX[usize::from(byte >> 4)] as char);
1305        encoded.push(HEX[usize::from(byte & 0x0f)] as char);
1306    }
1307    encoded
1308}
1309
1310fn pg_table_rows(state: &RelationalState) -> Vec<Row> {
1311    state
1312        .table_schemas()
1313        // Search index postings are an index, not a relation.
1314        .filter(|schema| schema.search_index().is_none())
1315        .map(|schema| {
1316            BTreeMap::from([
1317                (
1318                    "schemaname".to_string(),
1319                    Value::String("public".to_string()),
1320                ),
1321                ("tablename".to_string(), Value::String(schema.name.clone())),
1322                ("tableowner".to_string(), Value::String("hawdb".to_string())),
1323                ("tablespace".to_string(), Value::Null),
1324                (
1325                    "hasindexes".to_string(),
1326                    Value::Bool(
1327                        !schema.primary_key.is_empty()
1328                            || !schema.unique_constraints.is_empty()
1329                            || !schema.indexes.is_empty(),
1330                    ),
1331                ),
1332                ("hasrules".to_string(), Value::Bool(false)),
1333                ("hastriggers".to_string(), Value::Bool(false)),
1334                ("rowsecurity".to_string(), Value::Bool(false)),
1335            ])
1336        })
1337        .collect()
1338}
1339
1340fn pg_index_rows(state: &RelationalState) -> Vec<Row> {
1341    state
1342        .table_schemas()
1343        .flat_map(|schema| match schema.search_index() {
1344            Some(spec) => search_index_rows(schema, spec),
1345            None => relational_schema_index_rows(schema),
1346        })
1347        .collect()
1348}
1349
1350fn search_index_rows(
1351    schema: &RelationalTableSchema,
1352    spec: &hawdb_storage::relational::SearchIndexSpec,
1353) -> Vec<Row> {
1354    let Some(view) = schema.materialized_view.as_deref() else {
1355        return Vec::new();
1356    };
1357    let index_definition = format!(
1358        "CREATE SEARCH INDEX {} ON public.{} ({}) WITH (analyzer = '{}')",
1359        quote_postgres_identifier(&schema.name),
1360        quote_postgres_identifier(&view.source),
1361        quote_postgres_identifier(&spec.column),
1362        spec.analyzer.name(),
1363    );
1364    vec![BTreeMap::from([
1365        (
1366            "schemaname".to_string(),
1367            Value::String("public".to_string()),
1368        ),
1369        ("tablename".to_string(), Value::String(view.source.clone())),
1370        ("indexname".to_string(), Value::String(schema.name.clone())),
1371        ("tablespace".to_string(), Value::Null),
1372        ("indexdef".to_string(), Value::String(index_definition)),
1373    ])]
1374}
1375
1376fn relational_schema_index_rows(schema: &RelationalTableSchema) -> Vec<Row> {
1377    let mut rows = Vec::with_capacity(
1378        1usize
1379            .saturating_add(schema.unique_constraints.len())
1380            .saturating_add(schema.indexes.len()),
1381    );
1382    if !schema.primary_key.is_empty() {
1383        let name = format!("{}_pkey", schema.name);
1384        rows.push(pg_index_row(schema, &name, &schema.primary_key, true));
1385    }
1386    rows.extend(schema.unique_constraints.iter().map(|columns| {
1387        let name = format!("{}_{}_key", schema.name, columns.join("_"));
1388        pg_index_row(schema, &name, columns, true)
1389    }));
1390    rows.extend(
1391        schema
1392            .indexes
1393            .iter()
1394            .map(|index| pg_index_row(schema, &index.name, &index.columns, index.unique)),
1395    );
1396    rows
1397}
1398
1399fn pg_index_row(
1400    schema: &RelationalTableSchema,
1401    index_name: &str,
1402    columns: &[String],
1403    unique: bool,
1404) -> Row {
1405    let unique = if unique { "UNIQUE " } else { "" };
1406    let columns = columns
1407        .iter()
1408        .map(|column| quote_postgres_identifier(column))
1409        .collect::<Vec<_>>()
1410        .join(", ");
1411    let index_definition = format!(
1412        "CREATE {unique}INDEX {} ON public.{} USING btree ({columns})",
1413        quote_postgres_identifier(index_name),
1414        quote_postgres_identifier(&schema.name),
1415    );
1416    BTreeMap::from([
1417        (
1418            "schemaname".to_string(),
1419            Value::String("public".to_string()),
1420        ),
1421        ("tablename".to_string(), Value::String(schema.name.clone())),
1422        (
1423            "indexname".to_string(),
1424            Value::String(index_name.to_string()),
1425        ),
1426        ("tablespace".to_string(), Value::Null),
1427        ("indexdef".to_string(), Value::String(index_definition)),
1428    ])
1429}
1430
1431fn quote_postgres_identifier(identifier: &str) -> String {
1432    format!("\"{}\"", identifier.replace('"', "\"\""))
1433}
1434
1435fn property_rows(catalog: &Catalog) -> Vec<Row> {
1436    catalog
1437        .property_descriptors()
1438        .map(|property| {
1439            let table = catalog.table_descriptor(property.table_id);
1440            BTreeMap::from([
1441                ("property_id".to_string(), u32_value(property.id.0)),
1442                ("table_id".to_string(), u32_value(property.table_id.0)),
1443                (
1444                    "table_name".to_string(),
1445                    table
1446                        .map(|table| Value::String(table.name.clone()))
1447                        .unwrap_or(Value::Null),
1448                ),
1449                (
1450                    "table_kind".to_string(),
1451                    table
1452                        .map(|table| Value::String(table_kind_name(table.kind).to_string()))
1453                        .unwrap_or(Value::Null),
1454                ),
1455                (
1456                    "property_name".to_string(),
1457                    Value::String(property.name.clone()),
1458                ),
1459                (
1460                    "value_type".to_string(),
1461                    Value::String(property_type_name(property.value_type).to_string()),
1462                ),
1463                ("nullable".to_string(), Value::Bool(property.nullable)),
1464                (
1465                    "state".to_string(),
1466                    Value::String(schema_object_state_name(property.state).to_string()),
1467                ),
1468            ])
1469        })
1470        .collect()
1471}
1472
1473fn index_rows(catalog: &Catalog) -> Vec<Row> {
1474    let mut rows = catalog
1475        .property_indexes()
1476        .map(|index| {
1477            BTreeMap::from([
1478                ("index_id".to_string(), u32_value(index.id.0)),
1479                (
1480                    "subject_kind".to_string(),
1481                    Value::String("node".to_string()),
1482                ),
1483                ("subject_id".to_string(), u32_value(index.label_id.0)),
1484                (
1485                    "subject_name".to_string(),
1486                    optional_string_value(catalog.label_name(index.label_id)),
1487                ),
1488                (
1489                    "index_kind".to_string(),
1490                    Value::String(index_kind_name(index.kind).to_string()),
1491                ),
1492                (
1493                    "property_names".to_string(),
1494                    Value::List(vec![Value::String(index.property.clone())]),
1495                ),
1496            ])
1497        })
1498        .chain(catalog.composite_property_indexes().map(|index| {
1499            BTreeMap::from([
1500                ("index_id".to_string(), u32_value(index.id.0)),
1501                (
1502                    "subject_kind".to_string(),
1503                    Value::String("node".to_string()),
1504                ),
1505                ("subject_id".to_string(), u32_value(index.label_id.0)),
1506                (
1507                    "subject_name".to_string(),
1508                    optional_string_value(catalog.label_name(index.label_id)),
1509                ),
1510                (
1511                    "index_kind".to_string(),
1512                    Value::String("composite_equality".to_string()),
1513                ),
1514                (
1515                    "property_names".to_string(),
1516                    Value::List(
1517                        index
1518                            .properties
1519                            .iter()
1520                            .cloned()
1521                            .map(Value::String)
1522                            .collect(),
1523                    ),
1524                ),
1525            ])
1526        }))
1527        .collect::<Vec<_>>();
1528    rows.sort_by_key(|row| row.get("index_id").cloned());
1529    rows
1530}
1531
1532fn constraint_rows(catalog: &Catalog) -> Vec<Row> {
1533    let constraints = catalog
1534        .unique_constraints()
1535        .chain(catalog.node_property_exists_constraints())
1536        .chain(catalog.relationship_property_exists_constraints())
1537        .chain(catalog.relationship_unique_constraints());
1538    let mut rows = constraints
1539        .map(|constraint| {
1540            let (subject_kind, subject_id, subject_name) = match constraint.subject {
1541                ConstraintSubject::Node(label_id) => (
1542                    "node",
1543                    label_id.0,
1544                    optional_string_value(catalog.label_name(label_id)),
1545                ),
1546                ConstraintSubject::Relationship(rel_type_id) => (
1547                    "relationship",
1548                    rel_type_id.0,
1549                    optional_string_value(catalog.rel_type_name(rel_type_id)),
1550                ),
1551            };
1552            BTreeMap::from([
1553                ("constraint_id".to_string(), u32_value(constraint.id.0)),
1554                (
1555                    "subject_kind".to_string(),
1556                    Value::String(subject_kind.to_string()),
1557                ),
1558                ("subject_id".to_string(), u32_value(subject_id)),
1559                ("subject_name".to_string(), subject_name),
1560                (
1561                    "property_name".to_string(),
1562                    Value::String(constraint.property.clone()),
1563                ),
1564                (
1565                    "constraint_kind".to_string(),
1566                    Value::String(constraint_kind_name(constraint.kind).to_string()),
1567                ),
1568            ])
1569        })
1570        .collect::<Vec<_>>();
1571    rows.sort_by_key(|row| row.get("constraint_id").cloned());
1572    rows
1573}
1574
1575fn runtime_status_rows<Store: SystemSqlStore>(context: &SystemSqlContext<'_, Store>) -> Vec<Row> {
1576    vec![BTreeMap::from([
1577        (
1578            "commit_epoch".to_string(),
1579            u64_value(context.store.commit_epoch()),
1580        ),
1581        (
1582            "read_only".to_string(),
1583            Value::Bool(context.runtime.read_only),
1584        ),
1585        (
1586            "max_read_result_rows".to_string(),
1587            option_usize_value(context.runtime.max_read_result_rows),
1588        ),
1589        (
1590            "max_read_result_payload_bytes".to_string(),
1591            option_usize_value(context.runtime.max_read_result_payload_bytes),
1592        ),
1593        (
1594            "storage_residency_mode".to_string(),
1595            Value::String(
1596                storage_residency_mode_name(context.runtime.storage_residency_mode).to_string(),
1597            ),
1598        ),
1599        (
1600            "relational_index_mode".to_string(),
1601            Value::String(
1602                relational_index_mode_name(context.runtime.relational_index_mode).to_string(),
1603            ),
1604        ),
1605    ])]
1606}
1607
1608fn append_table_rows(state: &AppendState) -> Vec<Row> {
1609    state
1610        .schemas()
1611        .values()
1612        .map(|schema| {
1613            BTreeMap::from([
1614                ("table_name".to_string(), Value::String(schema.name.clone())),
1615                (
1616                    "storage_mode".to_string(),
1617                    Value::String("strict_append".to_string()),
1618                ),
1619                (
1620                    "partition_key".to_string(),
1621                    Value::List(
1622                        schema
1623                            .partition_key
1624                            .iter()
1625                            .cloned()
1626                            .map(Value::String)
1627                            .collect(),
1628                    ),
1629                ),
1630                (
1631                    "order_key".to_string(),
1632                    Value::List(
1633                        schema
1634                            .order_key
1635                            .iter()
1636                            .cloned()
1637                            .map(Value::String)
1638                            .collect(),
1639                    ),
1640                ),
1641                (
1642                    "order_mode".to_string(),
1643                    Value::String(
1644                        match schema.order_mode {
1645                            AppendOrderMode::CallerProvided => "caller_provided",
1646                            AppendOrderMode::CommitSequence => "commit_sequence",
1647                        }
1648                        .to_string(),
1649                    ),
1650                ),
1651                (
1652                    "generated_order_watermark".to_string(),
1653                    state
1654                        .generated_order_watermark(&schema.name)
1655                        .map_or(Value::Null, Value::Int),
1656                ),
1657                (
1658                    "column_count".to_string(),
1659                    Value::Int(i64::try_from(schema.columns.len()).unwrap_or(i64::MAX)),
1660                ),
1661            ])
1662        })
1663        .collect()
1664}
1665
1666fn append_storage_rows(store: &impl SystemSqlStore, state: &AppendState) -> Vec<Row> {
1667    let mut report = store.append_storage_residency_report();
1668    report.live_rows = state.live_rows();
1669    report.live_payload_bytes = state.live_payload_bytes();
1670    vec![BTreeMap::from([
1671        (
1672            "canonical_segment_count".to_string(),
1673            Value::Int(i64::try_from(report.canonical_segment_count).unwrap_or(i64::MAX)),
1674        ),
1675        (
1676            "canonical_segment_bytes".to_string(),
1677            Value::Int(i64::try_from(report.canonical_segment_bytes).unwrap_or(i64::MAX)),
1678        ),
1679        (
1680            "resident_segment_payload_bytes".to_string(),
1681            Value::Int(i64::try_from(report.resident_segment_payload_bytes).unwrap_or(i64::MAX)),
1682        ),
1683        (
1684            "resident_descriptor_count".to_string(),
1685            Value::Int(i64::try_from(report.resident_descriptor_count).unwrap_or(i64::MAX)),
1686        ),
1687        (
1688            "live_rows".to_string(),
1689            Value::Int(i64::try_from(report.live_rows).unwrap_or(i64::MAX)),
1690        ),
1691        (
1692            "live_payload_bytes".to_string(),
1693            Value::Int(i64::try_from(report.live_payload_bytes).unwrap_or(i64::MAX)),
1694        ),
1695    ])]
1696}
1697
1698fn runtime_capability_rows(runtime: SystemRuntimeSnapshot) -> Vec<Row> {
1699    [
1700        (
1701            "access_control",
1702            runtime.runtime_capabilities.access_control,
1703        ),
1704        (
1705            "full_text_search",
1706            runtime.runtime_capabilities.full_text_search,
1707        ),
1708        ("vector_search", runtime.runtime_capabilities.vector_search),
1709        (
1710            "graph_analytics",
1711            runtime.runtime_capabilities.graph_analytics,
1712        ),
1713        (
1714            "background_maintenance",
1715            runtime.runtime_capabilities.background_maintenance,
1716        ),
1717    ]
1718    .into_iter()
1719    .map(|(capability, enabled)| {
1720        BTreeMap::from([
1721            (
1722                "capability".to_string(),
1723                Value::String(capability.to_string()),
1724            ),
1725            ("enabled".to_string(), Value::Bool(enabled)),
1726        ])
1727    })
1728    .collect()
1729}
1730
1731fn graph_statistics_rows(catalog: &Catalog, statistics: &GraphStatistics) -> Vec<Row> {
1732    let mut rows = Vec::with_capacity(
1733        2usize
1734            .saturating_add(statistics.label_counts.len())
1735            .saturating_add(statistics.rel_type_counts.len())
1736            .saturating_add(statistics.rel_type_source_counts.len())
1737            .saturating_add(statistics.rel_type_target_counts.len())
1738            .saturating_add(statistics.path_counts.len())
1739            .saturating_add(statistics.path_source_distinct_counts.len())
1740            .saturating_add(statistics.path_target_distinct_counts.len())
1741            .saturating_add(statistics.bounded_path_counts.len())
1742            .saturating_add(statistics.bounded_path_source_distinct_counts.len())
1743            .saturating_add(statistics.bounded_path_target_distinct_counts.len())
1744            .saturating_add(statistics.index_samples.len())
1745            .saturating_add(statistics.property_distinct_counts.len())
1746            .saturating_add(statistics.rel_property_distinct_counts.len())
1747            .saturating_add(statistics.property_histograms.len())
1748            .saturating_add(statistics.rel_property_histograms.len()),
1749    );
1750    rows.push(graph_statistic_count_row(
1751        statistics,
1752        "node_count",
1753        statistics.node_count,
1754    ));
1755    rows.push(graph_statistic_count_row(
1756        statistics,
1757        "relationship_count",
1758        statistics.relationship_count,
1759    ));
1760
1761    for (label_id, count) in &statistics.label_counts {
1762        let mut row = graph_statistic_count_row(statistics, "label_count", *count);
1763        row.insert(
1764            "label_name".to_string(),
1765            optional_string_value(catalog.label_name(*label_id)),
1766        );
1767        rows.push(row);
1768    }
1769    for (rel_type_id, count) in &statistics.rel_type_counts {
1770        let mut row = graph_statistic_count_row(statistics, "relationship_type_count", *count);
1771        row.insert(
1772            "relationship_type_name".to_string(),
1773            optional_string_value(catalog.rel_type_name(*rel_type_id)),
1774        );
1775        rows.push(row);
1776    }
1777    for (kind, counts) in [
1778        (
1779            "relationship_source_count",
1780            &statistics.rel_type_source_counts,
1781        ),
1782        (
1783            "relationship_target_count",
1784            &statistics.rel_type_target_counts,
1785        ),
1786    ] {
1787        for (rel_type_id, count) in counts {
1788            let mut row = graph_statistic_count_row(statistics, kind, *count);
1789            row.insert(
1790                "relationship_type_name".to_string(),
1791                optional_string_value(catalog.rel_type_name(*rel_type_id)),
1792            );
1793            rows.push(row);
1794        }
1795    }
1796    for index in catalog.property_indexes() {
1797        let Some(sample) = statistics.index_samples.get(&index.id) else {
1798            continue;
1799        };
1800        let mut row = graph_statistic_base_row(statistics, "index_sample");
1801        row.insert("index_id".to_string(), u32_value(index.id.0));
1802        row.insert(
1803            "index_kind".to_string(),
1804            Value::String(index_kind_name(index.kind).to_string()),
1805        );
1806        row.insert(
1807            "label_name".to_string(),
1808            optional_string_value(catalog.label_name(index.label_id)),
1809        );
1810        row.insert(
1811            "property_name".to_string(),
1812            Value::String(index.property.clone()),
1813        );
1814        populate_index_sample(&mut row, *sample);
1815        rows.push(row);
1816    }
1817    for index in catalog.composite_property_indexes() {
1818        let Some(sample) = statistics.index_samples.get(&index.id) else {
1819            continue;
1820        };
1821        let mut row = graph_statistic_base_row(statistics, "index_sample");
1822        row.insert("index_id".to_string(), u32_value(index.id.0));
1823        row.insert(
1824            "index_kind".to_string(),
1825            Value::String("composite".to_string()),
1826        );
1827        row.insert(
1828            "label_name".to_string(),
1829            optional_string_value(catalog.label_name(index.label_id)),
1830        );
1831        row.insert(
1832            "index_properties".to_string(),
1833            Value::List(
1834                index
1835                    .properties
1836                    .iter()
1837                    .cloned()
1838                    .map(Value::String)
1839                    .collect(),
1840            ),
1841        );
1842        populate_index_sample(&mut row, *sample);
1843        rows.push(row);
1844    }
1845    for (kind, counts) in [
1846        ("path_count", &statistics.path_counts),
1847        (
1848            "path_source_distinct_count",
1849            &statistics.path_source_distinct_counts,
1850        ),
1851        (
1852            "path_target_distinct_count",
1853            &statistics.path_target_distinct_counts,
1854        ),
1855    ] {
1856        for ((source_label_id, rel_type_id, target_label_id), count) in counts {
1857            let mut row = graph_statistic_count_row(statistics, kind, *count);
1858            populate_path_statistic_names(
1859                &mut row,
1860                catalog,
1861                *source_label_id,
1862                *rel_type_id,
1863                *target_label_id,
1864            );
1865            rows.push(row);
1866        }
1867    }
1868    for (kind, counts) in [
1869        ("bounded_path_count", &statistics.bounded_path_counts),
1870        (
1871            "bounded_path_source_distinct_count",
1872            &statistics.bounded_path_source_distinct_counts,
1873        ),
1874        (
1875            "bounded_path_target_distinct_count",
1876            &statistics.bounded_path_target_distinct_counts,
1877        ),
1878    ] {
1879        for ((source_label_id, rel_type_id, target_label_id, depth), count) in counts {
1880            let mut row = graph_statistic_count_row(statistics, kind, *count);
1881            populate_path_statistic_names(
1882                &mut row,
1883                catalog,
1884                *source_label_id,
1885                *rel_type_id,
1886                *target_label_id,
1887            );
1888            row.insert("depth".to_string(), usize_value(*depth));
1889            rows.push(row);
1890        }
1891    }
1892    for ((label_id, property_name), count) in &statistics.property_distinct_counts {
1893        let mut row = graph_statistic_count_row(statistics, "node_property_distinct_count", *count);
1894        row.insert(
1895            "label_name".to_string(),
1896            optional_string_value(catalog.label_name(*label_id)),
1897        );
1898        row.insert(
1899            "property_name".to_string(),
1900            Value::String(property_name.clone()),
1901        );
1902        rows.push(row);
1903    }
1904    for ((rel_type_id, property_name), count) in &statistics.rel_property_distinct_counts {
1905        let mut row =
1906            graph_statistic_count_row(statistics, "relationship_property_distinct_count", *count);
1907        row.insert(
1908            "relationship_type_name".to_string(),
1909            optional_string_value(catalog.rel_type_name(*rel_type_id)),
1910        );
1911        row.insert(
1912            "property_name".to_string(),
1913            Value::String(property_name.clone()),
1914        );
1915        rows.push(row);
1916    }
1917    for ((label_id, property_name), histogram) in &statistics.property_histograms {
1918        let mut row = graph_statistic_base_row(statistics, "node_property_histogram");
1919        row.insert(
1920            "label_name".to_string(),
1921            optional_string_value(catalog.label_name(*label_id)),
1922        );
1923        row.insert(
1924            "property_name".to_string(),
1925            Value::String(property_name.clone()),
1926        );
1927        row.insert("histogram".to_string(), Value::List(histogram.clone()));
1928        row.insert(
1929            "sampled".to_string(),
1930            Value::Bool(
1931                statistics
1932                    .sampled_property_histograms
1933                    .get(&(*label_id, property_name.clone()))
1934                    .copied()
1935                    .unwrap_or(false),
1936            ),
1937        );
1938        rows.push(row);
1939    }
1940    for ((rel_type_id, property_name), histogram) in &statistics.rel_property_histograms {
1941        let mut row = graph_statistic_base_row(statistics, "relationship_property_histogram");
1942        row.insert(
1943            "relationship_type_name".to_string(),
1944            optional_string_value(catalog.rel_type_name(*rel_type_id)),
1945        );
1946        row.insert(
1947            "property_name".to_string(),
1948            Value::String(property_name.clone()),
1949        );
1950        row.insert("histogram".to_string(), Value::List(histogram.clone()));
1951        row.insert(
1952            "sampled".to_string(),
1953            Value::Bool(
1954                statistics
1955                    .sampled_rel_property_histograms
1956                    .get(&(*rel_type_id, property_name.clone()))
1957                    .copied()
1958                    .unwrap_or(false),
1959            ),
1960        );
1961        rows.push(row);
1962    }
1963    rows
1964}
1965
1966fn graph_statistic_count_row(statistics: &GraphStatistics, kind: &str, count: u64) -> Row {
1967    let mut row = graph_statistic_base_row(statistics, kind);
1968    row.insert("count".to_string(), u64_value(count));
1969    row
1970}
1971
1972fn populate_index_sample(row: &mut Row, sample: IndexStatisticsSample) {
1973    row.insert("index_size".to_string(), u64_value(sample.index_size));
1974    row.insert("unique_values".to_string(), u64_value(sample.unique_values));
1975    row.insert("sample_size".to_string(), u64_value(sample.sample_size));
1976    row.insert(
1977        "updates_since_sample".to_string(),
1978        u64_value(sample.updates_since_sample),
1979    );
1980    row.insert("stale".to_string(), Value::Bool(sample.is_stale()));
1981}
1982
1983fn graph_statistic_base_row(statistics: &GraphStatistics, kind: &str) -> Row {
1984    BTreeMap::from([
1985        (
1986            "statistic_kind".to_string(),
1987            Value::String(kind.to_string()),
1988        ),
1989        (
1990            "computed_at_commit_epoch".to_string(),
1991            u64_value(statistics.computed_at_commit_epoch),
1992        ),
1993        (
1994            "advanced_statistics_complete".to_string(),
1995            Value::Bool(statistics.advanced_statistics_complete),
1996        ),
1997        (
1998            "histogram_sample_limit".to_string(),
1999            usize_value(statistics.histogram_sample_limit),
2000        ),
2001        ("label_name".to_string(), Value::Null),
2002        ("relationship_type_name".to_string(), Value::Null),
2003        ("source_label_name".to_string(), Value::Null),
2004        ("target_label_name".to_string(), Value::Null),
2005        ("depth".to_string(), Value::Null),
2006        ("property_name".to_string(), Value::Null),
2007        ("index_id".to_string(), Value::Null),
2008        ("index_kind".to_string(), Value::Null),
2009        ("index_properties".to_string(), Value::Null),
2010        ("index_size".to_string(), Value::Null),
2011        ("unique_values".to_string(), Value::Null),
2012        ("sample_size".to_string(), Value::Null),
2013        ("updates_since_sample".to_string(), Value::Null),
2014        ("stale".to_string(), Value::Null),
2015        ("count".to_string(), Value::Null),
2016        ("histogram".to_string(), Value::Null),
2017        ("sampled".to_string(), Value::Null),
2018    ])
2019}
2020
2021fn populate_path_statistic_names(
2022    row: &mut Row,
2023    catalog: &Catalog,
2024    source_label_id: LabelId,
2025    rel_type_id: RelTypeId,
2026    target_label_id: LabelId,
2027) {
2028    row.insert(
2029        "source_label_name".to_string(),
2030        optional_string_value(catalog.label_name(source_label_id)),
2031    );
2032    row.insert(
2033        "relationship_type_name".to_string(),
2034        optional_string_value(catalog.rel_type_name(rel_type_id)),
2035    );
2036    row.insert(
2037        "target_label_name".to_string(),
2038        optional_string_value(catalog.label_name(target_label_id)),
2039    );
2040}
2041
2042fn projected_graph_rows(statuses: Vec<ProjectedGraphStatus>) -> Vec<Row> {
2043    statuses
2044        .into_iter()
2045        .map(|status| {
2046            BTreeMap::from([
2047                ("name".to_string(), Value::String(status.name)),
2048                (
2049                    "node_labels".to_string(),
2050                    Value::List(status.node_labels.into_iter().map(Value::String).collect()),
2051                ),
2052                (
2053                    "relationship_types".to_string(),
2054                    Value::List(status.rel_types.into_iter().map(Value::String).collect()),
2055                ),
2056                (
2057                    "projection_epoch".to_string(),
2058                    option_u64_value(status.projection_epoch),
2059                ),
2060                (
2061                    "commit_epoch".to_string(),
2062                    option_u64_value(status.commit_epoch),
2063                ),
2064                (
2065                    "node_count".to_string(),
2066                    option_usize_value(status.node_count),
2067                ),
2068                (
2069                    "edge_count".to_string(),
2070                    option_usize_value(status.edge_count),
2071                ),
2072                ("reusable".to_string(), Value::Bool(status.reusable)),
2073            ])
2074        })
2075        .collect()
2076}
2077
2078fn search_projection_changefeed_rows(status: SearchProjectionChangefeedStatus) -> Vec<Row> {
2079    vec![BTreeMap::from([
2080        (
2081            "graph_commit_epoch".to_string(),
2082            u64_value(status.graph_commit_epoch),
2083        ),
2084        (
2085            "resume_floor_commit_epoch".to_string(),
2086            u64_value(status.resume_floor_commit_epoch),
2087        ),
2088        (
2089            "oldest_retained_mutation_id".to_string(),
2090            option_u64_value(
2091                status
2092                    .oldest_retained_mutation_id
2093                    .map(|id| id.commit_epoch()),
2094            ),
2095        ),
2096        (
2097            "newest_retained_mutation_id".to_string(),
2098            option_u64_value(
2099                status
2100                    .newest_retained_mutation_id
2101                    .map(|id| id.commit_epoch()),
2102            ),
2103        ),
2104        (
2105            "retained_mutation_count".to_string(),
2106            usize_value(status.retained_mutation_count),
2107        ),
2108        (
2109            "restart_recoverable".to_string(),
2110            Value::Bool(status.restart_recoverable),
2111        ),
2112    ])]
2113}
2114
2115fn optional_string_value(value: Option<&str>) -> Value {
2116    value
2117        .map(|value| Value::String(value.to_string()))
2118        .unwrap_or(Value::Null)
2119}
2120
2121const fn table_kind_name(kind: TableKind) -> &'static str {
2122    match kind {
2123        TableKind::Node => "node",
2124        TableKind::Relationship => "relationship",
2125    }
2126}
2127
2128const fn schema_object_state_name(state: SchemaObjectState) -> &'static str {
2129    match state {
2130        SchemaObjectState::DeleteOnly => "delete_only",
2131        SchemaObjectState::WriteOnly => "write_only",
2132        SchemaObjectState::Backfill => "backfill",
2133        SchemaObjectState::Validating => "validating",
2134        SchemaObjectState::Public => "public",
2135        SchemaObjectState::Gc => "gc",
2136    }
2137}
2138
2139fn property_type_name(value_type: PropertyType) -> std::borrow::Cow<'static, str> {
2140    match value_type {
2141        PropertyType::Any => "any",
2142        PropertyType::Bool => "bool",
2143        PropertyType::Int => "int",
2144        PropertyType::Float => "float",
2145        PropertyType::String => "string",
2146        PropertyType::Text => "text",
2147        PropertyType::List => "list",
2148        PropertyType::Vector(dimension) => return format!("vector({})", dimension.get()).into(),
2149    }
2150    .into()
2151}
2152
2153const fn index_kind_name(kind: IndexKind) -> &'static str {
2154    match kind {
2155        IndexKind::Equality => "equality",
2156        IndexKind::Range => "range",
2157        IndexKind::FullText => "full_text",
2158    }
2159}
2160
2161const fn constraint_kind_name(kind: ConstraintKind) -> &'static str {
2162    match kind {
2163        ConstraintKind::NodePropertyUnique => "node_property_unique",
2164        ConstraintKind::NodePropertyExists => "node_property_exists",
2165        ConstraintKind::RelationshipPropertyUnique => "relationship_property_unique",
2166        ConstraintKind::RelationshipPropertyExists => "relationship_property_exists",
2167    }
2168}
2169
2170fn plan_cache_rows(stats: &PlanCacheStats) -> Vec<Row> {
2171    [
2172        ("max_entries", option_usize_value(stats.max_entries)),
2173        ("max_bytes", option_usize_value(stats.max_bytes)),
2174        ("max_entry_bytes", option_usize_value(stats.max_entry_bytes)),
2175        ("charged_bytes", option_usize_value(stats.charged_bytes)),
2176        ("rejected_admissions", u64_value(stats.rejected_admissions)),
2177        ("entries", usize_value(stats.entries)),
2178        ("hits", u64_value(stats.hits)),
2179        ("misses", u64_value(stats.misses)),
2180        ("admissions", u64_value(stats.admissions)),
2181        ("disabled_misses", u64_value(stats.disabled_misses)),
2182        ("bypasses", u64_value(stats.bypasses)),
2183        ("evictions", u64_value(stats.evictions)),
2184        (
2185            "memory_pressure_events",
2186            u64_value(stats.memory_pressure_events),
2187        ),
2188    ]
2189    .into_iter()
2190    .map(|(metric, value)| {
2191        BTreeMap::from([
2192            ("metric".to_string(), Value::String(metric.to_string())),
2193            ("value".to_string(), value),
2194        ])
2195    })
2196    .collect()
2197}
2198
2199fn slow_query_rows(records: &[SlowQueryRecord]) -> Vec<Row> {
2200    records
2201        .iter()
2202        .map(|record| {
2203            BTreeMap::from([
2204                ("sequence".to_string(), u64_value(record.sequence)),
2205                (
2206                    "query_language".to_string(),
2207                    Value::String(record.query_language.clone()),
2208                ),
2209                (
2210                    "statement_kind".to_string(),
2211                    Value::String(record.statement_kind.clone()),
2212                ),
2213                (
2214                    "query_digest".to_string(),
2215                    Value::String(record.query_digest.clone()),
2216                ),
2217                (
2218                    "query_text_hash".to_string(),
2219                    Value::String(record.query_text_hash.clone()),
2220                ),
2221                (
2222                    "query_text".to_string(),
2223                    Value::String(record.query_text.clone()),
2224                ),
2225                (
2226                    "started_unix_micros".to_string(),
2227                    Value::Int(record.started_unix_micros),
2228                ),
2229                (
2230                    "elapsed_micros".to_string(),
2231                    Value::Int(record.elapsed_micros),
2232                ),
2233                ("row_count".to_string(), Value::Int(record.row_count)),
2234                ("success".to_string(), Value::Bool(record.success)),
2235                (
2236                    "error".to_string(),
2237                    record
2238                        .error
2239                        .as_ref()
2240                        .map(|error| Value::String(error.clone()))
2241                        .unwrap_or(Value::Null),
2242                ),
2243                (
2244                    "slow_log_candidate".to_string(),
2245                    Value::Bool(record.slow_log_candidate),
2246                ),
2247                (
2248                    "access_control_policy_epoch".to_string(),
2249                    record
2250                        .access_control_policy_epoch
2251                        .map(u64_value)
2252                        .unwrap_or(Value::Null),
2253                ),
2254            ])
2255        })
2256        .collect()
2257}
2258
2259fn statement_summary_rows(records: &[StatementSummaryRecord]) -> Vec<Row> {
2260    records
2261        .iter()
2262        .map(|record| {
2263            BTreeMap::from([
2264                ("digest".to_string(), Value::String(record.digest.clone())),
2265                (
2266                    "query_language".to_string(),
2267                    Value::String(record.query_language.clone()),
2268                ),
2269                (
2270                    "query_text".to_string(),
2271                    Value::String(record.query_text.clone()),
2272                ),
2273                (
2274                    "sample_query_text_hash".to_string(),
2275                    Value::String(record.sample_query_text_hash.clone()),
2276                ),
2277                (
2278                    "statement_kind".to_string(),
2279                    Value::String(record.statement_kind.clone()),
2280                ),
2281                (
2282                    "execution_count".to_string(),
2283                    Value::Int(record.execution_count),
2284                ),
2285                (
2286                    "success_count".to_string(),
2287                    Value::Int(record.success_count),
2288                ),
2289                ("error_count".to_string(), Value::Int(record.error_count)),
2290                (
2291                    "total_elapsed_micros".to_string(),
2292                    Value::Int(record.total_elapsed_micros),
2293                ),
2294                (
2295                    "max_elapsed_micros".to_string(),
2296                    Value::Int(record.max_elapsed_micros),
2297                ),
2298                (
2299                    "avg_elapsed_micros".to_string(),
2300                    Value::Int(avg_i64(record.total_elapsed_micros, record.execution_count)),
2301                ),
2302                (
2303                    "total_row_count".to_string(),
2304                    Value::Int(record.total_row_count),
2305                ),
2306                (
2307                    "last_seen_unix_micros".to_string(),
2308                    Value::Int(record.last_seen_unix_micros),
2309                ),
2310                (
2311                    "last_elapsed_micros".to_string(),
2312                    Value::Int(record.last_elapsed_micros),
2313                ),
2314                (
2315                    "last_row_count".to_string(),
2316                    Value::Int(record.last_row_count),
2317                ),
2318                ("last_success".to_string(), Value::Bool(record.last_success)),
2319                (
2320                    "last_error".to_string(),
2321                    record
2322                        .last_error
2323                        .as_ref()
2324                        .map(|error| Value::String(error.clone()))
2325                        .unwrap_or(Value::Null),
2326                ),
2327            ])
2328        })
2329        .collect()
2330}
2331
2332fn predicate_matches(predicate: &SqlPredicate, row: &Row) -> Result<bool> {
2333    Ok(match &predicate.kind {
2334        ExprKind::And(left, right) => {
2335            predicate_matches(left, row)? && predicate_matches(right, row)?
2336        }
2337        ExprKind::Or(left, right) => {
2338            predicate_matches(left, row)? || predicate_matches(right, row)?
2339        }
2340        ExprKind::Not(inner) => !predicate_matches(inner, row)?,
2341        ExprKind::Compare { left, op, right } => {
2342            let left = system_expression_value(left, row)?;
2343            let right = system_expression_value(right, row)?;
2344            compare_values(&left, *op, &right)?
2345        }
2346        ExprKind::InList {
2347            left,
2348            values,
2349            negated,
2350        } => {
2351            let left = system_expression_value(left, row)?;
2352            let mut matched = false;
2353            for value in values {
2354                let value = system_expression_value(value, row)?;
2355                if compare_values(&left, SqlComparisonOp::Eq, &value)? {
2356                    matched = true;
2357                    break;
2358                }
2359            }
2360            matched != *negated
2361        }
2362        ExprKind::Like {
2363            left,
2364            pattern,
2365            case_insensitive,
2366            negated,
2367            escape,
2368        } => {
2369            let left = system_expression_value(left, row)?;
2370            let pattern = system_expression_value(pattern, row)?;
2371            let (Value::String(value), Value::String(pattern)) = (left.as_ref(), pattern.as_ref())
2372            else {
2373                return Ok(false);
2374            };
2375            hawdb_sql::sql_like_matches(value, pattern, *escape, *case_insensitive)? != *negated
2376        }
2377        ExprKind::IsNull {
2378            expression,
2379            negated,
2380        } => {
2381            matches!(
2382                system_expression_value(expression, row)?.as_ref(),
2383                Value::Null
2384            ) != *negated
2385        }
2386        _ => {
2387            return Err(HawDBError::Semantic(
2388                "unsupported system SQL predicate".into(),
2389            ))
2390        }
2391    })
2392}
2393
2394fn system_expression_value<'a>(
2395    expression: &'a Expr,
2396    row: &'a Row,
2397) -> Result<std::borrow::Cow<'a, Value>> {
2398    use std::borrow::Cow;
2399    let value = match &expression.kind {
2400        ExprKind::Column(column) => Cow::Borrowed(row.get(&column.name).unwrap_or(&Value::Null)),
2401        ExprKind::Value(SqlValue::Literal(value)) => Cow::Borrowed(value),
2402        ExprKind::Arithmetic { left, op, right } => {
2403            let left = system_expression_value(left, row)?;
2404            let right = system_expression_value(right, row)?;
2405            Cow::Owned(hawdb_core::numeric::evaluate_numeric(
2406                left.as_ref().as_ref(),
2407                *op,
2408                right.as_ref().as_ref(),
2409            )?)
2410        }
2411        ExprKind::Negate(expression) => {
2412            let value = system_expression_value(expression, row)?;
2413            Cow::Owned(hawdb_core::numeric::negate_numeric(
2414                value.as_ref().as_ref(),
2415            )?)
2416        }
2417        ExprKind::Cast { expression, target } => {
2418            let value = system_expression_value(expression, row)?;
2419            Cow::Owned(hawdb_core::numeric::cast_numeric(
2420                value.as_ref().as_ref(),
2421                *target,
2422            )?)
2423        }
2424        _ => {
2425            return Err(HawDBError::Semantic(
2426                "unsupported system SQL scalar expression".into(),
2427            ))
2428        }
2429    };
2430    Ok(value)
2431}
2432
2433fn compare_values(left: &Value, op: SqlComparisonOp, right: &Value) -> Result<bool> {
2434    if matches!(left, Value::Null) || matches!(right, Value::Null) {
2435        return Ok(false);
2436    }
2437    let ordering = if left.logical_type().is_some_and(|kind| kind.is_numeric())
2438        && right.logical_type().is_some_and(|kind| kind.is_numeric())
2439    {
2440        hawdb_core::numeric::compare_numeric(left.as_ref(), right.as_ref())?
2441    } else {
2442        left.cmp(right)
2443    };
2444    Ok(match op {
2445        SqlComparisonOp::Eq => ordering.is_eq(),
2446        SqlComparisonOp::NotEq => !ordering.is_eq(),
2447        SqlComparisonOp::Lt => ordering.is_lt(),
2448        SqlComparisonOp::Lte => !ordering.is_gt(),
2449        SqlComparisonOp::Gt => ordering.is_gt(),
2450        SqlComparisonOp::Gte => !ordering.is_lt(),
2451    })
2452}
2453
2454fn compare_ordered_rows(left: &Row, right: &Row, order_by: &[SqlOrderItem]) -> Ordering {
2455    for item in order_by {
2456        let column = item
2457            .expression
2458            .as_column()
2459            .expect("system ORDER BY columns were validated");
2460        let ordering = left.get(&column.name).cmp(&right.get(&column.name));
2461        let ordering = match item.direction {
2462            SqlOrderDirection::Asc => ordering,
2463            SqlOrderDirection::Desc => ordering.reverse(),
2464        };
2465        if ordering != Ordering::Equal {
2466            return ordering;
2467        }
2468    }
2469    Ordering::Equal
2470}
2471
2472fn system_table(select: &SelectStatement) -> Result<SystemTable> {
2473    let from = select.from_table();
2474    match (from.schema.as_deref(), from.name.as_str()) {
2475        (Some("system"), "tables") => Ok(SystemTable::Tables),
2476        (Some("system"), "vector_columns") => Ok(SystemTable::VectorColumns),
2477        (Some("system"), "properties") => Ok(SystemTable::Properties),
2478        (Some("system"), "indexes") => Ok(SystemTable::Indexes),
2479        (Some("system"), "constraints") => Ok(SystemTable::Constraints),
2480        (Some("system"), "append_tables") => Ok(SystemTable::AppendTables),
2481        (Some("system"), "append_storage") => Ok(SystemTable::AppendStorage),
2482        (Some("system"), "runtime_status") => Ok(SystemTable::RuntimeStatus),
2483        (Some("system"), "runtime_capabilities") => Ok(SystemTable::RuntimeCapabilities),
2484        (Some("system"), "graph_statistics") => Ok(SystemTable::GraphStatistics),
2485        (Some("system"), "projected_graphs") => Ok(SystemTable::ProjectedGraphs),
2486        (Some("system"), "search_projection_changefeed") => {
2487            Ok(SystemTable::SearchProjectionChangefeed)
2488        }
2489        (Some("system"), "plan_cache") => Ok(SystemTable::PlanCache),
2490        (Some("system"), "slow_queries") => Ok(SystemTable::SlowQueries),
2491        (Some("system"), "statement_summary") => Ok(SystemTable::StatementSummary),
2492        (Some("information_schema"), "tables") => Ok(SystemTable::InformationSchemaTables),
2493        (Some("information_schema"), "columns") => Ok(SystemTable::InformationSchemaColumns),
2494        (Some("pg_catalog"), "pg_tables") => Ok(SystemTable::PgTables),
2495        (Some("pg_catalog"), "pg_indexes") => Ok(SystemTable::PgIndexes),
2496        (None, "pg_tables") => Ok(SystemTable::PgTables),
2497        (None, "pg_indexes") => Ok(SystemTable::PgIndexes),
2498        _ => Err(HawDBError::Semantic(format!(
2499            "unknown SQL virtual catalog table {}",
2500            format_table_name(select)
2501        ))),
2502    }
2503}
2504
2505fn validate_projection(table: SystemTable, projection: &[SelectProjection]) -> Result<()> {
2506    for projection in projection {
2507        match projection {
2508            SelectProjection::Wildcard => {}
2509            SelectProjection::Expression {
2510                expression:
2511                    Expr {
2512                        kind: ExprKind::Column(name),
2513                        ..
2514                    },
2515                ..
2516            } => validate_column(table, name)?,
2517            SelectProjection::Expression { .. } => {
2518                return Err(HawDBError::Semantic(
2519                    "system SQL aggregate expressions are not supported".to_string(),
2520                ));
2521            }
2522        }
2523    }
2524    Ok(())
2525}
2526
2527fn validate_predicate_columns(table: SystemTable, predicate: Option<&SqlPredicate>) -> Result<()> {
2528    let mut result = Ok(());
2529    if let Some(predicate) = predicate {
2530        predicate.visit(&mut |expression| {
2531            if result.is_ok()
2532                && let Some(column) = expression.as_column()
2533            {
2534                result = validate_column(table, column);
2535            }
2536        });
2537    }
2538    result
2539}
2540
2541fn validate_order_columns(table: SystemTable, order_by: &[SqlOrderItem]) -> Result<()> {
2542    for item in order_by {
2543        validate_column(table, item.expression.require_column()?)?;
2544    }
2545    Ok(())
2546}
2547
2548fn validate_column(table: SystemTable, column: &SqlColumnRef) -> Result<()> {
2549    if let Some(qualifier) = &column.qualifier {
2550        let table_name = match table {
2551            SystemTable::Tables => "tables",
2552            SystemTable::VectorColumns => "vector_columns",
2553            SystemTable::Properties => "properties",
2554            SystemTable::Indexes => "indexes",
2555            SystemTable::Constraints => "constraints",
2556            SystemTable::AppendTables => "append_tables",
2557            SystemTable::AppendStorage => "append_storage",
2558            SystemTable::RuntimeStatus => "runtime_status",
2559            SystemTable::RuntimeCapabilities => "runtime_capabilities",
2560            SystemTable::GraphStatistics => "graph_statistics",
2561            SystemTable::ProjectedGraphs => "projected_graphs",
2562            SystemTable::SearchProjectionChangefeed => "search_projection_changefeed",
2563            SystemTable::PlanCache => "plan_cache",
2564            SystemTable::SlowQueries => "slow_queries",
2565            SystemTable::StatementSummary => "statement_summary",
2566            SystemTable::InformationSchemaTables => "tables",
2567            SystemTable::InformationSchemaColumns => "columns",
2568            SystemTable::PgTables => "pg_tables",
2569            SystemTable::PgIndexes => "pg_indexes",
2570        };
2571        if qualifier != table_name {
2572            return Err(HawDBError::Semantic(format!(
2573                "unknown SQL column qualifier {qualifier}"
2574            )));
2575        }
2576    }
2577    if table_columns(table).contains(&column.name.as_str()) {
2578        Ok(())
2579    } else {
2580        Err(HawDBError::Semantic(format!(
2581            "unknown SQL column {}",
2582            column.name
2583        )))
2584    }
2585}
2586
2587fn table_columns(table: SystemTable) -> &'static [&'static str] {
2588    match table {
2589        SystemTable::Tables => &["table_id", "table_name", "table_kind", "state"],
2590        SystemTable::VectorColumns => &[
2591            "table_schema",
2592            "table_name",
2593            "column_name",
2594            "dimensions",
2595            "element_type",
2596            "nullable",
2597        ],
2598        SystemTable::Properties => &[
2599            "property_id",
2600            "table_id",
2601            "table_name",
2602            "table_kind",
2603            "property_name",
2604            "value_type",
2605            "nullable",
2606            "state",
2607        ],
2608        SystemTable::Indexes => &[
2609            "index_id",
2610            "subject_kind",
2611            "subject_id",
2612            "subject_name",
2613            "index_kind",
2614            "property_names",
2615        ],
2616        SystemTable::Constraints => &[
2617            "constraint_id",
2618            "subject_kind",
2619            "subject_id",
2620            "subject_name",
2621            "property_name",
2622            "constraint_kind",
2623        ],
2624        SystemTable::AppendTables => &[
2625            "table_name",
2626            "storage_mode",
2627            "partition_key",
2628            "order_key",
2629            "order_mode",
2630            "generated_order_watermark",
2631            "column_count",
2632        ],
2633        SystemTable::AppendStorage => &[
2634            "canonical_segment_count",
2635            "canonical_segment_bytes",
2636            "resident_segment_payload_bytes",
2637            "resident_descriptor_count",
2638            "live_rows",
2639            "live_payload_bytes",
2640        ],
2641        SystemTable::RuntimeStatus => &[
2642            "commit_epoch",
2643            "read_only",
2644            "max_read_result_rows",
2645            "max_read_result_payload_bytes",
2646            "storage_residency_mode",
2647            "relational_index_mode",
2648        ],
2649        SystemTable::RuntimeCapabilities => &["capability", "enabled"],
2650        SystemTable::GraphStatistics => &[
2651            "statistic_kind",
2652            "computed_at_commit_epoch",
2653            "advanced_statistics_complete",
2654            "histogram_sample_limit",
2655            "label_name",
2656            "relationship_type_name",
2657            "source_label_name",
2658            "target_label_name",
2659            "depth",
2660            "property_name",
2661            "index_id",
2662            "index_kind",
2663            "index_properties",
2664            "index_size",
2665            "unique_values",
2666            "sample_size",
2667            "updates_since_sample",
2668            "stale",
2669            "count",
2670            "histogram",
2671            "sampled",
2672        ],
2673        SystemTable::ProjectedGraphs => &[
2674            "name",
2675            "node_labels",
2676            "relationship_types",
2677            "projection_epoch",
2678            "commit_epoch",
2679            "node_count",
2680            "edge_count",
2681            "reusable",
2682        ],
2683        SystemTable::SearchProjectionChangefeed => &[
2684            "graph_commit_epoch",
2685            "resume_floor_commit_epoch",
2686            "oldest_retained_mutation_id",
2687            "newest_retained_mutation_id",
2688            "retained_mutation_count",
2689            "restart_recoverable",
2690        ],
2691        SystemTable::PlanCache => &["metric", "value"],
2692        SystemTable::SlowQueries => &[
2693            "sequence",
2694            "query_language",
2695            "statement_kind",
2696            "query_digest",
2697            "query_text_hash",
2698            "query_text",
2699            "started_unix_micros",
2700            "elapsed_micros",
2701            "row_count",
2702            "success",
2703            "error",
2704            "slow_log_candidate",
2705            "access_control_policy_epoch",
2706        ],
2707        SystemTable::StatementSummary => &[
2708            "digest",
2709            "query_language",
2710            "query_text",
2711            "sample_query_text_hash",
2712            "statement_kind",
2713            "execution_count",
2714            "success_count",
2715            "error_count",
2716            "total_elapsed_micros",
2717            "max_elapsed_micros",
2718            "avg_elapsed_micros",
2719            "total_row_count",
2720            "last_seen_unix_micros",
2721            "last_elapsed_micros",
2722            "last_row_count",
2723            "last_success",
2724            "last_error",
2725        ],
2726        SystemTable::InformationSchemaTables => &[
2727            "table_catalog",
2728            "table_schema",
2729            "table_name",
2730            "table_type",
2731            "self_referencing_column_name",
2732            "reference_generation",
2733            "user_defined_type_catalog",
2734            "user_defined_type_schema",
2735            "user_defined_type_name",
2736            "is_insertable_into",
2737            "is_typed",
2738            "commit_action",
2739        ],
2740        SystemTable::InformationSchemaColumns => &[
2741            "table_catalog",
2742            "table_schema",
2743            "table_name",
2744            "column_name",
2745            "ordinal_position",
2746            "column_default",
2747            "is_nullable",
2748            "data_type",
2749            "character_maximum_length",
2750            "character_octet_length",
2751            "numeric_precision",
2752            "numeric_precision_radix",
2753            "numeric_scale",
2754            "datetime_precision",
2755            "interval_type",
2756            "interval_precision",
2757            "character_set_catalog",
2758            "character_set_schema",
2759            "character_set_name",
2760            "collation_catalog",
2761            "collation_schema",
2762            "collation_name",
2763            "domain_catalog",
2764            "domain_schema",
2765            "domain_name",
2766            "udt_catalog",
2767            "udt_schema",
2768            "udt_name",
2769            "scope_catalog",
2770            "scope_schema",
2771            "scope_name",
2772            "maximum_cardinality",
2773            "dtd_identifier",
2774            "is_self_referencing",
2775            "is_identity",
2776            "identity_generation",
2777            "identity_start",
2778            "identity_increment",
2779            "identity_maximum",
2780            "identity_minimum",
2781            "identity_cycle",
2782            "is_generated",
2783            "generation_expression",
2784            "is_updatable",
2785        ],
2786        SystemTable::PgTables => &[
2787            "schemaname",
2788            "tablename",
2789            "tableowner",
2790            "tablespace",
2791            "hasindexes",
2792            "hasrules",
2793            "hastriggers",
2794            "rowsecurity",
2795        ],
2796        SystemTable::PgIndexes => &[
2797            "schemaname",
2798            "tablename",
2799            "indexname",
2800            "tablespace",
2801            "indexdef",
2802        ],
2803    }
2804}
2805
2806fn format_table_name(select: &SelectStatement) -> String {
2807    let from = select.from_table();
2808    match &from.schema {
2809        Some(schema) => format!("{schema}.{}", from.name),
2810        None => from.name.clone(),
2811    }
2812}
2813
2814fn option_usize_value(value: Option<usize>) -> Value {
2815    value.map(usize_value).unwrap_or(Value::Null)
2816}
2817
2818fn option_i64_value(value: Option<i64>) -> Value {
2819    value.map(Value::Int).unwrap_or(Value::Null)
2820}
2821
2822fn option_u64_value(value: Option<u64>) -> Value {
2823    value.map(u64_value).unwrap_or(Value::Null)
2824}
2825
2826fn usize_value(value: usize) -> Value {
2827    Value::Int(i64::try_from(value).unwrap_or(i64::MAX))
2828}
2829
2830fn u32_value(value: u32) -> Value {
2831    Value::Int(i64::from(value))
2832}
2833
2834fn u64_value(value: u64) -> Value {
2835    Value::Int(i64::try_from(value).unwrap_or(i64::MAX))
2836}
2837
2838const fn storage_residency_mode_name(mode: StorageResidencyMode) -> &'static str {
2839    match mode {
2840        StorageResidencyMode::Auto => "auto",
2841        StorageResidencyMode::Materialized => "materialized",
2842        StorageResidencyMode::OutOfCore => "out_of_core",
2843    }
2844}
2845
2846const fn relational_index_mode_name(mode: RelationalIndexMode) -> &'static str {
2847    match mode {
2848        RelationalIndexMode::Materialized => "materialized",
2849        RelationalIndexMode::Shadow => "shadow",
2850        RelationalIndexMode::DemandPaged => "demand_paged",
2851        RelationalIndexMode::Authoritative => "authoritative",
2852    }
2853}
2854
2855fn avg_i64(total: i64, count: i64) -> i64 {
2856    if count <= 0 {
2857        0
2858    } else {
2859        total / count
2860    }
2861}
2862
2863fn saturating_i64_from_u128(value: u128) -> i64 {
2864    i64::try_from(value).unwrap_or(i64::MAX)
2865}
2866
2867fn unix_now_micros() -> i64 {
2868    let micros = SystemTime::now()
2869        .duration_since(UNIX_EPOCH)
2870        .map(|duration| duration.as_micros())
2871        .unwrap_or(0);
2872    saturating_i64_from_u128(micros)
2873}
2874
2875fn truncate_utf8(input: &str, max_bytes: usize) -> String {
2876    if input.len() <= max_bytes {
2877        return input.to_string();
2878    }
2879    let mut end = max_bytes;
2880    while !input.is_char_boundary(end) {
2881        end -= 1;
2882    }
2883    input[..end].to_string()
2884}
2885
2886mod graph_store_adapter;
2887
2888#[cfg(test)]
2889mod statement_summary_tests;
2890
2891#[cfg(test)]
2892mod tests {
2893    use super::*;
2894
2895    #[test]
2896    fn catalog_numeric_predicates_share_exact_arithmetic_and_comparison() {
2897        let row = BTreeMap::from([("value".into(), Value::Int(9_007_199_254_740_993))]);
2898        for sql in [
2899            "SELECT value FROM system.plan_cache WHERE value = 9007199254740993.00",
2900            "SELECT value FROM system.plan_cache WHERE CAST(value AS DECIMAL(38,2)) + 0.01 = $1",
2901            "SELECT value FROM system.plan_cache WHERE value IN (9007199254740993.00)",
2902        ] {
2903            let SqlStatement::Select(select) = hawdb_sql::parse_postgres_sql(sql).unwrap() else {
2904                panic!("SELECT");
2905            };
2906            let predicate = bind_predicate(
2907                select.selection.unwrap(),
2908                &[Value::Decimal("9007199254740993.01".parse().unwrap())],
2909            )
2910            .unwrap();
2911            assert!(predicate_matches(&predicate, &row).unwrap(), "{sql}");
2912        }
2913        let SqlStatement::Select(select) = hawdb_sql::parse_postgres_sql(
2914            "SELECT value FROM system.plan_cache WHERE value / 0 > 1",
2915        )
2916        .unwrap() else {
2917            panic!("SELECT");
2918        };
2919        assert!(predicate_matches(&select.selection.unwrap(), &row).is_err());
2920    }
2921
2922    #[derive(Debug, Default)]
2923    struct TestStore;
2924
2925    impl SystemSqlStore for TestStore {
2926        fn commit_epoch(&self) -> u64 {
2927            0
2928        }
2929
2930        fn append_storage_residency_report(&self) -> AppendStorageResidencyReport {
2931            AppendStorageResidencyReport::default()
2932        }
2933
2934        fn statistics(&self, _catalog: &Catalog) -> GraphStatistics {
2935            GraphStatistics::default()
2936        }
2937
2938        fn projected_graph_statuses(&self) -> Vec<ProjectedGraphStatus> {
2939            Vec::new()
2940        }
2941
2942        fn search_projection_changefeed_status(&self) -> SearchProjectionChangefeedStatus {
2943            SearchProjectionChangefeedStatus {
2944                graph_commit_epoch: 0,
2945                resume_floor_commit_epoch: 0,
2946                oldest_retained_mutation_id: None,
2947                newest_retained_mutation_id: None,
2948                first_rebuild_required_mutation_id: None,
2949                retained_mutation_count: 0,
2950                retained_bytes: 0,
2951                max_retained_bytes: None,
2952                restart_recoverable: true,
2953            }
2954        }
2955    }
2956
2957    fn default_runtime() -> SystemRuntimeSnapshot {
2958        SystemRuntimeSnapshot::new(
2959            false,
2960            Some(512),
2961            Some(4 * 1024 * 1024),
2962            StorageResidencyMode::Auto,
2963            RelationalIndexMode::default(),
2964            RuntimeCapabilities::default(),
2965        )
2966    }
2967
2968    #[test]
2969    fn predicate_binding_preserves_source_spans_and_system_null_behavior() {
2970        let SqlStatement::Select(select) = hawdb_sql::prepare_postgres_sql(
2971            "SELECT value FROM system.plan_cache WHERE \
2972             (value IN ($1, $2) OR NOT value = $3) AND \
2973             (metric LIKE $4 OR value IS NULL)",
2974        )
2975        .unwrap()
2976        .statement
2977        else {
2978            panic!("expected SELECT");
2979        };
2980        let predicate = select.selection.unwrap();
2981        let mut before = Vec::new();
2982        predicate.visit(&mut |node| before.push(node.span));
2983        let bound = bind_predicate(
2984            predicate.clone(),
2985            &[
2986                Value::Null,
2987                Value::Int(5),
2988                Value::Null,
2989                Value::String("hit%".to_owned()),
2990            ],
2991        )
2992        .unwrap();
2993        let mut after = Vec::new();
2994        let mut parameters = Vec::new();
2995        bound.visit(&mut |node| {
2996            after.push(node.span);
2997            if let ExprKind::Value(SqlValue::Parameter(position)) = &node.kind {
2998                parameters.push(*position);
2999            }
3000        });
3001        assert_eq!(after, before);
3002        assert!(parameters.is_empty());
3003        assert!(predicate_matches(
3004            &bound,
3005            &BTreeMap::from([
3006                ("value".to_owned(), Value::Null),
3007                ("metric".to_owned(), Value::String("misses".to_owned())),
3008            ])
3009        )
3010        .unwrap());
3011        assert!(bind_predicate(
3012            predicate,
3013            &[
3014                Value::Null,
3015                Value::Int(5),
3016                Value::Null,
3017                Value::String("dangling\\".to_owned()),
3018            ]
3019        )
3020        .unwrap_err()
3021        .to_string()
3022        .contains("ends with its escape"));
3023    }
3024
3025    #[test]
3026    fn query_plan_cache_virtual_table_with_predicate_and_projection() {
3027        let catalog = Catalog::default();
3028        let store = TestStore;
3029        let relational_state = RelationalState::default();
3030        let append_state = AppendState::default();
3031        let stats = PlanCacheStats {
3032            max_bytes: Some(16384),
3033            max_entry_bytes: Some(8192),
3034            charged_bytes: Some(4096),
3035            rejected_admissions: 2,
3036            max_entries: Some(128),
3037            entries: 3,
3038            hits: 5,
3039            misses: 7,
3040            admissions: 4,
3041            disabled_misses: 0,
3042            bypasses: 2,
3043            evictions: 1,
3044            memory_pressure_events: 1,
3045        };
3046
3047        let context = SystemSqlContext {
3048            catalog: &catalog,
3049            store: &store,
3050            relational_state: &relational_state,
3051            append_state: &append_state,
3052            runtime: default_runtime(),
3053            plan_cache_stats: &stats,
3054            slow_queries: &[],
3055            statement_summaries: &[],
3056        };
3057        let sql = "SELECT value FROM system.plan_cache WHERE metric = 'hits'";
3058        let output = query_sql(sql, None, None, &context).expect("system plan cache query");
3059
3060        assert_eq!(
3061            output.rows,
3062            vec![BTreeMap::from([("value".to_string(), Value::Int(5))])]
3063        );
3064        let payload_bytes = output.payload_bytes();
3065        for (metric, expected) in [
3066            ("max_bytes", 16384),
3067            ("max_entry_bytes", 8192),
3068            ("charged_bytes", 4096),
3069            ("rejected_admissions", 2),
3070        ] {
3071            let output = query_sql(
3072                &format!("SELECT value FROM system.plan_cache WHERE metric = '{metric}'"),
3073                Some(1),
3074                Some(1024),
3075                &context,
3076            )
3077            .unwrap();
3078            assert_eq!(
3079                output.rows,
3080                vec![BTreeMap::from([("value".into(), Value::Int(expected))])]
3081            );
3082        }
3083        let exact = query_sql(sql, Some(1), Some(payload_bytes), &context).unwrap();
3084        assert_eq!(exact.rows, output.rows);
3085        for (rows, payload, resource, limit) in [
3086            (Some(0), Some(0), hawdb_core::ReadBudgetResource::Rows, 0),
3087            (
3088                Some(1),
3089                Some(payload_bytes - 1),
3090                hawdb_core::ReadBudgetResource::PayloadBytes,
3091                payload_bytes - 1,
3092            ),
3093        ] {
3094            let error = query_sql(sql, rows, payload, &context).unwrap_err();
3095            assert!(
3096                matches!(&error, HawDBError::ReadBudgetExceeded(cause)
3097                    if cause.resource == resource && cause.limit == limit),
3098                "system SQL lost its result budget cause: {error}"
3099            );
3100        }
3101    }
3102
3103    #[test]
3104    fn query_system_table_with_postgres_parameters() {
3105        let catalog = Catalog::default();
3106        let store = TestStore;
3107        let relational_state = RelationalState::default();
3108        let append_state = AppendState::default();
3109        let stats = PlanCacheStats {
3110            max_bytes: None,
3111            max_entry_bytes: None,
3112            charged_bytes: None,
3113            rejected_admissions: 0,
3114            max_entries: Some(128),
3115            entries: 3,
3116            hits: 5,
3117            misses: 7,
3118            admissions: 4,
3119            disabled_misses: 0,
3120            bypasses: 2,
3121            evictions: 1,
3122            memory_pressure_events: 1,
3123        };
3124        let context = SystemSqlContext {
3125            catalog: &catalog,
3126            store: &store,
3127            relational_state: &relational_state,
3128            append_state: &append_state,
3129            runtime: default_runtime(),
3130            plan_cache_stats: &stats,
3131            slow_queries: &[],
3132            statement_summaries: &[],
3133        };
3134
3135        let output = query_sql_with_params(
3136            "SELECT metric, value FROM system.plan_cache \
3137             WHERE metric IN ($1, $2) ORDER BY metric ASC LIMIT $3 OFFSET $4",
3138            &[
3139                Value::String("hits".to_string()),
3140                Value::String("misses".to_string()),
3141                Value::Int(1),
3142                Value::Int(1),
3143            ],
3144            None,
3145            None,
3146            &context,
3147        )
3148        .expect("parameterized system table query");
3149
3150        assert_eq!(
3151            output.rows,
3152            vec![BTreeMap::from([
3153                ("metric".to_string(), Value::String("misses".to_string())),
3154                ("value".to_string(), Value::Int(7)),
3155            ])]
3156        );
3157    }
3158
3159    #[test]
3160    fn query_system_table_rejects_parameter_contract_mismatch() {
3161        let catalog = Catalog::default();
3162        let store = TestStore;
3163        let relational_state = RelationalState::default();
3164        let append_state = AppendState::default();
3165        let stats = PlanCacheStats {
3166            max_bytes: None,
3167            max_entry_bytes: None,
3168            charged_bytes: None,
3169            rejected_admissions: 0,
3170            max_entries: None,
3171            entries: 0,
3172            hits: 0,
3173            misses: 0,
3174            admissions: 0,
3175            disabled_misses: 0,
3176            bypasses: 0,
3177            evictions: 0,
3178            memory_pressure_events: 0,
3179        };
3180        let context = SystemSqlContext {
3181            catalog: &catalog,
3182            store: &store,
3183            relational_state: &relational_state,
3184            append_state: &append_state,
3185            runtime: default_runtime(),
3186            plan_cache_stats: &stats,
3187            slow_queries: &[],
3188            statement_summaries: &[],
3189        };
3190
3191        let missing = query_sql_with_params(
3192            "SELECT * FROM system.plan_cache WHERE metric = $1",
3193            &[],
3194            None,
3195            None,
3196            &context,
3197        )
3198        .expect_err("missing parameter must fail");
3199        assert!(missing.to_string().contains("requires 1 parameters"));
3200
3201        let invalid_bound = query_sql_with_params(
3202            "SELECT * FROM system.plan_cache LIMIT $1",
3203            &[Value::String("one".to_string())],
3204            None,
3205            None,
3206            &context,
3207        )
3208        .expect_err("non-integer LIMIT must fail");
3209        assert!(invalid_bound
3210            .to_string()
3211            .contains("must be a non-negative integer"));
3212    }
3213
3214    #[test]
3215    fn query_slow_queries_pushes_filter_order_and_limit_into_scan() {
3216        let catalog = Catalog::default();
3217        let store = TestStore;
3218        let relational_state = RelationalState::default();
3219        let append_state = AppendState::default();
3220        let stats = PlanCacheStats {
3221            max_bytes: None,
3222            max_entry_bytes: None,
3223            charged_bytes: None,
3224            rejected_admissions: 0,
3225            max_entries: None,
3226            entries: 0,
3227            hits: 0,
3228            misses: 0,
3229            admissions: 0,
3230            disabled_misses: 0,
3231            bypasses: 0,
3232            evictions: 0,
3233            memory_pressure_events: 0,
3234        };
3235        let records = vec![
3236            SlowQueryRecord {
3237                sequence: 1,
3238                query_language: "cypher".to_string(),
3239                statement_kind: "match_return".to_string(),
3240                query_digest: "q1:first".to_string(),
3241                query_text_hash: "t1:first".to_string(),
3242                query_text: "MATCH (m:Memory) RETURN m".to_string(),
3243                started_unix_micros: 10,
3244                elapsed_micros: 200,
3245                row_count: 1,
3246                success: true,
3247                error: None,
3248                slow_log_candidate: false,
3249                access_control_policy_epoch: None,
3250                vector_execution_reports: Vec::new(),
3251            },
3252            SlowQueryRecord {
3253                sequence: 2,
3254                query_language: "cypher".to_string(),
3255                statement_kind: "match_return".to_string(),
3256                query_digest: "q1:second".to_string(),
3257                query_text_hash: "t1:second".to_string(),
3258                query_text: "MATCH (m:Memory) RETURN m ORDER BY m.id".to_string(),
3259                started_unix_micros: 20,
3260                elapsed_micros: 500,
3261                row_count: 2,
3262                success: true,
3263                error: None,
3264                slow_log_candidate: true,
3265                access_control_policy_epoch: None,
3266                vector_execution_reports: Vec::new(),
3267            },
3268            SlowQueryRecord {
3269                sequence: 3,
3270                query_language: "cypher".to_string(),
3271                statement_kind: "match_return".to_string(),
3272                query_digest: "q1:third".to_string(),
3273                query_text_hash: "t1:third".to_string(),
3274                query_text: "MATCH (m:Memory {id: 'x'}) RETURN m".to_string(),
3275                started_unix_micros: 30,
3276                elapsed_micros: 300,
3277                row_count: 1,
3278                success: true,
3279                error: None,
3280                slow_log_candidate: true,
3281                access_control_policy_epoch: None,
3282                vector_execution_reports: Vec::new(),
3283            },
3284        ];
3285
3286        let output = query_sql(
3287            "SELECT sequence, elapsed_micros FROM system.slow_queries \
3288             WHERE slow_log_candidate = true \
3289             ORDER BY elapsed_micros DESC LIMIT 1",
3290            None,
3291            None,
3292            &SystemSqlContext {
3293                catalog: &catalog,
3294                store: &store,
3295                relational_state: &relational_state,
3296                append_state: &append_state,
3297                runtime: default_runtime(),
3298                plan_cache_stats: &stats,
3299                slow_queries: &records,
3300                statement_summaries: &[],
3301            },
3302        )
3303        .expect("system slow query scan");
3304
3305        assert_eq!(
3306            output.rows,
3307            vec![BTreeMap::from([
3308                ("elapsed_micros".to_string(), Value::Int(500)),
3309                ("sequence".to_string(), Value::Int(2)),
3310            ])]
3311        );
3312    }
3313
3314    #[test]
3315    fn query_catalog_virtual_tables_expose_schema_without_typed_getters() {
3316        let mut catalog = Catalog::default();
3317        let store = TestStore;
3318        let relational_state = RelationalState::default();
3319        let append_state = AppendState::default();
3320        let memory_label = catalog.get_or_create_label("Memory");
3321        let memory_table = catalog.get_or_create_table(TableKind::Node, "Memory");
3322        catalog.get_or_create_property(memory_table, "id", PropertyType::String, false);
3323        catalog.get_or_create_property_index_with_kind(memory_label, "id", IndexKind::Equality);
3324        catalog.get_or_create_unique_constraint(memory_label, "id");
3325        let stats = PlanCacheStats {
3326            max_bytes: None,
3327            max_entry_bytes: None,
3328            charged_bytes: None,
3329            rejected_admissions: 0,
3330            max_entries: None,
3331            entries: 0,
3332            hits: 0,
3333            misses: 0,
3334            admissions: 0,
3335            disabled_misses: 0,
3336            bypasses: 0,
3337            evictions: 0,
3338            memory_pressure_events: 0,
3339        };
3340        let context = SystemSqlContext {
3341            catalog: &catalog,
3342            store: &store,
3343            relational_state: &relational_state,
3344            append_state: &append_state,
3345            runtime: default_runtime(),
3346            plan_cache_stats: &stats,
3347            slow_queries: &[],
3348            statement_summaries: &[],
3349        };
3350
3351        let tables = query_sql(
3352            "SELECT table_id, table_name, table_kind, state FROM system.tables",
3353            None,
3354            None,
3355            &context,
3356        )
3357        .expect("system tables query");
3358        assert_eq!(
3359            tables.rows,
3360            vec![BTreeMap::from([
3361                ("state".to_string(), Value::String("public".to_string())),
3362                ("table_id".to_string(), Value::Int(0)),
3363                ("table_kind".to_string(), Value::String("node".to_string()),),
3364                (
3365                    "table_name".to_string(),
3366                    Value::String("Memory".to_string()),
3367                ),
3368            ])]
3369        );
3370
3371        let properties = query_sql(
3372            "SELECT table_name, property_name, value_type, nullable \
3373             FROM system.properties WHERE table_name = 'Memory'",
3374            None,
3375            None,
3376            &context,
3377        )
3378        .expect("system properties query");
3379        assert_eq!(
3380            properties.rows,
3381            vec![BTreeMap::from([
3382                ("nullable".to_string(), Value::Bool(false)),
3383                ("property_name".to_string(), Value::String("id".to_string()),),
3384                (
3385                    "table_name".to_string(),
3386                    Value::String("Memory".to_string()),
3387                ),
3388                (
3389                    "value_type".to_string(),
3390                    Value::String("string".to_string()),
3391                ),
3392            ])]
3393        );
3394
3395        let indexes = query_sql(
3396            "SELECT subject_name, index_kind, property_names FROM system.indexes",
3397            None,
3398            None,
3399            &context,
3400        )
3401        .expect("system indexes query");
3402        assert_eq!(
3403            indexes.rows,
3404            vec![BTreeMap::from([
3405                (
3406                    "index_kind".to_string(),
3407                    Value::String("equality".to_string()),
3408                ),
3409                (
3410                    "property_names".to_string(),
3411                    Value::List(vec![Value::String("id".to_string())]),
3412                ),
3413                (
3414                    "subject_name".to_string(),
3415                    Value::String("Memory".to_string()),
3416                ),
3417            ])]
3418        );
3419
3420        let constraints = query_sql(
3421            "SELECT subject_name, property_name, constraint_kind FROM system.constraints",
3422            None,
3423            None,
3424            &context,
3425        )
3426        .expect("system constraints query");
3427        assert_eq!(
3428            constraints.rows,
3429            vec![BTreeMap::from([
3430                (
3431                    "constraint_kind".to_string(),
3432                    Value::String("node_property_unique".to_string()),
3433                ),
3434                ("property_name".to_string(), Value::String("id".to_string()),),
3435                (
3436                    "subject_name".to_string(),
3437                    Value::String("Memory".to_string()),
3438                ),
3439            ])]
3440        );
3441    }
3442}
3443
3444#[cfg(all(test, feature = "loom-tests"))]
3445pub(crate) mod loom_tests {
3446    use super::{SlowQueryCompletion, SlowQueryLog, SlowQueryRecord};
3447    use hawdb_query::QueryIdentity;
3448    use loom::sync::{Arc, Mutex};
3449    use loom::thread;
3450
3451    #[test]
3452    fn slow_query_ring_preserves_bounds_under_modeled_concurrent_access() {
3453        loom::model(|| {
3454            let log = Arc::new(Mutex::new(SlowQueryLog::new(2)));
3455
3456            let first_writer = spawn_slow_query_writer(Arc::clone(&log), "first");
3457            let second_writer = spawn_slow_query_writer(Arc::clone(&log), "second");
3458            let snapshotter = {
3459                let log = Arc::clone(&log);
3460                thread::spawn(move || {
3461                    let snapshot = log.lock().unwrap().snapshot();
3462                    assert_snapshot_invariants(&snapshot, 2);
3463                })
3464            };
3465
3466            first_writer.join().unwrap();
3467            second_writer.join().unwrap();
3468            snapshotter.join().unwrap();
3469
3470            let snapshot = log.lock().unwrap().snapshot();
3471            assert_snapshot_invariants(&snapshot, 2);
3472            assert_eq!(snapshot.len(), 2);
3473            assert_eq!(snapshot.last().map(|record| record.sequence), Some(2));
3474        });
3475    }
3476
3477    fn spawn_slow_query_writer(
3478        log: Arc<Mutex<SlowQueryLog>>,
3479        query_text: &'static str,
3480    ) -> thread::JoinHandle<()> {
3481        thread::spawn(move || {
3482            let query_identity = QueryIdentity::new("cypher", query_text);
3483            log.lock()
3484                .unwrap()
3485                .push(SlowQueryRecord::completed(SlowQueryCompletion {
3486                    query_language: "cypher",
3487                    statement_kind: "match_return",
3488                    query_text,
3489                    query_identity: &query_identity,
3490                    elapsed_micros: 1,
3491                    row_count: 1,
3492                    success: true,
3493                    error: None,
3494                    slow_log_candidate: true,
3495                    access_control_policy_epoch: None,
3496                    vector_execution_reports: Vec::new(),
3497                }));
3498        })
3499    }
3500
3501    fn assert_snapshot_invariants(snapshot: &[SlowQueryRecord], capacity: usize) {
3502        assert!(snapshot.len() <= capacity);
3503        for pair in snapshot.windows(2) {
3504            assert!(pair[0].sequence < pair[1].sequence);
3505        }
3506    }
3507}