hawdb 0.5.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{
    system_sql, BranchInfo, Database, QueryOutput, QueryStreamOptions, SharedState,
    SlowQueryLogExportOptions, SlowQueryLogRecordSummary, StatementExecutionContext,
};
use crate::error::{HawDBError, Result};
use crate::executor;
use crate::relational_sql::{
    compile_append_statement_sql, compile_prepared_append_explain_sql,
    compile_prepared_append_select_sql, compile_relational_statement_sql_with_result,
    format_append_explain, project_append_rows,
};
use crate::sql::{
    BranchSqlSelector, BranchSqlStatement, BranchSqlValue, ShowBranchesStatement, SqlBound,
    SqlStatement,
};
use crate::telemetry::{QueryTelemetry, TelemetrySink};
use crate::value::Value;
use hawdb_storage::branch_catalog as storage;
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;

pub(super) fn sql_statement_kind(statement: &SqlStatement) -> &'static str {
    match statement {
        SqlStatement::Select(_) => "select",
        SqlStatement::Insert(_) => "insert",
        SqlStatement::Update(_) => "update",
        SqlStatement::Delete(_) => "delete",
        SqlStatement::CreateTable(_) => "create_table",
        SqlStatement::CreateIndex(_) => "create_index",
        SqlStatement::AlterTableAddColumn(_) => "alter_table_add_column",
        SqlStatement::Explain(_) => "explain",
        SqlStatement::Branch(_) => "branch",
    }
}

pub(super) fn admit_append_explain(
    rows: Vec<executor::Row>,
    config: &super::DatabaseConfig,
    options: QueryStreamOptions,
    task_context: Option<&hawdb_core::RuntimeTaskContext>,
) -> Result<QueryOutput> {
    use hawdb_executor::memory::{enforced_query_memory_budget, enforced_result_memory_budget};
    use hawdb_executor::result_delivery::{
        ConsumerMemoryMode, OutputLimits, QueryOutputAccumulator,
    };

    super::query_runtime::query_runtime_checkpoint(task_context)?;
    let ledger = hawdb_executor::QueryMemoryLedger::new(enforced_query_memory_budget(
        &config.execution_memory,
        task_context,
    )?);
    let result_budget = enforced_result_memory_budget(&config.execution_memory, task_context)?;
    let mut output = hawdb_executor::QueryRowsBuilder::with_row_capacity(rows.len());
    {
        let mut consumer = |row| output.push_named_row(row);
        let mut accumulator = QueryOutputAccumulator::new(
            OutputLimits {
                max_rows: options.max_rows,
                max_payload_bytes: options.max_payload_bytes,
            },
            result_budget,
            &ledger,
            ConsumerMemoryMode::Retained,
            &mut consumer,
        )?;
        // Diagnostic rows have their own admission after ANALYZE's data read.
        // Keep the complete report private until every row has been admitted.
        for row in rows {
            super::query_runtime::query_runtime_checkpoint(task_context)?;
            accumulator.emit(hawdb_executor::binding::Binding::values(row))?;
        }
        super::query_runtime::query_runtime_checkpoint(task_context)?;
    }
    Ok(QueryOutput {
        rows: output.finish(),
    })
}

// A snapshot read can finish recording after releasing the commit sequencer.
// Only the existing bounded observation containers and configured sink are shared.
pub(super) struct StatementRecorder {
    slow_query_log: Arc<SharedState<system_sql::SlowQueryLog>>,
    statement_summary: Arc<SharedState<system_sql::StatementSummary>>,
    slow_query_log_threshold_micros: u128,
    telemetry: Option<Arc<dyn TelemetrySink>>,
}

impl StatementRecorder {
    pub(super) fn refresh_read_snapshot(&self, snapshot: &mut super::DatabaseReadTransaction) {
        snapshot.slow_query_snapshot = self.slow_query_log.borrow().snapshot();
        snapshot.statement_summary_snapshot = self.statement_summary.borrow().snapshot();
    }
}

