use std::sync::{atomic::Ordering, Arc};
use uqa_sql::binding::production::{BindingMap, BindingNameSet};
use uqa_sql::catalog::roles::RoleReference;
use uqa_sql::plan::{CtePlan, QueryPlan};
use uqa_sql::SQLError;
use super::{CteScope, LockIdentityOptions};
use uqa_sql::catalog::resolution::RelationLookupMode;
impl<S: Clone> CteScope<S> {
pub fn command_cte_snapshot(&self) -> Option<std::sync::Arc<S>> {
self.command_cte_snapshot.clone()
}
pub fn set_command_cte_snapshot(&mut self, snapshot: Option<std::sync::Arc<S>>) {
self.command_cte_snapshot = snapshot;
}
pub fn set_statement_commands(&mut self, commands: std::sync::Arc<super::StatementCommands>) {
self.statement_commands = Some(commands);
}
pub fn statement_commands(&self) -> Option<&std::sync::Arc<super::StatementCommands>> {
self.statement_commands.as_ref()
}
pub fn statement_wrote(
&self,
row: &crate::mutation::candidate::PhysicalDocumentIdentity,
) -> bool {
self.statement_commands
.as_ref()
.is_some_and(|commands| commands.wrote(row))
}
pub fn statement_triggered_write(
&self,
row: &crate::mutation::candidate::PhysicalDocumentIdentity,
) -> bool {
self.statement_commands
.as_ref()
.is_some_and(|commands| commands.triggered_write(row))
}
pub fn inherit_cte_bindings(&mut self, parent: &Self) {
self.inherit_cte_bindings_with_control(
parent,
&uqa_core::memory::ProductionControl::uncontrolled(),
)
.expect("ordinary inherited CTE bindings");
}
pub fn inherit_cte_bindings_with_control(
&mut self,
parent: &Self,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<(), SQLError> {
control.check()?;
let rows = parent.rows.copy_with_control(control)?;
let deferred = parent
.deferred_ctes
.copy_with_control(control, |plan| Ok(plan.clone()))?;
let definitions = parent
.definition_scopes
.copy_with_control(control, |definition| Ok(Arc::clone(definition)))?;
let folded = parent.folded_ctes.copy_with_control(control)?;
let non_returning = parent.non_returning_ctes.copy_with_control(control)?;
let visible = parent.visible_cte_names.copy_with_control(control)?;
let widths = parent
.recursive_control_widths
.copy_with_control(control, |width| Ok(*width))?;
control.check()?;
self.rows = rows;
self.deferred_ctes = deferred;
self.definition_scopes = definitions;
self.folded_ctes = folded;
self.non_returning_ctes = non_returning;
self.visible_cte_names = visible;
self.recursive_control_widths = widths;
self.command_cte_snapshot
.clone_from(&parent.command_cte_snapshot);
self.statement_commands
.clone_from(&parent.statement_commands);
if self.privilege_subject.is_none() {
self.privilege_subject.clone_from(&parent.privilege_subject);
}
Ok(())
}
pub fn enter_privilege_subject(
&mut self,
subject: RoleReference,
) -> PrivilegeSubjectScope<'_, S> {
let previous = self.privilege_subject.replace(subject.into());
PrivilegeSubjectScope {
ctes: self,
previous,
}
}
pub fn enter_privilege_subject_with_control(
&mut self,
subject: uqa_core::memory::Produced<RoleReference>,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<PrivilegeSubjectScope<'_, S>, SQLError> {
let subject = super::production::subject::ScopeSubject::from_produced(subject, control)?;
let previous = self.privilege_subject.replace(subject);
Ok(PrivilegeSubjectScope {
ctes: self,
previous,
})
}
pub fn enter_relation_lookup_mode(
&mut self,
relations_bound: bool,
) -> Result<RelationLookupScope<'_, S>, SQLError> {
let resolution = self.catalog_resolution.as_mut().ok_or_else(|| {
SQLError::Internal(
"query execution scope has no statement name-resolution snapshot".into(),
)
})?;
let lookup_mode = if relations_bound {
RelationLookupMode::Bound
} else {
RelationLookupMode::Dynamic
};
let previous = resolution.set_lookup_mode(lookup_mode);
Ok(RelationLookupScope {
ctes: self,
previous,
})
}
pub fn enter_query_plan_scope(
&mut self,
plan: &QueryPlan,
) -> Result<QueryPlanScope<'_, S>, SQLError> {
self.enter_query_plan_scope_with_control(
plan,
&uqa_core::memory::ProductionControl::uncontrolled(),
)
}
pub fn enter_query_plan_scope_with_control(
&mut self,
plan: &QueryPlan,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<QueryPlanScope<'_, S>, SQLError> {
let mut lookup = self.enter_relation_lookup_mode(plan.relations_bound)?;
let previous_subject = match &plan.relation_privilege_subject {
Some(subject) => {
let subject = super::production::subject::ScopeSubject::capture(subject, control)?;
QueryPrivilege::Restore(lookup.privilege_subject.replace(subject))
}
None => QueryPrivilege::Unchanged,
};
Ok(QueryPlanScope {
lookup,
previous_subject,
})
}
pub fn insert_shared(&mut self, name: String, rows: crate::SharedSpill) {
self.insert_rows(name, crate::query::cte::rows::CteRows::Complete(rows));
}
pub fn insert_rows(&mut self, name: String, rows: crate::query::cte::rows::CteRows) {
self.deferred_ctes.remove(&name);
self.definition_scopes.remove(&name);
self.folded_ctes.remove(&name);
self.non_returning_ctes.remove(&name);
self.rows.insert(name, rows);
}
pub fn insert_deferred(&mut self, plan: uqa_sql::plan::RetainedCtePlan) {
self.insert_preparation_cte(plan, true);
}
pub fn remove_deferred(&mut self, name: &str) -> Option<uqa_sql::plan::RetainedCtePlan> {
self.non_returning_ctes.remove(name);
self.definition_scopes.remove(name);
self.folded_ctes.remove(name);
self.deferred_ctes.remove(name)
}
pub fn deferred_for_scan(&self, name: &str) -> Option<uqa_sql::plan::RetainedCtePlan> {
let reference = uqa_core::RelationIdentity::borrowed_reference(name)?;
(reference.schema.is_none())
.then(|| self.deferred_ctes.get_name(reference.name).cloned())
.flatten()
}
pub fn materialized_for_scan(
&self,
reference: &str,
) -> Option<crate::query::cte::rows::CteRows> {
let reference = uqa_core::RelationIdentity::borrowed_reference(reference)?;
(reference.schema.is_none())
.then(|| self.rows.get_name(reference.name).cloned())
.flatten()
}
pub fn deferred_reference(&self, reference: &str) -> Option<&CtePlan> {
let reference = uqa_core::RelationIdentity::borrowed_reference(reference)?;
(reference.schema.is_none())
.then(|| {
self.deferred_ctes
.get_name(reference.name)
.map(AsRef::as_ref)
})
.flatten()
}
pub fn deferred_ctes(&self) -> &BindingMap<uqa_sql::plan::RetainedCtePlan> {
&self.deferred_ctes
}
pub fn recursive_control_width(&self, name: &str) -> Option<usize> {
self.recursive_control_widths.get(name).copied()
}
pub fn set_recursive_control_width(&mut self, name: String, width: usize) -> Option<usize> {
self.recursive_control_widths.insert(name, width)
}
pub fn restore_recursive_control_width(&mut self, name: &str, previous: Option<usize>) {
match previous {
Some(width) => {
self.recursive_control_widths
.insert(name.to_string(), width);
}
None => {
self.recursive_control_widths.remove(name);
}
}
}
pub fn remove_materialized(&mut self, name: &str) -> Option<crate::query::cte::rows::CteRows> {
self.non_returning_ctes.remove(name);
self.rows.remove(name)
}
pub fn enter_query_block(
&mut self,
block: &uqa_sql::plan::QueryBlockPlan,
) -> ScalarSubqueryScope<'_, S> {
self.enter_query_block_with_control(
block,
&uqa_core::memory::ProductionControl::uncontrolled(),
)
.expect("ordinary query-block scope")
}
pub fn enter_query_block_with_control(
&mut self,
block: &uqa_sql::plan::QueryBlockPlan,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<ScalarSubqueryScope<'_, S>, SQLError> {
let arena = uqa_sql::plan::RetainedQueryArena::capture(&block.subqueries, control)?;
let rewrites = if block.deferred_outer_rewrites.is_empty() {
None
} else {
let mut rewrites = uqa_core::memory::ProductionVec::new(*control);
rewrites.reserve(block.deferred_outer_rewrites.len())?;
for rewrite in &block.deferred_outer_rewrites {
rewrites.push_produced(rewrite.clone_with_control(control)?)?;
}
Some(rewrites.finish()?.into_shared(control)?)
};
control.check()?;
let mut scope = self.enter_retained_scalar_subqueries(arena);
scope.source_outer_rewrites = rewrites;
Ok(scope)
}
pub fn enter_scalar_subqueries(
&mut self,
subqueries: &[QueryPlan],
) -> ScalarSubqueryScope<'_, S> {
self.enter_scalar_subqueries_with_control(
subqueries,
&uqa_core::memory::ProductionControl::uncontrolled(),
)
.expect("ordinary scalar-query scope")
}
pub fn enter_scalar_subqueries_with_control(
&mut self,
subqueries: &[QueryPlan],
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<ScalarSubqueryScope<'_, S>, SQLError> {
let arena = uqa_sql::plan::RetainedQueryArena::capture(subqueries, control)?;
Ok(self.enter_retained_scalar_subqueries(arena))
}
pub(crate) fn enter_retained_scalar_subqueries(
&mut self,
arena: uqa_sql::plan::RetainedQueryArena,
) -> ScalarSubqueryScope<'_, S> {
let previous = std::mem::replace(&mut self.scalar_subqueries, arena);
let next_arena = self
.next_scalar_subquery_arena
.fetch_add(1, Ordering::Relaxed);
let previous_arena = std::mem::replace(&mut self.scalar_subquery_arena, next_arena);
let previous_lock_identities = self.lock_identities;
let previous_outer_row = self.outer_row_binding();
let previous_source_rewrites = self.source_outer_rewrites.clone();
ScalarSubqueryScope {
ctes: self,
previous: Some(previous),
previous_arena,
previous_lock_identities,
previous_outer_row,
previous_source_rewrites,
}
}
pub fn enter_visible_ctes<'a, 'n>(
&'a mut self,
names: impl IntoIterator<Item = &'n str>,
) -> VisibleCteScope<'a, S> {
self.enter_visible_ctes_with_control(
names,
&uqa_core::memory::ProductionControl::uncontrolled(),
)
.expect("ordinary visible CTE scope")
}
pub fn enter_visible_ctes_with_control<'a, 'n>(
&'a mut self,
names: impl IntoIterator<Item = &'n str>,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<VisibleCteScope<'a, S>, SQLError> {
let mut visible = self.visible_cte_names.copy_with_control(control)?;
for name in names {
visible.insert_with_control(name, control)?;
}
control.check()?;
let previous = std::mem::replace(&mut self.visible_cte_names, visible);
Ok(VisibleCteScope {
ctes: self,
previous: Some(previous),
})
}
pub fn is_visible_cte(&self, name: &str) -> bool {
uqa_core::RelationIdentity::borrowed_reference(name).is_some_and(|reference| {
reference.schema.is_none()
&& (self.visible_cte_names.contains_name(reference.name)
|| self.rows.get_name(reference.name).is_some()
|| self.deferred_ctes.get_name(reference.name).is_some())
})
}
pub fn contains_cte_name(&self, name: &str) -> bool {
self.visible_cte_names.contains(name)
|| self.rows.contains_key(name)
|| self.deferred_ctes.contains_key(name)
}
pub fn returning_statement_snapshot_scope(&self) -> Self {
self.returning_statement_snapshot_scope_with_control(
&uqa_core::memory::ProductionControl::uncontrolled(),
)
.expect("ordinary returning scope")
}
pub fn returning_statement_snapshot_scope_with_control(
&self,
control: &uqa_core::memory::ProductionControl<'_>,
) -> Result<Self, SQLError> {
let mut scope = self.copy_with_control(control)?;
scope.read_command_overlay = false;
Ok(scope)
}
pub fn reads_command_overlay(&self) -> bool {
self.read_command_overlay
}
pub fn enable_command_progress_streaming(&mut self) {
self.stream_command_progress = true;
}
pub fn streams_command_progress(&self) -> bool {
self.stream_command_progress
}
pub fn enable_backwards_scanning(&mut self) {
self.scan_backwards = true;
}
pub fn scans_backwards(&self) -> bool {
self.scan_backwards
}
}
pub struct PrivilegeSubjectScope<'a, S: Clone> {
ctes: &'a mut CteScope<S>,
previous: Option<super::production::subject::ScopeSubject>,
}
impl<S: Clone> std::ops::Deref for PrivilegeSubjectScope<'_, S> {
type Target = CteScope<S>;
fn deref(&self) -> &Self::Target {
self.ctes
}
}
impl<S: Clone> std::ops::DerefMut for PrivilegeSubjectScope<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.ctes
}
}
impl<S: Clone> Drop for PrivilegeSubjectScope<'_, S> {
fn drop(&mut self) {
self.ctes.privilege_subject = self.previous.take();
}
}
pub struct RelationLookupScope<'a, S: Clone> {
ctes: &'a mut CteScope<S>,
previous: RelationLookupMode,
}
impl<S: Clone> std::ops::Deref for RelationLookupScope<'_, S> {
type Target = CteScope<S>;
fn deref(&self) -> &Self::Target {
self.ctes
}
}
impl<S: Clone> std::ops::DerefMut for RelationLookupScope<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.ctes
}
}
impl<S: Clone> Drop for RelationLookupScope<'_, S> {
fn drop(&mut self) {
let resolution = self
.ctes
.catalog_resolution
.as_mut()
.expect("relation lookup scope lost its statement resolution");
resolution.set_lookup_mode(self.previous);
}
}
pub struct QueryPlanScope<'a, S: Clone> {
lookup: RelationLookupScope<'a, S>,
previous_subject: QueryPrivilege,
}
enum QueryPrivilege {
Unchanged,
Restore(Option<super::production::subject::ScopeSubject>),
}
impl<S: Clone> std::ops::Deref for QueryPlanScope<'_, S> {
type Target = CteScope<S>;
fn deref(&self) -> &Self::Target {
&self.lookup
}
}
impl<S: Clone> std::ops::DerefMut for QueryPlanScope<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.lookup
}
}
impl<S: Clone> Drop for QueryPlanScope<'_, S> {
fn drop(&mut self) {
if let QueryPrivilege::Restore(previous) = &mut self.previous_subject {
self.lookup.privilege_subject = previous.take();
}
}
}
pub struct ScalarSubqueryScope<'a, S: Clone> {
ctes: &'a mut CteScope<S>,
previous: Option<uqa_sql::plan::RetainedQueryArena>,
previous_arena: u64,
previous_lock_identities: LockIdentityOptions,
previous_outer_row: Option<Arc<crate::OwnedPhysicalRow>>,
previous_source_rewrites: Option<super::SourceOuterRewrites>,
}
impl<S: Clone> std::ops::Deref for ScalarSubqueryScope<'_, S> {
type Target = CteScope<S>;
fn deref(&self) -> &Self::Target {
self.ctes
}
}
impl<S: Clone> std::ops::DerefMut for ScalarSubqueryScope<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.ctes
}
}
impl<S: Clone> Drop for ScalarSubqueryScope<'_, S> {
fn drop(&mut self) {
if let Some(previous) = self.previous.take() {
self.ctes.scalar_subqueries = previous;
self.ctes.scalar_subquery_arena = self.previous_arena;
self.ctes.lock_identities = self.previous_lock_identities;
self.ctes
.restore_outer_row_binding(self.previous_outer_row.take());
self.ctes.source_outer_rewrites = std::mem::take(&mut self.previous_source_rewrites);
}
}
}
pub struct VisibleCteScope<'a, S: Clone> {
ctes: &'a mut CteScope<S>,
previous: Option<BindingNameSet>,
}
impl<S: Clone> std::ops::Deref for VisibleCteScope<'_, S> {
type Target = CteScope<S>;
fn deref(&self) -> &Self::Target {
self.ctes
}
}
impl<S: Clone> std::ops::DerefMut for VisibleCteScope<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.ctes
}
}
impl<S: Clone> Drop for VisibleCteScope<'_, S> {
fn drop(&mut self) {
if let Some(previous) = self.previous.take() {
self.ctes.visible_cte_names = previous;
}
}
}