From f796889bbd77994358ed64085a32a0da1c08e4bb Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Tue, 24 Nov 2026 03:53:00 +0000 Subject: [PATCH] feat(postgres): jsonl COPY FROM STDIN via the arrow-json engine (#10109) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(postgres): Prometheus Remote Write protobuf ingest via COPY FROM STDIN COPY FROM STDIN WITH (FORMAT promwrite [, version 2] [, ]) ingests one Prometheus Remote Write request body over the postgres wire protocol — a GreptimeDB-specific, binary COPY format (wire format code 1). The payload is byte-for-byte the body a remote-write client POSTs to /v1/prometheus/write, compression included: buffered until CopyDone and completed through the exact ingestion core that endpoint runs. To share that core, the HTTP handlers' ingestion bodies are extracted into axum-free functions (ingest_remote_write_v1/v2 plus the context extension stamping), and the HTTP routes become thin wrappers — their behavior is unchanged, and the copy layer runs the identical decode, validation, conversion, batched/prepared write paths, per-batch write-progress accounting and context extensions, under the connection's regular postgres context. The WITH options carry what the HTTP endpoint takes as its content-type/-encoding and query parameters; session-provided values (database, user) are not repeated: - version 1|2 (default 1), matching the content-type's proto - zstd, matching Content-Encoding: zstd (snappy by default) - physical_table, matching the ?physical_table= parameter - pipeline_name/pipeline_version, matching the pipeline headers (v1 only; for v2 they are accepted and ignored, exactly like the HTTP route ignores them) Table-less like the other ingestion formats; one COPY statement is one bounded request (shared 64 MiB limit); the row count reports written rows (v1) or written samples plus histograms (v2). The flush enforces the frontend's shared request-memory quota (max_in_flight_write_bytes) — the same limiter the HTTP ingestion protocols use, so COPY cannot bypass the aggregate budget. Wiring: PostgresServer::with_prom_remote_write carries the handler, metric-engine flag, validation mode and shared memory limiter. e2e: v1 body chunked across CopyData boundaries; v2 samples with readback; physical_table option routing; garbage-body decode failure with connection reuse; a tiny-quota regression where a compressed body whose decompressed size exceeds the budget fails like the HTTP route. Signed-off-by: Ning Sun * feat(postgres): jsonl COPY FROM STDIN via the arrow-json engine COPY tbl [(cols)] FROM STDIN WITH (FORMAT jsonl) ingests newline-delimited JSON objects through arrow-json's incremental Decoder — the same engine behind file-based COPY ... FROM 'file.json' — so both COPY routes accept identical data. One JSON object per record; keys address the targeted columns by name, absent keys become NULL, and offset-free timestamp strings parse in the session timezone (the same schema substitution the csv codec makes), like SQL INSERT. The streaming contract mirrors arrow-csv's exactly (decode returns consumed bytes; a short read means a full batch), so the parser is a twin of the csv one: objects may span CopyData chunk boundaries, records surface in COPY_IN_FLUSH_ROWS batches, and a trailing object without its newline is accepted. Table-bound like csv (a named table is required; the column list fixes the target order); no options (the file format's layout options are writer-side; the reader parses date-times natively). The two table-bound codecs share the table path through a small TableBoundCodec trait (check_column_type + create_parser); csv's behavior is unchanged. e2e: chunked object-boundary ingest with absent-key NULLs; session-timezone parity against SQL INSERT; malformed JSON failure with table-left-clean and connection recovery. Signed-off-by: Ning Sun * feat(postgres): address jsonl COPY review — codec names, nullable-aware errors, docs and tests - `TableBoundCodec::name()` drives the codec name `CopyInState` logs instead of the hardcoded "csv"; `table_bound_state` reuses the query context `begin_copy_in` created; the csv/jsonl trait impls hold their bodies and share one supported-type check. - jsonl: the decode schema marks every field nullable, so a NULL in a non-nullable column is reported by column name instead of arrow-json's "unmasked nulls in non-nullable StructArray child" error; errors map to 22P02/22P04 by semantics (field value vs. syntax), never XX000; the no-op `decode(&[])` EOF signal is gone; a top-level JSON array under `FORMAT json` fails with a specific hint instead of `expected { got [`. - Module docs describe what arrow-json really accepts: numeric strings for numeric columns, numeric timestamps taken in the column's unit, unknown keys ignored (strict mode stays off so column subsets work). - Tests: multi-batch sweep through the mid-stream flush path, trailing and truncated records, column subset/reorder with extra keys, missing and null ts, the `json` alias, error classes. Signed-off-by: Ning Sun --------- Signed-off-by: Ning Sun --- src/servers/src/postgres/copy_in/codec.rs | 76 +++ src/servers/src/postgres/copy_in/csv.rs | 42 +- src/servers/src/postgres/copy_in/jsonl.rs | 619 ++++++++++++++++++ src/servers/src/postgres/copy_in/mod.rs | 120 +++- .../src/tests/postgres_copy_in_test.rs | 160 +++++ 5 files changed, 952 insertions(+), 65 deletions(-) create mode 100644 src/servers/src/postgres/copy_in/jsonl.rs diff --git a/src/servers/src/postgres/copy_in/codec.rs b/src/servers/src/postgres/copy_in/codec.rs index 7f7b9c78b35..614384b631c 100644 --- a/src/servers/src/postgres/copy_in/codec.rs +++ b/src/servers/src/postgres/copy_in/codec.rs @@ -51,13 +51,18 @@ //! format-specific shapes) and rejects the rest with //! `reject_leftovers`. +use datatypes::data_type::DataType; +use datatypes::prelude::ConcreteDataType; +use datatypes::schema::ColumnSchema; use pgwire::error::PgWireResult; use crate::postgres::copy_in::arrow::ArrowOptions; use crate::postgres::copy_in::csv::CsvCodec; use crate::postgres::copy_in::influxdb::InfluxdbOptions; +use crate::postgres::copy_in::jsonl::JsonlCodec; use crate::postgres::copy_in::otlp::OtlpOptions; use crate::postgres::copy_in::prom_write::PromWriteOptions; +use crate::postgres::copy_in::unsupported; /// A resolved COPY FROM STDIN format with its validated options. #[derive(Debug, Clone)] @@ -65,6 +70,10 @@ pub(super) enum CopyFormat { /// Table-bound CSV: records are parsed incrementally against the /// targeted table's columns and inserted in batches. Csv(CsvCodec), + /// Table-bound newline-delimited JSON: objects decode against the + /// targeted table's columns through arrow-json, the engine behind + /// file-based `COPY ... FROM 'file.json'`. + Jsonl(JsonlCodec), /// Table-bound Arrow IPC stream, completed batch-by-batch through Flight's /// bulk ingestion handler. Advertises binary wire format code 1. Arrow(ArrowOptions), @@ -87,6 +96,73 @@ pub(super) enum CopyFormat { PromWrite(PromWriteOptions), } +impl CopyFormat { + /// The canonical format name, used in error messages. + pub(crate) fn name(&self) -> &'static str { + match self { + CopyFormat::Csv(_) => "csv", + CopyFormat::Jsonl(_) => "jsonl", + CopyFormat::Arrow(_) => "arrow", + CopyFormat::Influxdb(_) => "influxdb", + CopyFormat::Otlp(_) => "otlp", + CopyFormat::PromWrite(_) => "promwrite", + } + } +} + +/// A table-bound COPY format: records decode against the targeted +/// table's columns into insertable rows (csv, jsonl). Implemented by +/// the codec config structs; the copy lifecycle treats these row-based +/// formats identically through it. Arrow IPC uses a separate bulk-ingestion path. +pub(crate) trait TableBoundCodec: Send + Sync { + /// The canonical format name, for logs. + fn name(&self) -> &'static str; + /// Validates that a column of `data_type` can be ingested. + fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>; + /// Creates the stateful parser for one copy stream over the + /// targeted columns (in COPY field order). `timezone` is the + /// session timezone for offset-free timestamp strings. + fn create_parser( + &self, + columns: &[ColumnSchema], + timezone: &str, + ) -> PgWireResult>; +} + +/// The column types the arrow-based decoders (csv, jsonl) can decode +/// against; shared by both codecs' [`TableBoundCodec::check_column_type`]. +/// `format` names the codec in the error. +pub(super) fn check_arrow_column_type( + data_type: &ConcreteDataType, + format: &str, +) -> PgWireResult<()> { + let supported = matches!( + data_type, + ConcreteDataType::Boolean(_) + | ConcreteDataType::Int8(_) + | ConcreteDataType::Int16(_) + | ConcreteDataType::Int32(_) + | ConcreteDataType::Int64(_) + | ConcreteDataType::UInt8(_) + | ConcreteDataType::UInt16(_) + | ConcreteDataType::UInt32(_) + | ConcreteDataType::UInt64(_) + | ConcreteDataType::Float32(_) + | ConcreteDataType::Float64(_) + | ConcreteDataType::String(_) + | ConcreteDataType::Date(_) + | ConcreteDataType::Timestamp(_) + | ConcreteDataType::Decimal128(_) + ); + if !supported { + return Err(unsupported(format!( + "column type \"{}\" is not supported by format {format}", + data_type.name() + ))); + } + Ok(()) +} + /// A parsed, insertable row: one gRPC value per targeted column, in COPY /// field order. Every parser emits these directly, whatever mechanism it /// used to produce them. diff --git a/src/servers/src/postgres/copy_in/csv.rs b/src/servers/src/postgres/copy_in/csv.rs index ab8f521098d..cc8e6cc883f 100644 --- a/src/servers/src/postgres/copy_in/csv.rs +++ b/src/servers/src/postgres/copy_in/csv.rs @@ -34,13 +34,14 @@ use api::helper::vectors_to_rows; use arrow::csv::ReaderBuilder; use arrow::csv::reader::Decoder as CsvDecoder; use arrow_schema::{ArrowError, DataType as ArrowDataType, Field, Schema as ArrowSchema}; -use datatypes::data_type::DataType; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema}; use datatypes::vectors::{BooleanVector, Helper, StringVector, Vector}; use pgwire::error::{PgWireError, PgWireResult}; -use crate::postgres::copy_in::codec::{CopyFormat, ParsedRow, RecordParser}; +use crate::postgres::copy_in::codec::{ + CopyFormat, ParsedRow, RecordParser, TableBoundCodec, check_arrow_column_type, +}; use crate::postgres::copy_in::options::CopyOptionSet; use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported}; @@ -83,37 +84,16 @@ pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult PgWireResult<()> { - let supported = matches!( - data_type, - ConcreteDataType::Boolean(_) - | ConcreteDataType::Int8(_) - | ConcreteDataType::Int16(_) - | ConcreteDataType::Int32(_) - | ConcreteDataType::Int64(_) - | ConcreteDataType::UInt8(_) - | ConcreteDataType::UInt16(_) - | ConcreteDataType::UInt32(_) - | ConcreteDataType::UInt64(_) - | ConcreteDataType::Float32(_) - | ConcreteDataType::Float64(_) - | ConcreteDataType::String(_) - | ConcreteDataType::Date(_) - | ConcreteDataType::Timestamp(_) - | ConcreteDataType::Decimal128(_) - ); - if !supported { - return Err(unsupported(format!( - "column type \"{}\" is not supported by format csv", - data_type.name() - ))); - } - Ok(()) +impl TableBoundCodec for CsvCodec { + fn name(&self) -> &'static str { + "csv" } - pub(super) fn create_parser( + fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { + check_arrow_column_type(data_type, "csv") + } + + fn create_parser( &self, columns: &[ColumnSchema], timezone: &str, diff --git a/src/servers/src/postgres/copy_in/jsonl.rs b/src/servers/src/postgres/copy_in/jsonl.rs new file mode 100644 index 00000000000..499cf0d5f85 --- /dev/null +++ b/src/servers/src/postgres/copy_in/jsonl.rs @@ -0,0 +1,619 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The `jsonl` format: newline-delimited JSON objects, one per record. +//! +//! Parsing and typed conversion both reuse arrow-json's incremental +//! [`Decoder`](arrow::json::reader::Decoder) — the engine behind +//! GreptimeDB's file-based `COPY ... FROM 'file.json'` (see +//! `common-datasource`'s `json` file format) — so both COPY routes +//! accept identical data. The decoder splits records (objects may span +//! chunk boundaries; pretty-printed multi-line objects and concatenated +//! `{...}{...}` streams are accepted too) and converts fields against +//! the targeted columns' schema in one pass; a record is one JSON +//! object whose keys address the columns **by name** (the COPY column +//! list fixes the target order, as with csv). +//! +//! What the engine actually accepts, so the rules match the behavior +//! rather than a strict reading of the column types: +//! +//! - Numeric columns take JSON numbers **or numeric strings** +//! (`"val": 1.5` and `"val": "1.5"` both decode); booleans must be +//! JSON booleans (`"b": "true"` is rejected). +//! - Timestamps are date-time strings (RFC 3339; offset-free ones parse +//! in the session timezone, like SQL INSERT) **or numbers**, taken as +//! the column's time unit verbatim: `"ts": 1704067200000` is an epoch +//! in milliseconds for a millisecond column — there is no unit +//! conversion, and `"ts": 1704067200` means 1970-01-20 in that column. +//! A quoted number is parsed as a date-time string and so fails. +//! - Keys outside the column list are ignored, so a misspelled key +//! (`"hots"`) yields NULL in its column instead of an error, and +//! records may carry more keys than a column subset selects. +//! (arrow-json's strict mode would change the first half of that but +//! also reject the second, so it stays off.) +//! - Absent keys become NULL; a NULL in a non-nullable column (such as +//! the time index) is rejected with a message naming the column. +//! - Column types arrow-json cannot decode (JSON, Binary) are rejected +//! up front. +//! +//! The format is table-bound like `csv` and takes no options; the +//! file-based json format's layout options are writer-side only, and +//! arrow-json's reader parses date-time strings natively (RFC 3339, +//! with the schema's timezone for offset-free strings). `json` is an +//! alias for `jsonl`, matching the file-based format's name; it still +//! means newline-delimited objects — a top-level JSON array `[{...}]` +//! is rejected with a specific hint. + +use std::sync::Arc; + +use api::helper::vectors_to_rows; +use arrow::json::reader::{Decoder as JsonDecoder, ReaderBuilder}; +use arrow::record_batch::RecordBatch; +use arrow_schema::{ArrowError, DataType as ArrowDataType, Field, Schema as ArrowSchema}; +use datatypes::prelude::ConcreteDataType; +use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema}; +use datatypes::vectors::Helper; +use pgwire::error::{PgWireError, PgWireResult}; + +use crate::postgres::copy_in::codec::{ + CopyFormat, ParsedRow, RecordParser, TableBoundCodec, check_arrow_column_type, +}; +use crate::postgres::copy_in::options::CopyOptionSet; +use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported}; + +/// The validated `jsonl` format configuration. +#[derive(Debug, Clone, Default)] +pub(super) struct JsonlCodec; + +/// Builds the codec from the parsed options. +pub(super) fn build_jsonl_codec(options: CopyOptionSet) -> PgWireResult { + options.reject_leftovers("jsonl")?; + Ok(CopyFormat::Jsonl(JsonlCodec)) +} + +impl TableBoundCodec for JsonlCodec { + fn name(&self) -> &'static str { + "jsonl" + } + + fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { + check_arrow_column_type(data_type, "jsonl") + } + + fn create_parser( + &self, + columns: &[ColumnSchema], + timezone: &str, + ) -> PgWireResult> { + // Decode schema: the greptime schema's arrow projection, with + // Timestamp fields carrying the SESSION timezone so offset-free + // strings parse like SQL INSERT does instead of as UTC (the same + // substitution the csv codec makes; explicit offsets in the + // input always win). Every field is made nullable: a missing or + // null value in a non-nullable column then surfaces as a NULL + // that `flush_batch` reports by column name, instead of + // arrow-json's generic "unmasked nulls in non-nullable + // StructArray child" error. + let arrow_schema = GreptimeSchema::try_new(columns.to_vec()) + .map_err(|e| unsupported(format!("invalid columns for format jsonl: {e}")))? + .arrow_schema() + .clone(); + let timezone = timezone.to_string(); + let fields = arrow_schema + .fields() + .iter() + .zip(columns) + .map(|(field, column)| { + let data_type = match &column.data_type { + ConcreteDataType::Timestamp(_) => match field.data_type() { + ArrowDataType::Timestamp(unit, None) => { + ArrowDataType::Timestamp(*unit, Some(Arc::from(timezone.as_str()))) + } + _ => field.data_type().clone(), + }, + _ => field.data_type().clone(), + }; + Field::new(field.name(), data_type, true) + }) + .collect::>(); + let builder = ReaderBuilder::new(Arc::new(ArrowSchema::new(fields))) + .with_batch_size(COPY_IN_FLUSH_ROWS); + Ok(Box::new(JsonlRecordParser { + decoder: builder.build_decoder().map_err(decode_error)?, + required: columns + .iter() + .enumerate() + .filter(|(_, column)| !column.is_nullable()) + .map(|(index, column)| (index, column.name.clone())) + .collect(), + started: false, + })) + } +} + +/// Incremental parser backed by arrow-json's decoder. Unlike +/// arrow-csv, a record finalizes as soon as its closing `}` is parsed, +/// and a single `flush` drains and clears the buffered tape — so there +/// is no EOF signal to send at `CopyDone`. +struct JsonlRecordParser { + decoder: JsonDecoder, + /// The non-nullable target columns (position and name), checked per + /// decoded batch because the decode schema marks every field + /// nullable (see [`TableBoundCodec::create_parser`]). + required: Vec<(usize, String)>, + /// Whether the first non-whitespace byte of the stream has been + /// seen; only that byte can be a top-level array's `[`. + started: bool, +} + +const TOP_LEVEL_ARRAY_HINT: &str = "format jsonl expects newline-delimited JSON objects, one \ + per record; a top-level JSON array is not supported, write one object per line instead"; + +/// arrow-json's whitespace set, which `Decoder::decode` skips freely. +fn is_json_whitespace(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\n' | b'\r') +} + +impl RecordParser for JsonlRecordParser { + fn feed(&mut self, data: &[u8]) -> PgWireResult> { + if !self.started { + // Report the most likely misuse of the `json` alias — a + // top-level array — specifically; arrow-json would only say + // `expected { got [...]`. + if let Some(first) = data.iter().copied().find(|&byte| !is_json_whitespace(byte)) { + self.started = true; + if first == b'[' { + return Err(bad_copy_data(TOP_LEVEL_ARRAY_HINT)); + } + } + } + let mut buf = data; + let mut rows = Vec::new(); + while !buf.is_empty() { + // `decode` returns once `batch_size` objects have been + // parsed since the last flush, leaving the rest of `buf` for + // the next call — which then consumes nothing, so the flush + // below runs mid-stream and the loop carries on. + let consumed = self.decoder.decode(buf).map_err(decode_error)?; + if consumed == 0 { + while let Some(batch) = self.decoder.flush().map_err(decode_error)? { + rows.extend(self.flush_batch(&batch)?); + } + } else { + buf = &buf[consumed..]; + } + } + Ok(rows) + } + + fn finish(&mut self) -> PgWireResult> { + // A trailing record without its newline is already complete + // (its `}` closed it); a truncated one fails in `flush` with + // "Truncated record". `Decoder::decode(&[])` would be a no-op. + let mut rows = Vec::new(); + while let Some(batch) = self.decoder.flush().map_err(decode_error)? { + rows.extend(self.flush_batch(&batch)?); + } + Ok(rows) + } +} + +impl JsonlRecordParser { + /// Converts one decoded arrow batch into insertable rows with the + /// shared [`vectors_to_rows`] helper, after checking the + /// non-nullable columns. + fn flush_batch(&self, batch: &RecordBatch) -> PgWireResult> { + for (index, name) in &self.required { + if batch.column(*index).null_count() > 0 { + return Err(bad_copy_data(format!( + "null value in non-nullable column \"{name}\"; every jsonl record must set it" + ))); + } + } + let vectors = Helper::try_into_vectors(batch.columns()) + .map_err(|e| bad_copy_data(format!("failed to convert decoded JSON batch: {e}")))?; + Ok(vectors_to_rows(vectors.iter(), batch.num_rows())) + } +} + +/// Maps arrow-json errors to PostgreSQL's COPY error classes, the +/// way `csv.rs` does. A field value that does not decode against its +/// column type is an invalid text representation (22P02): arrow-json +/// wraps those as `JsonError("whilst decoding field '': …")` (see +/// its `struct_array.rs`), since it has no separate `ParseError` for +/// them. JSON syntax errors (truncated records, unexpected tokens) and +/// anything else is bad copy data (22P04) — never an internal `XX000`. +fn decode_error(error: ArrowError) -> PgWireError { + const FIELD_PREFIX: &str = "whilst decoding field '"; + match &error { + ArrowError::ParseError(message) | ArrowError::CastError(message) => { + invalid_text_repr(format!("failed to parse JSON data: {message}")) + } + ArrowError::JsonError(message) if message.starts_with(FIELD_PREFIX) => { + invalid_text_repr(format!("failed to parse JSON data: {message}")) + } + _ => bad_copy_data(format!("failed to parse JSON data: {error}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::postgres::copy_in::codec::CopyFormat; + use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue}; + use api::v1::value::ValueData; + use datatypes::schema::ColumnSchema; + + fn columns() -> Vec { + vec![ + ColumnSchema::new("host", ConcreteDataType::string_datatype(), true), + ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true), + ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + ] + } + + fn codec() -> JsonlCodec { + match build_jsonl_codec(CopyOptionSet::default()).unwrap() { + CopyFormat::Jsonl(codec) => codec, + other => panic!("unexpected format {other:?}"), + } + } + + fn new_parser(columns: &[ColumnSchema]) -> Box { + codec().create_parser(columns, "UTC").unwrap() + } + + fn feed_all(parser: &mut Box, chunks: &[&[u8]]) -> Vec { + let mut rows = Vec::new(); + for chunk in chunks { + rows.extend(parser.feed(chunk).unwrap()); + } + rows.extend(parser.finish().unwrap()); + rows + } + + fn string_at(row: &ParsedRow, col: usize) -> Option { + row.values[col].value_data.as_ref().map(|v| match v { + ValueData::StringValue(s) => s.clone(), + other => panic!("expected string, got {other:?}"), + }) + } + + fn f64_at(row: &ParsedRow, col: usize) -> Option { + match row.values[col].value_data.as_ref() { + None => None, + Some(ValueData::F64Value(v)) => Some(*v), + other => panic!("expected f64, got {other:?}"), + } + } + + fn ts_millis_at(row: &ParsedRow, col: usize) -> Option { + match row.values[col].value_data.as_ref() { + None => None, + Some(ValueData::TimestampMillisecondValue(v)) => Some(*v), + other => panic!("expected timestamp ms, got {other:?}"), + } + } + + /// The SQLSTATE a copy error is sent to the client with. + fn error_code(error: &PgWireError) -> String { + error.code().to_string() + } + + /// Feeds `data` then finishes, returning the first error. arrow-json + /// reports JSON syntax errors from `feed` but converts values at + /// the flush in `finish`, so value-level failures surface there. + fn error_feeding(parser: &mut Box, data: &[u8]) -> PgWireError { + match parser.feed(data).and_then(|_| parser.finish()) { + Ok(_) => panic!("expected an error for {:?}", String::from_utf8_lossy(data)), + Err(error) => error, + } + } + + #[test] + fn test_jsonl_records_across_chunk_boundaries() { + let payload: Vec = br#"{"host":"a","val":1.5,"ts":"2024-01-01 00:00:00"} +{"host":"b","val":2.5,"ts":"2024-01-01 00:00:01"}"# + .to_vec(); + for chunk in [1usize, 2, 3, 7, 64] { + let mut parser = new_parser(&columns()); + let rows = feed_all(&mut parser, &payload.chunks(chunk).collect::>()); + assert_eq!(rows.len(), 2, "chunk={chunk}"); + assert_eq!(string_at(&rows[0], 0), Some("a".to_string())); + assert!(matches!( + rows[1].values[0].value_data, + Some(ValueData::StringValue(ref s)) if s == "b" + )); + } + } + + #[test] + fn test_jsonl_absent_key_is_null() { + let mut parser = new_parser(&columns()); + let rows = feed_all( + &mut parser, + &[b"{\"val\":3.5,\"ts\":\"2024-01-01 00:00:00\"}\n"], + ); + assert_eq!(rows.len(), 1); + assert!(rows[0].values[0].value_data.is_none()); + } + + #[test] + fn test_jsonl_trailing_record_without_newline() { + let mut parser = new_parser(&columns()); + let rows = feed_all( + &mut parser, + &[ + b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n", + b"{\"host\":\"b\",\"val\":2.5,\"ts\":\"2024-01-01 00:00:01\"}", + ], + ); + assert_eq!(rows.len(), 2); + assert_eq!(f64_at(&rows[1], 1), Some(2.5)); + } + + #[test] + fn test_jsonl_numeric_columns_take_native_and_quoted_numbers() { + let mut parser = new_parser(&columns()); + let rows = feed_all( + &mut parser, + &[ + b"{\"val\":2,\"ts\":\"2024-01-01 00:00:00\"}\n", + b"{\"val\":\"1.5\",\"ts\":\"2024-01-01 00:00:01\"}\n", + ], + ); + assert_eq!(rows.len(), 2); + assert_eq!(f64_at(&rows[0], 1), Some(2.0)); + assert_eq!(f64_at(&rows[1], 1), Some(1.5)); + + // Booleans, by contrast, must be JSON booleans. + let mut parser = new_parser(&[ColumnSchema::new( + "b", + ConcreteDataType::boolean_datatype(), + true, + )]); + let error = error_feeding(&mut parser, b"{\"b\":\"true\"}\n"); + assert_eq!(error_code(&error), "22P02", "{error}"); + assert!(error.to_string().contains("expected boolean"), "{error}"); + } + + #[test] + fn test_jsonl_numeric_timestamp_is_taken_in_the_column_unit() { + let mut parser = new_parser(&columns()); + let rows = feed_all( + &mut parser, + &[ + b"{\"val\":1,\"ts\":1704067200000}\n", + // A number is not re-scaled: 1704067200 is an epoch in + // the column's unit, milliseconds here. + b"{\"val\":2,\"ts\":1704067200}\n", + // Explicit offsets in strings win over the session zone. + b"{\"val\":3,\"ts\":\"2024-01-01T00:00:00+08:00\"}\n", + ], + ); + assert_eq!(rows.len(), 3); + assert_eq!(ts_millis_at(&rows[0], 2), Some(1704067200000)); + assert_eq!(ts_millis_at(&rows[1], 2), Some(1704067200)); + assert_eq!(ts_millis_at(&rows[2], 2), Some(1704038400000)); + + // A quoted number is parsed as a date-time string, and fails. + let mut parser = new_parser(&columns()); + let error = error_feeding(&mut parser, b"{\"ts\":\"1704067200000\"}\n"); + assert_eq!(error_code(&error), "22P02", "{error}"); + } + + #[test] + fn test_jsonl_unknown_keys_are_ignored() { + let mut parser = new_parser(&columns()); + // A misspelled key does not error: its column stays NULL. + let rows = feed_all( + &mut parser, + &[b"{\"hots\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n"], + ); + assert_eq!(rows.len(), 1); + assert!(rows[0].values[0].value_data.is_none()); + assert_eq!(f64_at(&rows[0], 1), Some(1.5)); + } + + #[test] + fn test_jsonl_column_subset_and_reorder_tolerate_extra_keys() { + // COPY t (ts, val) FROM STDIN: a reordered subset of the table's + // columns, keyed by name; records still carry the other keys. + let subset = vec![columns()[2].clone(), columns()[1].clone()]; + let mut parser = new_parser(&subset); + let rows = feed_all( + &mut parser, + &[b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\",\"extra\":true}\n"], + ); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].values.len(), 2); + assert_eq!(ts_millis_at(&rows[0], 0), Some(1704067200000)); + assert_eq!(f64_at(&rows[0], 1), Some(1.5)); + } + + #[test] + fn test_jsonl_null_in_non_nullable_column_is_named() { + for record in [ + // Missing key. + &b"{\"val\":1.5}\n"[..], + // Explicit null. + &b"{\"val\":1.5,\"ts\":null}\n"[..], + ] { + let mut parser = new_parser(&columns()); + let error = error_feeding(&mut parser, record); + assert_eq!(error_code(&error), "22P04", "{record:?}: {error}"); + let message = error.to_string(); + assert!(message.contains("\"ts\""), "{message}"); + assert!(message.contains("non-nullable"), "{message}"); + assert!(!message.contains("StructArray"), "{message}"); + } + } + + #[test] + fn test_jsonl_top_level_array_is_rejected_with_hint() { + let mut parser = new_parser(&columns()); + let error = parser + .feed(b"[{\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}]\n") + .unwrap_err(); + assert_eq!(error_code(&error), "22P04", "{error}"); + assert!(error.to_string().contains("one object per line"), "{error}"); + + // Leading whitespace, even across chunks, does not hide the `[`. + let mut parser = new_parser(&columns()); + parser.feed(b"\n").unwrap(); + parser.feed(b" \t").unwrap(); + let error = parser.feed(b" [{\"val\":1}").unwrap_err(); + assert!( + error.to_string().contains("top-level JSON array"), + "{error}" + ); + + // A `[` later in the stream is a value, not an array of records: + // it fails as an ordinary syntax/type error, without the hint. + let mut parser = new_parser(&[ColumnSchema::new( + "host", + ConcreteDataType::string_datatype(), + true, + )]); + let error = error_feeding(&mut parser, b"{\"host\":\"a\"}\n[1]\n"); + assert!( + !error.to_string().contains("top-level JSON array"), + "{error}" + ); + } + + #[test] + fn test_jsonl_syntax_errors_are_bad_copy_data() { + // A syntax error fails the feed itself. + let mut parser = new_parser(&columns()); + let error = parser.feed(b"hello\n").unwrap_err(); + assert_eq!(error_code(&error), "22P04", "{error}"); + + // Value-level failures are invalid text representation. + let mut parser = new_parser(&columns()); + let error = error_feeding( + &mut parser, + br#"{"host":"a","val":"not a number","ts":"2024-01-01 00:00:00"} +"#, + ); + assert_eq!(error_code(&error), "22P02", "{error}"); + assert!( + error.to_string().contains("failed to parse JSON data"), + "{error}" + ); + } + + #[test] + fn test_jsonl_truncated_tail_fails_at_finish() { + let mut parser = new_parser(&columns()); + parser + .feed(b"{\"host\":\"a\",\"val\":1.5,\"ts\":\"2024-01-01 00:00:00\"}\n") + .unwrap(); + parser.feed(b"{\"host\":\"b\",\"val\":2.5").unwrap(); + let error = parser.finish().unwrap_err(); + assert_eq!(error_code(&error), "22P04", "{error}"); + assert!(error.to_string().contains("Truncated record"), "{error}"); + } + + #[test] + fn test_jsonl_multi_batch_sweep_flushes_mid_stream() { + // More than two full batches, fed in chunks that align with + // nothing, so the mid-stream `consumed == 0` flush path in + // `feed` is exercised (the records are tiny to keep it quick). + let total = 2 * COPY_IN_FLUSH_ROWS + 137; + let mut payload = Vec::new(); + for i in 0..total { + payload.extend_from_slice(format!("{{\"val\":{i},\"ts\":{i}}}\n").as_bytes()); + } + let columns = columns(); + let mut parser = new_parser(&columns); + let mut rows = Vec::new(); + let mut feeds_with_rows = 0; + for chunk in payload.chunks(4093) { + let batch = parser.feed(chunk).unwrap(); + if !batch.is_empty() { + feeds_with_rows += 1; + } + rows.extend(batch); + } + let tail = parser.finish().unwrap(); + rows.extend(tail); + + assert_eq!(rows.len(), total); + assert!( + feeds_with_rows >= 2, + "rows only surfaced at finish: the mid-stream flush path was not exercised" + ); + for (i, row) in rows.iter().enumerate() { + assert_eq!(ts_millis_at(row, 2), Some(i as i64), "row {i}"); + assert_eq!(f64_at(row, 1), Some(i as f64), "row {i}"); + } + } + + #[test] + fn test_jsonl_decode_error_classes() { + let cases = [ + (ArrowError::ParseError("x".into()), "22P02"), + (ArrowError::CastError("x".into()), "22P02"), + ( + ArrowError::JsonError( + "whilst decoding field 'val': failed to parse \"a\" as Float64".into(), + ), + "22P02", + ), + ( + ArrowError::JsonError("Truncated record whilst reading string".into()), + "22P04", + ), + (ArrowError::JsonError("expected { got [".into()), "22P04"), + (ArrowError::NotYetImplemented("x".into()), "22P04"), + (ArrowError::DivideByZero, "22P04"), + ]; + for (error, expected) in cases { + let mapped = decode_error(error); + assert_eq!(error_code(&mapped), expected, "{mapped}"); + // Never an internal error. + assert!(!mapped.to_string().contains("XX000"), "{mapped}"); + } + } + + #[test] + fn test_jsonl_rejects_options_and_bad_columns() { + let mut set = CopyOptionSet::default(); + set.insert("header".into(), CopyOptionValue::Flag).unwrap(); + assert!(build_jsonl_codec(set).is_err()); + + let codec = codec(); + assert_eq!(codec.name(), "jsonl"); + assert!( + codec + .check_column_type(&ConcreteDataType::json_datatype()) + .is_err() + ); + assert!( + codec + .check_column_type(&ConcreteDataType::binary_datatype()) + .is_err() + ); + assert!( + codec + .check_column_type(&ConcreteDataType::timestamp_millisecond_datatype()) + .is_ok() + ); + } +} diff --git a/src/servers/src/postgres/copy_in/mod.rs b/src/servers/src/postgres/copy_in/mod.rs index c44b1a5d45f..8dc47e9b082 100644 --- a/src/servers/src/postgres/copy_in/mod.rs +++ b/src/servers/src/postgres/copy_in/mod.rs @@ -35,6 +35,7 @@ mod arrow; mod codec; mod csv; mod influxdb; +mod jsonl; mod options; mod otlp; mod parse; @@ -51,12 +52,11 @@ use api::v1::{ Row as GrpcRow, RowInsertRequest, RowInsertRequests, Rows as GrpcRows, SemanticType, }; use async_trait::async_trait; -use codec::{CopyFormat, RecordParser}; +use codec::{CopyFormat, RecordParser, TableBoundCodec}; use common_catalog::consts::{TRACE_TABLE_NAME, TRACE_TABLE_NAME_SESSION_KEY}; use common_grpc::precision::Precision; use common_query::OutputData; use common_telemetry::{info, warn}; -use csv::CsvCodec; use datafusion::sql::sqlparser::ast::{CopyTarget, Statement as SqlParserStatement}; use datatypes::data_type::DataType; use datatypes::schema::{ColumnSchema, SchemaRef}; @@ -107,6 +107,10 @@ type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult; /// to report a clear "not supported yet" instead of an unknown-format error. const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[ ("csv", csv::build_csv_codec), + ("jsonl", jsonl::build_jsonl_codec), + // Alias matching the file-based format's name; it still means + // newline-delimited objects, not a top-level JSON array. + ("json", jsonl::build_jsonl_codec), ("arrow", arrow::build_arrow_codec), ("influxdb", influxdb::build_influxdb_codec), ("influxdb_line", influxdb::build_influxdb_codec), @@ -332,7 +336,7 @@ enum Payload { impl CopyInState { fn new( - codec: &CsvCodec, + codec: &dyn TableBoundCodec, columns: Vec, table_info: Arc, query_ctx: QueryContextRef, @@ -368,7 +372,7 @@ impl CopyInState { }, memory_guards: Vec::new(), granted_bytes: 0, - codec_name: "csv", + codec_name: codec.name(), codec_format_code: 0, rows_written: 0, }) @@ -604,7 +608,7 @@ impl CopyInState { } fn resolve_columns( - codec: &CsvCodec, + codec: &dyn TableBoundCodec, columns: Vec, schema: &SchemaRef, table_info: &Arc, @@ -700,6 +704,16 @@ impl PostgresServerHandlerInner { // Each format states its own target rule and ingestion shape // explicitly. let state = match &stmt.format { + // Row-based table-bound formats parse records against the + // target columns and insert them in batches. + CopyFormat::Csv(codec) => { + self.table_bound_state(&stmt, codec, query_ctx.clone()) + .await? + } + CopyFormat::Jsonl(codec) => { + self.table_bound_state(&stmt, codec, query_ctx.clone()) + .await? + } CopyFormat::Arrow(options) => { if stmt.table.is_empty() { return Err(unsupported("format arrow requires a target table")); @@ -743,35 +757,6 @@ impl PostgresServerHandlerInner { rows_written: 0, } } - // csv requires a target table: records are parsed against - // its columns and inserted in batches. - CopyFormat::Csv(codec) => { - if stmt.table.is_empty() { - return Err(unsupported( - "format csv requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT csv)", - )); - } - let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; - - let Some(table_info) = self - .copy_in_handler - .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) - .await - .map_err(convert_err)? - else { - return Err(copy_in_error( - PgErrorCode::Ec42P01, - format!("relation \"{}\" does not exist", stmt.table.join(".")), - )); - }; - - // The insert path resolves the bare table name against the - // query context, so point the context at the resolved - // catalog and schema when the COPY target is qualified. - let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); - - CopyInState::new(codec, stmt.columns, table_info, query_ctx, table)? - } // influxdb forbids a target table — each line names its own // measurement — and completes through the line-protocol // pipeline the HTTP write endpoints use; the server must be @@ -865,6 +850,45 @@ impl PostgresServerHandlerInner { ))) } + /// Resolves the target table and builds the table-bound copy state + /// shared by csv and jsonl. `query_ctx` is the connection's context + /// `begin_copy_in` created, so every format arm works from the same + /// snapshot of the session. + async fn table_bound_state( + &self, + stmt: &CopyFromStdin, + codec: &dyn TableBoundCodec, + query_ctx: QueryContextRef, + ) -> PgWireResult { + if stmt.table.is_empty() { + return Err(unsupported(format!( + "format {} requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT {})", + stmt.format.name(), + stmt.format.name() + ))); + } + let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; + + let Some(table_info) = self + .copy_in_handler + .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) + .await + .map_err(convert_err)? + else { + return Err(copy_in_error( + PgErrorCode::Ec42P01, + format!("relation \"{}\" does not exist", stmt.table.join(".")), + )); + }; + + // The insert path resolves the bare table name against the query + // context, so point the context at the resolved catalog and schema + // when the COPY target is qualified. + let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); + + CopyInState::new(codec, stmt.columns.clone(), table_info, query_ctx, table) + } + /// Flushes the buffered payload of an in-progress copy. Returns the /// number of rows written by the flushed batch. async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult { @@ -1443,6 +1467,34 @@ mod tests { assert!(matches!(copy.format, CopyFormat::Csv(_))); } + #[test] + fn test_parse_copy_from_stdin_jsonl_and_json_alias() { + for sql in [ + "COPY t FROM STDIN WITH (FORMAT jsonl)", + "COPY t FROM STDIN WITH (FORMAT json)", + ] { + let copy = copy_from_stdin_from_sql(sql).unwrap().unwrap(); + assert!(matches!(copy.format, CopyFormat::Jsonl(_)), "{sql}"); + assert_eq!(copy.format.name(), "jsonl", "{sql}"); + } + } + + #[test] + fn test_table_bound_codec_names() { + // The codec names `CopyInState` logs come from the codecs + // themselves, not a literal per match arm. + let csv = match csv::build_csv_codec(options::CopyOptionSet::default()).unwrap() { + CopyFormat::Csv(codec) => codec, + other => panic!("expected csv, got {other:?}"), + }; + let jsonl = match jsonl::build_jsonl_codec(options::CopyOptionSet::default()).unwrap() { + CopyFormat::Jsonl(codec) => codec, + other => panic!("expected jsonl, got {other:?}"), + }; + assert_eq!(csv.name(), "csv"); + assert_eq!(jsonl.name(), "jsonl"); + } + #[test] fn test_parse_copy_from_stdin_text_unsupported() { for sql in [ diff --git a/tests-integration/src/tests/postgres_copy_in_test.rs b/tests-integration/src/tests/postgres_copy_in_test.rs index cde00ce17c3..564aae14215 100644 --- a/tests-integration/src/tests/postgres_copy_in_test.rs +++ b/tests-integration/src/tests/postgres_copy_in_test.rs @@ -2103,6 +2103,166 @@ async fn test_postgres_copy_in_prom_write_memory_quota() { pg_server.shutdown().await.unwrap(); } +/// `COPY ... FROM STDIN WITH (FORMAT jsonl)` ingests newline-delimited +/// JSON objects through arrow-json — the same engine as file-based +/// `COPY FROM 'file.json'` — including objects split across CopyData +/// chunks, absent-key NULLs and session-timezone timestamp parsing. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_jsonl_end_to_end() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_jsonl").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + client + .simple_query("CREATE TABLE js (host STRING, val DOUBLE, ts TIMESTAMP, TIME INDEX(ts))") + .await + .unwrap(); + + let payload: Vec = br#"{"host":"a","val":1.5,"ts":"2024-01-01 00:00:00"} +{"host":"b","ts":"2024-01-01 00:00:01"} +{"val":3.5,"ts":"2024-01-01 00:00:02"}"# + .to_vec(); + + let rows = feed_copy_in( + &client, + "COPY js (host, val, ts) FROM STDIN WITH (FORMAT jsonl)", + payload.chunks(13).map(Bytes::copy_from_slice).collect(), + ) + .await + .unwrap(); + assert_eq!(rows, 3); + + let messages = client + .simple_query("SELECT host, val FROM js ORDER BY ts") + .await + .unwrap(); + let rows: Vec<(String, String)> = messages + .iter() + .filter_map(|m| { + let tokio_postgres::SimpleQueryMessage::Row(row) = m else { + return None; + }; + Some(( + row.get(0).unwrap_or("").to_string(), + row.get(1).unwrap_or("").to_string(), + )) + }) + .collect(); + assert_eq!( + rows, + vec![ + ("a".into(), "1.5".into()), + ("b".into(), "".into()), // absent key -> NULL val + ("".into(), "3.5".into()), // absent key -> NULL host + ] + ); + + server.shutdown().await.unwrap(); +} + +/// Offset-free timestamp strings parse in the session timezone, like +/// SQL INSERT and the csv format. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_jsonl_session_timezone_parity() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_jsonl_tz").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + client + .simple_query("CREATE TABLE js_tz (host STRING PRIMARY KEY, ts TIMESTAMP, TIME INDEX(ts))") + .await + .unwrap(); + client + .simple_query("SET TIMEZONE TO 'Asia/Shanghai'") + .await + .unwrap(); + client + .simple_query("INSERT INTO js_tz VALUES ('insert', '2024-01-01 00:00:00')") + .await + .unwrap(); + let rows = feed_copy_in( + &client, + "COPY js_tz (host, ts) FROM STDIN WITH (FORMAT jsonl)", + vec![Bytes::from_static( + br#"{"host":"copy","ts":"2024-01-01 00:00:00"}"#, + )], + ) + .await + .unwrap(); + assert_eq!(rows, 1); + + // The same input string through INSERT and COPY must store the same + // instant. + let messages = client + .simple_query("SELECT host, CAST(ts AS BIGINT) FROM js_tz ORDER BY host") + .await + .unwrap(); + let rows: Vec<(String, Option)> = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => Some(( + row.get(0).unwrap_or("").to_string(), + row.get(1).map(str::to_string), + )), + _ => None, + }) + .collect(); + assert_eq!(rows.len(), 2, "both rows must exist: {rows:?}"); + assert_eq!( + rows[0].1, rows[1].1, + "INSERT and COPY must store the same instant: {rows:?}" + ); + + server.shutdown().await.unwrap(); +} + +/// Malformed JSON fails the copy with the decoder's error and the +/// connection stays usable. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_jsonl_errors() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_jsonl_err").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + client + .simple_query("CREATE TABLE js_err (host STRING, ts TIMESTAMP, TIME INDEX(ts))") + .await + .unwrap(); + + let error = feed_copy_in( + &client, + "COPY js_err (host, ts) FROM STDIN WITH (FORMAT jsonl)", + vec![Bytes::from_static( + br#"{"host":"a","ts":"not a timestamp"}"#, + )], + ) + .await + .unwrap_err(); + assert!(error.as_db_error().is_some(), "unexpected error: {error}"); + + let messages = client + .simple_query("SELECT count(*) FROM js_err") + .await + .unwrap(); + let count: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + assert_eq!(count, vec!["0".to_string()]); + + // The connection stays usable. + let messages = client.simple_query("SELECT 1").await.unwrap(); + assert!(!messages.is_empty()); + + server.shutdown().await.unwrap(); +} + /// Concurrent unfinished COPY requests share the receive-stage request /// memory quota. The fits check covers only a request's OWN holdings; /// cross-request contention is left to `acquire` and its policy: under