// Ordinary Database calls borrow their recording target without cloning handles.
struct StatementRecordingTarget<'a> {
    slow_query_log: &'a SharedState<system_sql::SlowQueryLog>,
    statement_summary: &'a SharedState<system_sql::StatementSummary>,
    slow_query_log_threshold_micros: u128,
    telemetry: Option<&'a dyn TelemetrySink>,
}

impl StatementRecordingTarget<'_> {
    pub(super) fn record_statement_execution(
        &self,
        query_language: &str,
        query_text: &str,
        statement_kind: &str,
        started: hawdb_core::time::Instant,
        result: std::result::Result<&QueryOutput, &HawDBError>,
        context: StatementExecutionContext<'_>,
    ) {
        let elapsed_micros = started.elapsed().as_micros();
        let query_identity = hawdb_query::QueryIdentity::new(query_language, query_text);
        let execution = match result {
            Ok(output) => system_sql::StatementExecution::completed(
                query_language,
                query_text,
                statement_kind,
                &query_identity,
                elapsed_micros,
                output.rows.len(),
            ),
            Err(error) => system_sql::StatementExecution::failed(
                query_language,
                query_text,
                statement_kind,
                &query_identity,
                elapsed_micros,
                error.to_string(),
            ),
        };
        if let Some(telemetry) = self.telemetry {
            let pipeline = context
                .execution_profile
                .map(|profile| &profile.pipeline_memory_report);
            telemetry.record_query(QueryTelemetry {
                query_language,
                query_digest: query_identity.query_digest(),
                statement_kind,
                success: result.is_ok(),
                elapsed_micros: elapsed_micros.min(u64::MAX as u128) as u64,
                parse_nanos: context.parse_nanos,
                row_count: result.map_or(0, |output| output.rows.len()),
                intermediate_rows: pipeline.map_or(0, |report| report.intermediate_rows),
                intermediate_payload_bytes: pipeline
                    .map_or(0, |report| report.intermediate_payload_bytes),
                output_payload_bytes: pipeline.map_or(0, |report| report.output_payload_bytes),
                steady_resident_bytes: pipeline.and_then(|report| report.steady_resident_bytes),
                peak_resident_bytes: pipeline.and_then(|report| report.peak_resident_bytes),
                total_page_faults: pipeline.and_then(|report| report.total_page_faults),
                minor_page_faults: pipeline.and_then(|report| report.minor_page_faults),
                major_page_faults: pipeline.and_then(|report| report.major_page_faults),
            });
        }
        self.statement_summary.borrow_mut().record(execution);

        let Ok(output) = result else {
            return;
        };
        let slow_log_candidate = elapsed_micros >= self.slow_query_log_threshold_micros;
        if !slow_log_candidate {
            return;
        }
        self.slow_query_log
            .borrow_mut()
            .push(system_sql::SlowQueryRecord::completed(
                system_sql::SlowQueryCompletion {
                    query_language,
                    statement_kind,
                    query_text,
                    query_identity: &query_identity,
                    elapsed_micros,
                    row_count: output.rows.len(),
                    success: true,
                    error: None,
                    slow_log_candidate,
                    access_control_policy_epoch: context
                        .access_control
                        .map(super::QueryAccessControlContext::policy_epoch),
                    vector_execution_reports: context
                        .execution_profile
                        .map(|profile| profile.vector_execution_reports.clone())
                        .unwrap_or_default(),
                },
            ));
    }
}

impl StatementRecorder {
    pub(super) fn record_statement_execution(
        &self,
        query_language: &str,
        query_text: &str,
        statement_kind: &str,
        started: hawdb_core::time::Instant,
        result: std::result::Result<&QueryOutput, &HawDBError>,
        context: StatementExecutionContext<'_>,
    ) {
        StatementRecordingTarget {
            slow_query_log: &self.slow_query_log,
            statement_summary: &self.statement_summary,
            slow_query_log_threshold_micros: self.slow_query_log_threshold_micros,
            telemetry: self.telemetry.as_deref(),
        }
        .record_statement_execution(
            query_language,
            query_text,
            statement_kind,
            started,
            result,
            context,
        );
    }
}

impl Database {
    pub(super) fn statement_recorder(&self) -> StatementRecorder {
        StatementRecorder {
            slow_query_log: Arc::clone(&self.slow_query_log),
            statement_summary: Arc::clone(&self.statement_summary),
            slow_query_log_threshold_micros: self.config.slow_query_log_threshold_micros,
            telemetry: self.telemetry.clone(),
        }
    }

