mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-03 07:55:25 +00:00
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 <sunning@greptime.com>
This commit is contained in:
@@ -51,10 +51,13 @@
|
||||
//! format-specific shapes) and rejects the rest with
|
||||
//! `reject_leftovers`.
|
||||
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::ColumnSchema;
|
||||
use pgwire::error::PgWireResult;
|
||||
|
||||
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;
|
||||
|
||||
@@ -64,6 +67,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-less influxdb line protocol: the whole payload is one
|
||||
/// bounded request body, completed through the line-protocol
|
||||
/// pipeline the HTTP write endpoints use (one COPY statement is one
|
||||
@@ -82,6 +89,62 @@ 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::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 every
|
||||
/// table-bound format identically through it.
|
||||
pub(crate) trait TableBoundCodec: Send + Sync {
|
||||
/// 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<Box<dyn RecordParser + Send>>;
|
||||
}
|
||||
|
||||
impl TableBoundCodec for CsvCodec {
|
||||
fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
|
||||
CsvCodec::check_column_type(self, data_type)
|
||||
}
|
||||
fn create_parser(
|
||||
&self,
|
||||
columns: &[ColumnSchema],
|
||||
timezone: &str,
|
||||
) -> PgWireResult<Box<dyn RecordParser + Send>> {
|
||||
CsvCodec::create_parser(self, columns, timezone)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableBoundCodec for JsonlCodec {
|
||||
fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> {
|
||||
JsonlCodec::check_column_type(self, data_type)
|
||||
}
|
||||
fn create_parser(
|
||||
&self,
|
||||
columns: &[ColumnSchema],
|
||||
timezone: &str,
|
||||
) -> PgWireResult<Box<dyn RecordParser + Send>> {
|
||||
JsonlCodec::create_parser(self, columns, timezone)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
// 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 same engine backing
|
||||
//! 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) 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).
|
||||
//!
|
||||
//! Consequences of sharing the engine: JSON native types (numbers,
|
||||
//! booleans, strings) must match the column types; absent keys become
|
||||
//! NULL; timestamps are RFC 3339 / date-time strings (offset-free ones
|
||||
//! parse in the session timezone, like SQL INSERT); and columns whose
|
||||
//! type arrow-json cannot decode (JSON, Binary) are rejected.
|
||||
//!
|
||||
//! 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).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::helper::vectors_to_rows;
|
||||
use arrow::json::reader::{Decoder as JsonDecoder, ReaderBuilder};
|
||||
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::Helper;
|
||||
use pgwire::error::{PgWireError, PgWireResult};
|
||||
|
||||
use crate::postgres::copy_in::codec::{CopyFormat, ParsedRow, RecordParser};
|
||||
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<CopyFormat> {
|
||||
options.reject_leftovers("jsonl")?;
|
||||
Ok(CopyFormat::Jsonl(JsonlCodec))
|
||||
}
|
||||
|
||||
impl JsonlCodec {
|
||||
/// The column types arrow-json can decode against.
|
||||
pub(crate) fn check_column_type(&self, data_type: &ConcreteDataType) -> 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 jsonl",
|
||||
data_type.name()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn create_parser(
|
||||
&self,
|
||||
columns: &[ColumnSchema],
|
||||
timezone: &str,
|
||||
) -> PgWireResult<Box<dyn RecordParser + Send>> {
|
||||
// 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.
|
||||
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)| match &column.data_type {
|
||||
ConcreteDataType::Timestamp(_) => match field.data_type() {
|
||||
ArrowDataType::Timestamp(unit, None) => Field::new(
|
||||
field.name(),
|
||||
ArrowDataType::Timestamp(*unit, Some(Arc::from(timezone.as_str()))),
|
||||
field.is_nullable(),
|
||||
),
|
||||
_ => field.as_ref().clone(),
|
||||
},
|
||||
_ => field.as_ref().clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
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)?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Incremental parser backed by arrow-json's decoder, whose streaming
|
||||
/// contract mirrors arrow-csv's (`decode` returns consumed bytes; a
|
||||
/// short read means a full batch is ready).
|
||||
struct JsonlRecordParser {
|
||||
decoder: JsonDecoder,
|
||||
}
|
||||
|
||||
impl RecordParser for JsonlRecordParser {
|
||||
fn feed(&mut self, data: &[u8]) -> PgWireResult<Vec<ParsedRow>> {
|
||||
let mut buf = data;
|
||||
let mut rows = Vec::new();
|
||||
while !buf.is_empty() {
|
||||
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(flush_batch(&batch)?);
|
||||
}
|
||||
} else {
|
||||
buf = &buf[consumed..];
|
||||
}
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> PgWireResult<Vec<ParsedRow>> {
|
||||
// An empty decode signals EOF, finalizing a trailing record
|
||||
// that lacks its newline.
|
||||
self.decoder.decode(&[]).map_err(decode_error)?;
|
||||
let mut rows = Vec::new();
|
||||
while let Some(batch) = self.decoder.flush().map_err(decode_error)? {
|
||||
rows.extend(flush_batch(&batch)?);
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts one decoded arrow batch into insertable rows with the
|
||||
/// shared [`vectors_to_rows`] helper.
|
||||
fn flush_batch(batch: &arrow::record_batch::RecordBatch) -> PgWireResult<Vec<ParsedRow>> {
|
||||
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()))
|
||||
}
|
||||
|
||||
fn decode_error(error: ArrowError) -> PgWireError {
|
||||
match &error {
|
||||
ArrowError::ParseError(reason) => invalid_text_repr(reason.clone()),
|
||||
ArrowError::JsonError(reason) => invalid_text_repr(reason.clone()),
|
||||
_ => PgWireError::ApiError(Box::new(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<ColumnSchema> {
|
||||
vec![
|
||||
ColumnSchema::new("host", ConcreteDataType::string_datatype(), true),
|
||||
ColumnSchema::new("val", ConcreteDataType::float64_datatype(), true),
|
||||
ColumnSchema::new(
|
||||
"ts",
|
||||
ConcreteDataType::timestamp_millisecond_datatype(),
|
||||
false,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn parser() -> Box<dyn RecordParser + Send> {
|
||||
match build_jsonl_codec(CopyOptionSet::default()).unwrap() {
|
||||
CopyFormat::Jsonl(codec) => codec.create_parser(&columns(), "UTC").unwrap(),
|
||||
other => panic!("unexpected format {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn feed_all(parser: &mut Box<dyn RecordParser + Send>, chunks: &[&[u8]]) -> Vec<ParsedRow> {
|
||||
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<String> {
|
||||
row.values[col].value_data.as_ref().map(|v| match v {
|
||||
ValueData::StringValue(s) => s.clone(),
|
||||
other => panic!("expected string, got {other:?}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_jsonl_records_across_chunk_boundaries() {
|
||||
let payload: Vec<u8> = 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 = parser();
|
||||
let rows = feed_all(&mut parser, &payload.chunks(chunk).collect::<Vec<_>>());
|
||||
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 = parser();
|
||||
let rows = feed_all(
|
||||
&mut parser,
|
||||
&[b"{\"val\":3.5,\"ts\":\"2024-01-01 00:00:00\"}
|
||||
"],
|
||||
);
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert!(rows[0].values[0].value_data.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_jsonl_type_mismatch_fails() {
|
||||
let mut parser = parser();
|
||||
// The mismatch surfaces when the record is decoded at flush.
|
||||
parser
|
||||
.feed(
|
||||
br#"{"host":"a","val":"not a number","ts":"2024-01-01 00:00:00"}
|
||||
"#
|
||||
.as_ref(),
|
||||
)
|
||||
.unwrap();
|
||||
let error = parser.finish().unwrap_err();
|
||||
assert!(!error.to_string().is_empty());
|
||||
}
|
||||
|
||||
#[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 = JsonlCodec;
|
||||
assert!(
|
||||
codec
|
||||
.check_column_type(&ConcreteDataType::json_datatype())
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
codec
|
||||
.check_column_type(&ConcreteDataType::binary_datatype())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
mod codec;
|
||||
mod csv;
|
||||
mod influxdb;
|
||||
mod jsonl;
|
||||
mod options;
|
||||
mod otlp;
|
||||
mod parse;
|
||||
@@ -50,12 +51,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,8 @@ type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult<CopyFormat>;
|
||||
/// unknown-format error.
|
||||
const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[
|
||||
("csv", csv::build_csv_codec),
|
||||
("jsonl", jsonl::build_jsonl_codec),
|
||||
("json", jsonl::build_jsonl_codec),
|
||||
("influxdb", influxdb::build_influxdb_codec),
|
||||
("influxdb_line", influxdb::build_influxdb_codec),
|
||||
("otlp", otlp::build_otlp_codec),
|
||||
@@ -294,7 +296,7 @@ enum Payload {
|
||||
|
||||
impl CopyInState {
|
||||
fn new(
|
||||
codec: &CsvCodec,
|
||||
codec: &dyn TableBoundCodec,
|
||||
columns: Vec<String>,
|
||||
table_info: Arc<TableInfo>,
|
||||
query_ctx: QueryContextRef,
|
||||
@@ -494,7 +496,7 @@ impl CopyInState {
|
||||
}
|
||||
|
||||
fn resolve_columns(
|
||||
codec: &CsvCodec,
|
||||
codec: &dyn TableBoundCodec,
|
||||
columns: Vec<String>,
|
||||
schema: &SchemaRef,
|
||||
table_info: &Arc<TableInfo>,
|
||||
@@ -590,35 +592,10 @@ impl PostgresServerHandlerInner {
|
||||
// Each format states its own target rule and ingestion shape
|
||||
// explicitly.
|
||||
let state = match &stmt.format {
|
||||
// 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)?
|
||||
}
|
||||
// Table-bound formats require a target table: records are
|
||||
// parsed against its columns and inserted in batches.
|
||||
CopyFormat::Csv(codec) => self.table_bound_state(&stmt, codec).await?,
|
||||
CopyFormat::Jsonl(codec) => self.table_bound_state(&stmt, codec).await?,
|
||||
// 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
|
||||
@@ -689,6 +666,43 @@ impl PostgresServerHandlerInner {
|
||||
|
||||
/// Flushes the buffered payload of an in-progress copy. Returns the
|
||||
/// number of rows written by the flushed batch.
|
||||
/// Resolves the target table and builds the table-bound copy state
|
||||
/// shared by csv and jsonl.
|
||||
async fn table_bound_state(
|
||||
&self,
|
||||
stmt: &CopyFromStdin,
|
||||
codec: &dyn TableBoundCodec,
|
||||
) -> PgWireResult<CopyInState> {
|
||||
let query_ctx = self.new_query_context();
|
||||
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)
|
||||
}
|
||||
|
||||
async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult<u64> {
|
||||
let query_ctx = state.query_ctx.clone();
|
||||
// The buffered influxdb payload is completed through the
|
||||
|
||||
@@ -1411,3 +1411,163 @@ 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<u8> = 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<String>)> = 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<String> = 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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user