uqa_sql/routines/inlining/
table.rs1use super::{
10 arguments, ensure_routine_execute_privilege, properties, sql_function_result_layout,
11 ColumnType, CreateFunction, FunctionBinding, RoutineInliningContext, SQLError,
12 SQLFunctionResultKind, ScalarExpr, UnifiedPlan,
13};
14use crate::ast::FunctionVolatility;
15use crate::plan::QueryPlan;
16
17mod scopes;
18
19pub struct InlineRoutineQuery {
20 pub identity: [u8; 16],
21 pub query: Box<QueryPlan>,
22 pub declared_columns: Option<Vec<String>>,
24}
25
26impl RoutineInliningContext<'_> {
27 pub fn scalar_from_columns(
29 &self,
30 binding: &FunctionBinding,
31 arguments: &[ScalarExpr],
32 output_name: &str,
33 alias: Option<&str>,
34 columns: &[String],
35 ordinality: bool,
36 ) -> Result<Option<Vec<String>>, SQLError> {
37 let Some(function) = self.selected_function(binding) else {
38 return Ok(None);
39 };
40 if function.def.returns_set()
41 || !closed_arguments(self, arguments)?
42 || crate::semantics::user_function_composite_result(
43 self.routines,
44 &function,
45 binding.invocation.as_deref(),
46 )?
47 .is_some()
48 {
49 return Ok(None);
50 }
51 let names = crate::semantics::user_table_function_columns(
52 self.routines,
53 &function,
54 binding.invocation.as_deref(),
55 output_name,
56 alias,
57 columns,
58 ordinality,
59 )?;
60 Ok((names.len() == 1 + usize::from(ordinality)).then_some(names))
61 }
62
63 pub fn prepare_table(
65 &self,
66 binding: &FunctionBinding,
67 arguments: &[ScalarExpr],
68 active: &[[u8; 16]],
69 column_names: &[String],
70 column_types: &[String],
71 ) -> Result<Option<InlineRoutineQuery>, SQLError> {
72 let Some(function) = self.selected_function(binding) else {
73 return Ok(None);
74 };
75 let Some(identity) = binding.object_id else {
76 return Ok(None);
77 };
78 let Some(invocation) = binding.invocation.as_deref() else {
79 return Ok(None);
80 };
81 let specialized =
82 super::super::invocation::specialized_definition(&function.def, invocation)?;
83 let definition = specialized.as_ref().unwrap_or(&function.def);
84 if active.contains(&identity) || !eligible_definition(definition) {
85 return Ok(None);
86 }
87 let Some(arguments) = arguments::prepare(self, definition, invocation, arguments)? else {
88 return Ok(None);
89 };
90 if !substitutable_arguments(self, &arguments)? {
91 return Ok(None);
92 }
93 match ensure_routine_execute_privilege(self.authority, definition) {
94 Ok(()) => {}
95 Err(error) if error.sqlstate() == Some("42501") => return Ok(None),
96 Err(error) => return Err(error),
97 }
98 let Some((plan, result, _)) =
99 self.analyze_plan(&function, definition).map_err(|error| {
100 error.with_context(super::super::diagnostics::sql_context(
101 definition,
102 super::super::diagnostics::SQLRoutineStage::Inlining,
103 ))
104 })?
105 else {
106 return Ok(None);
107 };
108 let UnifiedPlan::Query(mut query) = plan else {
109 return Ok(None);
110 };
111 if query.ctes.iter().any(|cte| cte.body.modifies_data()) {
112 return Ok(None);
113 }
114 self.bind_inline_relations(&mut query).map_err(|error| {
115 error.with_context(super::super::diagnostics::sql_context(
116 definition,
117 super::super::diagnostics::SQLRoutineStage::Inlining,
118 ))
119 })?;
120 let layout = self
121 .table_result_layout(definition, &result, column_names, column_types)
122 .map_err(|error| {
123 error.with_context(super::super::diagnostics::sql_context(
124 definition,
125 super::super::diagnostics::SQLRoutineStage::Inlining,
126 ))
127 })?;
128 if layout.kind == SQLFunctionResultKind::Void
129 || layout.kind == SQLFunctionResultKind::Value
130 && matches!(
131 crate::type_resolution::base_type(&layout.declared_type),
132 ColumnType::Composite(_) | ColumnType::Record
133 )
134 {
135 return Ok(None);
136 }
137 let targets = layout.columns.as_ref().map_or_else(
138 || vec![layout.declared_type.clone()],
139 |columns| columns.iter().map(|column| column.ty.clone()).collect(),
140 );
141 let source_types = result.column_types().unwrap_or_default();
142 if source_types.len() != targets.len() {
143 return Ok(None);
144 }
145 query = Box::new(scopes::coerce_result(*query, &targets, source_types));
146 let declared_columns = crate::semantics::user_function_declared_columns(
147 self.routines,
148 &function,
149 Some(invocation),
150 )?
151 .or_else(|| {
152 layout
153 .columns
154 .as_ref()
155 .map(|columns| columns.iter().map(|column| column.name.clone()).collect())
156 });
157 query = scopes::substitute(query, &arguments, targets.len())?;
158 Ok(Some(InlineRoutineQuery {
159 identity,
160 query,
161 declared_columns,
162 }))
163 }
164 fn bind_inline_relations(&self, query: &mut QueryPlan) -> Result<(), SQLError> {
165 let namespace = self.catalog.stored_query_namespace();
166 let mode = if query.relations_bound {
167 crate::catalog::resolution::RelationLookupMode::Bound
168 } else {
169 crate::catalog::resolution::RelationLookupMode::Dynamic
170 };
171 let mut dependencies = std::collections::BTreeSet::default();
172 crate::binding::view_dependencies::bind_query_plan_relations(
173 query,
174 &namespace.transition_relations,
175 &mut |reference| {
176 let mut reference = reference.to_string();
177 crate::binding::stored_relations::bind_catalog_relation_reference(
178 self.relations,
179 &mut reference,
180 mode,
181 false,
182 "function",
183 &mut dependencies,
184 )?;
185 Ok::<_, SQLError>(reference)
186 },
187 )
188 }
189
190 fn table_result_layout(
191 &self,
192 definition: &CreateFunction,
193 result: &crate::binding::statements::AnalyzedResult,
194 names: &[String],
195 types: &[String],
196 ) -> Result<super::super::result_check::SQLFunctionResultLayout, SQLError> {
197 use super::super::result_check::{
198 validate_anonymous_record_result, SQLFunctionResultColumn,
199 };
200 let mut layout = sql_function_result_layout(self.types, definition, Some(result))?;
201 if layout.kind == SQLFunctionResultKind::Tuple && !types.is_empty() {
202 let target = names
203 .iter()
204 .zip(types)
205 .map(|(name, ty)| {
206 Ok(SQLFunctionResultColumn {
207 name: name.clone(),
208 ty: self.types.resolve_catalog_column_type_name(ty)?,
209 })
210 })
211 .collect::<Result<Vec<_>, SQLError>>()?;
212 validate_anonymous_record_result(
213 self.types,
214 result.column_types().unwrap_or_default(),
215 &target,
216 Some(SQLFunctionResultKind::Tuple),
217 )?;
218 layout.columns = Some(target);
219 }
220 Ok(layout)
221 }
222}
223
224pub(super) fn eligible_definition(definition: &CreateFunction) -> bool {
225 definition.language == "sql"
226 && definition.returns_set()
227 && definition.volatility != FunctionVolatility::Volatile
228 && !definition.strict
229 && !definition.security.security_definer
230 && definition.config.is_empty()
231}
232
233fn closed_arguments(
234 context: &RoutineInliningContext<'_>,
235 arguments: &[ScalarExpr],
236) -> Result<bool, SQLError> {
237 for argument in arguments {
239 let mut closed = true;
240 argument.visit(&mut |node| {
241 closed &= !matches!(
242 node,
243 ScalarExpr::Column(_)
244 | ScalarExpr::QualifiedColumn { .. }
245 | ScalarExpr::InternalColumn(_)
246 | ScalarExpr::ScalarSubquery(_)
247 | ScalarExpr::Exists { .. }
248 | ScalarExpr::InSubquery { .. }
249 );
250 });
251 if !closed
252 || properties::volatility(context, argument, &crate::RowSchema::default())?
253 == FunctionVolatility::Volatile
254 {
255 return Ok(false);
256 }
257 }
258 Ok(true)
259}
260
261fn substitutable_arguments(
262 context: &RoutineInliningContext<'_>,
263 arguments: &[ScalarExpr],
264) -> Result<bool, SQLError> {
265 for argument in arguments {
266 let mut subplan = false;
267 argument.visit(&mut |node| {
268 subplan |= matches!(
269 node,
270 ScalarExpr::ScalarSubquery(_)
271 | ScalarExpr::Exists { .. }
272 | ScalarExpr::InSubquery { .. }
273 );
274 });
275 if subplan
276 || properties::volatility(context, argument, &crate::RowSchema::default())?
277 == FunctionVolatility::Volatile
278 {
279 return Ok(false);
280 }
281 }
282 Ok(true)
283}