    pub(super) fn record_statement_execution(
        &self,
        query_language: &str,
        query_text: &str,
        statement_kind: &str,
        started: hawdb_core::time::Instant,
        result: std::result::Result<&QueryOutput, &HawDBError>,
        context: StatementExecutionContext<'_>,
    ) {
        StatementRecordingTarget {
            slow_query_log: &self.slow_query_log,
            statement_summary: &self.statement_summary,
            slow_query_log_threshold_micros: self.config.slow_query_log_threshold_micros,
            telemetry: self.telemetry.as_deref(),
        }
        .record_statement_execution(
            query_language,
            query_text,
            statement_kind,
            started,
            result,
            context,
        );
    }

    pub fn query_sql(&mut self, sql_text: &str) -> Result<QueryOutput> {
        self.query_sql_bounded(sql_text, self.config.max_read_result_rows)
    }

    pub fn query_sql_with_params(
        &mut self,
        sql_text: &str,
        parameters: &[Value],
    ) -> Result<QueryOutput> {
        self.query_sql_with_params_bounded(sql_text, parameters, self.config.max_read_result_rows)
    }

    pub fn query_sql_bounded(
        &mut self,
        sql_text: &str,
        max_rows: Option<usize>,
    ) -> Result<QueryOutput> {
        self.query_sql_with_params_bounded(sql_text, &[], max_rows)
    }

    pub fn query_sql_with_params_bounded(
        &mut self,
        sql_text: &str,
        parameters: &[Value],
        max_rows: Option<usize>,
    ) -> Result<QueryOutput> {
        self.query_sql_with_params_options(
            sql_text,
            parameters,
            QueryStreamOptions {
                max_rows,
                max_payload_bytes: self.config.max_read_result_payload_bytes,
            },
        )
    }

    /// Executes PostgreSQL-dialect SQL with per-statement row and payload
    /// admission. Configured database limits remain hard upper bounds.
    pub fn query_sql_with_params_options(
        &mut self,
        sql_text: &str,
        parameters: &[Value],
        options: QueryStreamOptions,
    ) -> Result<QueryOutput> {
        if let Some(runtime) = self.runtime.peek() {
            runtime.store.ensure_usable()?;
        }
        let started = hawdb_core::time::Instant::now();
        let max_rows =
            super::restrictive_query_limit(self.config.max_read_result_rows, options.max_rows);
        let max_payload_bytes = super::restrictive_query_limit(
            self.config.max_read_result_payload_bytes,
            options.max_payload_bytes,
        );
        // Lifecycle/catalog statements need only project metadata. Parse them
        // before touching the selected runtime's data or plan caches.
        if let SqlStatement::Branch(statement) = crate::sql::parse_postgres_sql(sql_text)? {
            let result =
                self.execute_branch_sql(&statement, parameters, max_rows, max_payload_bytes);
            self.record_statement_execution(
                "sql",
                sql_text,
                "branch",
                started,
                result.as_ref(),
                StatementExecutionContext::default(),
            );
            return result;
        }
        self.runtime.get()?.store.ensure_usable()?;
        let prepared = self
            .runtime
            .get()?
            .relational_plan_template_cache
            .prepare(sql_text)?;
        self.query_sql_with_prepared_params_inner(
            sql_text,
            parameters,
            prepared,
            max_rows,
            max_payload_bytes,
            started,
        )
    }

    pub(super) fn query_sql_with_prepared_params(
        &mut self,
        sql_text: &str,
        parameters: &[Value],
        prepared: crate::relational_sql::PreparedRelationalSql,
    ) -> Result<QueryOutput> {
        if let Some(runtime) = self.runtime.peek() {
            runtime.store.ensure_usable()?;
        }
        let started = hawdb_core::time::Instant::now();
        self.query_sql_with_prepared_params_inner(
            sql_text,
            parameters,
            prepared,
            self.config.max_read_result_rows,
            self.config.max_read_result_payload_bytes,
            started,
        )
    }

