Skip to main content

micromegas/servers/
flight_sql_service_impl.rs

1use super::deployment_notes_table_function::register_deployment_notes;
2use super::http_utils::get_client_ip;
3use super::query_admission::{AdmissionPermit, AdmissionScheduler};
4use super::query_audit::{OutputStats, QueryAuditRecord, ScanMetrics, aggregate_scan_metrics};
5use super::sqlinfo::{
6    SQL_INFO_DATE_TIME_FUNCTIONS, SQL_INFO_NUMERIC_FUNCTIONS, SQL_INFO_SQL_KEYWORDS,
7    SQL_INFO_STRING_FUNCTIONS, SQL_INFO_SYSTEM_FUNCTIONS,
8};
9use crate::settings::SettingsSource;
10use anyhow::Result;
11use arrow_flight::decode::FlightRecordBatchStream;
12use arrow_flight::encode::{DictionaryHandling, FlightDataEncoderBuilder};
13use arrow_flight::error::FlightError;
14use arrow_flight::sql::DoPutPreparedStatementResult;
15use arrow_flight::sql::metadata::{SqlInfoData, SqlInfoDataBuilder};
16use arrow_flight::sql::server::PeekableFlightDataStream;
17use arrow_flight::sql::{
18    ActionBeginSavepointRequest, ActionBeginSavepointResult, ActionBeginTransactionRequest,
19    ActionBeginTransactionResult, ActionCancelQueryRequest, ActionCancelQueryResult,
20    ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
21    ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
22    ActionEndSavepointRequest, ActionEndTransactionRequest, Any, CommandGetCatalogs,
23    CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys,
24    CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
25    CommandGetXdbcTypeInfo, CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
26    CommandStatementIngest, CommandStatementQuery, CommandStatementSubstraitPlan,
27    CommandStatementUpdate, ProstMessageExt, SqlInfo, TicketStatementQuery,
28    server::FlightSqlService,
29};
30use arrow_flight::{
31    Action, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest, HandshakeResponse,
32    Ticket, flight_service_server::FlightService,
33};
34use core::str;
35use datafusion::arrow::array::{RecordBatch, StringArray};
36use datafusion::arrow::datatypes::{DataType, Field, Schema};
37use datafusion::arrow::ipc::writer::StreamWriter;
38use datafusion::error::DataFusionError;
39use datafusion::physical_plan::{ExecutionPlan, execute_stream};
40use futures::StreamExt;
41use futures::{Stream, TryStreamExt};
42use micromegas_analytics::lakehouse::lakehouse_context::LakehouseContext;
43use micromegas_analytics::lakehouse::partition_cache::QueryPartitionProvider;
44use micromegas_analytics::lakehouse::query::{SessionRange, make_session_context};
45use micromegas_analytics::lakehouse::query_deny_list::{
46    QueryAttribution, fingerprint_of, skip_for_admin_recovery,
47};
48use micromegas_analytics::lakehouse::read_scope::{CallerContext, ReadScope};
49use micromegas_analytics::lakehouse::runtime::scoped_runtime;
50use micromegas_analytics::lakehouse::scan_cost::estimate_scan_cost;
51use micromegas_analytics::lakehouse::scoped_memory_pool::ScopedMemoryPool;
52use micromegas_analytics::lakehouse::session_configurator::SessionConfigurator;
53use micromegas_analytics::lakehouse::view_definition::{
54    build_sql_batch_view, validate_view_definition,
55};
56use micromegas_analytics::lakehouse::view_definition_store::{
57    delete_tx, list_tx, partition_insert_range, upsert_tx,
58};
59use micromegas_analytics::lakehouse::view_registry::{BuildPurpose, ViewRegistry};
60use micromegas_analytics::lakehouse::write_partition::{RetireMatch, retire_partitions};
61use micromegas_analytics::replication::bulk_ingest;
62use micromegas_analytics::response_writer::ResponseWriter;
63use micromegas_analytics::time::TimeRange;
64use micromegas_auth::policy::{ReadPolicy, ReadableAudiences, caller_selectors};
65use micromegas_auth::types::{AuthContext, ProviderUnavailable};
66use micromegas_auth::user_attribution::{is_admin, validate_and_resolve_user_attribution_grpc};
67use micromegas_ingestion::remote_data_lake::acquire_lock;
68use micromegas_tracing::prelude::*;
69use once_cell::sync::Lazy;
70use prost::Message;
71use std::pin::Pin;
72use std::str::FromStr;
73use std::sync::Arc;
74use std::task::{Context, Poll};
75use std::time::Instant;
76use tonic::metadata::MetadataMap;
77use tonic::{Request, Response, Status, Streaming};
78use uuid::Uuid;
79
80use super::view_ddl::{ViewDdl, authorize_view_ddl, parse_view_ddl};
81
82/// `pg_advisory_xact_lock` key serializing every view-definition mutation cluster-wide: `0` is
83/// `migrate_db`'s, `1` is `migrate_lakehouse`'s, so this DDL executor gets its own, `2`, rather
84/// than reusing either and serializing unrelated migrations against it.
85const VIEW_DDL_ADVISORY_LOCK_KEY: i64 = 2;
86
87type FlightDataStream =
88    Pin<Box<dyn Stream<Item = Result<arrow_flight::FlightData, Status>> + Send>>;
89
90macro_rules! status {
91    ($desc:expr, $err:expr) => {
92        Status::internal(format!("{}: {} at {}:{}", $desc, $err, file!(), line!()))
93    };
94}
95
96macro_rules! api_entry_not_implemented {
97    () => {{
98        let function_name = micromegas_tracing::__function_name!();
99        error!("not implemented: {function_name}");
100        Err(Status::unimplemented(format!(
101            "{}:{} not implemented: {function_name}",
102            file!(),
103            line!()
104        )))
105    }};
106}
107
108/// For gRPC-metadata parses that are unambiguously caller-supplied input
109/// (range-header/limit-header values the caller set directly) with no
110/// `DataFusionError` involved -- `Status::invalid_argument` directly, no
111/// file:line/path suffix (nothing here ever went through `status!`'s own
112/// `file!()/line!()`).
113macro_rules! client_input_error {
114    ($desc:expr, $err:expr) => {
115        Status::invalid_argument(format!("{}: {}", $desc, $err))
116    };
117}
118
119/// Classifies the root cause of a `DataFusionError` into the gRPC status code
120/// that best distinguishes "the caller's SQL/input was bad" from "the server
121/// broke": `Execution`/`Configuration` land under `InvalidArgument` since they
122/// signal bad input, while `ArrowError` stays `Internal` since it reflects a
123/// real server-side decode failure.
124pub fn classify_datafusion_error(err: &DataFusionError) -> tonic::Code {
125    use datafusion::error::DataFusionError as DFE;
126    match err.find_root() {
127        DFE::SQL(..)
128        | DFE::Plan(_)
129        | DFE::SchemaError(..)
130        | DFE::Execution(_)
131        | DFE::Configuration(_) => tonic::Code::InvalidArgument,
132        DFE::ResourcesExhausted(_) => tonic::Code::ResourceExhausted,
133        DFE::NotImplemented(_) => tonic::Code::Unimplemented,
134        _ => tonic::Code::Internal,
135    }
136}
137
138/// Maps a gRPC status code to the `QueryAuditRecord.error_class` bucket used
139/// both by the audit log and to gate the `query_failed`/
140/// `query_duration_with_error` metrics. This is the *derived* mapping used for
141/// every `DataFusionError`-rooted failure; the query-deny-list check stamps a fourth value,
142/// `"denied"`, directly via `QueryAuditState::fail_with_class` rather than through this
143/// function, since a denial's `ResourceExhausted` code would otherwise land in the
144/// `"resource"` bucket alongside a genuine resource-budget failure.
145pub fn error_class(code: tonic::Code) -> &'static str {
146    match code {
147        tonic::Code::InvalidArgument | tonic::Code::Unimplemented => "user",
148        tonic::Code::ResourceExhausted => "resource",
149        _ => "internal",
150    }
151}
152
153/// Cap on the physical-plan text appended to the server-side log line. The
154/// plan can render arbitrarily long `file_groups=` sections for wide
155/// scans, and this text is server-log-only, never returned to the client.
156pub const MAX_PLAN_CHARS: usize = 2000;
157
158/// Truncate `text` at a char boundary once it exceeds `MAX_PLAN_CHARS`, tagging
159/// the cut with a trailing marker. Driven by `char_indices()` (not byte
160/// length) so a multibyte plan text (e.g. a non-ASCII string literal from a
161/// query predicate, rendered via `ScalarValue`'s `Display` impl) can't panic
162/// on a byte-offset slice landing mid-character.
163fn truncate_plan_text(text: &str) -> String {
164    match text.char_indices().nth(MAX_PLAN_CHARS) {
165        None => text.to_string(),
166        Some((i, _)) => format!("{}... (truncated)", &text[..i]),
167    }
168}
169
170/// Builds the full server-side log line for a classified `DataFusionError`:
171/// `desc`, the error's own `Display` (its outer `Context` chain intact, with
172/// backtrace if enabled -- unlike `find_root()`, which is for classification
173/// only), the `query_id`, and -- when there's no diagnostic span to show the
174/// caller instead -- the truncated physical plan text. `pub` so
175/// tests can assert its content, including the truncation marker,
176/// without capturing log output.
177pub fn build_log_line(
178    desc: &str,
179    err: &DataFusionError,
180    query_id: &str,
181    plan: Option<&Arc<dyn ExecutionPlan>>,
182) -> String {
183    let mut full = format!("{desc}: {err} (query_id={query_id})");
184    if let Some(plan) = plan {
185        let plan_text = format!(
186            "{}",
187            datafusion::physical_plan::displayable(plan.as_ref()).indent(true)
188        );
189        full.push_str(&format!(
190            "\nphysical plan:\n{}",
191            truncate_plan_text(&plan_text)
192        ));
193    }
194    full
195}
196
197/// Builds the `warn!` line for a query-deny-list denial: the rule id, its
198/// reason, the query's normalized fingerprint, the caller's identity/client attribution, and
199/// the `query_id`. `pub` so a test can assert its content directly, the same way
200/// `build_log_line`'s content is asserted, rather than by capturing log output.
201#[allow(clippy::too_many_arguments)]
202pub fn build_denial_warn_line(
203    rule_id: &str,
204    reason: &str,
205    sql_hash: &str,
206    user: &str,
207    email: &str,
208    client: &str,
209    entrypoint: &str,
210    client_ip: &str,
211    query_id: &str,
212) -> String {
213    format!(
214        "query denied rule_id={rule_id} reason={reason:?} sql_hash={sql_hash} user={user} \
215         email={email} client={client} entrypoint={entrypoint} client_ip={client_ip} \
216         query_id={query_id}"
217    )
218}
219
220/// Logs `build_log_line`'s output at `error!` for `error_class == "internal"`,
221/// `warn!` otherwise -- the single log point for every `DataFusionError`
222/// reaching `client_error`/`classify_flight_error`.
223fn error_or_warn_log(
224    code: tonic::Code,
225    desc: &str,
226    err: &DataFusionError,
227    query_id: &str,
228    plan: Option<&Arc<dyn ExecutionPlan>>,
229) {
230    let full = build_log_line(desc, err, query_id, plan);
231    match error_class(code) {
232        "internal" => error!("{full}"),
233        _ => warn!("{full}"),
234    }
235}
236
237/// Classifies `err`, builds the client-facing `Status` -- `desc` + root-error
238/// text (backtrace stripped) + an optional diagnostic span/notes/helps +
239/// `query_id` -- and logs the full error server-side. The physical
240/// plan, when present and there's no diagnostic span to show instead, only
241/// ever reaches the server log, never the returned `Status`: `displayable`
242/// can render object-store partition paths from Micromegas view scans, which
243/// would leak internal lakehouse details to every caller hitting an
244/// execution-time error.
245pub fn client_error(
246    desc: &str,
247    err: DataFusionError,
248    query_id: &str,
249    plan: Option<&Arc<dyn ExecutionPlan>>,
250) -> Status {
251    let code = classify_datafusion_error(&err);
252    let mut msg = format!("{desc}: {}", err.find_root().strip_backtrace());
253    let mut has_span = false;
254    if let Some(diag) = err.diagnostic() {
255        if let Some(span) = diag.span {
256            has_span = true;
257            msg.push_str(&format!(
258                " (at line {}, column {})",
259                span.start.line, span.start.column
260            ));
261        }
262        for note in &diag.notes {
263            msg.push_str(&format!("\nnote: {}", note.message));
264        }
265        for help in &diag.helps {
266            msg.push_str(&format!("\nhelp: {}", help.message));
267        }
268    }
269    msg.push_str(&format!(" (query_id={query_id})"));
270    error_or_warn_log(
271        code,
272        desc,
273        &err,
274        query_id,
275        if has_span { None } else { plan },
276    );
277    Status::new(code, msg)
278}
279
280/// Recovers the `DataFusionError` from the per-batch `FlightError` re-wrap
281/// (`FlightError::ExternalError(Box::new(e))`, applied once the raw
282/// `DataFusionError` stream is wrapped for Arrow Flight) and classifies it via
283/// `client_error`. Every branch logs exactly once before returning, so this is
284/// a single, unconditional log point for the per-batch stream-error site
285/// regardless of which branch is taken. `pub` so step 9's external
286/// integration tests can exercise this recovery path directly.
287pub fn classify_flight_error(
288    err: FlightError,
289    query_id: &str,
290    plan: Option<&Arc<dyn ExecutionPlan>>,
291) -> Status {
292    match err {
293        FlightError::ExternalError(inner) => match inner.downcast::<DataFusionError>() {
294            Ok(df_err) => client_error("error building data stream", *df_err, query_id, plan),
295            Err(inner) => {
296                error!("error building data stream: {inner} (query_id={query_id})");
297                Status::internal(format!(
298                    "error building data stream: {inner} (query_id={query_id})"
299                ))
300            }
301        },
302        other => {
303            error!("error building data stream: {other} (query_id={query_id})");
304            Status::internal(format!(
305                "error building data stream: {other} (query_id={query_id})"
306            ))
307        }
308    }
309}
310
311/// Attribution, per-stage timing, and (once created) the physical plan for
312/// one query. Built as soon as attribution is resolved, updated as each
313/// setup stage completes, and emitted exactly once as a [`QueryAuditRecord`]
314/// under the `flightsql_query_audit` log target — either on an early setup
315/// failure, at stream completion/error, or (if the stream is dropped mid-drain)
316/// from `CompletionTrackedStream`'s `Drop` impl.
317struct QueryAuditState {
318    /// Minted as the very first statement of `execute_query`, before any
319    /// fallible step -- included in every client-facing `Status` built by
320    /// `client_error`/`classify_flight_error` and in this query's audit
321    /// record, so a failure's server-log line and its audit record can be
322    /// correlated by grepping this id.
323    query_id: String,
324    client_ip: String,
325    client: String,
326    agent: String,
327    entrypoint: String,
328    session: Option<String>,
329    notebook: Option<String>,
330    cell: Option<String>,
331    user: String,
332    email: String,
333    name: Option<String>,
334    service_account: bool,
335    service_account_name: Option<String>,
336    sql: String,
337    /// Normalized SQL fingerprint, computed once per query
338    /// regardless of whether the deny list is in active use.
339    sql_hash: String,
340    range_begin: Option<String>,
341    range_end: Option<String>,
342    limit: Option<u64>,
343    context_init_ms: f64,
344    planning_ms: f64,
345    execution_ms: f64,
346    setup_ms: f64,
347    request_start: Instant,
348    /// `None` until the physical plan is created; set as soon as it is, and
349    /// still `None` for a record emitted on a setup failure that happens
350    /// before that point.
351    plan: Option<Arc<dyn ExecutionPlan>>,
352    /// This query's per-query memory-pool wrapper; owned from construction so
353    /// `emit()` can read its peak on every terminal path, including setup
354    /// failures.
355    pool: Arc<ScopedMemoryPool>,
356    estimated_scan_bytes: Option<u64>,
357    estimate_precision: Option<&'static str>,
358    partition_bytes: Option<u64>,
359    admission_cost: Option<u64>,
360    queue_wait_ms: Option<f64>,
361    output: OutputStats,
362    /// Held until the audit state is dropped, which every terminal path does -- including the
363    /// early `fail` returns and a stream dropped mid-drain -- so the admission budget is
364    /// released on all of them without extra plumbing.
365    _admission_permit: Option<AdmissionPermit>,
366}
367
368/// Emits the "incomplete" audit record when `execute_query` is dropped while still queued for
369/// admission. Without it a cancelled waiter would vanish from the audit log, since the stream
370/// that normally emits it does not exist yet.
371struct QueueWaitGuard<'a> {
372    state: &'a mut QueryAuditState,
373    begin: Instant,
374}
375
376impl QueueWaitGuard<'_> {
377    fn finish(self) -> f64 {
378        let ms = self.begin.elapsed().as_secs_f64() * 1000.0;
379        std::mem::forget(self);
380        ms
381    }
382}
383
384impl Drop for QueueWaitGuard<'_> {
385    fn drop(&mut self) {
386        self.state.queue_wait_ms = Some(self.begin.elapsed().as_secs_f64() * 1000.0);
387        self.state.emit("incomplete", None, None);
388    }
389}
390
391impl QueryAuditState {
392    /// Aggregate the plan's DataFusion metrics (if a physical plan was
393    /// created before the failure/completion), assemble the audit record,
394    /// and emit it as a single JSON log line.
395    ///
396    /// Takes `&self` (rather than consuming) so it can be called from a
397    /// setup-error `map_err` closure while leaving the state available for
398    /// further updates/completion on the success path, and so `Drop` can
399    /// call it on an abandoned/cancelled stream without needing to
400    /// reconstruct anything.
401    fn emit(&self, status: &'static str, error: Option<String>, error_class: Option<&'static str>) {
402        let scan = match &self.plan {
403            Some(plan) => aggregate_scan_metrics(plan.as_ref()),
404            None => ScanMetrics {
405                output_rows: None,
406                bytes_scanned: 0,
407                spilled_bytes: 0,
408                spill_count: 0,
409            },
410        };
411        let peak_memory_bytes = self.pool.peak() as u64;
412        imetric!("query_peak_memory_bytes", "bytes", peak_memory_bytes);
413        imetric!("query_output_bytes", "bytes", self.output.bytes);
414        let total_ms = self.request_start.elapsed().as_secs_f64() * 1000.0;
415        let record = QueryAuditRecord {
416            query_id: self.query_id.clone(),
417            client_ip: self.client_ip.clone(),
418            client: self.client.clone(),
419            agent: self.agent.clone(),
420            entrypoint: self.entrypoint.clone(),
421            session: self.session.clone(),
422            notebook: self.notebook.clone(),
423            cell: self.cell.clone(),
424            user: self.user.clone(),
425            email: self.email.clone(),
426            name: self.name.clone(),
427            service_account: self.service_account,
428            service_account_name: self.service_account_name.clone(),
429            sql: self.sql.clone(),
430            sql_hash: self.sql_hash.clone(),
431            range_begin: self.range_begin.clone(),
432            range_end: self.range_end.clone(),
433            limit: self.limit,
434            context_init_ms: self.context_init_ms,
435            planning_ms: self.planning_ms,
436            execution_ms: self.execution_ms,
437            setup_ms: self.setup_ms,
438            total_ms,
439            status,
440            error,
441            error_class,
442            output_rows: scan.output_rows,
443            bytes_scanned: scan.bytes_scanned,
444            peak_memory_bytes,
445            spilled_bytes: scan.spilled_bytes,
446            spill_count: scan.spill_count,
447            estimated_scan_bytes: self.estimated_scan_bytes,
448            estimate_precision: self.estimate_precision,
449            partition_bytes: self.partition_bytes,
450            admission_cost: self.admission_cost,
451            queue_wait_ms: self.queue_wait_ms,
452            output_bytes: self.output.bytes,
453            output_messages: self.output.messages,
454        };
455        match serde_json::to_string(&record) {
456            Ok(json) => info!(target: "flightsql_query_audit", "{json}"),
457            Err(e) => warn!("failed to serialize query audit record: {e}"),
458        }
459    }
460
461    /// Emits an "error" audit record for an already-built client-facing `status`, with an
462    /// explicit `error_class` rather than one derived from the gRPC code -- used by the
463    /// query-deny-list check, whose `error_class` is `"denied"`, a value
464    /// `error_class(status.code())` (`ResourceExhausted` -> `"resource"`) would get wrong.
465    /// Returns `status` unchanged.
466    fn fail_with_class(&self, status: Status, class: &'static str) -> Status {
467        self.emit("error", Some(status.message().to_string()), Some(class));
468        status
469    }
470
471    /// Emits an "error" audit record for an already-built client-facing
472    /// `status` (message + `error_class` derived from its code) and returns it
473    /// unchanged -- the shared tail of every setup-phase `map_err` in
474    /// `execute_query`. A thin wrapper over [`Self::fail_with_class`] that derives the class
475    /// from the code.
476    fn fail(&self, status: Status) -> Status {
477        let class = error_class(status.code());
478        self.fail_with_class(status, class)
479    }
480}
481
482/// Stream wrapper that tracks when the stream is fully consumed
483struct CompletionTrackedStream<S> {
484    inner: S,
485    start_time: i64,
486    completed: bool,
487    audit: Option<QueryAuditState>,
488}
489
490impl<S> CompletionTrackedStream<S> {
491    fn new(inner: S, start_time: i64, audit: QueryAuditState) -> Self {
492        Self {
493            inner,
494            start_time,
495            completed: false,
496            audit: Some(audit),
497        }
498    }
499}
500
501impl<S> Drop for CompletionTrackedStream<S> {
502    /// If the stream is dropped before yielding `None` or an `Err` (client
503    /// disconnect/cancel mid-drain), `poll_next` never ran its completion
504    /// arms, so `self.audit` is still `Some(...)`. Emit it here with a
505    /// terminal "incomplete" status so cancelled/abandoned queries are still
506    /// audited instead of silently vanishing. A no-op for streams that
507    /// completed or errored normally, since those arms already `take()` the
508    /// audit state.
509    fn drop(&mut self) {
510        if let Some(state) = self.audit.take() {
511            state.emit("incomplete", None, None);
512        }
513    }
514}
515
516impl<S> Stream for CompletionTrackedStream<S>
517where
518    S: Stream<Item = Result<arrow_flight::FlightData, Status>> + Unpin + Send,
519{
520    type Item = Result<arrow_flight::FlightData, Status>;
521
522    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
523        match Pin::new(&mut self.inner).poll_next(cx) {
524            Poll::Ready(Some(result)) => {
525                if let Ok(ref data) = result
526                    && let Some(state) = self.audit.as_mut()
527                {
528                    state.output.record(data);
529                }
530                // Every `Status` reaching this stream was already logged once by
531                // `classify_flight_error` (the sole `map_err` feeding it) when it
532                // built that `Status` -- this arm only reads the code to derive
533                // the audit/metric class, it never logs again.
534                if let Err(ref err) = result
535                    && !self.completed
536                {
537                    let class = error_class(err.code());
538                    let total_duration = now() - self.start_time;
539                    match class {
540                        "internal" => {
541                            imetric!("query_duration_with_error", "ticks", total_duration as u64);
542                            imetric!("query_failed", "count", 1);
543                        }
544                        "resource" => {
545                            imetric!("query_failed_resource", "count", 1);
546                        }
547                        _ => {
548                            imetric!("query_failed_user", "count", 1);
549                        }
550                    }
551                    self.completed = true;
552                    if let Some(state) = self.audit.take() {
553                        state.emit("error", Some(err.message().to_string()), Some(class));
554                    }
555                }
556                Poll::Ready(Some(result))
557            }
558            Poll::Ready(None) => {
559                // Stream completed successfully
560                if !self.completed {
561                    let total_duration = now() - self.start_time;
562                    imetric!("query_duration_total", "ticks", total_duration as u64);
563                    imetric!("query_completed_successfully", "count", 1);
564                    self.completed = true;
565                    if let Some(state) = self.audit.take() {
566                        state.emit("ok", None, None);
567                    }
568                }
569                Poll::Ready(None)
570            }
571            Poll::Pending => Poll::Pending,
572        }
573    }
574}
575
576static INSTANCE_SQL_DATA: Lazy<SqlInfoData> = Lazy::new(|| {
577    let mut builder = SqlInfoDataBuilder::new();
578    // Server information
579    builder.append(SqlInfo::FlightSqlServerName, "Micromegas Flight SQL Server");
580    builder.append(SqlInfo::FlightSqlServerVersion, "1");
581    // 1.3 comes from https://github.com/apache/arrow/blob/f9324b79bf4fc1ec7e97b32e3cce16e75ef0f5e3/format/Schema.fbs#L24
582    builder.append(SqlInfo::FlightSqlServerArrowVersion, "1.3");
583    builder.append(SqlInfo::SqlKeywords, SQL_INFO_SQL_KEYWORDS);
584    builder.append(SqlInfo::SqlNumericFunctions, SQL_INFO_NUMERIC_FUNCTIONS);
585    builder.append(SqlInfo::SqlStringFunctions, SQL_INFO_STRING_FUNCTIONS);
586    builder.append(SqlInfo::SqlSystemFunctions, SQL_INFO_SYSTEM_FUNCTIONS);
587    builder.append(SqlInfo::SqlDatetimeFunctions, SQL_INFO_DATE_TIME_FUNCTIONS);
588    builder.build().unwrap()
589});
590
591/// Implementation of the Flight SQL service.
592#[derive(Clone)]
593pub struct FlightSqlServiceImpl {
594    lakehouse: Arc<LakehouseContext>,
595    part_provider: Arc<dyn QueryPartitionProvider>,
596    view_registry: Arc<ViewRegistry>,
597    session_configurator: Arc<dyn SessionConfigurator>,
598    read_policy: Arc<dyn ReadPolicy>,
599    settings: Arc<SettingsSource>,
600    /// Flat cost the scan estimator charges for a plan leaf it cannot see into.
601    opaque_leaf_cost: u64,
602    /// `None` disables admission: queries run at once and only the estimate is recorded.
603    admission: Option<Arc<AdmissionScheduler>>,
604}
605
606impl FlightSqlServiceImpl {
607    #[allow(clippy::too_many_arguments)]
608    pub fn new(
609        lakehouse: Arc<LakehouseContext>,
610        part_provider: Arc<dyn QueryPartitionProvider>,
611        view_registry: Arc<ViewRegistry>,
612        session_configurator: Arc<dyn SessionConfigurator>,
613        read_policy: Arc<dyn ReadPolicy>,
614        settings: Arc<SettingsSource>,
615        opaque_leaf_cost: u64,
616        admission: Option<Arc<AdmissionScheduler>>,
617    ) -> Self {
618        Self {
619            lakehouse,
620            part_provider,
621            view_registry,
622            session_configurator,
623            read_policy,
624            settings,
625            opaque_leaf_cost,
626            admission,
627        }
628    }
629
630    /// Resolves the [`CallerContext`] a request should plan under -- the seam's fail-closed
631    /// resolver.
632    ///
633    /// **Absent-extension convention.** When no `AuthContext` extension is present at all (no
634    /// auth provider configured, e.g. `--disable-auth`), the resolved scope is
635    /// [`ReadScope::All`]. This is the *only* permissive branch here: `AuthService::call`
636    /// (`rust/auth/src/tower.rs`) rejects the request before this inner service ever runs
637    /// whenever a provider *is* configured, so the extension is always present in that case --
638    /// the same safety argument `is_admin`'s absent-header-⇒-trusted convention already relies
639    /// on (`user_attribution.rs`).
640    ///
641    /// **Failure convention.** A [`ReadPolicy::resolve`] that returns `Err` is a hard failure and
642    /// must never become a scope -- not `ReadScope::Audiences(Arc::from([]))` (which would read
643    /// as a legitimate, audited fail-closed decision by the isolation-config layer) and not
644    /// `ReadScope::All` (a silent fail-open bypass). Mirrors `tower.rs`'s own discriminator:
645    /// `Status::unavailable` when the error downcasts to [`ProviderUnavailable`] (a
646    /// store/provider outage), `Status::permission_denied` otherwise.
647    ///
648    /// `is_admin` is read from `md` unchanged (`is_admin(md)`), equivalent to reading
649    /// `AuthContext.is_admin` off `ext` when the extension is present, since the header is
650    /// derived from the same `AuthContext` with client-supplied copies stripped
651    /// (`tower.rs:107-139`) -- and it is what preserves today's `--disable-auth`
652    /// absent-header-⇒-trusted convention when `ext` has none.
653    async fn caller_context(
654        &self,
655        ext: &http::Extensions,
656        md: &MetadataMap,
657    ) -> Result<CallerContext, Status> {
658        // `deny_queries` requires `Some` -- resolved from the
659        // same attribution `execute_query` already validates, so a query already carries this by
660        // the time it could call `deny_queries`. This is simply "the caller's resolved user id"
661        // (`user_attribution::validate_and_resolve_user_attribution_grpc`).
662        let identity = validate_and_resolve_user_attribution_grpc(md)
663            .ok()
664            .map(|attr| attr.user_id);
665        // Read once, up front, so both `read_scope`'s resolution below and `grant_selectors`
666        // can consult the same `AuthContext` -- the `Some(auth_ctx)` arm's
667        // binding otherwise goes out of scope before the `CallerContext` literal is built.
668        let auth_ctx = ext.get::<AuthContext>();
669        // Resolved only on the `Some(auth_ctx)` arm: with no `AuthContext` the scope is
670        // `ReadScope::All`, which makes the isolation config irrelevant, so an auth-disabled
671        // server never has to load the settings table.
672        let mut isolation_config = None;
673        let read_scope = match auth_ctx {
674            Some(auth_ctx) => match self.read_policy.resolve(auth_ctx).await {
675                Ok(audiences) => {
676                    isolation_config =
677                        Some(self.settings.isolation_config().await.map_err(|e| {
678                            if e.downcast_ref::<ProviderUnavailable>().is_some() {
679                                Status::unavailable(format!("settings unavailable: {e:#}"))
680                            } else {
681                                Status::internal(format!("settings load failed: {e:#}"))
682                            }
683                        })?);
684                    match audiences {
685                        ReadableAudiences::Listed(a) => ReadScope::Audiences(a),
686                        ReadableAudiences::Every => ReadScope::EveryAudience,
687                    }
688                }
689                Err(e) => {
690                    return Err(if e.downcast_ref::<ProviderUnavailable>().is_some() {
691                        Status::unavailable(format!("read policy unavailable: {e:#}"))
692                    } else {
693                        Status::permission_denied(format!("read scope denied: {e:#}"))
694                    });
695                }
696            },
697            None => ReadScope::All,
698        };
699        Ok(CallerContext {
700            read_scope,
701            is_admin: is_admin(md),
702            isolation_config: isolation_config
703                .unwrap_or_else(|| self.settings.env_isolation_config()),
704            identity,
705            // Empty when there's no `AuthContext` extension at all (no auth provider configured,
706            // e.g. `--disable-auth`) -- the same absent-extension convention `read_scope` follows
707            // above.
708            grant_selectors: auth_ctx.map(caller_selectors).unwrap_or_default().into(),
709        })
710    }
711
712    fn should_preserve_dictionary(metadata: &MetadataMap) -> bool {
713        metadata
714            .get("preserve_dictionary")
715            .and_then(|v| v.to_str().ok())
716            .map(|s| s.eq_ignore_ascii_case("true"))
717            .unwrap_or(false)
718    }
719
720    /// Extracts an optional client-attribution header, treating an empty string as absent.
721    fn optional_metadata(metadata: &MetadataMap, key: &str) -> Option<String> {
722        metadata
723            .get(key)
724            .and_then(|v| v.to_str().ok())
725            .filter(|s| !s.is_empty())
726            .map(|s| s.to_string())
727    }
728
729    #[span_fn]
730    async fn execute_query(
731        &self,
732        ticket_stmt: TicketStatementQuery,
733        metadata: &MetadataMap,
734        extensions: &http::Extensions,
735        client_ip: &str,
736    ) -> Result<Response<FlightDataStream>, Status> {
737        // Minted first, before any fallible step, so it's Always available --
738        // for every client-facing `Status` built by `client_error`/
739        // `classify_flight_error` and for this query's audit record.
740        let query_id = Uuid::new_v4().to_string();
741        let begin_request = now();
742        let request_start = Instant::now();
743        let sql = std::str::from_utf8(&ticket_stmt.statement_handle)
744            .map_err(|e| status!("Unable to parse query", e))?;
745
746        let mut begin = metadata.get("query_range_begin");
747        if let Some(s) = &begin
748            && s.is_empty()
749        {
750            begin = None;
751        }
752        let mut end = metadata.get("query_range_end");
753        if let Some(s) = &end
754            && s.is_empty()
755        {
756            end = None;
757        }
758        let query_range = if begin.is_some() && end.is_some() {
759            let begin_datetime =
760                chrono::DateTime::parse_from_rfc3339(begin.unwrap().to_str().map_err(|e| {
761                    client_input_error!("Unable to convert query_range_begin to string", e)
762                })?)
763                .map_err(|e| {
764                    client_input_error!(
765                        "Unable to parse query_range_begin as a rfc3339 datetime",
766                        e
767                    )
768                })?;
769            let end_datetime =
770                chrono::DateTime::parse_from_rfc3339(end.unwrap().to_str().map_err(|e| {
771                    client_input_error!("Unable to convert query_range_end to string", e)
772                })?)
773                .map_err(|e| {
774                    client_input_error!("Unable to parse query_range_end as a rfc3339 datetime", e)
775                })?;
776            Some(TimeRange::new(begin_datetime.into(), end_datetime.into()))
777        } else {
778            None
779        };
780
781        // Validate and resolve user attribution
782        let attr = validate_and_resolve_user_attribution_grpc(metadata).map_err(|e| *e)?;
783
784        let client_type = metadata
785            .get("x-client-type")
786            .and_then(|v| v.to_str().ok())
787            .unwrap_or("unknown");
788        let client_agent = metadata
789            .get("x-client-agent")
790            .and_then(|v| v.to_str().ok())
791            .unwrap_or("unknown");
792        let client_entrypoint = metadata
793            .get("x-client-entrypoint")
794            .and_then(|v| v.to_str().ok())
795            .unwrap_or("unknown");
796        let client_session = Self::optional_metadata(metadata, "x-client-session");
797        let client_notebook = Self::optional_metadata(metadata, "x-client-notebook");
798        let client_cell = Self::optional_metadata(metadata, "x-client-cell");
799
800        let user_name_display = attr.user_name.as_deref().unwrap_or("");
801
802        // Log query with full attribution
803        if let Some(service_account_name) = &attr.service_account {
804            info!(
805                "execute_query range={query_range:?} sql={sql:?} limit={:?} user={} email={} name={user_name_display:?} service_account={service_account_name} client={client_type} agent={client_agent} entrypoint={client_entrypoint} notebook={client_notebook:?} cell={client_cell:?} client_ip={client_ip}",
806                metadata.get("limit"),
807                attr.user_id,
808                attr.user_email
809            );
810        } else {
811            info!(
812                "execute_query range={query_range:?} sql={sql:?} limit={:?} user={} email={} name={user_name_display:?} client={client_type} agent={client_agent} entrypoint={client_entrypoint} notebook={client_notebook:?} cell={client_cell:?} client_ip={client_ip}",
813                metadata.get("limit"),
814                attr.user_id,
815                attr.user_email
816            );
817        }
818
819        // The per-query memory-pool wrapper is infallible to construct, so it's built
820        // before `audit_state` and owned by it from the start -- every subsequent
821        // setup failure (session context, planning, limit, physical plan, stream
822        // construction) can then still emit an "error" audit record carrying whatever
823        // peak the pool had accrued by that point, instead of silently disappearing on
824        // an early `?` return.
825        let scoped_pool = Arc::new(ScopedMemoryPool::new(
826            self.lakehouse.runtime().memory_pool.clone(),
827        ));
828
829        // Attribution is resolved from here on, so build the audit state now
830        // (durations/limit/plan filled in as they become known) instead of
831        // only after the physical plan exists.
832        // Computed once per query, regardless of whether the deny list is in active use --
833        // it's what an operator pastes into `deny_queries` after finding an offender in the
834        // audit log.
835        let sql_hash = fingerprint_of(sql);
836
837        let mut audit_state = QueryAuditState {
838            query_id: query_id.clone(),
839            client_ip: client_ip.to_string(),
840            client: client_type.to_string(),
841            agent: client_agent.to_string(),
842            entrypoint: client_entrypoint.to_string(),
843            session: client_session,
844            notebook: client_notebook,
845            cell: client_cell,
846            user: attr.user_id.clone(),
847            email: attr.user_email.clone(),
848            name: attr.user_name.clone(),
849            service_account: attr.service_account.is_some(),
850            service_account_name: attr.service_account.clone(),
851            sql: sql.to_string(),
852            sql_hash: sql_hash.clone(),
853            range_begin: query_range.as_ref().map(|r| r.begin.to_rfc3339()),
854            range_end: query_range.as_ref().map(|r| r.end.to_rfc3339()),
855            limit: None,
856            context_init_ms: 0.0,
857            planning_ms: 0.0,
858            execution_ms: 0.0,
859            setup_ms: 0.0,
860            request_start,
861            plan: None,
862            pool: scoped_pool.clone(),
863            estimated_scan_bytes: None,
864            estimate_precision: None,
865            partition_bytes: None,
866            admission_cost: None,
867            queue_wait_ms: None,
868            output: OutputStats::default(),
869            _admission_permit: None,
870        };
871
872        // The deny-list check, in front of everything expensive -- before the scoped
873        // runtime/session context/planning below. `check` returns `None` immediately on an
874        // empty snapshot, so this costs nothing while the deny list stands empty.
875        if let Some(rule) = self.lakehouse.query_denials().check(&QueryAttribution {
876            user_id: &attr.user_id,
877            email: &attr.user_email,
878            service_account: attr.service_account.as_deref(),
879            client: client_type,
880            agent: client_agent,
881            entrypoint: client_entrypoint,
882            session: audit_state.session.as_deref(),
883            notebook: audit_state.notebook.as_deref(),
884            cell: audit_state.cell.as_deref(),
885            client_ip,
886            sql,
887            sql_hash: &sql_hash,
888        }) && !skip_for_admin_recovery(sql, is_admin(metadata))
889        {
890            let status = Status::resource_exhausted(format!(
891                "query denied by rule {} (reason: {}); ask an admin to lift it with \
892                 remove_query_denial('{}'); query_id={query_id}",
893                rule.row.rule_id, rule.row.reason, rule.row.rule_id
894            ));
895            warn!(
896                "{}",
897                build_denial_warn_line(
898                    &rule.row.rule_id.to_string(),
899                    &rule.row.reason,
900                    &sql_hash,
901                    &attr.user_id,
902                    &attr.user_email,
903                    client_type,
904                    client_entrypoint,
905                    client_ip,
906                    &query_id,
907                )
908            );
909            imetric!("query_denied", "count", rule_id = %rule.row.rule_id, 1_u64);
910            rule.record_hit();
911            return Err(audit_state.fail_with_class(status, "denied"));
912        }
913
914        // Caller is resolved here, ahead of the scoped runtime, because the view-DDL intercept
915        // below needs it and returns before either the scoped runtime or a session context is
916        // ever built for a `CREATE`/`DROP MATERIALIZED VIEW` statement.
917        //
918        // `context_init_ms` is measured starting here (not at `make_session_context`) because
919        // caller resolution can itself hit the read-policy store (e.g. a DB round trip to
920        // resolve audience grants), and that cost belongs in the same phase.
921        let session_begin = now();
922        let session_begin_instant = Instant::now();
923        let caller = self
924            .caller_context(extensions, metadata)
925            .await
926            .map_err(|status| audit_state.fail(status))?;
927
928        // View DDL is intercepted here, ahead of the scoped runtime/`make_session_context`: a
929        // `CREATE`/`DROP MATERIALIZED VIEW` statement is never planned as an ordinary query.
930        match parse_view_ddl(sql) {
931            Ok(Some(ddl)) => {
932                return self
933                    .execute_view_ddl(ddl, &caller, begin_request, audit_state)
934                    .await;
935            }
936            Ok(None) => {}
937            Err(e) => {
938                return Err(audit_state.fail(client_input_error!("error parsing view DDL", e)));
939            }
940        }
941
942        // Build a `RuntimeEnv`/`LakehouseContext` scoped to this query's memory-pool
943        // wrapper, so every session context created from it (including nested ones,
944        // e.g. Perfetto trace queries and JIT materialization) attributes its memory
945        // to this query alone instead of the process-shared pool.
946        let scoped_env = scoped_runtime(self.lakehouse.runtime(), scoped_pool.clone())
947            .map_err(|e| audit_state.fail(status!("error building scoped runtime", e)))?;
948        let lakehouse = self.lakehouse.with_runtime(scoped_env);
949
950        // Session context creation phase
951        let ctx = make_session_context(
952            lakehouse,
953            self.part_provider.clone(),
954            query_range.map_or(SessionRange::Unbounded, SessionRange::Query),
955            self.view_registry.current(),
956            self.session_configurator.clone(),
957            caller,
958        )
959        .await
960        .map_err(|e| audit_state.fail(status!("error in make_session_context", e)))?;
961        register_deployment_notes(&ctx, self.settings.clone());
962        let context_init_duration = now() - session_begin;
963        audit_state.context_init_ms = session_begin_instant.elapsed().as_secs_f64() * 1000.0;
964
965        // Query planning phase
966        let planning_begin = now();
967        let planning_begin_instant = Instant::now();
968        let mut df = ctx.sql(sql).await.map_err(|e| {
969            audit_state.fail(client_error("error building dataframe", e, &query_id, None))
970        })?;
971        let planning_duration = now() - planning_begin;
972        audit_state.planning_ms = planning_begin_instant.elapsed().as_secs_f64() * 1000.0;
973
974        if let Some(limit_str) = metadata.get("limit") {
975            let parsed_limit: usize = usize::from_str(limit_str.to_str().map_err(|e| {
976                audit_state.fail(client_input_error!("error converting limit to str", e))
977            })?)
978            .map_err(|e| audit_state.fail(client_input_error!("error parsing limit", e)))?;
979            audit_state.limit = Some(parsed_limit as u64);
980            df = df.limit(0, Some(parsed_limit)).map_err(|e| {
981                audit_state.fail(client_error(
982                    "error building dataframe with limit",
983                    e,
984                    &query_id,
985                    None,
986                ))
987            })?;
988        }
989
990        // Query execution phase: build the physical plan (kept for post-drain metrics)
991        // and run it via the free-function `execute_stream`, which is what
992        // `DataFrame::execute_stream` does internally, minus dropping the plan.
993        let execution_begin = now();
994        let execution_begin_instant = Instant::now();
995        let schema = Arc::new(df.schema().as_arrow().clone());
996        let task_ctx = Arc::new(df.task_ctx());
997        let plan = df.create_physical_plan().await.map_err(|e| {
998            audit_state.fail(client_error(
999                "error creating physical plan",
1000                e,
1001                &query_id,
1002                None,
1003            ))
1004        })?;
1005        audit_state.plan = Some(plan.clone());
1006
1007        let estimate = estimate_scan_cost(
1008            &plan,
1009            self.lakehouse.metadata_cache(),
1010            self.opaque_leaf_cost,
1011        )
1012        .await;
1013        audit_state.estimated_scan_bytes = Some(estimate.bytes);
1014        audit_state.estimate_precision = Some(estimate.precision.as_str());
1015        audit_state.partition_bytes = Some(estimate.partition_bytes);
1016
1017        // The gate must precede `execute_stream`, not just the first poll: for a plan with
1018        // several output partitions `execute_stream` wraps it in a `CoalescePartitionsExec`
1019        // that spawns the scan tasks immediately.
1020        let mut queue_wait_ticks = 0;
1021        let mut queue_wait_ms = 0.0;
1022        if let Some(scheduler) = &self.admission {
1023            // A delegating key shares its service account's queue. The client-asserted `client`
1024            // is not part of the key: it would let a caller multiply its share.
1025            let identity: Arc<str> = Arc::from(
1026                attr.service_account
1027                    .as_deref()
1028                    .unwrap_or(attr.user_id.as_str()),
1029            );
1030            audit_state.admission_cost = Some(scheduler.charged_cost(estimate.bytes));
1031            let wait_begin = now();
1032            let guard = QueueWaitGuard {
1033                begin: Instant::now(),
1034                state: &mut audit_state,
1035            };
1036            let permit = scheduler.admit(identity, estimate.bytes).await;
1037            queue_wait_ms = guard.finish();
1038            queue_wait_ticks = now() - wait_begin;
1039            audit_state.queue_wait_ms = Some(queue_wait_ms);
1040            audit_state._admission_permit = Some(permit);
1041            imetric!("admission_queue_wait", "ticks", queue_wait_ticks as u64);
1042        }
1043        // `plan`/`query_id` are cloned here because both are moved shortly:
1044        // `plan` into `execute_stream` below, `audit_state` (which owns
1045        // `query_id`'s sibling on the struct) into `CompletionTrackedStream::new`
1046        // further down. The per-batch closure below outlives this function call
1047        // (it's polled from the returned stream), so it needs its own owned
1048        // clones rather than borrowing `plan`/`query_id` directly.
1049        let plan_for_errors = plan.clone();
1050        let query_id_for_stream = query_id.clone();
1051        let stream = execute_stream(plan, task_ctx)
1052            .map_err(|e| {
1053                audit_state.fail(client_error(
1054                    "error executing plan",
1055                    e,
1056                    &query_id_for_stream,
1057                    Some(&plan_for_errors),
1058                ))
1059            })?
1060            .map_err(|e| FlightError::ExternalError(Box::new(e)));
1061        let builder = if Self::should_preserve_dictionary(metadata) {
1062            FlightDataEncoderBuilder::new()
1063                .with_schema(schema.clone())
1064                .with_dictionary_handling(DictionaryHandling::Resend)
1065        } else {
1066            FlightDataEncoderBuilder::new().with_schema(schema.clone())
1067        };
1068        let flight_data_stream = builder.build(stream);
1069        // Queue wait is taken out of the setup/execution timings so latency dashboards keep
1070        // their meaning; `total_ms` and `query_duration_total` still include it.
1071        let execution_duration = now() - execution_begin - queue_wait_ticks;
1072        audit_state.execution_ms =
1073            execution_begin_instant.elapsed().as_secs_f64() * 1000.0 - queue_wait_ms;
1074
1075        // Calculate total setup time and record detailed metrics
1076        let total_setup_duration = now() - begin_request - queue_wait_ticks;
1077        audit_state.setup_ms = request_start.elapsed().as_secs_f64() * 1000.0 - queue_wait_ms;
1078
1079        // Record detailed timing metrics
1080        imetric!(
1081            "context_init_duration",
1082            "ticks",
1083            context_init_duration as u64
1084        );
1085        imetric!("query_planning_duration", "ticks", planning_duration as u64);
1086        imetric!(
1087            "query_execution_duration",
1088            "ticks",
1089            execution_duration as u64
1090        );
1091        imetric!("query_setup_duration", "ticks", total_setup_duration as u64);
1092
1093        // Create instrumented stream that tracks completion. This closure owns
1094        // `plan_for_errors`/`query_id_for_stream` (moved in) since it's polled
1095        // from the returned stream, long after this function returns -- see the
1096        // comment above `plan_for_errors`'s definition.
1097        let instrumented_stream = flight_data_stream.map_err(move |e| {
1098            classify_flight_error(e, &query_id_for_stream, Some(&plan_for_errors))
1099        });
1100        let completion_tracked_stream =
1101            CompletionTrackedStream::new(instrumented_stream.boxed(), begin_request, audit_state);
1102        Ok(Response::new(
1103            Box::pin(completion_tracked_stream) as FlightDataStream
1104        ))
1105    }
1106
1107    /// Executes a parsed `CREATE [OR REPLACE] MATERIALIZED VIEW` / `DROP MATERIALIZED VIEW`
1108    /// statement: admin-gates it, validates/upserts or deletes its row inside one transaction
1109    /// (serialized cluster-wide by an advisory lock), refuses a mutation that would break a
1110    /// dependent, retires partitions on `DROP`, reloads this replica's registry inline after
1111    /// commit, and returns a one-row `(view_set_name, status)` result through the same
1112    /// `CompletionTrackedStream` every other query uses.
1113    async fn execute_view_ddl(
1114        &self,
1115        ddl: ViewDdl,
1116        caller: &CallerContext,
1117        begin_request: i64,
1118        audit_state: QueryAuditState,
1119    ) -> Result<Response<FlightDataStream>, Status> {
1120        authorize_view_ddl(caller).map_err(|status| audit_state.fail(status))?;
1121
1122        let pool = self.lakehouse.lake().db_pool.clone();
1123        let mut tx = pool
1124            .begin()
1125            .await
1126            .map_err(|e| audit_state.fail(status!("error starting view DDL transaction", e)))?;
1127        acquire_lock(&mut tx, VIEW_DDL_ADVISORY_LOCK_KEY)
1128            .await
1129            .map_err(|e| audit_state.fail(status!("error acquiring view DDL lock", e)))?;
1130        let pre_rows = list_tx(&mut tx)
1131            .await
1132            .map_err(|e| audit_state.fail(status!("error reading view definitions", e)))?;
1133
1134        let (view_set_name, status_text) = match ddl {
1135            ViewDdl::Create {
1136                name,
1137                or_replace,
1138                definition,
1139                sql,
1140            } => {
1141                let existing = pre_rows.iter().any(|r| r.view_set_name == name);
1142                if existing && !or_replace {
1143                    return Err(audit_state.fail(Status::already_exists(format!(
1144                        "materialized view '{name}' already exists; use CREATE OR REPLACE to \
1145                         redefine it"
1146                    ))));
1147                }
1148                // Validated against the factory the loader would build for this row: the
1149                // pre-mutation rows, this row's own name excluded (identical to the
1150                // post-mutation set for this single-row mutation) -- so a definition reading
1151                // another DDL view validates against the real thing, and a `CREATE OR REPLACE`
1152                // that raises its own update_group cannot validate against a since-superseded
1153                // copy of itself.
1154                let validation_rows: Vec<_> = pre_rows
1155                    .iter()
1156                    .filter(|r| r.view_set_name != name)
1157                    .cloned()
1158                    .collect();
1159                // A `Probe`: a row in `validation_rows` that no longer builds is a pre-existing
1160                // breakage the live reload already reports on every tick -- re-logging it here
1161                // would pin it on whoever happened to run the next DDL statement.
1162                let (factory, _failed) = self
1163                    .view_registry
1164                    .build_from_rows(&validation_rows, BuildPurpose::Probe)
1165                    .await
1166                    .map_err(|e| {
1167                        audit_state.fail(status!("error building validation factory", e))
1168                    })?;
1169                let view = build_sql_batch_view(
1170                    &definition,
1171                    self.lakehouse.runtime().clone(),
1172                    self.lakehouse.lake().clone(),
1173                    factory.clone(),
1174                    self.session_configurator.clone(),
1175                )
1176                .await
1177                .map_err(|e| {
1178                    audit_state.fail(client_input_error!("error building materialized view", e))
1179                })?;
1180                validate_view_definition(
1181                    &definition,
1182                    &view,
1183                    &factory,
1184                    self.lakehouse.runtime().clone(),
1185                    self.lakehouse.lake().clone(),
1186                    self.session_configurator.clone(),
1187                )
1188                .await
1189                .map_err(|e| {
1190                    audit_state.fail(client_input_error!("view definition failed validation", e))
1191                })?;
1192                let updated_by = caller.identity.as_deref().unwrap_or("unknown");
1193                upsert_tx(&mut tx, &definition, &sql, updated_by)
1194                    .await
1195                    .map_err(|e| audit_state.fail(status!("error upserting view definition", e)))?;
1196                (name, if existing { "replaced" } else { "created" })
1197            }
1198            ViewDdl::Drop { name, if_exists } => {
1199                let existing = pre_rows.iter().any(|r| r.view_set_name == name);
1200                if !existing {
1201                    if if_exists {
1202                        (name, "not_found")
1203                    } else {
1204                        return Err(audit_state.fail(Status::not_found(format!(
1205                            "materialized view '{name}' does not exist"
1206                        ))));
1207                    }
1208                } else {
1209                    let range = partition_insert_range(&mut tx, &name).await.map_err(|e| {
1210                        audit_state.fail(status!("error reading partition insert range", e))
1211                    })?;
1212                    delete_tx(&mut tx, &name).await.map_err(|e| {
1213                        audit_state.fail(status!("error deleting view definition", e))
1214                    })?;
1215                    if let Some((begin, end)) = range {
1216                        let null_logger = Arc::new(ResponseWriter::new(None));
1217                        retire_partitions(
1218                            &mut tx,
1219                            &name,
1220                            "global",
1221                            begin,
1222                            end,
1223                            RetireMatch::Containment,
1224                            &[],
1225                            null_logger,
1226                        )
1227                        .await
1228                        .map_err(|e| audit_state.fail(status!("error retiring partitions", e)))?;
1229                    }
1230                    (name, "dropped")
1231                }
1232            }
1233        };
1234
1235        // `DROP ... IF EXISTS` on an absent view writes nothing, so `post_rows` would be
1236        // byte-identical to `pre_rows`; skip the probe rather than replanning every stored
1237        // definition twice over for a statement that changed nothing, all while holding the
1238        // advisory lock and this open transaction.
1239        if status_text != "not_found" {
1240            let post_rows = list_tx(&mut tx)
1241                .await
1242                .map_err(|e| audit_state.fail(status!("error reading view definitions", e)))?;
1243            self.view_registry
1244                .check_dependents_survive(&pre_rows, &post_rows)
1245                .await
1246                .map_err(|e| {
1247                    // The inner error already says what would break and why; this prefix only has
1248                    // to mark where the refusal came from.
1249                    audit_state.fail(client_input_error!("view DDL refused", e))
1250                })?;
1251        }
1252
1253        tx.commit()
1254            .await
1255            .map_err(|e| audit_state.fail(status!("error committing view DDL transaction", e)))?;
1256
1257        // Run after the commit: `reload()` starts with a second, uncommitted-write-blind
1258        // connection, so calling it any earlier would have it read the pre-mutation rows and
1259        // swap in the old factory. `Err` is `warn!`-logged and discarded -- the row is already
1260        // committed, and the next periodic refresh will pick it up regardless.
1261        if let Err(e) = self.view_registry.reload().await {
1262            warn!("view_ddl: inline reload after DDL failed: {e:#}");
1263        }
1264
1265        let schema = Arc::new(Schema::new(vec![
1266            Field::new("view_set_name", DataType::Utf8, false),
1267            Field::new("status", DataType::Utf8, false),
1268        ]));
1269        let batch = RecordBatch::try_new(
1270            schema.clone(),
1271            vec![
1272                Arc::new(StringArray::from(vec![view_set_name])),
1273                Arc::new(StringArray::from(vec![status_text.to_string()])),
1274            ],
1275        )
1276        .map_err(|e| audit_state.fail(status!("error building view DDL result batch", e)))?;
1277        let stream = FlightDataEncoderBuilder::new()
1278            .with_schema(schema)
1279            .build(futures::stream::once(async { Ok(batch) }))
1280            .map_err(Status::from);
1281        let completion_tracked_stream =
1282            CompletionTrackedStream::new(stream.boxed(), begin_request, audit_state);
1283        Ok(Response::new(
1284            Box::pin(completion_tracked_stream) as FlightDataStream
1285        ))
1286    }
1287}
1288
1289#[tonic::async_trait]
1290impl FlightSqlService for FlightSqlServiceImpl {
1291    type FlightService = FlightSqlServiceImpl;
1292
1293    async fn do_handshake(
1294        &self,
1295        _request: Request<Streaming<HandshakeRequest>>,
1296    ) -> Result<
1297        Response<Pin<Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send>>>,
1298        Status,
1299    > {
1300        api_entry_not_implemented!()
1301    }
1302
1303    #[span_fn]
1304    async fn do_get_fallback(
1305        &self,
1306        request: Request<Ticket>,
1307        _message: Any,
1308    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1309        let client_ip = get_client_ip(request.metadata().as_ref(), request.extensions());
1310        let ticket_stmt = TicketStatementQuery::decode(request.get_ref().ticket.clone())
1311            .map_err(|e| status!("Could not read ticket", e))?;
1312        self.execute_query(
1313            ticket_stmt,
1314            request.metadata(),
1315            request.extensions(),
1316            &client_ip,
1317        )
1318        .await
1319    }
1320
1321    #[span_fn]
1322    async fn get_flight_info_statement(
1323        &self,
1324        query: CommandStatementQuery,
1325        _request: Request<FlightDescriptor>,
1326    ) -> Result<Response<FlightInfo>, Status> {
1327        let begin_request = now();
1328        info!("get_flight_info_statement {query:?} ");
1329        let CommandStatementQuery { query, .. } = query;
1330        let schema = Schema::empty();
1331        let ticket = TicketStatementQuery {
1332            statement_handle: query.into(),
1333        };
1334        let mut bytes: Vec<u8> = Vec::new();
1335        if ticket.encode(&mut bytes).is_ok() {
1336            let info = FlightInfo::new()
1337                .try_with_schema(&schema)
1338                .unwrap()
1339                .with_endpoint(FlightEndpoint::new().with_ticket(Ticket::new(bytes)));
1340            let duration = now() - begin_request;
1341            imetric!("request_duration", "ticks", duration as u64);
1342            Ok(Response::new(info))
1343        } else {
1344            error!("Error encoding ticket");
1345            Err(Status::internal("Error encoding ticket"))
1346        }
1347    }
1348
1349    async fn get_flight_info_substrait_plan(
1350        &self,
1351        _query: CommandStatementSubstraitPlan,
1352        _request: Request<FlightDescriptor>,
1353    ) -> Result<Response<FlightInfo>, Status> {
1354        api_entry_not_implemented!()
1355    }
1356
1357    async fn get_flight_info_prepared_statement(
1358        &self,
1359        _cmd: CommandPreparedStatementQuery,
1360        _request: Request<FlightDescriptor>,
1361    ) -> Result<Response<FlightInfo>, Status> {
1362        api_entry_not_implemented!()
1363    }
1364
1365    async fn get_flight_info_catalogs(
1366        &self,
1367        _query: CommandGetCatalogs,
1368        _request: Request<FlightDescriptor>,
1369    ) -> Result<Response<FlightInfo>, Status> {
1370        api_entry_not_implemented!()
1371    }
1372
1373    async fn get_flight_info_schemas(
1374        &self,
1375        _query: CommandGetDbSchemas,
1376        _request: Request<FlightDescriptor>,
1377    ) -> Result<Response<FlightInfo>, Status> {
1378        api_entry_not_implemented!()
1379    }
1380
1381    #[span_fn]
1382    async fn get_flight_info_tables(
1383        &self,
1384        query: CommandGetTables,
1385        request: Request<FlightDescriptor>,
1386    ) -> Result<Response<FlightInfo>, Status> {
1387        let begin_request = now();
1388        info!("get_flight_info_tables");
1389        let flight_descriptor = request.into_inner();
1390        let ticket = Ticket {
1391            ticket: query.as_any().encode_to_vec().into(),
1392        };
1393        let endpoint = FlightEndpoint::new().with_ticket(ticket);
1394        let flight_info = FlightInfo::new()
1395            .try_with_schema(&query.into_builder().schema())
1396            .map_err(|e| status!("Unable to encode schema", e))?
1397            .with_endpoint(endpoint)
1398            .with_descriptor(flight_descriptor);
1399        let duration = now() - begin_request;
1400        imetric!("request_duration", "ticks", duration as u64);
1401        Ok(tonic::Response::new(flight_info))
1402    }
1403
1404    async fn get_flight_info_table_types(
1405        &self,
1406        _query: CommandGetTableTypes,
1407        _request: Request<FlightDescriptor>,
1408    ) -> Result<Response<FlightInfo>, Status> {
1409        api_entry_not_implemented!()
1410    }
1411
1412    #[span_fn]
1413    async fn get_flight_info_sql_info(
1414        &self,
1415        query: CommandGetSqlInfo,
1416        request: Request<FlightDescriptor>,
1417    ) -> Result<Response<FlightInfo>, Status> {
1418        let begin_request = now();
1419        info!("get_flight_info_sql_info");
1420        let flight_descriptor = request.into_inner();
1421        let ticket = Ticket::new(query.as_any().encode_to_vec());
1422        let endpoint = FlightEndpoint::new().with_ticket(ticket);
1423        let flight_info = FlightInfo::new()
1424            .try_with_schema(query.into_builder(&INSTANCE_SQL_DATA).schema().as_ref())
1425            .map_err(|e| status!("Unable to encode schema", e))?
1426            .with_endpoint(endpoint)
1427            .with_descriptor(flight_descriptor);
1428        let duration = now() - begin_request;
1429        imetric!("request_duration", "ticks", duration as u64);
1430        Ok(tonic::Response::new(flight_info))
1431    }
1432
1433    async fn get_flight_info_primary_keys(
1434        &self,
1435        _query: CommandGetPrimaryKeys,
1436        _request: Request<FlightDescriptor>,
1437    ) -> Result<Response<FlightInfo>, Status> {
1438        api_entry_not_implemented!()
1439    }
1440
1441    async fn get_flight_info_exported_keys(
1442        &self,
1443        _query: CommandGetExportedKeys,
1444        _request: Request<FlightDescriptor>,
1445    ) -> Result<Response<FlightInfo>, Status> {
1446        api_entry_not_implemented!()
1447    }
1448
1449    async fn get_flight_info_imported_keys(
1450        &self,
1451        _query: CommandGetImportedKeys,
1452        _request: Request<FlightDescriptor>,
1453    ) -> Result<Response<FlightInfo>, Status> {
1454        api_entry_not_implemented!()
1455    }
1456
1457    async fn get_flight_info_cross_reference(
1458        &self,
1459        _query: CommandGetCrossReference,
1460        _request: Request<FlightDescriptor>,
1461    ) -> Result<Response<FlightInfo>, Status> {
1462        api_entry_not_implemented!()
1463    }
1464
1465    async fn get_flight_info_xdbc_type_info(
1466        &self,
1467        _query: CommandGetXdbcTypeInfo,
1468        _request: Request<FlightDescriptor>,
1469    ) -> Result<Response<FlightInfo>, Status> {
1470        api_entry_not_implemented!()
1471    }
1472
1473    #[span_fn]
1474    async fn do_get_statement(
1475        &self,
1476        ticket: TicketStatementQuery,
1477        request: Request<Ticket>,
1478    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1479        let client_ip = get_client_ip(request.metadata().as_ref(), request.extensions());
1480        self.execute_query(ticket, request.metadata(), request.extensions(), &client_ip)
1481            .await
1482    }
1483
1484    async fn do_get_prepared_statement(
1485        &self,
1486        _query: CommandPreparedStatementQuery,
1487        _request: Request<Ticket>,
1488    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1489        api_entry_not_implemented!()
1490    }
1491
1492    async fn do_get_catalogs(
1493        &self,
1494        _query: CommandGetCatalogs,
1495        _request: Request<Ticket>,
1496    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1497        api_entry_not_implemented!()
1498    }
1499
1500    async fn do_get_schemas(
1501        &self,
1502        _query: CommandGetDbSchemas,
1503        _request: Request<Ticket>,
1504    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1505        api_entry_not_implemented!()
1506    }
1507
1508    #[span_fn]
1509    async fn do_get_tables(
1510        &self,
1511        query: CommandGetTables,
1512        _request: Request<Ticket>,
1513    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1514        let begin_request = now();
1515        info!("do_get_tables {query:?}");
1516        let mut builder = query.into_builder();
1517        let view_factory = self.view_registry.current();
1518        for view in view_factory.get_global_views() {
1519            let catalog_name = "";
1520            let schema_name = "";
1521            builder
1522                .append(
1523                    catalog_name,
1524                    schema_name,
1525                    &*view.get_view_set_name(),
1526                    "table",
1527                    &view.get_file_schema(),
1528                )
1529                .map_err(Status::from)?;
1530        }
1531        let schema = builder.schema();
1532        let batch = builder.build();
1533        let stream = FlightDataEncoderBuilder::new()
1534            .with_schema(schema)
1535            .build(futures::stream::once(async { batch }))
1536            .map_err(Status::from);
1537        let duration = now() - begin_request;
1538        imetric!("request_duration", "ticks", duration as u64);
1539        Ok(Response::new(Box::pin(stream)))
1540    }
1541
1542    async fn do_get_table_types(
1543        &self,
1544        _query: CommandGetTableTypes,
1545        _request: Request<Ticket>,
1546    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1547        api_entry_not_implemented!()
1548    }
1549
1550    #[span_fn]
1551    async fn do_get_sql_info(
1552        &self,
1553        query: CommandGetSqlInfo,
1554        _request: Request<Ticket>,
1555    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1556        info!("do_get_sql_info");
1557        let builder = query.into_builder(&INSTANCE_SQL_DATA);
1558        let schema = builder.schema();
1559        let batch = builder.build();
1560        let stream = FlightDataEncoderBuilder::new()
1561            .with_schema(schema)
1562            .build(futures::stream::once(async { batch }))
1563            .map_err(Status::from);
1564        Ok(Response::new(Box::pin(stream)))
1565    }
1566
1567    async fn do_get_primary_keys(
1568        &self,
1569        _query: CommandGetPrimaryKeys,
1570        _request: Request<Ticket>,
1571    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1572        api_entry_not_implemented!()
1573    }
1574
1575    async fn do_get_exported_keys(
1576        &self,
1577        _query: CommandGetExportedKeys,
1578        _request: Request<Ticket>,
1579    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1580        api_entry_not_implemented!()
1581    }
1582
1583    async fn do_get_imported_keys(
1584        &self,
1585        _query: CommandGetImportedKeys,
1586        _request: Request<Ticket>,
1587    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1588        api_entry_not_implemented!()
1589    }
1590
1591    async fn do_get_cross_reference(
1592        &self,
1593        _query: CommandGetCrossReference,
1594        _request: Request<Ticket>,
1595    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1596        api_entry_not_implemented!()
1597    }
1598
1599    async fn do_get_xdbc_type_info(
1600        &self,
1601        _query: CommandGetXdbcTypeInfo,
1602        _request: Request<Ticket>,
1603    ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
1604        api_entry_not_implemented!()
1605    }
1606
1607    async fn do_put_statement_update(
1608        &self,
1609        _ticket: CommandStatementUpdate,
1610        _request: Request<PeekableFlightDataStream>,
1611    ) -> Result<i64, Status> {
1612        api_entry_not_implemented!()
1613    }
1614
1615    /// `bulk_ingest` (routed here from `CommandStatementIngest`) is a replication/administrative
1616    /// API, not an ordinary analytics write path: it writes the authoritative `audience` column
1617    /// on `processes`/`streams`/`blocks` rows -- and every other column, including properties --
1618    /// verbatim, with none of the server-side stamping or reserved-namespace stripping the HTTP
1619    /// ingestion paths apply; a missing `audience` column is a hard error rather than a silent
1620    /// default. Gating this RPC on `is_admin` is what keeps that verbatim write safe: an
1621    /// admin-run replication tool re-ingesting rows already stamped at their origin lake is
1622    /// exactly the case the docs describe (`mkdocs/docs/query-guide/python-api.md`), while an
1623    /// ordinary authenticated analytics client must not be able to set the `audience` column
1624    /// directly.
1625    #[span_fn]
1626    async fn do_put_statement_ingest(
1627        &self,
1628        command: CommandStatementIngest,
1629        request: Request<PeekableFlightDataStream>,
1630    ) -> Result<i64, Status> {
1631        let table_name = command.table;
1632        info!("do_put_statement_ingest table_name={table_name}");
1633        if !is_admin(request.metadata()) {
1634            return Err(Status::permission_denied(
1635                "bulk_ingest requires admin privileges",
1636            ));
1637        }
1638        let stream = FlightRecordBatchStream::new_from_flight_data(
1639            request.into_inner().map_err(|e| e.into()),
1640        );
1641        bulk_ingest(self.lakehouse.lake().clone(), &table_name, stream)
1642            .await
1643            .map_err(|e| {
1644                let msg = format!("error ingesting into {table_name}: {e:?}");
1645                error!("{msg}");
1646                status!(msg, e)
1647            })
1648    }
1649
1650    async fn do_put_substrait_plan(
1651        &self,
1652        _ticket: CommandStatementSubstraitPlan,
1653        _request: Request<PeekableFlightDataStream>,
1654    ) -> Result<i64, Status> {
1655        api_entry_not_implemented!()
1656    }
1657
1658    async fn do_put_prepared_statement_query(
1659        &self,
1660        _query: CommandPreparedStatementQuery,
1661        _request: Request<PeekableFlightDataStream>,
1662    ) -> Result<DoPutPreparedStatementResult, Status> {
1663        api_entry_not_implemented!()
1664    }
1665
1666    async fn do_put_prepared_statement_update(
1667        &self,
1668        _query: CommandPreparedStatementUpdate,
1669        _request: Request<PeekableFlightDataStream>,
1670    ) -> Result<i64, Status> {
1671        api_entry_not_implemented!()
1672    }
1673
1674    #[span_fn]
1675    async fn do_action_create_prepared_statement(
1676        &self,
1677        query: ActionCreatePreparedStatementRequest,
1678        request: Request<Action>,
1679    ) -> Result<ActionCreatePreparedStatementResult, Status> {
1680        info!("do_action_create_prepared_statement query={}", &query.query);
1681
1682        // DDL (`CREATE`/`DROP MATERIALIZED VIEW`) is never prepared: nothing in the repo
1683        // prepares DDL, and planning it here via `ctx.sql` would fail with an opaque DataFusion
1684        // error instead of this clear message.
1685        if parse_view_ddl(&query.query)
1686            .map_err(|e| client_input_error!("error parsing view DDL", e))?
1687            .is_some()
1688        {
1689            return Err(Status::invalid_argument(
1690                "CREATE/DROP MATERIALIZED VIEW must be executed directly, not prepared",
1691            ));
1692        }
1693
1694        // Prepared statements resolve the same CallerContext as the do_get execute path.
1695        let caller = self
1696            .caller_context(request.extensions(), request.metadata())
1697            .await?;
1698        let ctx = make_session_context(
1699            self.lakehouse.clone(),
1700            self.part_provider.clone(),
1701            SessionRange::NoPartitions,
1702            self.view_registry.current(),
1703            self.session_configurator.clone(),
1704            caller,
1705        )
1706        .await
1707        .map_err(|e| status!("error in make_session_context", e))?;
1708        register_deployment_notes(&ctx, self.settings.clone());
1709
1710        // No `QueryAuditState`/audit record exists on this RPC (it only plans the
1711        // query, never executes it) -- this id exists solely so the client-facing
1712        // message and a server log line can be correlated with each other.
1713        let local_query_id = Uuid::new_v4().to_string();
1714        let df = ctx
1715            .sql(&query.query)
1716            .await
1717            .map_err(|e| client_error("error building dataframe", e, &local_query_id, None))?;
1718        let schema = df.schema().as_arrow();
1719        let mut schema_buffer = Vec::new();
1720        let mut writer = StreamWriter::try_new(&mut schema_buffer, schema)
1721            .map_err(|e| status!("error writing schema to in-memory buffer", e))?;
1722        writer
1723            .finish()
1724            .map_err(|e| status!("error closing arrow ipc stream writer", e))?;
1725        // here we could serialize the logical plan and return that as the prepared statement, but we would
1726        // need to register LogicalExtensionCodec for user-defined functions
1727        // instead, we are sending back the sql as we received it
1728        let result = ActionCreatePreparedStatementResult {
1729            prepared_statement_handle: query.query.into(),
1730            dataset_schema: schema_buffer.into(),
1731            parameter_schema: "".into(),
1732        };
1733        Ok(result)
1734    }
1735
1736    async fn do_action_close_prepared_statement(
1737        &self,
1738        _query: ActionClosePreparedStatementRequest,
1739        _request: Request<Action>,
1740    ) -> Result<(), Status> {
1741        info!("do_action_close_prepared_statement");
1742        Ok(())
1743    }
1744
1745    async fn do_action_create_prepared_substrait_plan(
1746        &self,
1747        _query: ActionCreatePreparedSubstraitPlanRequest,
1748        _request: Request<Action>,
1749    ) -> Result<ActionCreatePreparedStatementResult, Status> {
1750        api_entry_not_implemented!()
1751    }
1752
1753    async fn do_action_begin_transaction(
1754        &self,
1755        _query: ActionBeginTransactionRequest,
1756        _request: Request<Action>,
1757    ) -> Result<ActionBeginTransactionResult, Status> {
1758        api_entry_not_implemented!()
1759    }
1760
1761    async fn do_action_end_transaction(
1762        &self,
1763        _query: ActionEndTransactionRequest,
1764        _request: Request<Action>,
1765    ) -> Result<(), Status> {
1766        api_entry_not_implemented!()
1767    }
1768
1769    async fn do_action_begin_savepoint(
1770        &self,
1771        _query: ActionBeginSavepointRequest,
1772        _request: Request<Action>,
1773    ) -> Result<ActionBeginSavepointResult, Status> {
1774        api_entry_not_implemented!()
1775    }
1776
1777    async fn do_action_end_savepoint(
1778        &self,
1779        _query: ActionEndSavepointRequest,
1780        _request: Request<Action>,
1781    ) -> Result<(), Status> {
1782        api_entry_not_implemented!()
1783    }
1784
1785    async fn do_action_cancel_query(
1786        &self,
1787        _query: ActionCancelQueryRequest,
1788        _request: Request<Action>,
1789    ) -> Result<ActionCancelQueryResult, Status> {
1790        api_entry_not_implemented!()
1791    }
1792
1793    async fn register_sql_info(&self, _id: i32, _result: &SqlInfo) {
1794        info!("register_sql_info");
1795    }
1796}