Skip to main content

operator/statement/
admin.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod event;
16mod layer;
17
18use std::sync::Arc;
19
20use common_function::function::FunctionContext;
21use common_function::function_registry::{FUNCTION_REGISTRY, get_admin_function};
22use common_function::state::FunctionState;
23use common_query::Output;
24use common_recordbatch::{RecordBatch, RecordBatches};
25use common_sql::convert::sql_value_to_value;
26use common_telemetry::tracing;
27use common_time::Timezone;
28use datafusion_expr::TypeSignature;
29use datatypes::arrow::datatypes::DataType as ArrowDataType;
30use datatypes::data_type::DataType;
31use datatypes::prelude::ConcreteDataType;
32use datatypes::schema::{ColumnSchema, Schema};
33use datatypes::value::Value;
34use datatypes::vectors::VectorRef;
35pub use layer::{
36    AdminEventRecorderHandle, AdminFunctionLayer, AdminFunctionLayerRef,
37    AdminFunctionRecordingLayer,
38};
39use session::context::QueryContextRef;
40use snafu::{OptionExt, ResultExt, ensure};
41use sql::ast::{
42    Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments, Value as SqlValue,
43};
44use sql::statements::admin::Admin;
45use sqlparser::ast::UnaryOperator;
46
47use crate::error::{self, CastSnafu, ExecuteAdminFunctionSnafu, Result};
48use crate::statement::StatementExecutor;
49
50const DUMMY_COLUMN: &str = "<dummy>";
51
52/// A request to execute one ADMIN function statement.
53#[derive(Clone)]
54pub struct AdminFunctionRequest {
55    /// The parsed ADMIN statement to execute.
56    pub statement: Admin,
57    /// The query context of the request.
58    pub query_ctx: QueryContextRef,
59}
60
61/// The client output and immediate typed result of one ADMIN function execution.
62pub struct AdminFunctionResponse {
63    /// The output returned to the client.
64    pub output: Output,
65    /// The typed immediate result exposed to outer layers.
66    pub immediate_result: Option<Value>,
67}
68
69/// Executes an ADMIN function request.
70#[async_trait::async_trait]
71pub trait AdminFunctionService: Send + Sync {
72    /// Executes an ADMIN function request.
73    async fn call(&self, request: AdminFunctionRequest) -> Result<AdminFunctionResponse>;
74}
75
76/// A shared ADMIN function service.
77pub type AdminFunctionServiceRef = Arc<dyn AdminFunctionService>;
78
79#[derive(Clone)]
80struct CoreAdminFunctionService {
81    query_engine: query::QueryEngineRef,
82}
83
84/// Parts of an `ADMIN` call needed both for execution and schema derivation.
85#[derive(Debug)]
86struct ResolvedAdminFunction {
87    admin_udf: datafusion_expr::ScalarUDF,
88    fn_name: String,
89    args: Vec<VectorRef>,
90    arg_types: Vec<ArrowDataType>,
91    ret_type: ArrowDataType,
92}
93
94/// Modifiers the SQL parser attaches to a function call; `ADMIN` executes a
95/// bare call and must not silently drop them.
96fn admin_function_modifiers(func: &Function) -> Vec<String> {
97    let mut modifiers = Vec::new();
98    if !matches!(&func.parameters, FunctionArguments::None) {
99        modifiers.push(format!("parametric arguments `{}`", func.parameters));
100    }
101    if let FunctionArguments::List(args) = &func.args {
102        modifiers.extend(args.duplicate_treatment.as_ref().map(|t| t.to_string()));
103        modifiers.extend(args.clauses.iter().map(|clause| clause.to_string()));
104    }
105    if !func.within_group.is_empty() {
106        modifiers.push("WITHIN GROUP".to_string());
107    }
108    if func.filter.is_some() {
109        modifiers.push("FILTER".to_string());
110    }
111    if let Some(null_treatment) = &func.null_treatment {
112        modifiers.push(null_treatment.to_string());
113    }
114    if func.over.is_some() {
115        modifiers.push("OVER".to_string());
116    }
117    modifiers
118}
119
120/// Resolves the function, parses its literal arguments and derives its
121/// return type, without executing it.
122fn resolve_admin_function(
123    stmt: &Admin,
124    query_ctx: &QueryContextRef,
125    state: Arc<FunctionState>,
126) -> Result<ResolvedAdminFunction> {
127    let Admin::Func(func) = stmt;
128    let modifiers = admin_function_modifiers(func);
129    ensure!(
130        modifiers.is_empty(),
131        error::BuildAdminFunctionArgsSnafu {
132            msg: format!(
133                "ADMIN {} does not accept {}",
134                func.name,
135                modifiers.join("/")
136            ),
137        }
138    );
139    // the function name should be in lower case.
140    let func_name = func.name.to_string().to_lowercase();
141    let factory = get_admin_function(&func_name)
142        .or_else(|| FUNCTION_REGISTRY.get_function(&func_name))
143        .context(error::AdminFunctionNotFoundSnafu {
144            name: func_name.clone(),
145        })?;
146
147    let func_ctx = FunctionContext {
148        query_ctx: query_ctx.clone(),
149        state,
150    };
151
152    let admin_udf = factory.provide(func_ctx);
153    admin_udf
154        .as_async()
155        .context(error::AdminFunctionNotFoundSnafu { name: func_name })?;
156
157    let fn_name = admin_udf.name().to_string();
158    let signature = admin_udf.signature();
159
160    // Parse function arguments
161    let FunctionArguments::List(args) = &func.args else {
162        return error::BuildAdminFunctionArgsSnafu {
163            msg: format!("unsupported function args {} for {}", func.args, fn_name),
164        }
165        .fail();
166    };
167    // A signed numeric literal is a unary expression in sqlparser: accept one
168    // leading sign per argument.
169    let mut owned_args = Vec::with_capacity(args.args.len());
170    for arg in &args.args {
171        let value = match arg {
172            FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(value))) => value.value.clone(),
173            FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::UnaryOp { op, expr })) => {
174                let Expr::Value(value) = expr.as_ref() else {
175                    return error::BuildAdminFunctionArgsSnafu {
176                        msg: format!("unsupported function arg {arg} for {}", fn_name),
177                    }
178                    .fail();
179                };
180                let SqlValue::Number(raw, _) = &value.value else {
181                    return error::BuildAdminFunctionArgsSnafu {
182                        msg: format!("unsupported function arg {arg} for {}", fn_name),
183                    }
184                    .fail();
185                };
186                match op {
187                    UnaryOperator::Plus => SqlValue::Number(raw.clone(), false),
188                    UnaryOperator::Minus => SqlValue::Number(format!("-{raw}"), false),
189                    _ => {
190                        return error::BuildAdminFunctionArgsSnafu {
191                            msg: format!("unsupported function arg {arg} for {}", fn_name),
192                        }
193                        .fail();
194                    }
195                }
196            }
197            _ => {
198                return error::BuildAdminFunctionArgsSnafu {
199                    msg: format!("unsupported function arg {arg} for {}", fn_name),
200                }
201                .fail();
202            }
203        };
204        owned_args.push(value);
205    }
206    let arg_values = owned_args.iter().collect::<Vec<_>>();
207
208    let args = args_to_vector(&signature.type_signature, &arg_values, query_ctx)?;
209    let arg_types = args
210        .iter()
211        .map(|arg| arg.data_type().as_arrow_type())
212        .collect::<Vec<_>>();
213    let ret_type =
214        admin_udf
215            .return_type(&arg_types)
216            .map_err(|e| error::Error::BuildAdminFunctionArgs {
217                msg: format!(
218                    "Failed to get return type of admin function {}: {}",
219                    fn_name, e
220                ),
221            })?;
222
223    Ok(ResolvedAdminFunction {
224        admin_udf,
225        fn_name,
226        args,
227        arg_types,
228        ret_type,
229    })
230}
231
232/// Output schema of an `ADMIN` statement, mirroring what
233/// [`CoreAdminFunctionService::execute`] produces. `None` if the function
234/// or arguments are unresolvable; execution will then surface the error.
235pub fn admin_output_schema(stmt: &Admin, query_ctx: &QueryContextRef) -> Option<Schema> {
236    let resolved =
237        resolve_admin_function(stmt, query_ctx, Arc::new(FunctionState::default())).ok()?;
238    Some(Schema::new(vec![ColumnSchema::new(
239        // Use statement as the result column name
240        stmt.to_string(),
241        ConcreteDataType::from_arrow_type(&resolved.ret_type),
242        false,
243    )]))
244}
245
246impl CoreAdminFunctionService {
247    fn new(query_engine: query::QueryEngineRef) -> Self {
248        Self { query_engine }
249    }
250
251    async fn execute(&self, request: AdminFunctionRequest) -> Result<AdminFunctionResponse> {
252        let AdminFunctionRequest {
253            statement: stmt,
254            query_ctx,
255        } = request;
256
257        let resolved = resolve_admin_function(
258            &stmt,
259            &query_ctx,
260            self.query_engine.engine_state().function_state(),
261        )?;
262        let ResolvedAdminFunction {
263            admin_udf,
264            fn_name,
265            args,
266            arg_types,
267            ret_type,
268        } = resolved;
269        let admin_async_fn = admin_udf
270            .as_async()
271            .context(error::AdminFunctionNotFoundSnafu {
272                name: fn_name.clone(),
273            })?;
274
275        // Convert arguments to DataFusion ColumnarValue format
276        let columnar_args: Vec<datafusion_expr::ColumnarValue> = args
277            .iter()
278            .map(|vector| datafusion_expr::ColumnarValue::Array(vector.to_arrow_array()))
279            .collect();
280
281        // Create ScalarFunctionArgs following the same pattern as udf.rs
282        let func_args = datafusion::logical_expr::ScalarFunctionArgs {
283            args: columnar_args,
284            arg_fields: args
285                .iter()
286                .enumerate()
287                .map(|(i, vector)| {
288                    Arc::new(arrow::datatypes::Field::new(
289                        format!("arg_{}", i),
290                        arg_types[i].clone(),
291                        vector.null_count() > 0,
292                    ))
293                })
294                .collect(),
295            return_field: Arc::new(arrow::datatypes::Field::new("result", ret_type, true)),
296            number_rows: if args.is_empty() { 1 } else { args[0].len() },
297            config_options: Arc::new(query_ctx.create_config_options()),
298        };
299
300        // Execute the async UDF
301        let result_columnar = admin_async_fn
302            .invoke_async_with_args(func_args)
303            .await
304            .with_context(|_| ExecuteAdminFunctionSnafu { msg: fn_name })?;
305
306        // Convert result back to VectorRef
307        let result_columnar: common_query::prelude::ColumnarValue =
308            (&result_columnar).try_into().context(CastSnafu)?;
309
310        let result_vector: VectorRef = result_columnar.try_into_vector(1).context(CastSnafu)?;
311        let immediate_result = immediate_result(&result_vector);
312
313        let column_schemas = vec![ColumnSchema::new(
314            // Use statement as the result column name
315            stmt.to_string(),
316            result_vector.data_type(),
317            false,
318        )];
319        let schema = Arc::new(Schema::new(column_schemas));
320        let batch = RecordBatch::new(schema.clone(), vec![result_vector])
321            .context(error::BuildRecordBatchSnafu)?;
322        let batches =
323            RecordBatches::try_new(schema, vec![batch]).context(error::BuildRecordBatchSnafu)?;
324
325        Ok(AdminFunctionResponse {
326            output: Output::new_with_record_batches(batches),
327            immediate_result,
328        })
329    }
330}
331
332fn immediate_result(result_vector: &VectorRef) -> Option<Value> {
333    (!result_vector.is_empty()).then(|| result_vector.get(0))
334}
335
336#[async_trait::async_trait]
337impl AdminFunctionService for CoreAdminFunctionService {
338    async fn call(&self, request: AdminFunctionRequest) -> Result<AdminFunctionResponse> {
339        self.execute(request).await
340    }
341}
342
343/// Creates the core ADMIN function service.
344pub(crate) fn new_admin_function_service(
345    query_engine: query::QueryEngineRef,
346) -> AdminFunctionServiceRef {
347    Arc::new(CoreAdminFunctionService::new(query_engine))
348}
349
350impl StatementExecutor {
351    /// Executes the [`Admin`] statement and returns the output.
352    #[tracing::instrument(skip_all)]
353    pub(crate) async fn execute_admin_command(
354        &self,
355        stmt: Admin,
356        query_ctx: QueryContextRef,
357    ) -> Result<Output> {
358        self.admin_function_service
359            .call(AdminFunctionRequest {
360                statement: stmt,
361                query_ctx,
362            })
363            .await
364            .map(|response| response.output)
365    }
366}
367
368/// Try to cast the arguments to vectors by function's signature.
369fn args_to_vector(
370    type_signature: &TypeSignature,
371    args: &Vec<&SqlValue>,
372    query_ctx: &QueryContextRef,
373) -> Result<Vec<VectorRef>> {
374    let tz = query_ctx.timezone();
375
376    match type_signature {
377        TypeSignature::Nullary => {
378            ensure!(
379                args.is_empty(),
380                error::FunctionArityMismatchSnafu {
381                    actual: args.len(),
382                    expected: 0_usize,
383                }
384            );
385            Ok(vec![])
386        }
387
388        TypeSignature::Variadic(valid_types) => {
389            values_to_vectors_by_valid_types(valid_types, args, Some(&tz))
390        }
391
392        TypeSignature::Uniform(arity, valid_types) => {
393            ensure!(
394                *arity == args.len(),
395                error::FunctionArityMismatchSnafu {
396                    actual: args.len(),
397                    expected: *arity,
398                }
399            );
400
401            values_to_vectors_by_valid_types(valid_types, args, Some(&tz))
402        }
403
404        TypeSignature::Exact(data_types) => {
405            ensure!(
406                args.len() == data_types.len(),
407                error::FunctionArityMismatchSnafu {
408                    actual: args.len(),
409                    expected: data_types.len(),
410                }
411            );
412            values_to_vectors_by_exact_types(data_types, args, Some(&tz))
413        }
414
415        TypeSignature::VariadicAny => {
416            let data_types = args
417                .iter()
418                .map(|value| try_get_data_type_for_sql_value(value))
419                .collect::<Result<Vec<_>>>()?;
420
421            values_to_vectors_by_exact_types(&data_types, args, Some(&tz))
422        }
423
424        TypeSignature::Any(arity) => {
425            ensure!(
426                *arity == args.len(),
427                error::FunctionArityMismatchSnafu {
428                    actual: args.len(),
429                    expected: *arity,
430                }
431            );
432
433            let data_types = args
434                .iter()
435                .map(|value| try_get_data_type_for_sql_value(value))
436                .collect::<Result<Vec<_>>>()?;
437
438            values_to_vectors_by_exact_types(&data_types, args, Some(&tz))
439        }
440
441        TypeSignature::OneOf(type_sigs) => {
442            for type_sig in type_sigs {
443                if let Ok(vectors) = args_to_vector(type_sig, args, query_ctx) {
444                    return Ok(vectors);
445                }
446            }
447
448            error::BuildAdminFunctionArgsSnafu {
449                msg: "function signature not match",
450            }
451            .fail()
452        }
453
454        _ => error::BuildAdminFunctionArgsSnafu {
455            msg: format!("unknown function type signature: {type_signature:?}"),
456        }
457        .fail(),
458    }
459}
460
461/// Try to cast sql values to vectors by exact data types.
462fn values_to_vectors_by_exact_types(
463    exact_types: &[ArrowDataType],
464    args: &[&SqlValue],
465    tz: Option<&Timezone>,
466) -> Result<Vec<VectorRef>> {
467    args.iter()
468        .zip(exact_types.iter())
469        .map(|(value, data_type)| {
470            let schema = ColumnSchema::new(
471                DUMMY_COLUMN,
472                ConcreteDataType::from_arrow_type(data_type),
473                true,
474            );
475            let value = sql_value_to_value(&schema, value, tz, None, false)
476                .context(error::SqlCommonSnafu)?;
477
478            Ok(value_to_vector(value))
479        })
480        .collect()
481}
482
483/// Try to cast sql values to vectors by valid data types.
484fn values_to_vectors_by_valid_types(
485    valid_types: &[ArrowDataType],
486    args: &[&SqlValue],
487    tz: Option<&Timezone>,
488) -> Result<Vec<VectorRef>> {
489    args.iter()
490        .map(|value| {
491            for data_type in valid_types {
492                let schema = ColumnSchema::new(
493                    DUMMY_COLUMN,
494                    ConcreteDataType::from_arrow_type(data_type),
495                    true,
496                );
497                if let Ok(value) = sql_value_to_value(&schema, value, tz, None, false) {
498                    return Ok(value_to_vector(value));
499                }
500            }
501
502            error::BuildAdminFunctionArgsSnafu {
503                msg: format!("failed to cast {value}"),
504            }
505            .fail()
506        })
507        .collect::<Result<Vec<_>>>()
508}
509
510/// Build a [`VectorRef`] from [`Value`]
511fn value_to_vector(value: Value) -> VectorRef {
512    let data_type = value.data_type();
513    let mut mutable_vector = data_type.create_mutable_vector(1);
514    mutable_vector.push_value_ref(&value.as_value_ref());
515
516    mutable_vector.to_vector()
517}
518
519/// Try to infer the data type from sql value.
520fn try_get_data_type_for_sql_value(value: &SqlValue) -> Result<ArrowDataType> {
521    match value {
522        SqlValue::Number(_, _) => Ok(ArrowDataType::Float64),
523        SqlValue::Null => Ok(ArrowDataType::Null),
524        SqlValue::Boolean(_) => Ok(ArrowDataType::Boolean),
525        SqlValue::HexStringLiteral(_)
526        | SqlValue::DoubleQuotedString(_)
527        | SqlValue::SingleQuotedString(_) => Ok(ArrowDataType::Utf8),
528        _ => error::BuildAdminFunctionArgsSnafu {
529            msg: format!("unsupported sql value: {value}"),
530        }
531        .fail(),
532    }
533}
534
535#[cfg(test)]
536mod tests {
537    use std::sync::Arc;
538
539    use common_error::ext::ErrorExt;
540    use common_error::status_code::StatusCode;
541    use common_function::state::FunctionState;
542    use datafusion_expr::TypeSignature;
543    use datatypes::arrow::datatypes::DataType as ArrowDataType;
544    use datatypes::value::Value;
545    use datatypes::vectors::{Int32Vector, VectorRef};
546    use session::context::{Channel, QueryContext, QueryContextRef};
547    use sql::ast::Value as SqlValue;
548    use sql::dialect::GreptimeDbDialect;
549    use sql::parser::{ParseOptions, ParserContext};
550    use sql::statements::admin::Admin;
551    use sql::statements::statement::Statement;
552
553    use crate::error::Error;
554    use crate::statement::admin::{
555        AdminFunctionRequest, AdminFunctionResponse, admin_output_schema, args_to_vector,
556        immediate_result, new_admin_function_service, resolve_admin_function,
557    };
558
559    fn parse_admin(sql: &str) -> Admin {
560        let Statement::Admin(statement) =
561            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
562                .unwrap_or_else(|e| panic!("{sql} must parse: {e}"))
563                .remove(0)
564        else {
565            panic!("{sql} must be an ADMIN statement");
566        };
567        statement
568    }
569
570    fn resolved_args(sql: &str) -> Result<Vec<Value>, Error> {
571        resolve_admin_function(
572            &parse_admin(sql),
573            &QueryContext::arc(),
574            Arc::new(FunctionState::default()),
575        )
576        .map(|resolved| resolved.args.iter().map(|arg| arg.get(0)).collect())
577    }
578
579    #[test]
580    fn test_admin_rejects_statement_modifiers() {
581        for (sql, modifier) in [
582            ("ADMIN gc_regions(1) FILTER (WHERE false)", "FILTER"),
583            ("ADMIN gc_regions(DISTINCT 1)", "DISTINCT"),
584            ("ADMIN gc_regions(ALL 1)", "ALL"),
585            ("ADMIN gc_regions(1 ORDER BY 1)", "ORDER BY 1"),
586            ("ADMIN gc_regions(1 LIMIT 1)", "LIMIT 1"),
587            (
588                "ADMIN gc_regions(1) WITHIN GROUP (ORDER BY 1)",
589                "WITHIN GROUP",
590            ),
591            ("ADMIN gc_regions(1) IGNORE NULLS", "IGNORE NULLS"),
592            ("ADMIN gc_regions(1) OVER ()", "OVER"),
593        ] {
594            let error = resolved_args(sql).unwrap_err();
595            let Error::BuildAdminFunctionArgs { msg } = &error else {
596                panic!("{sql} must be rejected as unsupported arguments: {error}");
597            };
598            assert_eq!(
599                format!("ADMIN gc_regions does not accept {modifier}"),
600                *msg,
601                "{sql}"
602            );
603        }
604    }
605
606    #[test]
607    fn test_admin_signed_numeric_args_resolve() {
608        // `gc_regions` takes any argument, so only the literal itself decides.
609        for (sql, expected) in [
610            ("ADMIN gc_regions(-1000)", -1000.0),
611            ("ADMIN gc_regions(+1000)", 1000.0),
612        ] {
613            let args = resolved_args(sql).unwrap_or_else(|e| panic!("{sql} must resolve: {e}"));
614            assert_eq!(vec![Value::from(expected)], args, "{sql}");
615        }
616
617        for sql in [
618            "ADMIN gc_regions(-'1000')",
619            "ADMIN gc_regions(- -1000)",
620            "ADMIN gc_regions(1 + 1)",
621        ] {
622            let err = resolved_args(sql).unwrap_err();
623            assert!(
624                matches!(err, Error::BuildAdminFunctionArgs { .. }),
625                "{sql}: {err}"
626            );
627        }
628    }
629
630    async fn call_admin(
631        sql: &str,
632        query_ctx: QueryContextRef,
633    ) -> Result<AdminFunctionResponse, Error> {
634        let query_engine = query::QueryEngineFactory::new(
635            catalog::memory::new_memory_catalog_manager().unwrap(),
636            None,
637            None,
638            None,
639            None,
640            false,
641            query::options::QueryOptions::default(),
642        )
643        .query_engine();
644
645        new_admin_function_service(query_engine)
646            .call(AdminFunctionRequest {
647                statement: parse_admin(sql),
648                query_ctx,
649            })
650            .await
651    }
652
653    #[tokio::test]
654    async fn test_admin_function_outside_the_default_catalog_is_permission_denied() {
655        let other_catalog = Arc::new(QueryContext::with_channel(
656            "other_catalog",
657            "public",
658            Channel::Postgres,
659        ));
660
661        let error = call_admin("ADMIN flush_flow('flow')", other_catalog)
662            .await
663            .err()
664            .unwrap();
665        assert_eq!(StatusCode::PermissionDenied, error.status_code());
666    }
667
668    #[test]
669    fn test_args_to_vector_arity() {
670        let query_ctx = QueryContext::arc();
671        let value = SqlValue::SingleQuotedString("explicit-id".to_string());
672        for (signature, expected) in [
673            (TypeSignature::Nullary, 0),
674            (TypeSignature::Exact(vec![]), 0),
675            (TypeSignature::Exact(vec![ArrowDataType::Utf8]), 1),
676            (TypeSignature::Exact(vec![ArrowDataType::Utf8; 2]), 2),
677        ] {
678            for actual in 0..=3 {
679                let result = args_to_vector(&signature, &vec![&value; actual], &query_ctx);
680                if actual == expected {
681                    let vectors = result.unwrap();
682                    assert_eq!(vectors.len(), expected);
683                    for vector in vectors {
684                        assert_eq!(vector.get(0), Value::from("explicit-id"));
685                    }
686                } else {
687                    assert!(matches!(
688                        result,
689                        Err(Error::FunctionArityMismatch { actual: a, expected: e })
690                            if a == actual && e == expected
691                    ));
692                }
693            }
694        }
695    }
696
697    #[test]
698    fn test_admin_reconcile_catalog_nullary() {
699        let Statement::Admin(statement) = ParserContext::create_with_dialect(
700            "ADMIN reconcile_catalog()",
701            &GreptimeDbDialect {},
702            ParseOptions::default(),
703        )
704        .unwrap()
705        .remove(0) else {
706            panic!("expected ADMIN statement");
707        };
708        assert!(admin_output_schema(&statement, &QueryContext::arc()).is_some());
709    }
710
711    #[test]
712    fn empty_admin_function_result_has_no_immediate_value() {
713        let result_vector: VectorRef = Arc::new(Int32Vector::from(vec![]));
714
715        assert_eq!(immediate_result(&result_vector), None);
716    }
717}