    fn query_sql_with_prepared_params_inner(
        &mut self,
        sql_text: &str,
        parameters: &[Value],
        prepared: crate::relational_sql::PreparedRelationalSql,
        max_rows: Option<usize>,
        max_payload_bytes: Option<usize>,
        started: hawdb_core::time::Instant,
    ) -> Result<QueryOutput> {
        let statement_kind = sql_statement_kind(prepared.statement());
        let query_result = (|| {
            if let SqlStatement::Branch(statement) = prepared.statement() {
                return self.execute_branch_sql(statement, parameters, max_rows, max_payload_bytes);
            }
            self.runtime.get()?.store.ensure_usable()?;
            super::reject_locking_select_without_manager(prepared.statement(), false)?;
            if hawdb_relational::system_schema::statement_writes_system_schema_registry(
                prepared.statement(),
            ) {
                return Err(HawDBError::Semantic(
                    "hawdb_schema_migrations is read-only outside system schema upgrade"
                        .to_string(),
                ));
            }
            if matches!(
                prepared.statement(),
                crate::sql::SqlStatement::Select(select)
                    if system_sql::is_virtual_catalog_select(select)
            ) {
                let plan_cache_stats = self.runtime.get()?.plan_cache.borrow().stats();
                let slow_queries = self.slow_query_log.borrow().snapshot();
                let statement_summaries = self.statement_summary.borrow().snapshot();
                return {
                    let branch_runtime = self.runtime.get_mut()?;
                    system_sql::query_sql_with_params(
                        sql_text,
                        parameters,
                        max_rows,
                        max_payload_bytes,
                        &system_sql::SystemSqlContext {
                            catalog: &branch_runtime.catalog,
                            store: &branch_runtime.store,
                            relational_state: branch_runtime.store.relational_state(),
                            append_state: branch_runtime.store.append_state(),
                            runtime: super::system_runtime_snapshot(&self.config),
                            plan_cache_stats: &plan_cache_stats,
                            slow_queries: &slow_queries,
                            statement_summaries: &statement_summaries,
                        },
                    )
                };
            }

            if let Some(plan) = compile_prepared_append_select_sql(
                &prepared.template,
                parameters,
                self.runtime.get()?.store.append_state(),
                max_rows.unwrap_or(usize::MAX),
            )? {
                let output = self.runtime.get()?.store.read_append_partition_bounded(
                    &plan.table,
                    &plan.partition,
                    plan.after.as_ref(),
                    plan.max_rows,
                    max_payload_bytes.unwrap_or(usize::MAX),
                )?;
                return Ok(QueryOutput {
                    rows: project_append_rows(&plan, &output.rows)?.into(),
                });
            }
            if let Some(plan) = compile_prepared_append_explain_sql(
                &prepared.template,
                parameters,
                self.runtime.get()?.store.append_state(),
                max_rows.unwrap_or(usize::MAX),
            )? {
                let report = if plan.analyze {
                    Some(
                        self.runtime
                            .get()?
                            .store
                            .read_append_partition_bounded(
                                &plan.select.table,
                                &plan.select.partition,
                                plan.select.after.as_ref(),
                                plan.select.max_rows,
                                max_payload_bytes.unwrap_or(usize::MAX),
                            )?
                            .report,
                    )
                } else {
                    None
                };
                return admit_append_explain(
                    format_append_explain(&plan, report.as_ref()),
                    &self.config,
                    QueryStreamOptions {
                        max_rows,
                        max_payload_bytes,
                    },
                    None,
                );
            }

            if matches!(
                prepared.statement(),
                crate::sql::SqlStatement::Select(_) | crate::sql::SqlStatement::Explain(_)
            ) {
                let query_result =
                    crate::relational_sql::execute_prepared_relational_query_with_resources(
                        prepared,
                        parameters,
                        self.runtime.get()?.store.relational_state(),
                        {
                            let branch_runtime = self.runtime.get()?;
                            crate::relational_sql::RelationalQueryReadModes::new(
                                super::relational_index_read_mode(
                                    &self.config,
                                    &branch_runtime.store,
                                ),
                                crate::relational_sql::RelationalRowReadMode::Store(
                                    &branch_runtime.store,
                                ),
                            )
                        },
                        super::relational_query_resource_context(
                            &self.config,
                            max_rows,
                            max_payload_bytes,
                            None,
                        ),
                    );
                self.runtime
                    .get()?
                    .store
                    .poison_on_storage_error(&query_result);
                let output = query_result?;
                return Ok(QueryOutput { rows: output.rows });
            }

            self.ensure_writable()?;
            if let Some(transaction) = compile_append_statement_sql(
                sql_text,
                parameters,
                self.runtime.get()?.store.append_state(),
            )? {
                if let crate::sql::SqlStatement::CreateTable(create) = prepared.statement()
                    && self
                        .runtime
                        .get()?
                        .store
                        .relational_state()
                        .table_schema(&create.table.name)
                        .is_some()
                {
                    return Err(HawDBError::Semantic(format!(
                        "table {} already exists as a RowPage table",
                        create.table.name
                    )));
                }
                let summary = {
                    let branch_runtime = self.runtime.get_mut()?;
                    branch_runtime.store.commit_kernel_write_batch(
                        &mut branch_runtime.catalog,
                        crate::store::KernelWriteBatch {
                            append: transaction,
                            ..crate::store::KernelWriteBatch::default()
                        },
                        self.config.mutation_limits,
                    )
                }?;
                return Ok(QueryOutput {
                    rows: summary.rows.into(),
                });
            }
            if let crate::sql::SqlStatement::CreateTable(create) = prepared.statement()
                && self
                    .runtime
                    .get()?
                    .store
                    .append_table_schema(&create.table.name)
                    .is_some()
            {
                return Err(HawDBError::Semantic(format!(
                    "table {} already exists as a strict append table",
                    create.table.name
                )));
            }
            let compiled = compile_relational_statement_sql_with_result(
                sql_text,
                parameters,
                self.runtime.get()?.store.relational_state(),
            )?;
            let summary = {
                let branch_runtime = self.runtime.get_mut()?;
                branch_runtime.store.commit_relational_transaction(
                    &mut branch_runtime.catalog,
                    compiled.transaction,
                )
            }?;
            self.complete_required_relational_row_checkpoint("SQL commit")?;
            if summary.relational_mutation_outcomes.len() > 1 {
                return Err(HawDBError::StorageIntegrity(
                    "one SQL statement produced multiple relational mutation outcomes".to_string(),
                ));
            }
            let mutation = summary
                .relational_mutation_outcomes
                .first()
                .map(|outcome| {
                    super::project_relational_mutation_outcome(
                        outcome,
                        compiled.returning.as_ref(),
                        self.runtime.get()?.store.relational_state(),
                        self.config.mutation_limits,
                        false,
                    )
                })
                .transpose()?;
            let mut rows: executor::QueryRows = summary.rows.into();
            if rows.is_empty()
                && let Some(mutation) = mutation
            {
                rows = mutation.rows;
            }
            Ok(QueryOutput { rows })
        })();
        self.record_statement_execution(
            "sql",
            sql_text,
            statement_kind,
            started,
            query_result.as_ref(),
            StatementExecutionContext::default(),
        );
        query_result
    }

