1use 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, RelationalComparisonOp, RelationalPredicate, RelationalScalarType,
43 RelationalState, RelationalTableSchema, 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#[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 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 .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 .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(
1385 schema,
1386 &name,
1387 &schema.primary_key,
1388 &[],
1389 true,
1390 None,
1391 ));
1392 }
1393 rows.extend(schema.unique_constraints.iter().map(|columns| {
1394 let name = format!("{}_{}_key", schema.name, columns.join("_"));
1395 pg_index_row(schema, &name, columns, &[], true, None)
1396 }));
1397 rows.extend(schema.indexes.iter().map(|index| {
1398 pg_index_row(
1399 schema,
1400 &index.name,
1401 &index.columns,
1402 &index.included_columns,
1403 index.unique,
1404 index.predicate.as_ref(),
1405 )
1406 }));
1407 rows
1408}
1409
1410fn pg_index_row(
1411 schema: &RelationalTableSchema,
1412 index_name: &str,
1413 columns: &[String],
1414 included_columns: &[String],
1415 unique: bool,
1416 predicate: Option<&RelationalPredicate>,
1417) -> Row {
1418 let unique = if unique { "UNIQUE " } else { "" };
1419 let columns = columns
1420 .iter()
1421 .map(|column| quote_postgres_identifier(column))
1422 .collect::<Vec<_>>()
1423 .join(", ");
1424 let predicate = predicate
1425 .map(|predicate| format!(" WHERE {}", pg_index_predicate(predicate)))
1426 .unwrap_or_default();
1427 let include = if included_columns.is_empty() {
1428 String::new()
1429 } else {
1430 format!(
1431 " INCLUDE ({})",
1432 included_columns
1433 .iter()
1434 .map(|column| quote_postgres_identifier(column))
1435 .collect::<Vec<_>>()
1436 .join(", ")
1437 )
1438 };
1439 let index_definition = format!(
1440 "CREATE {unique}INDEX {} ON public.{} USING btree ({columns}){include}{predicate}",
1441 quote_postgres_identifier(index_name),
1442 quote_postgres_identifier(&schema.name),
1443 );
1444 BTreeMap::from([
1445 (
1446 "schemaname".to_string(),
1447 Value::String("public".to_string()),
1448 ),
1449 ("tablename".to_string(), Value::String(schema.name.clone())),
1450 (
1451 "indexname".to_string(),
1452 Value::String(index_name.to_string()),
1453 ),
1454 ("tablespace".to_string(), Value::Null),
1455 ("indexdef".to_string(), Value::String(index_definition)),
1456 ])
1457}
1458
1459fn pg_index_predicate(predicate: &RelationalPredicate) -> String {
1460 match predicate {
1461 RelationalPredicate::And(left, right) => format!(
1462 "({} AND {})",
1463 pg_index_predicate(left),
1464 pg_index_predicate(right)
1465 ),
1466 RelationalPredicate::Or(left, right) => format!(
1467 "({} OR {})",
1468 pg_index_predicate(left),
1469 pg_index_predicate(right)
1470 ),
1471 RelationalPredicate::Not(predicate) => format!("(NOT {})", pg_index_predicate(predicate)),
1472 RelationalPredicate::Compare { column, op, value } => format!(
1473 "{} {} {}",
1474 quote_postgres_identifier(column),
1475 match op {
1476 RelationalComparisonOp::Eq => "=",
1477 RelationalComparisonOp::NotEq => "<>",
1478 RelationalComparisonOp::Lt => "<",
1479 RelationalComparisonOp::Lte => "<=",
1480 RelationalComparisonOp::Gt => ">",
1481 RelationalComparisonOp::Gte => ">=",
1482 },
1483 pg_relational_literal(value)
1484 ),
1485 RelationalPredicate::IsNull { column, negated } => format!(
1486 "{} IS {}NULL",
1487 quote_postgres_identifier(column),
1488 if *negated { "NOT " } else { "" }
1489 ),
1490 RelationalPredicate::RowCompare { .. }
1491 | RelationalPredicate::NumericCompare { .. }
1492 | RelationalPredicate::NumericIsNull { .. } => {
1493 "/* unsupported partial-index predicate */ FALSE".to_string()
1494 }
1495 }
1496}
1497
1498fn pg_relational_literal(value: &RelationalValue) -> String {
1499 match value {
1500 RelationalValue::Null => "NULL".to_string(),
1501 RelationalValue::Boolean(value) => value.to_string(),
1502 RelationalValue::BigInt(value) => value.to_string(),
1503 RelationalValue::Decimal(value) => value.to_string(),
1504 RelationalValue::DoublePrecision(value) => value.to_string(),
1505 RelationalValue::Text(value) => format!("'{}'::text", value.replace('\'', "''")),
1506 RelationalValue::Bytea(value) => format!("'\\x{}'::bytea", encode_hex(value)),
1507 RelationalValue::Uuid(value) => format!("'{value}'::uuid"),
1508 RelationalValue::Vector(value) => Value::Vector(value.clone()).to_string(),
1509 RelationalValue::Timestamp(value) => {
1510 hawdb_core::sql_timestamp::format_timestamp(value.get())
1511 .map(|text| format!("'{text}'::timestamp without time zone"))
1512 .unwrap_or_else(|_| "NULL".to_string())
1513 }
1514 RelationalValue::TimestampTz(value) => {
1515 hawdb_core::sql_timestamp::format_timestamptz(value.get())
1516 .map(|text| format!("'{text}'::timestamp with time zone"))
1517 .unwrap_or_else(|_| "NULL".to_string())
1518 }
1519 RelationalValue::Overflow(_) => "NULL".to_string(),
1520 }
1521}
1522
1523fn quote_postgres_identifier(identifier: &str) -> String {
1524 format!("\"{}\"", identifier.replace('"', "\"\""))
1525}
1526
1527fn property_rows(catalog: &Catalog) -> Vec<Row> {
1528 catalog
1529 .property_descriptors()
1530 .map(|property| {
1531 let table = catalog.table_descriptor(property.table_id);
1532 BTreeMap::from([
1533 ("property_id".to_string(), u32_value(property.id.0)),
1534 ("table_id".to_string(), u32_value(property.table_id.0)),
1535 (
1536 "table_name".to_string(),
1537 table
1538 .map(|table| Value::String(table.name.clone()))
1539 .unwrap_or(Value::Null),
1540 ),
1541 (
1542 "table_kind".to_string(),
1543 table
1544 .map(|table| Value::String(table_kind_name(table.kind).to_string()))
1545 .unwrap_or(Value::Null),
1546 ),
1547 (
1548 "property_name".to_string(),
1549 Value::String(property.name.clone()),
1550 ),
1551 (
1552 "value_type".to_string(),
1553 Value::String(property_type_name(property.value_type).to_string()),
1554 ),
1555 ("nullable".to_string(), Value::Bool(property.nullable)),
1556 (
1557 "state".to_string(),
1558 Value::String(schema_object_state_name(property.state).to_string()),
1559 ),
1560 ])
1561 })
1562 .collect()
1563}
1564
1565fn index_rows(catalog: &Catalog) -> Vec<Row> {
1566 let mut rows = catalog
1567 .property_indexes()
1568 .map(|index| {
1569 BTreeMap::from([
1570 ("index_id".to_string(), u32_value(index.id.0)),
1571 (
1572 "subject_kind".to_string(),
1573 Value::String("node".to_string()),
1574 ),
1575 ("subject_id".to_string(), u32_value(index.label_id.0)),
1576 (
1577 "subject_name".to_string(),
1578 optional_string_value(catalog.label_name(index.label_id)),
1579 ),
1580 (
1581 "index_kind".to_string(),
1582 Value::String(index_kind_name(index.kind).to_string()),
1583 ),
1584 (
1585 "property_names".to_string(),
1586 Value::List(vec![Value::String(index.property.clone())]),
1587 ),
1588 ])
1589 })
1590 .chain(catalog.composite_property_indexes().map(|index| {
1591 BTreeMap::from([
1592 ("index_id".to_string(), u32_value(index.id.0)),
1593 (
1594 "subject_kind".to_string(),
1595 Value::String("node".to_string()),
1596 ),
1597 ("subject_id".to_string(), u32_value(index.label_id.0)),
1598 (
1599 "subject_name".to_string(),
1600 optional_string_value(catalog.label_name(index.label_id)),
1601 ),
1602 (
1603 "index_kind".to_string(),
1604 Value::String("composite_equality".to_string()),
1605 ),
1606 (
1607 "property_names".to_string(),
1608 Value::List(
1609 index
1610 .properties
1611 .iter()
1612 .cloned()
1613 .map(Value::String)
1614 .collect(),
1615 ),
1616 ),
1617 ])
1618 }))
1619 .collect::<Vec<_>>();
1620 rows.sort_by_key(|row| row.get("index_id").cloned());
1621 rows
1622}
1623
1624fn constraint_rows(catalog: &Catalog) -> Vec<Row> {
1625 let constraints = catalog
1626 .unique_constraints()
1627 .chain(catalog.node_property_exists_constraints())
1628 .chain(catalog.relationship_property_exists_constraints())
1629 .chain(catalog.relationship_unique_constraints());
1630 let mut rows = constraints
1631 .map(|constraint| {
1632 let (subject_kind, subject_id, subject_name) = match constraint.subject {
1633 ConstraintSubject::Node(label_id) => (
1634 "node",
1635 label_id.0,
1636 optional_string_value(catalog.label_name(label_id)),
1637 ),
1638 ConstraintSubject::Relationship(rel_type_id) => (
1639 "relationship",
1640 rel_type_id.0,
1641 optional_string_value(catalog.rel_type_name(rel_type_id)),
1642 ),
1643 };
1644 BTreeMap::from([
1645 ("constraint_id".to_string(), u32_value(constraint.id.0)),
1646 (
1647 "subject_kind".to_string(),
1648 Value::String(subject_kind.to_string()),
1649 ),
1650 ("subject_id".to_string(), u32_value(subject_id)),
1651 ("subject_name".to_string(), subject_name),
1652 (
1653 "property_name".to_string(),
1654 Value::String(constraint.property.clone()),
1655 ),
1656 (
1657 "constraint_kind".to_string(),
1658 Value::String(constraint_kind_name(constraint.kind).to_string()),
1659 ),
1660 ])
1661 })
1662 .collect::<Vec<_>>();
1663 rows.sort_by_key(|row| row.get("constraint_id").cloned());
1664 rows
1665}
1666
1667fn runtime_status_rows<Store: SystemSqlStore>(context: &SystemSqlContext<'_, Store>) -> Vec<Row> {
1668 vec![BTreeMap::from([
1669 (
1670 "commit_epoch".to_string(),
1671 u64_value(context.store.commit_epoch()),
1672 ),
1673 (
1674 "read_only".to_string(),
1675 Value::Bool(context.runtime.read_only),
1676 ),
1677 (
1678 "max_read_result_rows".to_string(),
1679 option_usize_value(context.runtime.max_read_result_rows),
1680 ),
1681 (
1682 "max_read_result_payload_bytes".to_string(),
1683 option_usize_value(context.runtime.max_read_result_payload_bytes),
1684 ),
1685 (
1686 "storage_residency_mode".to_string(),
1687 Value::String(
1688 storage_residency_mode_name(context.runtime.storage_residency_mode).to_string(),
1689 ),
1690 ),
1691 (
1692 "relational_index_mode".to_string(),
1693 Value::String(
1694 relational_index_mode_name(context.runtime.relational_index_mode).to_string(),
1695 ),
1696 ),
1697 ])]
1698}
1699
1700fn append_table_rows(state: &AppendState) -> Vec<Row> {
1701 state
1702 .schemas()
1703 .values()
1704 .map(|schema| {
1705 BTreeMap::from([
1706 ("table_name".to_string(), Value::String(schema.name.clone())),
1707 (
1708 "storage_mode".to_string(),
1709 Value::String("strict_append".to_string()),
1710 ),
1711 (
1712 "partition_key".to_string(),
1713 Value::List(
1714 schema
1715 .partition_key
1716 .iter()
1717 .cloned()
1718 .map(Value::String)
1719 .collect(),
1720 ),
1721 ),
1722 (
1723 "order_key".to_string(),
1724 Value::List(
1725 schema
1726 .order_key
1727 .iter()
1728 .cloned()
1729 .map(Value::String)
1730 .collect(),
1731 ),
1732 ),
1733 (
1734 "order_mode".to_string(),
1735 Value::String(
1736 match schema.order_mode {
1737 AppendOrderMode::CallerProvided => "caller_provided",
1738 AppendOrderMode::CommitSequence => "commit_sequence",
1739 }
1740 .to_string(),
1741 ),
1742 ),
1743 (
1744 "generated_order_watermark".to_string(),
1745 state
1746 .generated_order_watermark(&schema.name)
1747 .map_or(Value::Null, Value::Int),
1748 ),
1749 (
1750 "column_count".to_string(),
1751 Value::Int(i64::try_from(schema.columns.len()).unwrap_or(i64::MAX)),
1752 ),
1753 ])
1754 })
1755 .collect()
1756}
1757
1758fn append_storage_rows(store: &impl SystemSqlStore, state: &AppendState) -> Vec<Row> {
1759 let mut report = store.append_storage_residency_report();
1760 report.live_rows = state.live_rows();
1761 report.live_payload_bytes = state.live_payload_bytes();
1762 vec![BTreeMap::from([
1763 (
1764 "canonical_segment_count".to_string(),
1765 Value::Int(i64::try_from(report.canonical_segment_count).unwrap_or(i64::MAX)),
1766 ),
1767 (
1768 "canonical_segment_bytes".to_string(),
1769 Value::Int(i64::try_from(report.canonical_segment_bytes).unwrap_or(i64::MAX)),
1770 ),
1771 (
1772 "resident_segment_payload_bytes".to_string(),
1773 Value::Int(i64::try_from(report.resident_segment_payload_bytes).unwrap_or(i64::MAX)),
1774 ),
1775 (
1776 "resident_descriptor_count".to_string(),
1777 Value::Int(i64::try_from(report.resident_descriptor_count).unwrap_or(i64::MAX)),
1778 ),
1779 (
1780 "live_rows".to_string(),
1781 Value::Int(i64::try_from(report.live_rows).unwrap_or(i64::MAX)),
1782 ),
1783 (
1784 "live_payload_bytes".to_string(),
1785 Value::Int(i64::try_from(report.live_payload_bytes).unwrap_or(i64::MAX)),
1786 ),
1787 ])]
1788}
1789
1790fn runtime_capability_rows(runtime: SystemRuntimeSnapshot) -> Vec<Row> {
1791 [
1792 (
1793 "access_control",
1794 runtime.runtime_capabilities.access_control,
1795 ),
1796 (
1797 "full_text_search",
1798 runtime.runtime_capabilities.full_text_search,
1799 ),
1800 ("vector_search", runtime.runtime_capabilities.vector_search),
1801 (
1802 "graph_analytics",
1803 runtime.runtime_capabilities.graph_analytics,
1804 ),
1805 (
1806 "background_maintenance",
1807 runtime.runtime_capabilities.background_maintenance,
1808 ),
1809 ]
1810 .into_iter()
1811 .map(|(capability, enabled)| {
1812 BTreeMap::from([
1813 (
1814 "capability".to_string(),
1815 Value::String(capability.to_string()),
1816 ),
1817 ("enabled".to_string(), Value::Bool(enabled)),
1818 ])
1819 })
1820 .collect()
1821}
1822
1823fn graph_statistics_rows(catalog: &Catalog, statistics: &GraphStatistics) -> Vec<Row> {
1824 let mut rows = Vec::with_capacity(
1825 2usize
1826 .saturating_add(statistics.label_counts.len())
1827 .saturating_add(statistics.rel_type_counts.len())
1828 .saturating_add(statistics.rel_type_source_counts.len())
1829 .saturating_add(statistics.rel_type_target_counts.len())
1830 .saturating_add(statistics.path_counts.len())
1831 .saturating_add(statistics.path_source_distinct_counts.len())
1832 .saturating_add(statistics.path_target_distinct_counts.len())
1833 .saturating_add(statistics.bounded_path_counts.len())
1834 .saturating_add(statistics.bounded_path_source_distinct_counts.len())
1835 .saturating_add(statistics.bounded_path_target_distinct_counts.len())
1836 .saturating_add(statistics.index_samples.len())
1837 .saturating_add(statistics.property_distinct_counts.len())
1838 .saturating_add(statistics.rel_property_distinct_counts.len())
1839 .saturating_add(statistics.property_histograms.len())
1840 .saturating_add(statistics.rel_property_histograms.len()),
1841 );
1842 rows.push(graph_statistic_count_row(
1843 statistics,
1844 "node_count",
1845 statistics.node_count,
1846 ));
1847 rows.push(graph_statistic_count_row(
1848 statistics,
1849 "relationship_count",
1850 statistics.relationship_count,
1851 ));
1852
1853 for (label_id, count) in &statistics.label_counts {
1854 let mut row = graph_statistic_count_row(statistics, "label_count", *count);
1855 row.insert(
1856 "label_name".to_string(),
1857 optional_string_value(catalog.label_name(*label_id)),
1858 );
1859 rows.push(row);
1860 }
1861 for (rel_type_id, count) in &statistics.rel_type_counts {
1862 let mut row = graph_statistic_count_row(statistics, "relationship_type_count", *count);
1863 row.insert(
1864 "relationship_type_name".to_string(),
1865 optional_string_value(catalog.rel_type_name(*rel_type_id)),
1866 );
1867 rows.push(row);
1868 }
1869 for (kind, counts) in [
1870 (
1871 "relationship_source_count",
1872 &statistics.rel_type_source_counts,
1873 ),
1874 (
1875 "relationship_target_count",
1876 &statistics.rel_type_target_counts,
1877 ),
1878 ] {
1879 for (rel_type_id, count) in counts {
1880 let mut row = graph_statistic_count_row(statistics, kind, *count);
1881 row.insert(
1882 "relationship_type_name".to_string(),
1883 optional_string_value(catalog.rel_type_name(*rel_type_id)),
1884 );
1885 rows.push(row);
1886 }
1887 }
1888 for index in catalog.property_indexes() {
1889 let Some(sample) = statistics.index_samples.get(&index.id) else {
1890 continue;
1891 };
1892 let mut row = graph_statistic_base_row(statistics, "index_sample");
1893 row.insert("index_id".to_string(), u32_value(index.id.0));
1894 row.insert(
1895 "index_kind".to_string(),
1896 Value::String(index_kind_name(index.kind).to_string()),
1897 );
1898 row.insert(
1899 "label_name".to_string(),
1900 optional_string_value(catalog.label_name(index.label_id)),
1901 );
1902 row.insert(
1903 "property_name".to_string(),
1904 Value::String(index.property.clone()),
1905 );
1906 populate_index_sample(&mut row, *sample);
1907 rows.push(row);
1908 }
1909 for index in catalog.composite_property_indexes() {
1910 let Some(sample) = statistics.index_samples.get(&index.id) else {
1911 continue;
1912 };
1913 let mut row = graph_statistic_base_row(statistics, "index_sample");
1914 row.insert("index_id".to_string(), u32_value(index.id.0));
1915 row.insert(
1916 "index_kind".to_string(),
1917 Value::String("composite".to_string()),
1918 );
1919 row.insert(
1920 "label_name".to_string(),
1921 optional_string_value(catalog.label_name(index.label_id)),
1922 );
1923 row.insert(
1924 "index_properties".to_string(),
1925 Value::List(
1926 index
1927 .properties
1928 .iter()
1929 .cloned()
1930 .map(Value::String)
1931 .collect(),
1932 ),
1933 );
1934 populate_index_sample(&mut row, *sample);
1935 rows.push(row);
1936 }
1937 for (kind, counts) in [
1938 ("path_count", &statistics.path_counts),
1939 (
1940 "path_source_distinct_count",
1941 &statistics.path_source_distinct_counts,
1942 ),
1943 (
1944 "path_target_distinct_count",
1945 &statistics.path_target_distinct_counts,
1946 ),
1947 ] {
1948 for ((source_label_id, rel_type_id, target_label_id), count) in counts {
1949 let mut row = graph_statistic_count_row(statistics, kind, *count);
1950 populate_path_statistic_names(
1951 &mut row,
1952 catalog,
1953 *source_label_id,
1954 *rel_type_id,
1955 *target_label_id,
1956 );
1957 rows.push(row);
1958 }
1959 }
1960 for (kind, counts) in [
1961 ("bounded_path_count", &statistics.bounded_path_counts),
1962 (
1963 "bounded_path_source_distinct_count",
1964 &statistics.bounded_path_source_distinct_counts,
1965 ),
1966 (
1967 "bounded_path_target_distinct_count",
1968 &statistics.bounded_path_target_distinct_counts,
1969 ),
1970 ] {
1971 for ((source_label_id, rel_type_id, target_label_id, depth), count) in counts {
1972 let mut row = graph_statistic_count_row(statistics, kind, *count);
1973 populate_path_statistic_names(
1974 &mut row,
1975 catalog,
1976 *source_label_id,
1977 *rel_type_id,
1978 *target_label_id,
1979 );
1980 row.insert("depth".to_string(), usize_value(*depth));
1981 rows.push(row);
1982 }
1983 }
1984 for ((label_id, property_name), count) in &statistics.property_distinct_counts {
1985 let mut row = graph_statistic_count_row(statistics, "node_property_distinct_count", *count);
1986 row.insert(
1987 "label_name".to_string(),
1988 optional_string_value(catalog.label_name(*label_id)),
1989 );
1990 row.insert(
1991 "property_name".to_string(),
1992 Value::String(property_name.clone()),
1993 );
1994 rows.push(row);
1995 }
1996 for ((rel_type_id, property_name), count) in &statistics.rel_property_distinct_counts {
1997 let mut row =
1998 graph_statistic_count_row(statistics, "relationship_property_distinct_count", *count);
1999 row.insert(
2000 "relationship_type_name".to_string(),
2001 optional_string_value(catalog.rel_type_name(*rel_type_id)),
2002 );
2003 row.insert(
2004 "property_name".to_string(),
2005 Value::String(property_name.clone()),
2006 );
2007 rows.push(row);
2008 }
2009 for ((label_id, property_name), histogram) in &statistics.property_histograms {
2010 let mut row = graph_statistic_base_row(statistics, "node_property_histogram");
2011 row.insert(
2012 "label_name".to_string(),
2013 optional_string_value(catalog.label_name(*label_id)),
2014 );
2015 row.insert(
2016 "property_name".to_string(),
2017 Value::String(property_name.clone()),
2018 );
2019 row.insert("histogram".to_string(), Value::List(histogram.clone()));
2020 row.insert(
2021 "sampled".to_string(),
2022 Value::Bool(
2023 statistics
2024 .sampled_property_histograms
2025 .get(&(*label_id, property_name.clone()))
2026 .copied()
2027 .unwrap_or(false),
2028 ),
2029 );
2030 rows.push(row);
2031 }
2032 for ((rel_type_id, property_name), histogram) in &statistics.rel_property_histograms {
2033 let mut row = graph_statistic_base_row(statistics, "relationship_property_histogram");
2034 row.insert(
2035 "relationship_type_name".to_string(),
2036 optional_string_value(catalog.rel_type_name(*rel_type_id)),
2037 );
2038 row.insert(
2039 "property_name".to_string(),
2040 Value::String(property_name.clone()),
2041 );
2042 row.insert("histogram".to_string(), Value::List(histogram.clone()));
2043 row.insert(
2044 "sampled".to_string(),
2045 Value::Bool(
2046 statistics
2047 .sampled_rel_property_histograms
2048 .get(&(*rel_type_id, property_name.clone()))
2049 .copied()
2050 .unwrap_or(false),
2051 ),
2052 );
2053 rows.push(row);
2054 }
2055 rows
2056}
2057
2058fn graph_statistic_count_row(statistics: &GraphStatistics, kind: &str, count: u64) -> Row {
2059 let mut row = graph_statistic_base_row(statistics, kind);
2060 row.insert("count".to_string(), u64_value(count));
2061 row
2062}
2063
2064fn populate_index_sample(row: &mut Row, sample: IndexStatisticsSample) {
2065 row.insert("index_size".to_string(), u64_value(sample.index_size));
2066 row.insert("unique_values".to_string(), u64_value(sample.unique_values));
2067 row.insert("sample_size".to_string(), u64_value(sample.sample_size));
2068 row.insert(
2069 "updates_since_sample".to_string(),
2070 u64_value(sample.updates_since_sample),
2071 );
2072 row.insert("stale".to_string(), Value::Bool(sample.is_stale()));
2073}
2074
2075fn graph_statistic_base_row(statistics: &GraphStatistics, kind: &str) -> Row {
2076 BTreeMap::from([
2077 (
2078 "statistic_kind".to_string(),
2079 Value::String(kind.to_string()),
2080 ),
2081 (
2082 "computed_at_commit_epoch".to_string(),
2083 u64_value(statistics.computed_at_commit_epoch),
2084 ),
2085 (
2086 "advanced_statistics_complete".to_string(),
2087 Value::Bool(statistics.advanced_statistics_complete),
2088 ),
2089 (
2090 "histogram_sample_limit".to_string(),
2091 usize_value(statistics.histogram_sample_limit),
2092 ),
2093 ("label_name".to_string(), Value::Null),
2094 ("relationship_type_name".to_string(), Value::Null),
2095 ("source_label_name".to_string(), Value::Null),
2096 ("target_label_name".to_string(), Value::Null),
2097 ("depth".to_string(), Value::Null),
2098 ("property_name".to_string(), Value::Null),
2099 ("index_id".to_string(), Value::Null),
2100 ("index_kind".to_string(), Value::Null),
2101 ("index_properties".to_string(), Value::Null),
2102 ("index_size".to_string(), Value::Null),
2103 ("unique_values".to_string(), Value::Null),
2104 ("sample_size".to_string(), Value::Null),
2105 ("updates_since_sample".to_string(), Value::Null),
2106 ("stale".to_string(), Value::Null),
2107 ("count".to_string(), Value::Null),
2108 ("histogram".to_string(), Value::Null),
2109 ("sampled".to_string(), Value::Null),
2110 ])
2111}
2112
2113fn populate_path_statistic_names(
2114 row: &mut Row,
2115 catalog: &Catalog,
2116 source_label_id: LabelId,
2117 rel_type_id: RelTypeId,
2118 target_label_id: LabelId,
2119) {
2120 row.insert(
2121 "source_label_name".to_string(),
2122 optional_string_value(catalog.label_name(source_label_id)),
2123 );
2124 row.insert(
2125 "relationship_type_name".to_string(),
2126 optional_string_value(catalog.rel_type_name(rel_type_id)),
2127 );
2128 row.insert(
2129 "target_label_name".to_string(),
2130 optional_string_value(catalog.label_name(target_label_id)),
2131 );
2132}
2133
2134fn projected_graph_rows(statuses: Vec<ProjectedGraphStatus>) -> Vec<Row> {
2135 statuses
2136 .into_iter()
2137 .map(|status| {
2138 BTreeMap::from([
2139 ("name".to_string(), Value::String(status.name)),
2140 (
2141 "node_labels".to_string(),
2142 Value::List(status.node_labels.into_iter().map(Value::String).collect()),
2143 ),
2144 (
2145 "relationship_types".to_string(),
2146 Value::List(status.rel_types.into_iter().map(Value::String).collect()),
2147 ),
2148 (
2149 "projection_epoch".to_string(),
2150 option_u64_value(status.projection_epoch),
2151 ),
2152 (
2153 "commit_epoch".to_string(),
2154 option_u64_value(status.commit_epoch),
2155 ),
2156 (
2157 "node_count".to_string(),
2158 option_usize_value(status.node_count),
2159 ),
2160 (
2161 "edge_count".to_string(),
2162 option_usize_value(status.edge_count),
2163 ),
2164 ("reusable".to_string(), Value::Bool(status.reusable)),
2165 ])
2166 })
2167 .collect()
2168}
2169
2170fn search_projection_changefeed_rows(status: SearchProjectionChangefeedStatus) -> Vec<Row> {
2171 vec![BTreeMap::from([
2172 (
2173 "graph_commit_epoch".to_string(),
2174 u64_value(status.graph_commit_epoch),
2175 ),
2176 (
2177 "resume_floor_commit_epoch".to_string(),
2178 u64_value(status.resume_floor_commit_epoch),
2179 ),
2180 (
2181 "oldest_retained_mutation_id".to_string(),
2182 option_u64_value(
2183 status
2184 .oldest_retained_mutation_id
2185 .map(|id| id.commit_epoch()),
2186 ),
2187 ),
2188 (
2189 "newest_retained_mutation_id".to_string(),
2190 option_u64_value(
2191 status
2192 .newest_retained_mutation_id
2193 .map(|id| id.commit_epoch()),
2194 ),
2195 ),
2196 (
2197 "retained_mutation_count".to_string(),
2198 usize_value(status.retained_mutation_count),
2199 ),
2200 (
2201 "restart_recoverable".to_string(),
2202 Value::Bool(status.restart_recoverable),
2203 ),
2204 ])]
2205}
2206
2207fn optional_string_value(value: Option<&str>) -> Value {
2208 value
2209 .map(|value| Value::String(value.to_string()))
2210 .unwrap_or(Value::Null)
2211}
2212
2213const fn table_kind_name(kind: TableKind) -> &'static str {
2214 match kind {
2215 TableKind::Node => "node",
2216 TableKind::Relationship => "relationship",
2217 }
2218}
2219
2220const fn schema_object_state_name(state: SchemaObjectState) -> &'static str {
2221 match state {
2222 SchemaObjectState::DeleteOnly => "delete_only",
2223 SchemaObjectState::WriteOnly => "write_only",
2224 SchemaObjectState::Backfill => "backfill",
2225 SchemaObjectState::Validating => "validating",
2226 SchemaObjectState::Public => "public",
2227 SchemaObjectState::Gc => "gc",
2228 }
2229}
2230
2231fn property_type_name(value_type: PropertyType) -> std::borrow::Cow<'static, str> {
2232 match value_type {
2233 PropertyType::Any => "any",
2234 PropertyType::Bool => "bool",
2235 PropertyType::Int => "int",
2236 PropertyType::Float => "float",
2237 PropertyType::String => "string",
2238 PropertyType::Text => "text",
2239 PropertyType::List => "list",
2240 PropertyType::Vector(dimension) => return format!("vector({})", dimension.get()).into(),
2241 }
2242 .into()
2243}
2244
2245const fn index_kind_name(kind: IndexKind) -> &'static str {
2246 match kind {
2247 IndexKind::Equality => "equality",
2248 IndexKind::Range => "range",
2249 IndexKind::FullText => "full_text",
2250 }
2251}
2252
2253const fn constraint_kind_name(kind: ConstraintKind) -> &'static str {
2254 match kind {
2255 ConstraintKind::NodePropertyUnique => "node_property_unique",
2256 ConstraintKind::NodePropertyExists => "node_property_exists",
2257 ConstraintKind::RelationshipPropertyUnique => "relationship_property_unique",
2258 ConstraintKind::RelationshipPropertyExists => "relationship_property_exists",
2259 }
2260}
2261
2262fn plan_cache_rows(stats: &PlanCacheStats) -> Vec<Row> {
2263 [
2264 ("max_entries", option_usize_value(stats.max_entries)),
2265 ("max_bytes", option_usize_value(stats.max_bytes)),
2266 ("max_entry_bytes", option_usize_value(stats.max_entry_bytes)),
2267 ("charged_bytes", option_usize_value(stats.charged_bytes)),
2268 ("rejected_admissions", u64_value(stats.rejected_admissions)),
2269 ("entries", usize_value(stats.entries)),
2270 ("hits", u64_value(stats.hits)),
2271 ("misses", u64_value(stats.misses)),
2272 ("admissions", u64_value(stats.admissions)),
2273 ("disabled_misses", u64_value(stats.disabled_misses)),
2274 ("bypasses", u64_value(stats.bypasses)),
2275 ("evictions", u64_value(stats.evictions)),
2276 (
2277 "memory_pressure_events",
2278 u64_value(stats.memory_pressure_events),
2279 ),
2280 ]
2281 .into_iter()
2282 .map(|(metric, value)| {
2283 BTreeMap::from([
2284 ("metric".to_string(), Value::String(metric.to_string())),
2285 ("value".to_string(), value),
2286 ])
2287 })
2288 .collect()
2289}
2290
2291fn slow_query_rows(records: &[SlowQueryRecord]) -> Vec<Row> {
2292 records
2293 .iter()
2294 .map(|record| {
2295 BTreeMap::from([
2296 ("sequence".to_string(), u64_value(record.sequence)),
2297 (
2298 "query_language".to_string(),
2299 Value::String(record.query_language.clone()),
2300 ),
2301 (
2302 "statement_kind".to_string(),
2303 Value::String(record.statement_kind.clone()),
2304 ),
2305 (
2306 "query_digest".to_string(),
2307 Value::String(record.query_digest.clone()),
2308 ),
2309 (
2310 "query_text_hash".to_string(),
2311 Value::String(record.query_text_hash.clone()),
2312 ),
2313 (
2314 "query_text".to_string(),
2315 Value::String(record.query_text.clone()),
2316 ),
2317 (
2318 "started_unix_micros".to_string(),
2319 Value::Int(record.started_unix_micros),
2320 ),
2321 (
2322 "elapsed_micros".to_string(),
2323 Value::Int(record.elapsed_micros),
2324 ),
2325 ("row_count".to_string(), Value::Int(record.row_count)),
2326 ("success".to_string(), Value::Bool(record.success)),
2327 (
2328 "error".to_string(),
2329 record
2330 .error
2331 .as_ref()
2332 .map(|error| Value::String(error.clone()))
2333 .unwrap_or(Value::Null),
2334 ),
2335 (
2336 "slow_log_candidate".to_string(),
2337 Value::Bool(record.slow_log_candidate),
2338 ),
2339 (
2340 "access_control_policy_epoch".to_string(),
2341 record
2342 .access_control_policy_epoch
2343 .map(u64_value)
2344 .unwrap_or(Value::Null),
2345 ),
2346 ])
2347 })
2348 .collect()
2349}
2350
2351fn statement_summary_rows(records: &[StatementSummaryRecord]) -> Vec<Row> {
2352 records
2353 .iter()
2354 .map(|record| {
2355 BTreeMap::from([
2356 ("digest".to_string(), Value::String(record.digest.clone())),
2357 (
2358 "query_language".to_string(),
2359 Value::String(record.query_language.clone()),
2360 ),
2361 (
2362 "query_text".to_string(),
2363 Value::String(record.query_text.clone()),
2364 ),
2365 (
2366 "sample_query_text_hash".to_string(),
2367 Value::String(record.sample_query_text_hash.clone()),
2368 ),
2369 (
2370 "statement_kind".to_string(),
2371 Value::String(record.statement_kind.clone()),
2372 ),
2373 (
2374 "execution_count".to_string(),
2375 Value::Int(record.execution_count),
2376 ),
2377 (
2378 "success_count".to_string(),
2379 Value::Int(record.success_count),
2380 ),
2381 ("error_count".to_string(), Value::Int(record.error_count)),
2382 (
2383 "total_elapsed_micros".to_string(),
2384 Value::Int(record.total_elapsed_micros),
2385 ),
2386 (
2387 "max_elapsed_micros".to_string(),
2388 Value::Int(record.max_elapsed_micros),
2389 ),
2390 (
2391 "avg_elapsed_micros".to_string(),
2392 Value::Int(avg_i64(record.total_elapsed_micros, record.execution_count)),
2393 ),
2394 (
2395 "total_row_count".to_string(),
2396 Value::Int(record.total_row_count),
2397 ),
2398 (
2399 "last_seen_unix_micros".to_string(),
2400 Value::Int(record.last_seen_unix_micros),
2401 ),
2402 (
2403 "last_elapsed_micros".to_string(),
2404 Value::Int(record.last_elapsed_micros),
2405 ),
2406 (
2407 "last_row_count".to_string(),
2408 Value::Int(record.last_row_count),
2409 ),
2410 ("last_success".to_string(), Value::Bool(record.last_success)),
2411 (
2412 "last_error".to_string(),
2413 record
2414 .last_error
2415 .as_ref()
2416 .map(|error| Value::String(error.clone()))
2417 .unwrap_or(Value::Null),
2418 ),
2419 ])
2420 })
2421 .collect()
2422}
2423
2424fn predicate_matches(predicate: &SqlPredicate, row: &Row) -> Result<bool> {
2425 Ok(match &predicate.kind {
2426 ExprKind::And(left, right) => {
2427 predicate_matches(left, row)? && predicate_matches(right, row)?
2428 }
2429 ExprKind::Or(left, right) => {
2430 predicate_matches(left, row)? || predicate_matches(right, row)?
2431 }
2432 ExprKind::Not(inner) => !predicate_matches(inner, row)?,
2433 ExprKind::Compare { left, op, right } => {
2434 let left = system_expression_value(left, row)?;
2435 let right = system_expression_value(right, row)?;
2436 compare_values(&left, *op, &right)?
2437 }
2438 ExprKind::InList {
2439 left,
2440 values,
2441 negated,
2442 } => {
2443 let left = system_expression_value(left, row)?;
2444 let mut matched = false;
2445 for value in values {
2446 let value = system_expression_value(value, row)?;
2447 if compare_values(&left, SqlComparisonOp::Eq, &value)? {
2448 matched = true;
2449 break;
2450 }
2451 }
2452 matched != *negated
2453 }
2454 ExprKind::Like {
2455 left,
2456 pattern,
2457 case_insensitive,
2458 negated,
2459 escape,
2460 } => {
2461 let left = system_expression_value(left, row)?;
2462 let pattern = system_expression_value(pattern, row)?;
2463 let (Value::String(value), Value::String(pattern)) = (left.as_ref(), pattern.as_ref())
2464 else {
2465 return Ok(false);
2466 };
2467 hawdb_sql::sql_like_matches(value, pattern, *escape, *case_insensitive)? != *negated
2468 }
2469 ExprKind::IsNull {
2470 expression,
2471 negated,
2472 } => {
2473 matches!(
2474 system_expression_value(expression, row)?.as_ref(),
2475 Value::Null
2476 ) != *negated
2477 }
2478 _ => {
2479 return Err(HawDBError::Semantic(
2480 "unsupported system SQL predicate".into(),
2481 ))
2482 }
2483 })
2484}
2485
2486fn system_expression_value<'a>(
2487 expression: &'a Expr,
2488 row: &'a Row,
2489) -> Result<std::borrow::Cow<'a, Value>> {
2490 use std::borrow::Cow;
2491 let value = match &expression.kind {
2492 ExprKind::Column(column) => Cow::Borrowed(row.get(&column.name).unwrap_or(&Value::Null)),
2493 ExprKind::Value(SqlValue::Literal(value)) => Cow::Borrowed(value),
2494 ExprKind::Arithmetic { left, op, right } => {
2495 let left = system_expression_value(left, row)?;
2496 let right = system_expression_value(right, row)?;
2497 Cow::Owned(hawdb_core::numeric::evaluate_numeric(
2498 left.as_ref().as_ref(),
2499 *op,
2500 right.as_ref().as_ref(),
2501 )?)
2502 }
2503 ExprKind::Negate(expression) => {
2504 let value = system_expression_value(expression, row)?;
2505 Cow::Owned(hawdb_core::numeric::negate_numeric(
2506 value.as_ref().as_ref(),
2507 )?)
2508 }
2509 ExprKind::Cast { expression, target } => {
2510 let value = system_expression_value(expression, row)?;
2511 Cow::Owned(hawdb_core::numeric::cast_numeric(
2512 value.as_ref().as_ref(),
2513 *target,
2514 )?)
2515 }
2516 _ => {
2517 return Err(HawDBError::Semantic(
2518 "unsupported system SQL scalar expression".into(),
2519 ))
2520 }
2521 };
2522 Ok(value)
2523}
2524
2525fn compare_values(left: &Value, op: SqlComparisonOp, right: &Value) -> Result<bool> {
2526 if matches!(left, Value::Null) || matches!(right, Value::Null) {
2527 return Ok(false);
2528 }
2529 let ordering = if left.logical_type().is_some_and(|kind| kind.is_numeric())
2530 && right.logical_type().is_some_and(|kind| kind.is_numeric())
2531 {
2532 hawdb_core::numeric::compare_numeric(left.as_ref(), right.as_ref())?
2533 } else {
2534 left.cmp(right)
2535 };
2536 Ok(match op {
2537 SqlComparisonOp::Eq => ordering.is_eq(),
2538 SqlComparisonOp::NotEq => !ordering.is_eq(),
2539 SqlComparisonOp::Lt => ordering.is_lt(),
2540 SqlComparisonOp::Lte => !ordering.is_gt(),
2541 SqlComparisonOp::Gt => ordering.is_gt(),
2542 SqlComparisonOp::Gte => !ordering.is_lt(),
2543 })
2544}
2545
2546fn compare_ordered_rows(left: &Row, right: &Row, order_by: &[SqlOrderItem]) -> Ordering {
2547 for item in order_by {
2548 let column = item
2549 .expression
2550 .as_column()
2551 .expect("system ORDER BY columns were validated");
2552 let ordering = left.get(&column.name).cmp(&right.get(&column.name));
2553 let ordering = match item.direction {
2554 SqlOrderDirection::Asc => ordering,
2555 SqlOrderDirection::Desc => ordering.reverse(),
2556 };
2557 if ordering != Ordering::Equal {
2558 return ordering;
2559 }
2560 }
2561 Ordering::Equal
2562}
2563
2564fn system_table(select: &SelectStatement) -> Result<SystemTable> {
2565 let from = select.from_table();
2566 match (from.schema.as_deref(), from.name.as_str()) {
2567 (Some("system"), "tables") => Ok(SystemTable::Tables),
2568 (Some("system"), "vector_columns") => Ok(SystemTable::VectorColumns),
2569 (Some("system"), "properties") => Ok(SystemTable::Properties),
2570 (Some("system"), "indexes") => Ok(SystemTable::Indexes),
2571 (Some("system"), "constraints") => Ok(SystemTable::Constraints),
2572 (Some("system"), "append_tables") => Ok(SystemTable::AppendTables),
2573 (Some("system"), "append_storage") => Ok(SystemTable::AppendStorage),
2574 (Some("system"), "runtime_status") => Ok(SystemTable::RuntimeStatus),
2575 (Some("system"), "runtime_capabilities") => Ok(SystemTable::RuntimeCapabilities),
2576 (Some("system"), "graph_statistics") => Ok(SystemTable::GraphStatistics),
2577 (Some("system"), "projected_graphs") => Ok(SystemTable::ProjectedGraphs),
2578 (Some("system"), "search_projection_changefeed") => {
2579 Ok(SystemTable::SearchProjectionChangefeed)
2580 }
2581 (Some("system"), "plan_cache") => Ok(SystemTable::PlanCache),
2582 (Some("system"), "slow_queries") => Ok(SystemTable::SlowQueries),
2583 (Some("system"), "statement_summary") => Ok(SystemTable::StatementSummary),
2584 (Some("information_schema"), "tables") => Ok(SystemTable::InformationSchemaTables),
2585 (Some("information_schema"), "columns") => Ok(SystemTable::InformationSchemaColumns),
2586 (Some("pg_catalog"), "pg_tables") => Ok(SystemTable::PgTables),
2587 (Some("pg_catalog"), "pg_indexes") => Ok(SystemTable::PgIndexes),
2588 (None, "pg_tables") => Ok(SystemTable::PgTables),
2589 (None, "pg_indexes") => Ok(SystemTable::PgIndexes),
2590 _ => Err(HawDBError::Semantic(format!(
2591 "unknown SQL virtual catalog table {}",
2592 format_table_name(select)
2593 ))),
2594 }
2595}
2596
2597fn validate_projection(table: SystemTable, projection: &[SelectProjection]) -> Result<()> {
2598 for projection in projection {
2599 match projection {
2600 SelectProjection::Wildcard => {}
2601 SelectProjection::Expression {
2602 expression:
2603 Expr {
2604 kind: ExprKind::Column(name),
2605 ..
2606 },
2607 ..
2608 } => validate_column(table, name)?,
2609 SelectProjection::Expression { .. } => {
2610 return Err(HawDBError::Semantic(
2611 "system SQL aggregate expressions are not supported".to_string(),
2612 ));
2613 }
2614 }
2615 }
2616 Ok(())
2617}
2618
2619fn validate_predicate_columns(table: SystemTable, predicate: Option<&SqlPredicate>) -> Result<()> {
2620 let mut result = Ok(());
2621 if let Some(predicate) = predicate {
2622 predicate.visit(&mut |expression| {
2623 if result.is_ok()
2624 && let Some(column) = expression.as_column()
2625 {
2626 result = validate_column(table, column);
2627 }
2628 });
2629 }
2630 result
2631}
2632
2633fn validate_order_columns(table: SystemTable, order_by: &[SqlOrderItem]) -> Result<()> {
2634 for item in order_by {
2635 validate_column(table, item.expression.require_column()?)?;
2636 }
2637 Ok(())
2638}
2639
2640fn validate_column(table: SystemTable, column: &SqlColumnRef) -> Result<()> {
2641 if let Some(qualifier) = &column.qualifier {
2642 let table_name = match table {
2643 SystemTable::Tables => "tables",
2644 SystemTable::VectorColumns => "vector_columns",
2645 SystemTable::Properties => "properties",
2646 SystemTable::Indexes => "indexes",
2647 SystemTable::Constraints => "constraints",
2648 SystemTable::AppendTables => "append_tables",
2649 SystemTable::AppendStorage => "append_storage",
2650 SystemTable::RuntimeStatus => "runtime_status",
2651 SystemTable::RuntimeCapabilities => "runtime_capabilities",
2652 SystemTable::GraphStatistics => "graph_statistics",
2653 SystemTable::ProjectedGraphs => "projected_graphs",
2654 SystemTable::SearchProjectionChangefeed => "search_projection_changefeed",
2655 SystemTable::PlanCache => "plan_cache",
2656 SystemTable::SlowQueries => "slow_queries",
2657 SystemTable::StatementSummary => "statement_summary",
2658 SystemTable::InformationSchemaTables => "tables",
2659 SystemTable::InformationSchemaColumns => "columns",
2660 SystemTable::PgTables => "pg_tables",
2661 SystemTable::PgIndexes => "pg_indexes",
2662 };
2663 if qualifier != table_name {
2664 return Err(HawDBError::Semantic(format!(
2665 "unknown SQL column qualifier {qualifier}"
2666 )));
2667 }
2668 }
2669 if table_columns(table).contains(&column.name.as_str()) {
2670 Ok(())
2671 } else {
2672 Err(HawDBError::Semantic(format!(
2673 "unknown SQL column {}",
2674 column.name
2675 )))
2676 }
2677}
2678
2679fn table_columns(table: SystemTable) -> &'static [&'static str] {
2680 match table {
2681 SystemTable::Tables => &["table_id", "table_name", "table_kind", "state"],
2682 SystemTable::VectorColumns => &[
2683 "table_schema",
2684 "table_name",
2685 "column_name",
2686 "dimensions",
2687 "element_type",
2688 "nullable",
2689 ],
2690 SystemTable::Properties => &[
2691 "property_id",
2692 "table_id",
2693 "table_name",
2694 "table_kind",
2695 "property_name",
2696 "value_type",
2697 "nullable",
2698 "state",
2699 ],
2700 SystemTable::Indexes => &[
2701 "index_id",
2702 "subject_kind",
2703 "subject_id",
2704 "subject_name",
2705 "index_kind",
2706 "property_names",
2707 ],
2708 SystemTable::Constraints => &[
2709 "constraint_id",
2710 "subject_kind",
2711 "subject_id",
2712 "subject_name",
2713 "property_name",
2714 "constraint_kind",
2715 ],
2716 SystemTable::AppendTables => &[
2717 "table_name",
2718 "storage_mode",
2719 "partition_key",
2720 "order_key",
2721 "order_mode",
2722 "generated_order_watermark",
2723 "column_count",
2724 ],
2725 SystemTable::AppendStorage => &[
2726 "canonical_segment_count",
2727 "canonical_segment_bytes",
2728 "resident_segment_payload_bytes",
2729 "resident_descriptor_count",
2730 "live_rows",
2731 "live_payload_bytes",
2732 ],
2733 SystemTable::RuntimeStatus => &[
2734 "commit_epoch",
2735 "read_only",
2736 "max_read_result_rows",
2737 "max_read_result_payload_bytes",
2738 "storage_residency_mode",
2739 "relational_index_mode",
2740 ],
2741 SystemTable::RuntimeCapabilities => &["capability", "enabled"],
2742 SystemTable::GraphStatistics => &[
2743 "statistic_kind",
2744 "computed_at_commit_epoch",
2745 "advanced_statistics_complete",
2746 "histogram_sample_limit",
2747 "label_name",
2748 "relationship_type_name",
2749 "source_label_name",
2750 "target_label_name",
2751 "depth",
2752 "property_name",
2753 "index_id",
2754 "index_kind",
2755 "index_properties",
2756 "index_size",
2757 "unique_values",
2758 "sample_size",
2759 "updates_since_sample",
2760 "stale",
2761 "count",
2762 "histogram",
2763 "sampled",
2764 ],
2765 SystemTable::ProjectedGraphs => &[
2766 "name",
2767 "node_labels",
2768 "relationship_types",
2769 "projection_epoch",
2770 "commit_epoch",
2771 "node_count",
2772 "edge_count",
2773 "reusable",
2774 ],
2775 SystemTable::SearchProjectionChangefeed => &[
2776 "graph_commit_epoch",
2777 "resume_floor_commit_epoch",
2778 "oldest_retained_mutation_id",
2779 "newest_retained_mutation_id",
2780 "retained_mutation_count",
2781 "restart_recoverable",
2782 ],
2783 SystemTable::PlanCache => &["metric", "value"],
2784 SystemTable::SlowQueries => &[
2785 "sequence",
2786 "query_language",
2787 "statement_kind",
2788 "query_digest",
2789 "query_text_hash",
2790 "query_text",
2791 "started_unix_micros",
2792 "elapsed_micros",
2793 "row_count",
2794 "success",
2795 "error",
2796 "slow_log_candidate",
2797 "access_control_policy_epoch",
2798 ],
2799 SystemTable::StatementSummary => &[
2800 "digest",
2801 "query_language",
2802 "query_text",
2803 "sample_query_text_hash",
2804 "statement_kind",
2805 "execution_count",
2806 "success_count",
2807 "error_count",
2808 "total_elapsed_micros",
2809 "max_elapsed_micros",
2810 "avg_elapsed_micros",
2811 "total_row_count",
2812 "last_seen_unix_micros",
2813 "last_elapsed_micros",
2814 "last_row_count",
2815 "last_success",
2816 "last_error",
2817 ],
2818 SystemTable::InformationSchemaTables => &[
2819 "table_catalog",
2820 "table_schema",
2821 "table_name",
2822 "table_type",
2823 "self_referencing_column_name",
2824 "reference_generation",
2825 "user_defined_type_catalog",
2826 "user_defined_type_schema",
2827 "user_defined_type_name",
2828 "is_insertable_into",
2829 "is_typed",
2830 "commit_action",
2831 ],
2832 SystemTable::InformationSchemaColumns => &[
2833 "table_catalog",
2834 "table_schema",
2835 "table_name",
2836 "column_name",
2837 "ordinal_position",
2838 "column_default",
2839 "is_nullable",
2840 "data_type",
2841 "character_maximum_length",
2842 "character_octet_length",
2843 "numeric_precision",
2844 "numeric_precision_radix",
2845 "numeric_scale",
2846 "datetime_precision",
2847 "interval_type",
2848 "interval_precision",
2849 "character_set_catalog",
2850 "character_set_schema",
2851 "character_set_name",
2852 "collation_catalog",
2853 "collation_schema",
2854 "collation_name",
2855 "domain_catalog",
2856 "domain_schema",
2857 "domain_name",
2858 "udt_catalog",
2859 "udt_schema",
2860 "udt_name",
2861 "scope_catalog",
2862 "scope_schema",
2863 "scope_name",
2864 "maximum_cardinality",
2865 "dtd_identifier",
2866 "is_self_referencing",
2867 "is_identity",
2868 "identity_generation",
2869 "identity_start",
2870 "identity_increment",
2871 "identity_maximum",
2872 "identity_minimum",
2873 "identity_cycle",
2874 "is_generated",
2875 "generation_expression",
2876 "is_updatable",
2877 ],
2878 SystemTable::PgTables => &[
2879 "schemaname",
2880 "tablename",
2881 "tableowner",
2882 "tablespace",
2883 "hasindexes",
2884 "hasrules",
2885 "hastriggers",
2886 "rowsecurity",
2887 ],
2888 SystemTable::PgIndexes => &[
2889 "schemaname",
2890 "tablename",
2891 "indexname",
2892 "tablespace",
2893 "indexdef",
2894 ],
2895 }
2896}
2897
2898fn format_table_name(select: &SelectStatement) -> String {
2899 let from = select.from_table();
2900 match &from.schema {
2901 Some(schema) => format!("{schema}.{}", from.name),
2902 None => from.name.clone(),
2903 }
2904}
2905
2906fn option_usize_value(value: Option<usize>) -> Value {
2907 value.map(usize_value).unwrap_or(Value::Null)
2908}
2909
2910fn option_i64_value(value: Option<i64>) -> Value {
2911 value.map(Value::Int).unwrap_or(Value::Null)
2912}
2913
2914fn option_u64_value(value: Option<u64>) -> Value {
2915 value.map(u64_value).unwrap_or(Value::Null)
2916}
2917
2918fn usize_value(value: usize) -> Value {
2919 Value::Int(i64::try_from(value).unwrap_or(i64::MAX))
2920}
2921
2922fn u32_value(value: u32) -> Value {
2923 Value::Int(i64::from(value))
2924}
2925
2926fn u64_value(value: u64) -> Value {
2927 Value::Int(i64::try_from(value).unwrap_or(i64::MAX))
2928}
2929
2930const fn storage_residency_mode_name(mode: StorageResidencyMode) -> &'static str {
2931 match mode {
2932 StorageResidencyMode::Auto => "auto",
2933 StorageResidencyMode::Materialized => "materialized",
2934 StorageResidencyMode::OutOfCore => "out_of_core",
2935 }
2936}
2937
2938const fn relational_index_mode_name(mode: RelationalIndexMode) -> &'static str {
2939 match mode {
2940 RelationalIndexMode::Materialized => "materialized",
2941 RelationalIndexMode::Shadow => "shadow",
2942 RelationalIndexMode::DemandPaged => "demand_paged",
2943 RelationalIndexMode::Authoritative => "authoritative",
2944 }
2945}
2946
2947fn avg_i64(total: i64, count: i64) -> i64 {
2948 if count <= 0 {
2949 0
2950 } else {
2951 total / count
2952 }
2953}
2954
2955fn saturating_i64_from_u128(value: u128) -> i64 {
2956 i64::try_from(value).unwrap_or(i64::MAX)
2957}
2958
2959fn unix_now_micros() -> i64 {
2960 let micros = SystemTime::now()
2961 .duration_since(UNIX_EPOCH)
2962 .map(|duration| duration.as_micros())
2963 .unwrap_or(0);
2964 saturating_i64_from_u128(micros)
2965}
2966
2967fn truncate_utf8(input: &str, max_bytes: usize) -> String {
2968 if input.len() <= max_bytes {
2969 return input.to_string();
2970 }
2971 let mut end = max_bytes;
2972 while !input.is_char_boundary(end) {
2973 end -= 1;
2974 }
2975 input[..end].to_string()
2976}
2977
2978mod graph_store_adapter;
2979
2980#[cfg(test)]
2981mod statement_summary_tests;
2982
2983#[cfg(test)]
2984mod tests {
2985 use super::*;
2986
2987 #[test]
2988 fn catalog_numeric_predicates_share_exact_arithmetic_and_comparison() {
2989 let row = BTreeMap::from([("value".into(), Value::Int(9_007_199_254_740_993))]);
2990 for sql in [
2991 "SELECT value FROM system.plan_cache WHERE value = 9007199254740993.00",
2992 "SELECT value FROM system.plan_cache WHERE CAST(value AS DECIMAL(38,2)) + 0.01 = $1",
2993 "SELECT value FROM system.plan_cache WHERE value IN (9007199254740993.00)",
2994 ] {
2995 let SqlStatement::Select(select) = hawdb_sql::parse_postgres_sql(sql).unwrap() else {
2996 panic!("SELECT");
2997 };
2998 let predicate = bind_predicate(
2999 select.selection.unwrap(),
3000 &[Value::Decimal("9007199254740993.01".parse().unwrap())],
3001 )
3002 .unwrap();
3003 assert!(predicate_matches(&predicate, &row).unwrap(), "{sql}");
3004 }
3005 let SqlStatement::Select(select) = hawdb_sql::parse_postgres_sql(
3006 "SELECT value FROM system.plan_cache WHERE value / 0 > 1",
3007 )
3008 .unwrap() else {
3009 panic!("SELECT");
3010 };
3011 assert!(predicate_matches(&select.selection.unwrap(), &row).is_err());
3012 }
3013
3014 #[derive(Debug, Default)]
3015 struct TestStore;
3016
3017 impl SystemSqlStore for TestStore {
3018 fn commit_epoch(&self) -> u64 {
3019 0
3020 }
3021
3022 fn append_storage_residency_report(&self) -> AppendStorageResidencyReport {
3023 AppendStorageResidencyReport::default()
3024 }
3025
3026 fn statistics(&self, _catalog: &Catalog) -> GraphStatistics {
3027 GraphStatistics::default()
3028 }
3029
3030 fn projected_graph_statuses(&self) -> Vec<ProjectedGraphStatus> {
3031 Vec::new()
3032 }
3033
3034 fn search_projection_changefeed_status(&self) -> SearchProjectionChangefeedStatus {
3035 SearchProjectionChangefeedStatus {
3036 graph_commit_epoch: 0,
3037 resume_floor_commit_epoch: 0,
3038 oldest_retained_mutation_id: None,
3039 newest_retained_mutation_id: None,
3040 first_rebuild_required_mutation_id: None,
3041 retained_mutation_count: 0,
3042 retained_bytes: 0,
3043 max_retained_bytes: None,
3044 restart_recoverable: true,
3045 }
3046 }
3047 }
3048
3049 fn default_runtime() -> SystemRuntimeSnapshot {
3050 SystemRuntimeSnapshot::new(
3051 false,
3052 Some(512),
3053 Some(4 * 1024 * 1024),
3054 StorageResidencyMode::Auto,
3055 RelationalIndexMode::default(),
3056 RuntimeCapabilities::default(),
3057 )
3058 }
3059
3060 #[test]
3061 fn predicate_binding_preserves_source_spans_and_system_null_behavior() {
3062 let SqlStatement::Select(select) = hawdb_sql::prepare_postgres_sql(
3063 "SELECT value FROM system.plan_cache WHERE \
3064 (value IN ($1, $2) OR NOT value = $3) AND \
3065 (metric LIKE $4 OR value IS NULL)",
3066 )
3067 .unwrap()
3068 .statement
3069 else {
3070 panic!("expected SELECT");
3071 };
3072 let predicate = select.selection.unwrap();
3073 let mut before = Vec::new();
3074 predicate.visit(&mut |node| before.push(node.span));
3075 let bound = bind_predicate(
3076 predicate.clone(),
3077 &[
3078 Value::Null,
3079 Value::Int(5),
3080 Value::Null,
3081 Value::String("hit%".to_owned()),
3082 ],
3083 )
3084 .unwrap();
3085 let mut after = Vec::new();
3086 let mut parameters = Vec::new();
3087 bound.visit(&mut |node| {
3088 after.push(node.span);
3089 if let ExprKind::Value(SqlValue::Parameter(position)) = &node.kind {
3090 parameters.push(*position);
3091 }
3092 });
3093 assert_eq!(after, before);
3094 assert!(parameters.is_empty());
3095 assert!(predicate_matches(
3096 &bound,
3097 &BTreeMap::from([
3098 ("value".to_owned(), Value::Null),
3099 ("metric".to_owned(), Value::String("misses".to_owned())),
3100 ])
3101 )
3102 .unwrap());
3103 assert!(bind_predicate(
3104 predicate,
3105 &[
3106 Value::Null,
3107 Value::Int(5),
3108 Value::Null,
3109 Value::String("dangling\\".to_owned()),
3110 ]
3111 )
3112 .unwrap_err()
3113 .to_string()
3114 .contains("ends with its escape"));
3115 }
3116
3117 #[test]
3118 fn query_plan_cache_virtual_table_with_predicate_and_projection() {
3119 let catalog = Catalog::default();
3120 let store = TestStore;
3121 let relational_state = RelationalState::default();
3122 let append_state = AppendState::default();
3123 let stats = PlanCacheStats {
3124 max_bytes: Some(16384),
3125 max_entry_bytes: Some(8192),
3126 charged_bytes: Some(4096),
3127 rejected_admissions: 2,
3128 max_entries: Some(128),
3129 entries: 3,
3130 hits: 5,
3131 misses: 7,
3132 admissions: 4,
3133 disabled_misses: 0,
3134 bypasses: 2,
3135 evictions: 1,
3136 memory_pressure_events: 1,
3137 };
3138
3139 let context = SystemSqlContext {
3140 catalog: &catalog,
3141 store: &store,
3142 relational_state: &relational_state,
3143 append_state: &append_state,
3144 runtime: default_runtime(),
3145 plan_cache_stats: &stats,
3146 slow_queries: &[],
3147 statement_summaries: &[],
3148 };
3149 let sql = "SELECT value FROM system.plan_cache WHERE metric = 'hits'";
3150 let output = query_sql(sql, None, None, &context).expect("system plan cache query");
3151
3152 assert_eq!(
3153 output.rows,
3154 vec![BTreeMap::from([("value".to_string(), Value::Int(5))])]
3155 );
3156 let payload_bytes = output.payload_bytes();
3157 for (metric, expected) in [
3158 ("max_bytes", 16384),
3159 ("max_entry_bytes", 8192),
3160 ("charged_bytes", 4096),
3161 ("rejected_admissions", 2),
3162 ] {
3163 let output = query_sql(
3164 &format!("SELECT value FROM system.plan_cache WHERE metric = '{metric}'"),
3165 Some(1),
3166 Some(1024),
3167 &context,
3168 )
3169 .unwrap();
3170 assert_eq!(
3171 output.rows,
3172 vec![BTreeMap::from([("value".into(), Value::Int(expected))])]
3173 );
3174 }
3175 let exact = query_sql(sql, Some(1), Some(payload_bytes), &context).unwrap();
3176 assert_eq!(exact.rows, output.rows);
3177 for (rows, payload, resource, limit) in [
3178 (Some(0), Some(0), hawdb_core::ReadBudgetResource::Rows, 0),
3179 (
3180 Some(1),
3181 Some(payload_bytes - 1),
3182 hawdb_core::ReadBudgetResource::PayloadBytes,
3183 payload_bytes - 1,
3184 ),
3185 ] {
3186 let error = query_sql(sql, rows, payload, &context).unwrap_err();
3187 assert!(
3188 matches!(&error, HawDBError::ReadBudgetExceeded(cause)
3189 if cause.resource == resource && cause.limit == limit),
3190 "system SQL lost its result budget cause: {error}"
3191 );
3192 }
3193 }
3194
3195 #[test]
3196 fn query_system_table_with_postgres_parameters() {
3197 let catalog = Catalog::default();
3198 let store = TestStore;
3199 let relational_state = RelationalState::default();
3200 let append_state = AppendState::default();
3201 let stats = PlanCacheStats {
3202 max_bytes: None,
3203 max_entry_bytes: None,
3204 charged_bytes: None,
3205 rejected_admissions: 0,
3206 max_entries: Some(128),
3207 entries: 3,
3208 hits: 5,
3209 misses: 7,
3210 admissions: 4,
3211 disabled_misses: 0,
3212 bypasses: 2,
3213 evictions: 1,
3214 memory_pressure_events: 1,
3215 };
3216 let context = SystemSqlContext {
3217 catalog: &catalog,
3218 store: &store,
3219 relational_state: &relational_state,
3220 append_state: &append_state,
3221 runtime: default_runtime(),
3222 plan_cache_stats: &stats,
3223 slow_queries: &[],
3224 statement_summaries: &[],
3225 };
3226
3227 let output = query_sql_with_params(
3228 "SELECT metric, value FROM system.plan_cache \
3229 WHERE metric IN ($1, $2) ORDER BY metric ASC LIMIT $3 OFFSET $4",
3230 &[
3231 Value::String("hits".to_string()),
3232 Value::String("misses".to_string()),
3233 Value::Int(1),
3234 Value::Int(1),
3235 ],
3236 None,
3237 None,
3238 &context,
3239 )
3240 .expect("parameterized system table query");
3241
3242 assert_eq!(
3243 output.rows,
3244 vec![BTreeMap::from([
3245 ("metric".to_string(), Value::String("misses".to_string())),
3246 ("value".to_string(), Value::Int(7)),
3247 ])]
3248 );
3249 }
3250
3251 #[test]
3252 fn query_system_table_rejects_parameter_contract_mismatch() {
3253 let catalog = Catalog::default();
3254 let store = TestStore;
3255 let relational_state = RelationalState::default();
3256 let append_state = AppendState::default();
3257 let stats = PlanCacheStats {
3258 max_bytes: None,
3259 max_entry_bytes: None,
3260 charged_bytes: None,
3261 rejected_admissions: 0,
3262 max_entries: None,
3263 entries: 0,
3264 hits: 0,
3265 misses: 0,
3266 admissions: 0,
3267 disabled_misses: 0,
3268 bypasses: 0,
3269 evictions: 0,
3270 memory_pressure_events: 0,
3271 };
3272 let context = SystemSqlContext {
3273 catalog: &catalog,
3274 store: &store,
3275 relational_state: &relational_state,
3276 append_state: &append_state,
3277 runtime: default_runtime(),
3278 plan_cache_stats: &stats,
3279 slow_queries: &[],
3280 statement_summaries: &[],
3281 };
3282
3283 let missing = query_sql_with_params(
3284 "SELECT * FROM system.plan_cache WHERE metric = $1",
3285 &[],
3286 None,
3287 None,
3288 &context,
3289 )
3290 .expect_err("missing parameter must fail");
3291 assert!(missing.to_string().contains("requires 1 parameters"));
3292
3293 let invalid_bound = query_sql_with_params(
3294 "SELECT * FROM system.plan_cache LIMIT $1",
3295 &[Value::String("one".to_string())],
3296 None,
3297 None,
3298 &context,
3299 )
3300 .expect_err("non-integer LIMIT must fail");
3301 assert!(invalid_bound
3302 .to_string()
3303 .contains("must be a non-negative integer"));
3304 }
3305
3306 #[test]
3307 fn query_slow_queries_pushes_filter_order_and_limit_into_scan() {
3308 let catalog = Catalog::default();
3309 let store = TestStore;
3310 let relational_state = RelationalState::default();
3311 let append_state = AppendState::default();
3312 let stats = PlanCacheStats {
3313 max_bytes: None,
3314 max_entry_bytes: None,
3315 charged_bytes: None,
3316 rejected_admissions: 0,
3317 max_entries: None,
3318 entries: 0,
3319 hits: 0,
3320 misses: 0,
3321 admissions: 0,
3322 disabled_misses: 0,
3323 bypasses: 0,
3324 evictions: 0,
3325 memory_pressure_events: 0,
3326 };
3327 let records = vec![
3328 SlowQueryRecord {
3329 sequence: 1,
3330 query_language: "cypher".to_string(),
3331 statement_kind: "match_return".to_string(),
3332 query_digest: "q1:first".to_string(),
3333 query_text_hash: "t1:first".to_string(),
3334 query_text: "MATCH (m:Memory) RETURN m".to_string(),
3335 started_unix_micros: 10,
3336 elapsed_micros: 200,
3337 row_count: 1,
3338 success: true,
3339 error: None,
3340 slow_log_candidate: false,
3341 access_control_policy_epoch: None,
3342 vector_execution_reports: Vec::new(),
3343 },
3344 SlowQueryRecord {
3345 sequence: 2,
3346 query_language: "cypher".to_string(),
3347 statement_kind: "match_return".to_string(),
3348 query_digest: "q1:second".to_string(),
3349 query_text_hash: "t1:second".to_string(),
3350 query_text: "MATCH (m:Memory) RETURN m ORDER BY m.id".to_string(),
3351 started_unix_micros: 20,
3352 elapsed_micros: 500,
3353 row_count: 2,
3354 success: true,
3355 error: None,
3356 slow_log_candidate: true,
3357 access_control_policy_epoch: None,
3358 vector_execution_reports: Vec::new(),
3359 },
3360 SlowQueryRecord {
3361 sequence: 3,
3362 query_language: "cypher".to_string(),
3363 statement_kind: "match_return".to_string(),
3364 query_digest: "q1:third".to_string(),
3365 query_text_hash: "t1:third".to_string(),
3366 query_text: "MATCH (m:Memory {id: 'x'}) RETURN m".to_string(),
3367 started_unix_micros: 30,
3368 elapsed_micros: 300,
3369 row_count: 1,
3370 success: true,
3371 error: None,
3372 slow_log_candidate: true,
3373 access_control_policy_epoch: None,
3374 vector_execution_reports: Vec::new(),
3375 },
3376 ];
3377
3378 let output = query_sql(
3379 "SELECT sequence, elapsed_micros FROM system.slow_queries \
3380 WHERE slow_log_candidate = true \
3381 ORDER BY elapsed_micros DESC LIMIT 1",
3382 None,
3383 None,
3384 &SystemSqlContext {
3385 catalog: &catalog,
3386 store: &store,
3387 relational_state: &relational_state,
3388 append_state: &append_state,
3389 runtime: default_runtime(),
3390 plan_cache_stats: &stats,
3391 slow_queries: &records,
3392 statement_summaries: &[],
3393 },
3394 )
3395 .expect("system slow query scan");
3396
3397 assert_eq!(
3398 output.rows,
3399 vec![BTreeMap::from([
3400 ("elapsed_micros".to_string(), Value::Int(500)),
3401 ("sequence".to_string(), Value::Int(2)),
3402 ])]
3403 );
3404 }
3405
3406 #[test]
3407 fn query_catalog_virtual_tables_expose_schema_without_typed_getters() {
3408 let mut catalog = Catalog::default();
3409 let store = TestStore;
3410 let relational_state = RelationalState::default();
3411 let append_state = AppendState::default();
3412 let memory_label = catalog.get_or_create_label("Memory");
3413 let memory_table = catalog.get_or_create_table(TableKind::Node, "Memory");
3414 catalog.get_or_create_property(memory_table, "id", PropertyType::String, false);
3415 catalog.get_or_create_property_index_with_kind(memory_label, "id", IndexKind::Equality);
3416 catalog.get_or_create_unique_constraint(memory_label, "id");
3417 let stats = PlanCacheStats {
3418 max_bytes: None,
3419 max_entry_bytes: None,
3420 charged_bytes: None,
3421 rejected_admissions: 0,
3422 max_entries: None,
3423 entries: 0,
3424 hits: 0,
3425 misses: 0,
3426 admissions: 0,
3427 disabled_misses: 0,
3428 bypasses: 0,
3429 evictions: 0,
3430 memory_pressure_events: 0,
3431 };
3432 let context = SystemSqlContext {
3433 catalog: &catalog,
3434 store: &store,
3435 relational_state: &relational_state,
3436 append_state: &append_state,
3437 runtime: default_runtime(),
3438 plan_cache_stats: &stats,
3439 slow_queries: &[],
3440 statement_summaries: &[],
3441 };
3442
3443 let tables = query_sql(
3444 "SELECT table_id, table_name, table_kind, state FROM system.tables",
3445 None,
3446 None,
3447 &context,
3448 )
3449 .expect("system tables query");
3450 assert_eq!(
3451 tables.rows,
3452 vec![BTreeMap::from([
3453 ("state".to_string(), Value::String("public".to_string())),
3454 ("table_id".to_string(), Value::Int(0)),
3455 ("table_kind".to_string(), Value::String("node".to_string()),),
3456 (
3457 "table_name".to_string(),
3458 Value::String("Memory".to_string()),
3459 ),
3460 ])]
3461 );
3462
3463 let properties = query_sql(
3464 "SELECT table_name, property_name, value_type, nullable \
3465 FROM system.properties WHERE table_name = 'Memory'",
3466 None,
3467 None,
3468 &context,
3469 )
3470 .expect("system properties query");
3471 assert_eq!(
3472 properties.rows,
3473 vec![BTreeMap::from([
3474 ("nullable".to_string(), Value::Bool(false)),
3475 ("property_name".to_string(), Value::String("id".to_string()),),
3476 (
3477 "table_name".to_string(),
3478 Value::String("Memory".to_string()),
3479 ),
3480 (
3481 "value_type".to_string(),
3482 Value::String("string".to_string()),
3483 ),
3484 ])]
3485 );
3486
3487 let indexes = query_sql(
3488 "SELECT subject_name, index_kind, property_names FROM system.indexes",
3489 None,
3490 None,
3491 &context,
3492 )
3493 .expect("system indexes query");
3494 assert_eq!(
3495 indexes.rows,
3496 vec![BTreeMap::from([
3497 (
3498 "index_kind".to_string(),
3499 Value::String("equality".to_string()),
3500 ),
3501 (
3502 "property_names".to_string(),
3503 Value::List(vec![Value::String("id".to_string())]),
3504 ),
3505 (
3506 "subject_name".to_string(),
3507 Value::String("Memory".to_string()),
3508 ),
3509 ])]
3510 );
3511
3512 let constraints = query_sql(
3513 "SELECT subject_name, property_name, constraint_kind FROM system.constraints",
3514 None,
3515 None,
3516 &context,
3517 )
3518 .expect("system constraints query");
3519 assert_eq!(
3520 constraints.rows,
3521 vec![BTreeMap::from([
3522 (
3523 "constraint_kind".to_string(),
3524 Value::String("node_property_unique".to_string()),
3525 ),
3526 ("property_name".to_string(), Value::String("id".to_string()),),
3527 (
3528 "subject_name".to_string(),
3529 Value::String("Memory".to_string()),
3530 ),
3531 ])]
3532 );
3533 }
3534}
3535
3536#[cfg(all(test, feature = "loom-tests"))]
3537pub(crate) mod loom_tests {
3538 use super::{SlowQueryCompletion, SlowQueryLog, SlowQueryRecord};
3539 use hawdb_query::QueryIdentity;
3540 use loom::sync::{Arc, Mutex};
3541 use loom::thread;
3542
3543 #[test]
3544 fn slow_query_ring_preserves_bounds_under_modeled_concurrent_access() {
3545 loom::model(|| {
3546 let log = Arc::new(Mutex::new(SlowQueryLog::new(2)));
3547
3548 let first_writer = spawn_slow_query_writer(Arc::clone(&log), "first");
3549 let second_writer = spawn_slow_query_writer(Arc::clone(&log), "second");
3550 let snapshotter = {
3551 let log = Arc::clone(&log);
3552 thread::spawn(move || {
3553 let snapshot = log.lock().unwrap().snapshot();
3554 assert_snapshot_invariants(&snapshot, 2);
3555 })
3556 };
3557
3558 first_writer.join().unwrap();
3559 second_writer.join().unwrap();
3560 snapshotter.join().unwrap();
3561
3562 let snapshot = log.lock().unwrap().snapshot();
3563 assert_snapshot_invariants(&snapshot, 2);
3564 assert_eq!(snapshot.len(), 2);
3565 assert_eq!(snapshot.last().map(|record| record.sequence), Some(2));
3566 });
3567 }
3568
3569 fn spawn_slow_query_writer(
3570 log: Arc<Mutex<SlowQueryLog>>,
3571 query_text: &'static str,
3572 ) -> thread::JoinHandle<()> {
3573 thread::spawn(move || {
3574 let query_identity = QueryIdentity::new("cypher", query_text);
3575 log.lock()
3576 .unwrap()
3577 .push(SlowQueryRecord::completed(SlowQueryCompletion {
3578 query_language: "cypher",
3579 statement_kind: "match_return",
3580 query_text,
3581 query_identity: &query_identity,
3582 elapsed_micros: 1,
3583 row_count: 1,
3584 success: true,
3585 error: None,
3586 slow_log_candidate: true,
3587 access_control_policy_epoch: None,
3588 vector_execution_reports: Vec::new(),
3589 }));
3590 })
3591 }
3592
3593 fn assert_snapshot_invariants(snapshot: &[SlowQueryRecord], capacity: usize) {
3594 assert!(snapshot.len() <= capacity);
3595 for pair in snapshot.windows(2) {
3596 assert!(pair[0].sequence < pair[1].sequence);
3597 }
3598 }
3599}