Skip to main content

servers/postgres/
handler.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
15use std::fmt::Debug;
16use std::pin::Pin;
17use std::sync::Arc;
18
19use async_trait::async_trait;
20use common_query::{Output, OutputData};
21use common_recordbatch::RecordBatch;
22use common_recordbatch::error::Result as RecordBatchResult;
23use common_telemetry::{debug, info, tracing};
24use datafusion::sql::sqlparser::ast::{CopyOption, CopyTarget, Statement as SqlParserStatement};
25use datafusion_common::ParamValues;
26use datafusion_expr::LogicalPlan;
27use datafusion_pg_catalog::sql::PostgresCompatibilityParser;
28use datatypes::prelude::ConcreteDataType;
29use datatypes::schema::{Schema, SchemaRef};
30use futures::{Sink, SinkExt, Stream, StreamExt, future, stream};
31use operator::statement::admin_output_schema;
32use pgwire::api::portal::{Format, Portal};
33use pgwire::api::query::{ExtendedQueryHandler, SimpleQueryHandler};
34use pgwire::api::results::{
35    CopyCsvOptions, CopyEncoder, CopyResponse, CopyTextOptions, DataRowEncoder,
36    DescribePortalResponse, DescribeStatementResponse, FieldInfo, QueryResponse, Response, Tag,
37};
38use pgwire::api::stmt::{QueryParser, StoredStatement};
39use pgwire::api::{ClientInfo, ErrorHandler, Type};
40use pgwire::error::{ErrorInfo, PgWireError, PgWireResult};
41use pgwire::messages::PgWireBackendMessage;
42use pgwire::messages::copy::CopyData;
43use pgwire::messages::data::DataRow;
44use query::dist_analyze_output_schema;
45use query::planner::DfLogicalPlanner;
46use query::query_engine::DescribeResult;
47use query::sql::DESCRIBE_TABLE_OUTPUT_SCHEMA;
48use session::Session;
49use session::context::QueryContextRef;
50use snafu::ResultExt;
51use sql::dialect::PostgreSqlDialect;
52use sql::parser::{ParseOptions, ParserContext};
53use sql::statements::statement::Statement;
54
55use crate::SqlPlan;
56use crate::error::{DataFusionSnafu, InferParameterTypesSnafu, Result};
57use crate::postgres::types::*;
58use crate::postgres::utils::convert_err;
59use crate::postgres::{PostgresServerHandlerInner, copy_in, fixtures};
60use crate::query_handler::sql::ServerSqlQueryHandlerRef;
61
62impl PostgresServerHandlerInner {
63    /// Creates a query context carrying this connection's batching
64    /// selection, so write paths can route through the pending-rows
65    /// batcher when it is enabled.
66    pub(super) fn new_query_context(&self) -> QueryContextRef {
67        let mut ctx = self.session.new_query_context();
68        Arc::make_mut(&mut ctx).set_batching_enabled(self.batching_enabled);
69        ctx
70    }
71}
72
73#[async_trait]
74impl SimpleQueryHandler for PostgresServerHandlerInner {
75    #[tracing::instrument(skip_all, fields(protocol = "postgres"))]
76    async fn do_query<C>(&self, client: &mut C, query: &str) -> PgWireResult<Vec<Response>>
77    where
78        C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
79        C::Error: Debug,
80        PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
81    {
82        let query_ctx = self.new_query_context();
83        let db = query_ctx.get_db_string();
84        let _timer = crate::metrics::METRIC_POSTGRES_QUERY_TIMER
85            .with_label_values(&[crate::metrics::METRIC_POSTGRES_SIMPLE_QUERY, db.as_str()])
86            .start_timer();
87
88        if query.is_empty() {
89            // early return if query is empty
90            return Ok(vec![Response::EmptyQuery]);
91        }
92
93        // A leading COPY FROM STDIN takes over the connection for the copy
94        // sub-protocol; it is parsed textually so the WITH clause may carry
95        // options beyond sqlparser's COPY grammar. It must run alone.
96        if let Some(copy_from_stdin) = copy_in::copy_from_stdin_from_sql(query)? {
97            let response = self.begin_copy_in(copy_from_stdin).await?;
98            send_warning_opt(client, query_ctx).await?;
99            return Ok(vec![response]);
100        }
101
102        let parsed_query = self.query_parser.compatibility_parser.parse(query);
103
104        // A COPY FROM STDIN trailing other statements must be rejected;
105        // the textual scanner above only sees statement-leading COPYs.
106        if let Ok(statements) = &parsed_query
107            && statements.iter().any(copy_in::is_copy_from_stdin)
108        {
109            return Err(copy_in::copy_in_must_run_alone_error());
110        }
111
112        let queries = match &parsed_query {
113            Ok(statements) => {
114                // Comments, whitespace and empty statements also require EmptyQueryResponse.
115                if statements.is_empty() {
116                    return Ok(vec![Response::EmptyQuery]);
117                }
118                statements
119                    .iter()
120                    .map(|statement| (statement_to_query(statement), Some(statement)))
121                    .collect::<Vec<_>>()
122            }
123            Err(_) => vec![(query.to_string(), None)],
124        };
125
126        // Fixture statements are answered one by one; the statements between
127        // them run as one batch, so a fixture never swallows its neighbours.
128        let mut results = Vec::with_capacity(queries.len());
129        let mut batch = Vec::new();
130        for (query, statement) in queries {
131            if let Some(resps) = fixtures::process(&query, query_ctx.clone()) {
132                self.run_simple_batch(std::mem::take(&mut batch), &query_ctx, &mut results)
133                    .await?;
134                results.extend(resps);
135            } else {
136                batch.push((query, statement));
137            }
138        }
139        self.run_simple_batch(batch, &query_ctx, &mut results)
140            .await?;
141
142        send_warning_opt(client, query_ctx).await?;
143        Ok(results)
144    }
145}
146
147impl PostgresServerHandlerInner {
148    async fn run_simple_batch(
149        &self,
150        batch: Vec<(String, Option<&SqlParserStatement>)>,
151        query_ctx: &QueryContextRef,
152        results: &mut Vec<Response>,
153    ) -> PgWireResult<()> {
154        if batch.is_empty() {
155            return Ok(());
156        }
157        let query = batch
158            .iter()
159            .map(|(query, _)| query.as_str())
160            .collect::<Vec<_>>()
161            .join(";");
162        let outputs = self.query_handler.do_query(&query, query_ctx.clone()).await;
163        for (idx, output) in outputs.into_iter().enumerate() {
164            let copy_format = batch
165                .get(idx)
166                .and_then(|(_, statement)| *statement)
167                .and_then(check_copy_to_stdout);
168            let resp = if let Some(format) = &copy_format {
169                output_to_copy_response(query_ctx.clone(), output, format)?
170            } else {
171                output_to_query_response(query_ctx.clone(), output, &Format::UnifiedText)?
172            };
173            results.push(resp);
174        }
175        Ok(())
176    }
177}
178
179fn statement_to_query(statement: &SqlParserStatement) -> String {
180    if let SqlParserStatement::ShowVariable { variable } = statement
181        && variable.len() > 1
182        && (variable[0].value.eq_ignore_ascii_case("query")
183            || variable[0].value.eq_ignore_ascii_case("datafusion"))
184    {
185        return format!(
186            "SHOW {}",
187            variable
188                .iter()
189                .map(ToString::to_string)
190                .collect::<Vec<_>>()
191                .join(".")
192        );
193    }
194    statement.to_string()
195}
196
197async fn send_warning_opt<C>(client: &mut C, query_context: QueryContextRef) -> PgWireResult<()>
198where
199    C: Sink<PgWireBackendMessage> + Unpin + Send + Sync,
200    C::Error: Debug,
201    PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
202{
203    if let Some(warning) = query_context.warning() {
204        client
205            .feed(PgWireBackendMessage::NoticeResponse(
206                ErrorInfo::new(
207                    PgErrorSeverity::Warning.to_string(),
208                    PgErrorCode::Ec01000.code(),
209                    warning.clone(),
210                )
211                .into(),
212            ))
213            .await?;
214    }
215
216    Ok(())
217}
218
219pub(crate) fn output_to_query_response(
220    query_ctx: QueryContextRef,
221    output: Result<Output>,
222    field_format: &Format,
223) -> PgWireResult<Response> {
224    match output {
225        Ok(o) => match o.data {
226            OutputData::AffectedRows(rows) => {
227                Ok(Response::Execution(Tag::new("OK").with_rows(rows)))
228            }
229            OutputData::Stream(record_stream) => {
230                let schema = record_stream.schema();
231                recordbatches_to_query_response(query_ctx, record_stream, schema, field_format)
232            }
233            OutputData::RecordBatches(recordbatches) => {
234                let schema = recordbatches.schema();
235                recordbatches_to_query_response(
236                    query_ctx,
237                    recordbatches.as_stream(),
238                    schema,
239                    field_format,
240                )
241            }
242        },
243        Err(e) => Err(convert_err(e)),
244    }
245}
246
247type RowStream<T> = Pin<Box<dyn Stream<Item = PgWireResult<T>> + Send + Unpin>>;
248
249fn recordbatches_to_query_response<S>(
250    query_ctx: QueryContextRef,
251    recordbatches_stream: S,
252    schema: SchemaRef,
253    field_format: &Format,
254) -> PgWireResult<Response>
255where
256    S: Stream<Item = RecordBatchResult<RecordBatch>> + Send + Unpin + 'static,
257{
258    let format_options = format_options_from_query_ctx(&query_ctx);
259    let pg_schema = Arc::new(
260        schema_to_pg(schema.as_ref(), field_format, Some(format_options)).map_err(convert_err)?,
261    );
262
263    let encoder = DataRowEncoder::new(pg_schema.clone());
264    let row_stream = RecordBatchRowStream::new(
265        query_ctx.clone(),
266        pg_schema.clone(),
267        schema.clone(),
268        recordbatches_stream,
269        encoder,
270    );
271
272    let data_row_stream: RowStream<DataRow> = Box::pin(
273        row_stream
274            .map(move |result| match result {
275                Ok(rows) => Box::pin(stream::iter(rows.into_iter().map(Ok))) as RowStream<DataRow>,
276                Err(e) => Box::pin(stream::once(future::ready(Err(e)))) as RowStream<DataRow>,
277            })
278            .flatten(),
279    );
280
281    Ok(Response::Query(QueryResponse::new(
282        pg_schema,
283        data_row_stream,
284    )))
285}
286
287pub(crate) fn output_to_copy_response(
288    query_ctx: QueryContextRef,
289    output: Result<Output>,
290    format: &str,
291) -> PgWireResult<Response> {
292    match output {
293        Ok(o) => match o.data {
294            OutputData::AffectedRows(_) => Err(PgWireError::UserError(Box::new(ErrorInfo::new(
295                "ERROR".to_string(),
296                "42601".to_string(),
297                "COPY cannot be used with non-query statements".to_string(),
298            )))),
299            OutputData::Stream(record_stream) => {
300                let schema = record_stream.schema();
301                recordbatches_to_copy_response(query_ctx, record_stream, schema, format)
302            }
303            OutputData::RecordBatches(recordbatches) => {
304                let schema = recordbatches.schema();
305                recordbatches_to_copy_response(query_ctx, recordbatches.as_stream(), schema, format)
306            }
307        },
308        Err(e) => Err(convert_err(e)),
309    }
310}
311
312fn recordbatches_to_copy_response<S>(
313    query_ctx: QueryContextRef,
314    recordbatches_stream: S,
315    schema: SchemaRef,
316    format: &str,
317) -> PgWireResult<Response>
318where
319    S: Stream<Item = RecordBatchResult<RecordBatch>> + Send + Unpin + 'static,
320{
321    let format_options = format_options_from_query_ctx(&query_ctx);
322    let pg_fields = schema_to_pg(schema.as_ref(), &Format::UnifiedText, Some(format_options))
323        .map_err(convert_err)?;
324
325    let copy_format = match format.to_lowercase().as_str() {
326        "binary" => 1,
327        _ => 0,
328    };
329
330    // Render timestamps with an explicit session-timezone offset so the
331    // exported text carries the instant unambiguously: the timezone-aware
332    // COPY IN decoder honors embedded offsets, keeping COPY OUT -> COPY IN
333    // round trips exact in non-UTC sessions (matching SQL INSERT parity).
334    // This touches both halves of the encoder: the arrow schema drives
335    // value conversion into a tz-aware DateTime, and the pg field type
336    // selects the offset-bearing text format.
337    let arrow_schema_override = copy_out_schema_with_timezone(&schema, &query_ctx);
338    let pg_fields = if arrow_schema_override.is_some() {
339        pg_fields
340            .into_iter()
341            .map(|mut field| {
342                if field.datatype() == &Type::TIMESTAMP {
343                    field = FieldInfo::new(
344                        field.name().to_string(),
345                        None,
346                        None,
347                        Type::TIMESTAMPTZ,
348                        field.format(),
349                    )
350                    .with_type_size(field.type_size())
351                    .with_type_modifier(field.type_modifier());
352                }
353                field
354            })
355            .collect::<Vec<_>>()
356    } else {
357        pg_fields
358    };
359
360    let pg_schema = Arc::new(pg_fields);
361    let num_columns = pg_schema.len();
362
363    let copy_encoder = match format.to_lowercase().as_str() {
364        "csv" => CopyEncoder::new_csv(pg_schema.clone(), CopyCsvOptions::default()),
365        "binary" => CopyEncoder::new_binary(pg_schema.clone()),
366        _ => CopyEncoder::new_text(pg_schema.clone(), CopyTextOptions::default()),
367    };
368
369    let row_stream = RecordBatchRowStream::new(
370        query_ctx.clone(),
371        pg_schema.clone(),
372        schema.clone(),
373        recordbatches_stream,
374        copy_encoder,
375    )
376    .with_arrow_schema_override(arrow_schema_override);
377
378    let copy_stream: RowStream<CopyData> = Box::pin(
379        row_stream
380            .map(move |result| match result {
381                Ok(rows) => Box::pin(stream::iter(rows.into_iter().map(Ok))) as RowStream<CopyData>,
382                Err(e) => Box::pin(stream::once(future::ready(Err(e)))) as RowStream<CopyData>,
383            })
384            .flatten(),
385    );
386
387    Ok(Response::CopyOut(CopyResponse::new(
388        copy_format,
389        num_columns,
390        copy_stream,
391    )))
392}
393
394pub struct DefaultQueryParser {
395    query_handler: ServerSqlQueryHandlerRef,
396    session: Arc<Session>,
397    compatibility_parser: PostgresCompatibilityParser,
398}
399
400impl DefaultQueryParser {
401    pub fn new(query_handler: ServerSqlQueryHandlerRef, session: Arc<Session>) -> Self {
402        DefaultQueryParser {
403            query_handler,
404            session,
405            compatibility_parser: PostgresCompatibilityParser::new(),
406        }
407    }
408}
409
410/// A container type of parse result types
411#[derive(Clone, Debug)]
412pub struct PgSqlPlan {
413    pub(crate) plan: SqlPlan,
414    pub(crate) copy_to_stdout_format: Option<String>,
415    pub(crate) copy_from_stdin: Option<copy_in::CopyFromStdin>,
416}
417
418#[async_trait]
419impl QueryParser for DefaultQueryParser {
420    type Statement = PgSqlPlan;
421
422    async fn parse_sql<C>(
423        &self,
424        _client: &C,
425        sql: &str,
426        _types: &[Option<Type>],
427    ) -> PgWireResult<Option<Self::Statement>> {
428        crate::metrics::METRIC_POSTGRES_PREPARED_COUNT.inc();
429        let query_ctx = self.session.new_query_context();
430
431        // do not parse if query is empty or matches rules
432        if sql.is_empty() {
433            return Ok(None);
434        }
435
436        if fixtures::matches(sql) {
437            return Ok(Some(PgSqlPlan {
438                plan: SqlPlan::Shortcut(sql.to_string()),
439                copy_to_stdout_format: None,
440                copy_from_stdin: None,
441            }));
442        }
443
444        // A COPY FROM STDIN is parsed textually — not through sqlparser —
445        // so the WITH clause may carry options beyond sqlparser's COPY
446        // grammar; the extended query handler starts the copy sub-protocol
447        // when the statement is executed.
448        if let Some(copy_from_stdin) = copy_in::copy_from_stdin_from_sql(sql)? {
449            return Ok(Some(PgSqlPlan {
450                plan: SqlPlan::Shortcut(sql.to_string()),
451                copy_to_stdout_format: None,
452                copy_from_stdin: Some(copy_from_stdin),
453            }));
454        }
455
456        let parsed_statements = self.compatibility_parser.parse(sql);
457        let (sql, copy_to_stdout_format) = if let Ok(mut statements) = parsed_statements {
458            if statements.is_empty() {
459                return Ok(None);
460            }
461            if statements.len() > 1 {
462                return Err(PgWireError::UserError(Box::new(
463                    PgErrorCode::Ec42601.to_err_info(
464                        "cannot insert multiple commands into a prepared statement".to_string(),
465                    ),
466                )));
467            }
468            let first_stmt = statements.remove(0);
469            let format = check_copy_to_stdout(&first_stmt);
470            (first_stmt.to_string(), format)
471        } else {
472            // bypass the error: it can run into error because of different
473            // versions of sqlparser
474            (sql.to_string(), None)
475        };
476
477        let mut stmts = ParserContext::create_with_dialect(
478            &sql,
479            &PostgreSqlDialect {},
480            ParseOptions::default(),
481        )
482        .map_err(convert_err)?;
483        if stmts.len() != 1 {
484            Err(PgWireError::UserError(Box::new(ErrorInfo::from(
485                PgErrorCode::Ec42P14,
486            ))))
487        } else {
488            let stmt = stmts.remove(0);
489
490            if let Some(logical_plan) = self
491                .query_handler
492                .do_describe(stmt.clone(), query_ctx)
493                .await
494                .map_err(convert_err)?
495                .map(|DescribeResult { logical_plan }| logical_plan)
496            {
497                Ok(Some(PgSqlPlan {
498                    plan: SqlPlan::Plan(logical_plan, stmt),
499                    copy_to_stdout_format,
500                    copy_from_stdin: None,
501                }))
502            } else {
503                Ok(Some(PgSqlPlan {
504                    plan: SqlPlan::Statement(stmt, sql),
505                    copy_to_stdout_format,
506                    copy_from_stdin: None,
507                }))
508            }
509        }
510    }
511
512    fn get_parameter_types(&self, _stmt: &Self::Statement) -> PgWireResult<Vec<Type>> {
513        // we have our own implementation of describes in ExtendedQueryHandler
514        // so we don't use these methods
515        Err(PgWireError::ApiError(
516            "get_parameter_types is not expected to be called".into(),
517        ))
518    }
519
520    fn get_result_schema(
521        &self,
522        _stmt: &Self::Statement,
523        _column_format: Option<&Format>,
524    ) -> PgWireResult<Vec<FieldInfo>> {
525        // we have our own implementation of describes in ExtendedQueryHandler
526        // so we don't use these methods
527        Err(PgWireError::ApiError(
528            "get_result_schema is not expected to be called".into(),
529        ))
530    }
531}
532
533#[async_trait]
534impl ExtendedQueryHandler for PostgresServerHandlerInner {
535    type Statement = PgSqlPlan;
536    type QueryParser = DefaultQueryParser;
537
538    fn query_parser(&self) -> Arc<Self::QueryParser> {
539        self.query_parser.clone()
540    }
541
542    async fn do_query<C>(
543        &self,
544        client: &mut C,
545        portal: &Portal<Self::Statement>,
546        _max_rows: usize,
547    ) -> PgWireResult<Response>
548    where
549        C: ClientInfo + Sink<PgWireBackendMessage> + Unpin + Send + Sync,
550        C::Error: Debug,
551        PgWireError: From<<C as Sink<PgWireBackendMessage>>::Error>,
552    {
553        let query_ctx = self.new_query_context();
554        let db = query_ctx.get_db_string();
555        let _timer = crate::metrics::METRIC_POSTGRES_QUERY_TIMER
556            .with_label_values(&[crate::metrics::METRIC_POSTGRES_EXTENDED_QUERY, db.as_str()])
557            .start_timer();
558
559        let pg_sql_plan = &portal.statement.statement;
560        let sql_plan = &pg_sql_plan.plan;
561
562        // A COPY FROM STDIN takes over the connection for the copy
563        // sub-protocol.
564        if let Some(copy_from_stdin) = &pg_sql_plan.copy_from_stdin {
565            let response = self.begin_copy_in(copy_from_stdin.clone()).await?;
566            send_warning_opt(client, query_ctx).await?;
567            return Ok(response);
568        }
569
570        let output = match sql_plan {
571            SqlPlan::Empty => {
572                // early return if query is empty
573                return Ok(Response::EmptyQuery);
574            }
575            SqlPlan::Shortcut(query) => {
576                if let Some(mut resps) = fixtures::process(query, query_ctx.clone()) {
577                    send_warning_opt(client, query_ctx).await?;
578                    // if the statement matches our predefined rules, return it early
579                    return Ok(resps.remove(0));
580                } else {
581                    // unreachable logic
582                    return Ok(Response::EmptyQuery);
583                }
584            }
585            SqlPlan::Plan(plan, stmt) => {
586                let values = parameters_to_scalar_values(plan, portal)?;
587                let plan = plan
588                    .clone()
589                    .replace_params_with_values(&ParamValues::List(
590                        values.into_iter().map(Into::into).collect(),
591                    ))
592                    .context(DataFusionSnafu)
593                    .map_err(convert_err)?;
594                self.query_handler
595                    .do_exec_plan(plan, Some(stmt.clone()), query_ctx.clone())
596                    .await
597            }
598            SqlPlan::Statement(_stmt, query) => {
599                // We won't replace params from statement manually any more.
600                // Newer version of datafusion can generate plan for SELECT/INSERT/UPDATE/DELETE.
601                // Only CREATE TABLE and others minor statements cannot generate sql plan,
602                // in this case, we assume these statements will not carry parameters
603                // and execute them directly.
604                self.query_handler
605                    .do_query(query, query_ctx.clone())
606                    .await
607                    .remove(0)
608            }
609        };
610
611        send_warning_opt(client, query_ctx.clone()).await?;
612
613        if let Some(format) = &pg_sql_plan.copy_to_stdout_format {
614            output_to_copy_response(query_ctx, output, format)
615        } else {
616            output_to_query_response(query_ctx, output, &portal.result_column_format)
617        }
618    }
619
620    async fn do_describe_statement<C>(
621        &self,
622        _client: &mut C,
623        stmt: &StoredStatement<Self::Statement>,
624    ) -> PgWireResult<DescribeStatementResponse>
625    where
626        C: ClientInfo + Unpin + Send + Sync,
627    {
628        let sql_plan = &stmt.statement.plan;
629        // client provided parameter types, can be empty if client doesn't try to parse statement
630        let provided_param_types = &stmt.parameter_types;
631        let server_inferenced_types = if let SqlPlan::Plan(plan, _) = &sql_plan {
632            let param_types = DfLogicalPlanner::get_inferred_parameter_types(plan)
633                .context(InferParameterTypesSnafu)
634                .map_err(convert_err)?
635                .into_iter()
636                .map(|(k, v)| (k, v.map(|v| ConcreteDataType::from_arrow_type(&v))))
637                .collect();
638
639            let types = param_types_to_pg_types(&param_types).map_err(convert_err)?;
640
641            Some(types)
642        } else {
643            None
644        };
645
646        let param_count = if provided_param_types.is_empty() {
647            server_inferenced_types
648                .as_ref()
649                .map(|types| types.len())
650                .unwrap_or(0)
651        } else {
652            provided_param_types.len()
653        };
654
655        let param_types = (0..param_count)
656            .map(|i| {
657                let client_type = provided_param_types.get(i);
658                // use server type when client provided type is None (oid: 0 or other invalid values)
659                match client_type {
660                    Some(Some(client_type)) => client_type.clone(),
661                    _ => server_inferenced_types
662                        .as_ref()
663                        .and_then(|types| types.get(i).cloned())
664                        .unwrap_or(Type::UNKNOWN),
665                }
666            })
667            .collect::<Vec<_>>();
668
669        let fields = describe_fields(sql_plan, &Format::UnifiedText, &self.session)?;
670
671        Ok(DescribeStatementResponse::new(param_types, fields))
672    }
673
674    async fn do_describe_portal<C>(
675        &self,
676        _client: &mut C,
677        portal: &Portal<Self::Statement>,
678    ) -> PgWireResult<DescribePortalResponse>
679    where
680        C: ClientInfo + Unpin + Send + Sync,
681    {
682        let sql_plan = &portal.statement.statement.plan;
683        let format = &portal.result_column_format;
684
685        let fields = describe_fields(sql_plan, format, &self.session)?;
686
687        Ok(DescribePortalResponse::new(fields))
688    }
689}
690
691fn describe_fields(
692    sql_plan: &SqlPlan,
693    format: &Format,
694    session: &Arc<Session>,
695) -> PgWireResult<Vec<FieldInfo>> {
696    match sql_plan {
697        // Execution swaps in DistAnalyzeExec (stage/node/plan), whose schema
698        // differs from the logical `Analyze` plan's (plan_type/plan).
699        SqlPlan::Plan(LogicalPlan::Analyze(_), _) => {
700            let schema: Schema =
701                Schema::try_from(dist_analyze_output_schema()).map_err(convert_err)?;
702            schema_to_pg(&schema, format, None).map_err(convert_err)
703        }
704        // query
705        SqlPlan::Plan(plan, _) if !matches!(plan, LogicalPlan::Dml(_) | LogicalPlan::Ddl(_)) => {
706            let schema: Schema = plan.schema().clone().try_into().map_err(convert_err)?;
707            schema_to_pg(&schema, format, None).map_err(convert_err)
708        }
709        // We can cover only part of show statements
710        // these show create statements will return 2 columns
711        SqlPlan::Statement(
712            Statement::ShowCreateDatabase(_)
713            | Statement::ShowCreateTable(_)
714            | Statement::ShowCreateFlow(_)
715            | Statement::ShowCreateView(_),
716            _,
717        ) => Ok(vec![
718            FieldInfo::new(
719                "name".to_string(),
720                None,
721                None,
722                Type::TEXT,
723                format.format_for(0),
724            ),
725            FieldInfo::new(
726                "create_statement".to_string(),
727                None,
728                None,
729                Type::TEXT,
730                format.format_for(1),
731            ),
732        ]),
733        #[cfg(feature = "enterprise")]
734        SqlPlan::Statement(Statement::ShowCreateTrigger(_), _) => Ok(vec![
735            FieldInfo::new(
736                "name".to_string(),
737                None,
738                None,
739                Type::TEXT,
740                format.format_for(0),
741            ),
742            FieldInfo::new(
743                "create_statement".to_string(),
744                None,
745                None,
746                Type::TEXT,
747                format.format_for(1),
748            ),
749        ]),
750        // SHOW FLOW STATUS returns six columns; return their descriptions so
751        // prepared/extended-protocol clients receive the correct row description.
752        SqlPlan::Statement(Statement::ShowFlowStatus(_), _) => Ok(vec![
753            FieldInfo::new(
754                "flow_id".to_string(),
755                None,
756                None,
757                Type::INT8, // matches type_gt_to_pg(UInt32) — do not use INT4
758                format.format_for(0),
759            ),
760            FieldInfo::new(
761                "flow_name".to_string(),
762                None,
763                None,
764                Type::TEXT,
765                format.format_for(1),
766            ),
767            FieldInfo::new(
768                "start_time".to_string(),
769                None,
770                None,
771                Type::TIMESTAMP,
772                format.format_for(2),
773            ),
774            FieldInfo::new(
775                "last_execution_time".to_string(),
776                None,
777                None,
778                Type::TIMESTAMP,
779                format.format_for(3),
780            ),
781            FieldInfo::new(
782                "uptime_seconds".to_string(),
783                None,
784                None,
785                Type::INT8,
786                format.format_for(4),
787            ),
788            FieldInfo::new(
789                "state_size".to_string(),
790                None,
791                None,
792                Type::NUMERIC,
793                format.format_for(5),
794            ),
795        ]),
796
797        #[cfg(feature = "enterprise")]
798        SqlPlan::Statement(Statement::ShowTriggers(_), _) => Ok(vec![FieldInfo::new(
799            "name".to_string(),
800            None,
801            None,
802            Type::TEXT,
803            format.format_for(0),
804        )]),
805        // we will not support other show statements for extended query protocol at least for now.
806        // because the return columns is not predictable at this stage
807        SqlPlan::Shortcut(query) => {
808            // test if query caught by fixture
809            if let Some(mut resp) = fixtures::process(query, session.new_query_context())
810                && let Response::Query(query_response) = resp.remove(0)
811            {
812                Ok((*query_response.row_schema()).clone())
813            } else {
814                // fallback to NoData
815                Ok(vec![])
816            }
817        }
818        // Single column named after the variable (see `query::sql::show_variable`).
819        SqlPlan::Statement(Statement::ShowVariables(show), _) => Ok(vec![FieldInfo::new(
820            show.variable.to_string().to_uppercase(),
821            None,
822            None,
823            Type::TEXT,
824            format.format_for(0),
825        )]),
826        // Mirrors `query::sql::show_status` (currently always empty).
827        SqlPlan::Statement(Statement::ShowStatus(_), _) => Ok(vec![
828            FieldInfo::new(
829                "Variable_name".to_string(),
830                None,
831                None,
832                Type::TEXT,
833                format.format_for(0),
834            ),
835            FieldInfo::new(
836                "Value".to_string(),
837                None,
838                None,
839                Type::TEXT,
840                format.format_for(1),
841            ),
842        ]),
843        SqlPlan::Statement(Statement::ShowSearchPath(_), _) => Ok(vec![FieldInfo::new(
844            "search_path".to_string(),
845            None,
846            None,
847            Type::TEXT,
848            format.format_for(0),
849        )]),
850        // Mirrors `query::sql::describe_table`.
851        SqlPlan::Statement(Statement::DescribeTable(_), _) => {
852            schema_to_pg(&DESCRIBE_TABLE_OUTPUT_SCHEMA, format, None).map_err(convert_err)
853        }
854        // Single column typed with the function's return type (see
855        // `operator::statement::admin_output_schema`).
856        SqlPlan::Statement(Statement::Admin(admin), _) => {
857            let query_ctx = session.new_query_context();
858            match admin_output_schema(admin, &query_ctx) {
859                Some(schema) => schema_to_pg(&schema, format, None).map_err(convert_err),
860                // Unresolvable; execution will surface the error.
861                None => Ok(vec![]),
862            }
863        }
864        // Describe from the declared cursor's schema.
865        SqlPlan::Statement(Statement::FetchCursor(fetch), _) => {
866            let cursor_name = fetch.cursor_name.to_string();
867            match session.get_cursor(&cursor_name) {
868                Some(cursor) => schema_to_pg(&cursor.schema(), format, None).map_err(convert_err),
869                // Cursor not declared yet; execution will error.
870                None => Ok(vec![]),
871            }
872        }
873        _ => {
874            // NoData
875            Ok(vec![])
876        }
877    }
878}
879
880impl ErrorHandler for PostgresServerHandlerInner {
881    fn on_error<C>(&self, _client: &C, error: &mut PgWireError)
882    where
883        C: ClientInfo,
884    {
885        match error {
886            PgWireError::IoError(e) => debug!("Postgres client disconnected: {}", e),
887            _ => info!("Postgres interface error: {}", error),
888        }
889    }
890}
891
892/// Rewrites timestamp fields of the table's arrow schema to carry the
893/// session timezone, so COPY OUT renders them with an explicit offset
894/// (`2024-01-01 08:00:00+08:00`). Returns `None` when there is nothing
895/// to rewrite (no naive timestamps or a UTC session leaving output as-is
896/// is fine either way — offsets are always unambiguous on re-import).
897fn copy_out_schema_with_timezone(
898    schema: &SchemaRef,
899    query_ctx: &QueryContextRef,
900) -> Option<Arc<arrow::datatypes::Schema>> {
901    let timezone = query_ctx.timezone().to_string();
902    let arrow_schema = schema.arrow_schema();
903    let mut changed = false;
904    let fields = arrow_schema
905        .fields()
906        .iter()
907        .map(|field| match field.data_type() {
908            arrow::datatypes::DataType::Timestamp(unit, None) => {
909                changed = true;
910                field
911                    .as_ref()
912                    .clone()
913                    .with_data_type(arrow::datatypes::DataType::Timestamp(
914                        *unit,
915                        Some(Arc::from(timezone.as_str())),
916                    ))
917            }
918            _ => field.as_ref().clone(),
919        })
920        .collect::<Vec<_>>();
921    changed.then(|| Arc::new(arrow::datatypes::Schema::new(fields)))
922}
923
924fn check_copy_to_stdout(statement: &SqlParserStatement) -> Option<String> {
925    if let SqlParserStatement::Copy {
926        target, options, ..
927    } = statement
928        && matches!(target, CopyTarget::Stdout)
929    {
930        for opt in options {
931            if let CopyOption::Format(format_ident) = opt {
932                return Some(format_ident.value.to_lowercase());
933            }
934        }
935        return Some("txt".to_string());
936    }
937
938    None
939}
940
941#[cfg(test)]
942mod tests {
943    use datafusion_pg_catalog::sql::PostgresCompatibilityParser;
944
945    use super::*;
946
947    fn parse_copy_statement(sql: &str) -> SqlParserStatement {
948        let parser = PostgresCompatibilityParser::new();
949        let statements = parser.parse(sql).unwrap();
950        statements.into_iter().next().unwrap()
951    }
952
953    #[test]
954    fn test_check_copy_out_with_csv_format() {
955        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT WITH (FORMAT CSV)");
956        assert_eq!(check_copy_to_stdout(&statement), Some("csv".to_string()));
957    }
958
959    #[test]
960    fn test_check_copy_out_with_txt_format() {
961        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT WITH (FORMAT TXT)");
962        assert_eq!(check_copy_to_stdout(&statement), Some("txt".to_string()));
963    }
964
965    #[test]
966    fn test_check_copy_out_with_binary_format() {
967        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT WITH (FORMAT BINARY)");
968        assert_eq!(check_copy_to_stdout(&statement), Some("binary".to_string()));
969    }
970
971    #[test]
972    fn test_check_copy_out_without_format() {
973        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT");
974        assert_eq!(check_copy_to_stdout(&statement), Some("txt".to_string()));
975    }
976
977    #[test]
978    fn test_check_copy_out_to_file() {
979        let statement =
980            parse_copy_statement("COPY (SELECT 1) TO '/path/to/file.csv' WITH (FORMAT CSV)");
981        assert_eq!(check_copy_to_stdout(&statement), None);
982    }
983
984    #[test]
985    fn test_check_copy_out_case_insensitive() {
986        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT WITH (FORMAT csv)");
987        assert_eq!(check_copy_to_stdout(&statement), Some("csv".to_string()));
988
989        let statement = parse_copy_statement("COPY (SELECT 1) TO STDOUT WITH (FORMAT binary)");
990        assert_eq!(check_copy_to_stdout(&statement), Some("binary".to_string()));
991    }
992
993    #[test]
994    fn test_check_copy_out_with_multiple_options() {
995        let statement = parse_copy_statement(
996            "COPY (SELECT 1) TO STDOUT WITH (FORMAT csv, DELIMITER ',', HEADER)",
997        );
998        assert_eq!(check_copy_to_stdout(&statement), Some("csv".to_string()));
999
1000        let statement = parse_copy_statement(
1001            "COPY (SELECT 1) TO STDOUT WITH (DELIMITER ',', HEADER, FORMAT binary)",
1002        );
1003        assert_eq!(check_copy_to_stdout(&statement), Some("binary".to_string()));
1004    }
1005}