    pub fn slow_query_log_jsonl(&self) -> Result<String> {
        self.slow_query_log_jsonl_with_options(&SlowQueryLogExportOptions::default())
    }

    pub fn slow_query_log_jsonl_with_options(
        &self,
        options: &SlowQueryLogExportOptions,
    ) -> Result<String> {
        system_sql::slow_query_log_jsonl(
            &self.slow_query_log.borrow().snapshot(),
            options.include_query_text,
        )
    }

    pub fn slow_query_log_snapshot(&self) -> Vec<SlowQueryLogRecordSummary> {
        self.slow_query_log
            .borrow()
            .snapshot()
            .iter()
            .map(system_sql::slow_query_record_summary)
            .collect()
    }

    pub fn write_slow_query_log_jsonl(&self, path: impl AsRef<Path>) -> Result<()> {
        self.write_slow_query_log_jsonl_with_options(path, &SlowQueryLogExportOptions::default())
    }

    pub fn write_slow_query_log_jsonl_with_options(
        &self,
        path: impl AsRef<Path>,
        options: &SlowQueryLogExportOptions,
    ) -> Result<()> {
        let jsonl = self.slow_query_log_jsonl_with_options(options)?;
        let mut options = hawdb_storage::file_io::OpenOptions::new();
        options.write(true).create(true).truncate(true);
        // Export is engine IO even outside the project directory. Use the
        // source domain without admitting a deferred data runtime, and reserve
        // capacity before opening or truncating the destination.
        let mut file = match self.runtime.file_descriptor_context() {
            Some(context) => context.open(&options, path.as_ref())?,
            None => options.open(path)?,
        };
        file.write_all(jsonl.as_bytes())?;
        Ok(())
    }
}

