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,
)?;
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(),
})
}
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();
}
}
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,
},
)
}
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,
);
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);
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(¤t.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)
}
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 let Some(maximum) = max_rows
&& requested > maximum
{
return Err(HawDBError::read_budget_exceeded(
crate::ReadBudgetResource::Rows,
maximum,
"branch SQL page exceeds the configured result row budget",
));
}
Ok(())
}
fn enforce_branch_payload_budget(
output: &QueryOutput,
max_payload_bytes: Option<usize>,
) -> Result<()> {
if let Some(maximum) = max_payload_bytes
&& output.payload_bytes() > maximum
{
return Err(HawDBError::read_budget_exceeded(
crate::ReadBudgetResource::PayloadBytes,
maximum,
"branch SQL result exceeds the configured payload budget",
));
}
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),
),
]))
}