servers/postgres/copy_in/codec.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
15//! The COPY FROM STDIN formats.
16//!
17//! [`CopyFormat`] is the closed, explicit set of supported formats — a
18//! small enum over the real implementations rather than a generic
19//! format framework. Each variant carries its validated options and
20//! its rules are stated where they apply: a variant's match arms in
21//! the copy lifecycle (see the parent module) decide whether a target
22//! table is required, how the `CopyData` bytes are consumed, and which
23//! existing ingestion pipeline completes the copy. Adding a format is
24//! a normal extension: a new variant plus its arms.
25//!
26//! # Parsing and conversion
27//!
28//! Table-bound formats parse incrementally through a [`RecordParser`]:
29//! it consumes raw `CopyData` bytes and emits complete, insertable
30//! rows — one [`ParsedRow`] per record, in the order of the targeted
31//! columns. `csv` delegates splitting and typed conversion to
32//! arrow-csv's incremental decoder (the engine behind
33//! `COPY ... FROM 'file.csv'`) and turns decoded batches into rows
34//! with the shared `api::helper::vectors_to_rows`.
35//!
36//! Formats that delegate to an existing ingestion pipeline (the
37//! influxdb line protocol) do not parse here at all: the whole payload
38//! is buffered as one bounded request body and completed through that
39//! pipeline, so record boundaries and values stay with the pipeline's
40//! own parser.
41//!
42//! # Options
43//!
44//! The `WITH (...)` clause is open: every `KEY value` entry the client
45//! writes is collected into a [`CopyOptionSet`] (see `options`)
46//! regardless of whether any format understands it — the statement is
47//! parsed textually (see `parse`) precisely so options beyond
48//! sqlparser's COPY grammar can reach the formats. A format builder
49//! takes the options it understands (`take_string`,
50//! `take_single_byte`, `take_flag`, or raw `take_value` for
51//! format-specific shapes) and rejects the rest with
52//! `reject_leftovers`.
53
54use datatypes::data_type::DataType;
55use datatypes::prelude::ConcreteDataType;
56use datatypes::schema::ColumnSchema;
57use pgwire::error::PgWireResult;
58
59use crate::postgres::copy_in::arrow::ArrowOptions;
60use crate::postgres::copy_in::csv::CsvCodec;
61use crate::postgres::copy_in::influxdb::InfluxdbOptions;
62use crate::postgres::copy_in::jsonl::JsonlCodec;
63use crate::postgres::copy_in::otlp::OtlpOptions;
64use crate::postgres::copy_in::prom_write::PromWriteOptions;
65use crate::postgres::copy_in::unsupported;
66
67/// A resolved COPY FROM STDIN format with its validated options.
68#[derive(Debug, Clone)]
69pub(super) enum CopyFormat {
70 /// Table-bound CSV: records are parsed incrementally against the
71 /// targeted table's columns and inserted in batches.
72 Csv(CsvCodec),
73 /// Table-bound newline-delimited JSON: objects decode against the
74 /// targeted table's columns through arrow-json, the engine behind
75 /// file-based `COPY ... FROM 'file.json'`.
76 Jsonl(JsonlCodec),
77 /// Table-bound Arrow IPC stream, completed batch-by-batch through Flight's
78 /// bulk ingestion handler. Advertises binary wire format code 1.
79 Arrow(ArrowOptions),
80 /// Table-less influxdb line protocol: the whole payload is one
81 /// bounded request body, completed through the line-protocol
82 /// pipeline the HTTP write endpoints use (one COPY statement is one
83 /// ingestion request; streaming ingest is not supported).
84 Influxdb(InfluxdbOptions),
85 /// **Binary** OTLP (optionally table-targeted for logs/traces):
86 /// one `ExportMetricsServiceRequest`,
87 /// `ExportTraceServiceRequest` or `ExportLogsServiceRequest`
88 /// protobuf message, buffered whole and completed through the
89 /// matching OTLP pipeline the OTLP/HTTP endpoints use. Advertises
90 /// wire format code 1.
91 Otlp(OtlpOptions),
92 /// Table-less, **binary** Prometheus Remote Write: one request body
93 /// (v1 or v2, compressed protobuf), buffered whole and completed
94 /// through the same ingestion core the `/v1/prometheus/write`
95 /// endpoint runs. Advertises wire format code 1.
96 PromWrite(PromWriteOptions),
97}
98
99impl CopyFormat {
100 /// The canonical format name, used in error messages.
101 pub(crate) fn name(&self) -> &'static str {
102 match self {
103 CopyFormat::Csv(_) => "csv",
104 CopyFormat::Jsonl(_) => "jsonl",
105 CopyFormat::Arrow(_) => "arrow",
106 CopyFormat::Influxdb(_) => "influxdb",
107 CopyFormat::Otlp(_) => "otlp",
108 CopyFormat::PromWrite(_) => "promwrite",
109 }
110 }
111}
112
113/// A table-bound COPY format: records decode against the targeted
114/// table's columns into insertable rows (csv, jsonl). Implemented by
115/// the codec config structs; the copy lifecycle treats these row-based
116/// formats identically through it. Arrow IPC uses a separate bulk-ingestion path.
117pub(crate) trait TableBoundCodec: Send + Sync {
118 /// The canonical format name, for logs.
119 fn name(&self) -> &'static str;
120 /// Validates that a column of `data_type` can be ingested.
121 fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>;
122 /// Creates the stateful parser for one copy stream over the
123 /// targeted columns (in COPY field order). `timezone` is the
124 /// session timezone for offset-free timestamp strings.
125 fn create_parser(
126 &self,
127 columns: &[ColumnSchema],
128 timezone: &str,
129 ) -> PgWireResult<Box<dyn RecordParser + Send>>;
130}
131
132/// The column types the arrow-based decoders (csv, jsonl) can decode
133/// against; shared by both codecs' [`TableBoundCodec::check_column_type`].
134/// `format` names the codec in the error.
135pub(super) fn check_arrow_column_type(
136 data_type: &ConcreteDataType,
137 format: &str,
138) -> PgWireResult<()> {
139 let supported = matches!(
140 data_type,
141 ConcreteDataType::Boolean(_)
142 | ConcreteDataType::Int8(_)
143 | ConcreteDataType::Int16(_)
144 | ConcreteDataType::Int32(_)
145 | ConcreteDataType::Int64(_)
146 | ConcreteDataType::UInt8(_)
147 | ConcreteDataType::UInt16(_)
148 | ConcreteDataType::UInt32(_)
149 | ConcreteDataType::UInt64(_)
150 | ConcreteDataType::Float32(_)
151 | ConcreteDataType::Float64(_)
152 | ConcreteDataType::String(_)
153 | ConcreteDataType::Date(_)
154 | ConcreteDataType::Timestamp(_)
155 | ConcreteDataType::Decimal128(_)
156 );
157 if !supported {
158 return Err(unsupported(format!(
159 "column type \"{}\" is not supported by format {format}",
160 data_type.name()
161 )));
162 }
163 Ok(())
164}
165
166/// A parsed, insertable row: one gRPC value per targeted column, in COPY
167/// field order. Every parser emits these directly, whatever mechanism it
168/// used to produce them.
169pub(super) type ParsedRow = api::v1::Row;
170
171/// Incremental parser of one COPY FROM STDIN stream.
172///
173/// The wire protocol delivers the payload as an arbitrary sequence of
174/// `CopyData` chunks; implementations must keep state across [`feed`]
175/// calls because records (and even single fields) may span chunk
176/// boundaries. [`finish`] is called at `CopyDone`; a final record without
177/// a trailing record separator is accepted.
178pub(super) trait RecordParser: Send {
179 /// Feeds a chunk of `CopyData` bytes and returns all complete rows.
180 fn feed(&mut self, data: &[u8]) -> PgWireResult<Vec<ParsedRow>>;
181 /// Parses the buffered tail at `CopyDone`; returns no row when the
182 /// stream ended exactly at a record boundary.
183 fn finish(&mut self) -> PgWireResult<Vec<ParsedRow>>;
184}