impl Database {
    fn execute_branch_sql(
        &mut self,
        statement: &BranchSqlStatement,
        parameters: &[Value],
        max_rows: Option<usize>,
        max_payload_bytes: Option<usize>,
    ) -> Result<QueryOutput> {
        let output = match statement {
            BranchSqlStatement::UseBranch(selector) => {
                self.use_branch(branch_selector_from_sql(selector, parameters)?)?;
                QueryOutput::from_rows(Vec::new())
            }
            BranchSqlStatement::CreateBranch(statement) => {
                enforce_branch_result_budget(1, max_rows)?;
                let request = super::BranchCreateRequest {
                    name: statement
                        .name
                        .as_ref()
                        .map(|value| branch_selector_value(value, parameters))
                        .transpose()?,
                    parent: branch_selector_from_sql(&statement.source, parameters)?,
                    expected_source_commit_epoch: branch_revision(
                        statement.expected_source_revision,
                        parameters,
                    )?,
                    owner: statement
                        .owner
                        .as_ref()
                        .map(|value| branch_selector_value(value, parameters))
                        .transpose()?,
                    idempotency_key: branch_selector_value(&statement.request_key, parameters)?,
                };
                let preview = self.preview_create_branch(&request)?;
                enforce_branch_payload_budget(
                    &QueryOutput::from_rows(vec![branch_info_row(&preview)?]),
                    max_payload_bytes,
                )?;
                let branch = self.create_branch(request)?;
                QueryOutput::from_rows(vec![branch_info_row(&branch)?])
            }
            BranchSqlStatement::DropBranch(statement) => {
                enforce_branch_result_budget(1, max_rows)?;
                let super::BranchSelector::Id(id) = branch_selector_from_sql(
                    &BranchSqlSelector::Id(statement.id.clone()),
                    parameters,
                )?
                else {
                    unreachable!("typed ID selector")
                };
                let revision = branch_revision(statement.expected_metadata_revision, parameters)?;
                let mut preview = self.describe_branch(super::BranchSelector::Id(id))?;
                preview.state = super::BranchLifecycleState::Deleting;
                enforce_branch_payload_budget(
                    &QueryOutput::from_rows(vec![branch_info_row(&preview)?]),
                    max_payload_bytes,
                )?;
                let branch = self.delete_branch_at_revision(id, revision)?;
                QueryOutput::from_rows(vec![branch_info_row(&branch)?])
            }
            _ => {
                let catalog_path = self.branch_catalog_path().ok();
                let current = if matches!(statement, BranchSqlStatement::ShowCurrentBranch) {
                    self.current_branch()?
                } else {
                    None
                };
                return execute_branch_sql_at_path(
                    catalog_path.as_deref(),
                    current.as_ref(),
                    "mutable database",
                    statement,
                    parameters,
                    max_rows,
                    max_payload_bytes,
                );
            }
        };
        enforce_branch_result_budget(output.rows.len(), max_rows)?;
        enforce_branch_payload_budget(&output, max_payload_bytes)?;
        Ok(output)
    }
}

fn branch_revision(bound: SqlBound, parameters: &[Value]) -> Result<u64> {
    hawdb_relational::query_value::bind_bound(Some(bound), parameters, "branch revision")?
        .ok_or_else(|| HawDBError::Semantic("branch revision is required".into()))
}

fn current_branch_row(
    current: &super::branch_lifecycle::CurrentBranch,
) -> Result<crate::executor::Row> {
    let mut row = branch_info_row(&current.info)?;
    row.insert(
        "commit_epoch".into(),
        Value::Int(i64::try_from(current.commit_epoch).map_err(|_| {
            HawDBError::StorageIntegrity("branch commit epoch exceeds PostgreSQL BIGINT".into())
        })?),
    );
    row.insert(
        "durability".into(),
        Value::String(
            match current.durability {
                hawdb_storage::config::DurabilityPolicy::SyncOnEveryWrite => "sync_on_every_write",
                hawdb_storage::config::DurabilityPolicy::SyncOnCheckpoint => "sync_on_checkpoint",
            }
            .into(),
        ),
    );
    Ok(row)
}

/// Metadata statements observe the catalog and selected identity captured by
/// the caller. Explicit transactions and snapshots cannot retarget a runtime.
pub(super) fn execute_branch_sql_at_path(
    catalog_path: Option<&Path>,
    current: Option<&super::branch_lifecycle::CurrentBranch>,
    context: &'static str,
    statement: &BranchSqlStatement,
    parameters: &[Value],
    max_rows: Option<usize>,
    max_payload_bytes: Option<usize>,
) -> Result<QueryOutput> {
    if statement.changes_context_or_catalog() {
        return Err(HawDBError::BranchCommandUnsupported {
            command: statement.command(),
            context,
        });
    }
    if matches!(statement, BranchSqlStatement::ShowCurrentBranch) {
        let current =
            current.ok_or_else(|| HawDBError::Execution("no branch runtime is selected".into()))?;
        let output = QueryOutput::from_rows(vec![current_branch_row(current)?]);
        enforce_branch_result_budget(1, max_rows)?;
        enforce_branch_payload_budget(&output, max_payload_bytes)?;
        return Ok(output);
    }
    let branches = read_branch_catalog(catalog_path)?;
    let rows = match statement {
        BranchSqlStatement::ShowBranches(statement) => {
            show_branches_sql_rows(branches, statement, parameters)?
        }
        BranchSqlStatement::ShowBranch(statement) => {
            let selector = branch_selector_from_sql(&statement.selector, parameters)?;
            let matching = branches
                .into_iter()
                .filter(|branch| branch_matches_selector(branch, &selector));
            let branch = super::branch_lifecycle::prefer_current_branch(matching, |branch| {
                branch.state == super::BranchLifecycleState::Deleted
            })
            .ok_or_else(|| HawDBError::Semantic("branch does not exist".to_string()))?;
            vec![branch_info_row(&branch)?]
        }
        _ => unreachable!("context commands and current branch are handled before catalog reads"),
    };
    enforce_branch_result_budget(rows.len(), max_rows)?;
    let output = QueryOutput::from_rows(rows);
    enforce_branch_payload_budget(&output, max_payload_bytes)?;
    Ok(output)
}

fn read_branch_catalog(catalog_path: Option<&Path>) -> Result<Vec<BranchInfo>> {
    let catalog_path = catalog_path.ok_or_else(|| {
        HawDBError::Execution("branch lifecycle requires a durable database".to_string())
    })?;
    if !hawdb_storage::file_io::try_exists(catalog_path).map_err(HawDBError::from_storage_error)? {
        return Ok(Vec::new());
    }
    let catalog = storage::read_catalog(catalog_path).map_err(HawDBError::from_storage_error)?;
    Ok(catalog
        .branches
        .iter()
        .map(super::branch_lifecycle::branch_info)
        .collect())
}

fn show_branches_sql_rows(
    branches: Vec<BranchInfo>,
    statement: &ShowBranchesStatement,
    parameters: &[Value],
) -> Result<Vec<crate::executor::Row>> {
    let limit = branch_bound(&statement.limit, parameters)?;
    let offset = statement
        .offset
        .as_ref()
        .map(|offset| branch_bound(offset, parameters))
        .transpose()?
        .unwrap_or(0);
    branches
        .into_iter()
        .skip(offset)
        .take(limit)
        .map(|branch| branch_info_row(&branch))
        .collect()
}

fn branch_matches_selector(branch: &BranchInfo, selector: &super::BranchSelector) -> bool {
    match selector {
        super::BranchSelector::Id(id) => branch.id == *id,
        super::BranchSelector::Name(name) => branch.name == *name,
    }
}

pub(super) fn branch_selector_from_sql(
    selector: &BranchSqlSelector,
    parameters: &[Value],
) -> Result<super::BranchSelector> {
    match selector {
        BranchSqlSelector::Name(value) => Ok(super::BranchSelector::Name(branch_selector_value(
            value, parameters,
        )?)),
        BranchSqlSelector::Id(value) => {
            if let BranchSqlValue::Parameter(position) = value
                && let Some(Value::Uuid(id)) = parameters.get(position.saturating_sub(1))
            {
                return Ok(super::BranchSelector::Id(*id));
            }
            let raw = branch_selector_value(value, parameters)?;
            let id = raw.parse().map_err(|_| {
                HawDBError::Semantic(
                    "branch ID requires a valid UUID string or UUID parameter".to_string(),
                )
            })?;
            Ok(super::BranchSelector::Id(id))
        }
    }
}

fn branch_selector_value(value: &BranchSqlValue, parameters: &[Value]) -> Result<String> {
    match value {
        BranchSqlValue::Literal(value) => Ok(value.clone()),
        BranchSqlValue::Parameter(position) => match parameters.get(position.saturating_sub(1)) {
            Some(Value::String(value)) => Ok(value.clone()),
            Some(_) => Err(HawDBError::Semantic(format!(
                "branch SQL parameter ${position} must be a string"
            ))),
            None => Err(HawDBError::Semantic(format!(
                "missing branch SQL parameter ${position}"
            ))),
        },
    }
}

fn branch_bound(bound: &SqlBound, parameters: &[Value]) -> Result<usize> {
    let value = hawdb_relational::query_value::bind_bound(Some(*bound), parameters, "branch SQL")?
        .ok_or_else(|| {
            HawDBError::Semantic("branch SQL bound was unexpectedly absent".to_string())
        })?;
    usize::try_from(value)
        .map_err(|_| HawDBError::Semantic("branch SQL bound exceeds platform capacity".to_string()))
}

fn enforce_branch_result_budget(requested: usize, max_rows: Option<usize>) -> Result<()> {
    if max_rows.is_some_and(|maximum| requested > maximum) {
        return Err(HawDBError::Execution(
            "branch SQL page exceeds the configured result row budget".to_string(),
        ));
    }
    Ok(())
}

fn enforce_branch_payload_budget(
    output: &QueryOutput,
    max_payload_bytes: Option<usize>,
) -> Result<()> {
    if max_payload_bytes.is_some_and(|maximum| output.payload_bytes() > maximum) {
        return Err(HawDBError::Execution(
            "branch SQL result exceeds the configured payload budget".to_string(),
        ));
    }
    Ok(())
}

fn branch_info_row(branch: &super::BranchInfo) -> Result<crate::executor::Row> {
    let source_commit_epoch = i64::try_from(branch.source_commit_epoch).map_err(|_| {
        HawDBError::StorageIntegrity(
            "branch source commit epoch cannot be represented as PostgreSQL BIGINT".to_string(),
        )
    })?;
    Ok(BTreeMap::from([
        ("branch_id".to_string(), Value::Uuid(branch.id)),
        ("name".to_string(), Value::String(branch.name.clone())),
        (
            "metadata_revision".to_string(),
            Value::Int(i64::try_from(branch.metadata_revision).map_err(|_| {
                HawDBError::StorageIntegrity(
                    "branch metadata revision exceeds PostgreSQL BIGINT".into(),
                )
            })?),
        ),
        (
            "parent_id".to_string(),
            branch.parent_id.map(Value::Uuid).unwrap_or(Value::Null),
        ),
        (
            "source_commit_epoch".to_string(),
            Value::Int(source_commit_epoch),
        ),
        (
            "state".to_string(),
            Value::String(format!("{:?}", branch.state).to_lowercase()),
        ),
        (
            "owner".to_string(),
            branch
                .owner
                .clone()
                .map(Value::String)
                .unwrap_or(Value::Null),
        ),
    ]))
}