Hi Masahiko,
Short version: v4 is enough to write a format outside core. I ported
my ndjson module to it (master b4cc5e924b7) and everything I tried
works. The rough spots are in what copyapi.h says, not in the code.
What works: round trips through a file, with column lists, through
\copy, TO/FROM PROGRAM, file_fdw and with ENCODING 'SJIS' all give
back the same rows. ON_ERROR, REJECT_LIMIT, LOG_VERBOSITY, DEFAULT,
typmods and domains behave as the commit messages say, as with text.
Where I had to guess:
On Tue, Nov 24, 2026 at 12:10 PM Masahiko Sawada
<[email protected]> wrote:
> 0004 exports thin wrappers around them, CopyToSendData(),
> CopyToFlushData() and CopyFromGetData(), and copyapi.h says that they
> don't add any line termination.
1. When to flush. copyapi.h only asks a format to flush "by the end
of its CopyToEnd callback". A format that does just that keeps the
whole output in backend memory: for 1M rows of about 300 bytes, peak
RSS was 320 MB, against 33 MB when flushing after each row as text
does. Past 1 GB the COPY fails with "string buffer exceeds maximum
allowed length". I'd have copyapi.h say to flush after each row.
2. When to convert. copyapi.h says the format converts the data, but
not at which point. Parsing first breaks in SJIS: U+30BD is 0x83
0x5C, and 0x5C is a backslash, so a JSON parser sees an escape in the
middle of the character. Converting first doesn't work either, since
CopyFromConvertToServer() rejects a character cut in half. So a
format has to split records on the raw bytes and convert each record
afterwards. A sentence on which bytes are safe to split on would
help; the fields that tell (need_transcoding, encoding_embeds_ascii)
are in the internal part of copy_state.h.
> However, core still applies the typmod and the domain constraints of
> the columns to them, and ON_ERROR covers the errors there too.
3. It does: with ON_ERROR ignore, a row whose value fails a domain
CHECK is skipped, even when the format builds the Datum itself. But
the comment on the validate callback still says such a format "should
reject ON_ERROR here, since it would have no effect".
4. Smaller things. CopyFromSetErrorLine() drops the line whenever the
data is transcoded, so with ENCODING 'SJIS' the error context shows
only the line number, where text shows the converted line. And
copyapi.h doesn't mention opts->format_private_opts (I found it in
copy_fixed), or that the DEFAULT marker is opts->default_print.
Attached: the ported module and a script that reproduces each point.
Its scan_raw, typed and flush options exist only for these tests.
Regards,
Manu
/*-------------------------------------------------------------------------
*
* ndjson.c
* Newline-delimited JSON as a custom COPY format, written against
the
* v4 API of the "Make COPY format extendable" series.
*
* COPY TO writes one JSON object per row, keyed by column name, with each
* value as a JSON string (the text output of its type) or null. COPY FROM
* reads such objects back; a key missing from an object is a null. A
* string equal to the DEFAULT option, if given, is the DEFAULT marker.
*
* Three options exist only to test the API, not as features:
*
* typed COPY FROM builds each Datum itself, with the input
function of
* the column's base type and no typmod, instead
of letting core
* convert the field (exercises the typmod/domain
step).
* scan_raw COPY FROM parses the JSON BEFORE converting the record
to the
* server encoding, and converts each field
afterwards. Wrong on
* purpose, for encodings whose trailing bytes can
be ASCII.
* flush 'row' (default) or 'end': when COPY TO flushes its
output.
*
* Build with PGXS (MODULES = ndjson) against a tree with v4 0001-0008.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "commands/copy.h"
#include "commands/copyapi.h"
#include "commands/defrem.h"
#include "fmgr.h"
#include "lib/stringinfo.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/lsyscache.h"
PG_MODULE_MAGIC;
typedef struct NdjsonOptions
{
bool typed;
bool scan_raw;
bool flush_at_end;
} NdjsonOptions;
typedef struct NdjsonToState
{
TupleDesc tupDesc;
StringInfoData row;
bool flush_at_end;
} NdjsonToState;
typedef struct NdjsonFromState
{
StringInfoData line; /* current record, in the file encoding
*/
int natts; /* length of attnumlist
*/
char **fields; /* one per column of attnumlist
*/
bool *isdefault;
text **keys; /* column names, for the lookup
*/
FmgrInfo field_finfo; /* json_object_field_text */
FmgrInfo *base_in; /* typed: input function of the base
type */
Oid *base_ioparam;
bool typed;
bool scan_raw;
} NdjsonFromState;
static NdjsonOptions *
ndjson_opts(CopyFormatOptions *opts)
{
if (opts->format_private_opts == NULL)
opts->format_private_opts = palloc0_object(NdjsonOptions);
return (NdjsonOptions *) opts->format_private_opts;
}
/* ---------------------------------------------------------------- COPY TO */
static void
NdjsonToStart(CopyToState cstate, TupleDesc tupDesc)
{
NdjsonToState *st = palloc0_object(NdjsonToState);
NdjsonOptions *o = (NdjsonOptions *) cstate->opts.format_private_opts;
st->tupDesc = tupDesc;
st->flush_at_end = (o != NULL && o->flush_at_end);
initStringInfo(&st->row);
cstate->format_private = st;
}
static void
NdjsonToOneRow(CopyToState cstate, TupleTableSlot *slot)
{
NdjsonToState *st = (NdjsonToState *) cstate->format_private;
bool first = true;
char *out;
resetStringInfo(&st->row);
appendStringInfoChar(&st->row, '{');
foreach_int(attnum, cstate->attnumlist)
{
Form_pg_attribute attr = TupleDescAttr(st->tupDesc, attnum - 1);
if (!first)
appendStringInfoChar(&st->row, ',');
first = false;
escape_json(&st->row, NameStr(attr->attname));
appendStringInfoChar(&st->row, ':');
if (slot->tts_isnull[attnum - 1])
appendStringInfoString(&st->row, "null");
else
escape_json(&st->row,
OutputFunctionCall(&cstate->out_functions[attnum - 1],
slot->tts_values[attnum - 1]));
}
/* the API adds no line termination */
appendStringInfoString(&st->row, "}\n");
/* built in the server encoding, so escaping was safe; convert it whole
*/
out = CopyToConvertFromServer(cstate, st->row.data, st->row.len);
CopyToSendData(cstate, out, out == st->row.data ? st->row.len :
strlen(out));
if (!st->flush_at_end)
CopyToFlushData(cstate);
}
static void
NdjsonToEnd(CopyToState cstate)
{
CopyToFlushData(cstate);
}
static const CopyToRoutine NdjsonToRoutine = {
.CopyToOutFunc = NULL, /* core sets up the text output
functions */
.CopyToStart = NdjsonToStart,
.CopyToOneRow = NdjsonToOneRow,
.CopyToEnd = NdjsonToEnd,
};
/* -------------------------------------------------------------- COPY FROM */
static void
NdjsonFromStart(CopyFromState cstate, TupleDesc tupDesc)
{
NdjsonFromState *st = palloc0_object(NdjsonFromState);
NdjsonOptions *o = (NdjsonOptions *) cstate->opts.format_private_opts;
int i = 0;
st->natts = list_length(cstate->attnumlist);
st->fields = palloc0_array(char *, st->natts);
st->isdefault = palloc0_array(bool, st->natts);
st->keys = palloc_array(text *, st->natts);
st->typed = (o != NULL && o->typed);
st->scan_raw = (o != NULL && o->scan_raw);
if (st->typed)
{
st->base_in = palloc_array(FmgrInfo, st->natts);
st->base_ioparam = palloc_array(Oid, st->natts);
}
foreach_int(attnum, cstate->attnumlist)
{
Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
st->keys[i] = cstring_to_text(NameStr(attr->attname));
if (st->typed)
{
int32 typmod = attr->atttypmod;
Oid base =
getBaseTypeAndTypmod(attr->atttypid, &typmod);
Oid func;
getTypeInputInfo(base, &func, &st->base_ioparam[i]);
fmgr_info(func, &st->base_in[i]);
}
i++;
}
fmgr_info(F_JSON_OBJECT_FIELD_TEXT, &st->field_finfo);
initStringInfo(&st->line);
cstate->format_private = st;
}
/*
* Read one newline-terminated record. '\n' is never a trailing byte in any
* client encoding, so splitting before conversion is safe; anything else is
* scanned only after conversion.
*/
static bool
ndjson_read_line(CopyFromState cstate, NdjsonFromState *st)
{
char c;
resetStringInfo(&st->line);
for (;;)
{
if (CopyFromGetData(cstate, &c, 1, 1) != 1)
break;
if (c == '\n')
{
if (st->line.len > 0 && st->line.data[st->line.len - 1]
== '\r')
st->line.data[--st->line.len] = '\0';
return true;
}
appendStringInfoChar(&st->line, c);
}
return st->line.len > 0; /* last record without newline */
}
static bool
NdjsonFromOneRow(CopyFromState cstate, ExprContext *econtext,
Datum *values, bool *nulls)
{
NdjsonFromState *st = (NdjsonFromState *) cstate->format_private;
char *rec;
Datum json;
if (!ndjson_read_line(cstate, st))
return false;
/* given in the encoding of the COPY data, see copyapi.h */
CopyFromSetErrorLine(cstate, st->line.data, st->line.len);
if (st->scan_raw)
rec = st->line.data;
else
rec = CopyFromConvertToServer(cstate, st->line.data,
st->line.len);
/* a malformed record is the format's own error, as in text/CSV */
json = DirectFunctionCall1(json_in, CStringGetDatum(rec));
for (int i = 0; i < st->natts; i++)
{
LOCAL_FCINFO(fcinfo, 2);
Datum field;
/* json_object_field_text gives NULL for a missing key or a
null */
InitFunctionCallInfoData(*fcinfo, &st->field_finfo, 2,
InvalidOid,
NULL, NULL);
fcinfo->args[0].value = json;
fcinfo->args[0].isnull = false;
fcinfo->args[1].value = PointerGetDatum(st->keys[i]);
fcinfo->args[1].isnull = false;
field = FunctionCallInvoke(fcinfo);
st->isdefault[i] = false;
if (fcinfo->isnull)
st->fields[i] = NULL;
else
{
char *s = TextDatumGetCString(field);
if (st->scan_raw)
s = CopyFromConvertToServer(cstate, s,
strlen(s));
st->fields[i] = s;
if (cstate->opts.default_print != NULL &&
strcmp(s, cstate->opts.default_print) == 0)
st->isdefault[i] = true;
}
}
if (!st->typed)
{
/* core converts, applying ON_ERROR; false means the row is
dropped */
(void) CopyFromConvertFields(cstate, st->fields, st->isdefault,
st->natts, values, nulls);
return true;
}
/* typed: build base-type Datums ourselves; core applies typmod/domain
*/
for (int i = 0; i < st->natts; i++)
{
if (st->isdefault[i])
CopyFromSetDefault(cstate, i);
else if (st->fields[i] != NULL)
{
values[i] = InputFunctionCall(&st->base_in[i],
st->fields[i],
st->base_ioparam[i], -1);
nulls[i] = false;
}
/* else: left null, as core initialized it */
}
return true;
}
static void
NdjsonFromEnd(CopyFromState cstate)
{
}
static const CopyFromRoutine NdjsonFromRoutine = {
.CopyFromInFunc = NULL, /* core uses the text input functions */
.CopyFromStart = NdjsonFromStart,
.CopyFromOneRow = NdjsonFromOneRow,
.CopyFromEnd = NdjsonFromEnd,
};
/* ---------------------------------------------------------------- options */
static bool
ndjson_option(CopyFormatOptions *opts, bool is_from, DefElem *option)
{
NdjsonOptions *o = ndjson_opts(opts);
if (strcmp(option->defname, "typed") == 0)
o->typed = defGetBoolean(option);
else if (strcmp(option->defname, "scan_raw") == 0)
o->scan_raw = defGetBoolean(option);
else if (strcmp(option->defname, "flush") == 0)
{
char *v = defGetString(option);
if (strcmp(v, "row") == 0)
o->flush_at_end = false;
else if (strcmp(v, "end") == 0)
o->flush_at_end = true;
else
ereport(ERROR,
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("COPY format \"ndjson\" option
\"flush\" must be \"row\" or \"end\""));
}
else
return false;
return true;
}
static void
ndjson_reject(const char *name)
{
ereport(ERROR,
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("COPY format \"ndjson\" does not support option
%s", name));
}
static void
ndjson_validate(CopyFormatOptions *opts, bool is_from)
{
NdjsonOptions *o = ndjson_opts(opts);
if (opts->delim)
ndjson_reject("DELIMITER");
if (opts->quote)
ndjson_reject("QUOTE");
if (opts->escape)
ndjson_reject("ESCAPE");
if (opts->null_print)
ndjson_reject("NULL"); /* JSON has its own null */
if (opts->header_line != COPY_HEADER_FALSE)
ndjson_reject("HEADER");
if (opts->force_quote || opts->force_quote_all)
ndjson_reject("FORCE_QUOTE");
if (opts->force_notnull || opts->force_notnull_all)
ndjson_reject("FORCE_NOT_NULL");
if (opts->force_null || opts->force_null_all)
ndjson_reject("FORCE_NULL");
if (opts->force_array)
ndjson_reject("FORCE_ARRAY");
if (!is_from && (o->typed || o->scan_raw))
ndjson_reject(o->typed ? "typed" : "scan_raw");
}
static const CopyCustomFormatEntry ndjson_entry = {
.name = "ndjson",
.binary = false,
.to_routine = &NdjsonToRoutine,
.from_routine = &NdjsonFromRoutine,
.option_fn = ndjson_option,
.validate_fn = ndjson_validate,
};
void
_PG_init(void)
{
RegisterCopyCustomFormat(&ndjson_entry);
}
-- ndjson on the v4 COPY format API: round trip, then one block per point
-- raised in the mail. Needs a superuser (server-side files, PROGRAM,
-- pg_read_file of /proc) and a UTF8 database. The last block writes
-- over 1 GB through COPY TO and is slow.
\set ON_ERROR_STOP 0
LOAD 'ndjson';
-- Round trip: file, column list, frontend, PROGRAM, file_fdw.
CREATE TABLE ndj (id int, name text, amount numeric, ok bool, ts date);
INSERT INTO ndj VALUES
(1, 'hello', 1.25, true, '2026-01-31'),
(2, 'with "quotes" and \ backslash', -0.5, false, '1999-12-31'),
(3, NULL, NULL, NULL, NULL),
(4, E'tab\there and newline\nthere', 1e6, true, '2000-02-29');
CREATE TABLE ndj_back (LIKE ndj);
COPY ndj TO '/tmp/ndj.ndjson' WITH (FORMAT ndjson);
COPY ndj_back FROM '/tmp/ndj.ndjson' WITH (FORMAT ndjson);
SELECT * FROM ndj EXCEPT ALL SELECT * FROM ndj_back; -- 0 rows
SELECT * FROM ndj_back EXCEPT ALL SELECT * FROM ndj; -- 0 rows
TRUNCATE ndj_back;
COPY ndj (id, name) TO '/tmp/ndj_part.ndjson' WITH (FORMAT ndjson);
COPY ndj_back (id, name) FROM '/tmp/ndj_part.ndjson' WITH (FORMAT ndjson);
SELECT id, name, amount IS NULL AS amount_null FROM ndj_back ORDER BY id;
TRUNCATE ndj_back;
\copy ndj TO '/tmp/ndj_fe.ndjson' WITH (FORMAT ndjson)
\copy ndj_back FROM '/tmp/ndj_fe.ndjson' WITH (FORMAT ndjson)
SELECT count(*) AS diff FROM (SELECT * FROM ndj EXCEPT ALL SELECT * FROM
ndj_back) d;
TRUNCATE ndj_back;
COPY ndj TO PROGRAM 'cat > /tmp/ndj_prog.ndjson' WITH (FORMAT ndjson);
COPY ndj_back FROM PROGRAM 'cat /tmp/ndj_prog.ndjson' WITH (FORMAT ndjson);
SELECT count(*) AS diff FROM (SELECT * FROM ndj EXCEPT ALL SELECT * FROM
ndj_back) d;
CREATE EXTENSION IF NOT EXISTS file_fdw;
CREATE SERVER ndj_fs FOREIGN DATA WRAPPER file_fdw;
CREATE FOREIGN TABLE ndj_ft (id int, name text, amount numeric, ok bool, ts
date)
SERVER ndj_fs OPTIONS (filename '/tmp/ndj.ndjson', format 'ndjson');
SELECT count(*) AS diff FROM (SELECT * FROM ndj EXCEPT ALL SELECT * FROM
ndj_ft) d;
-- ON_ERROR with a bad integer on line 3 of 5, and the per-row NOTICE.
CREATE TABLE onerr (id int, v int);
COPY onerr FROM STDIN WITH (FORMAT ndjson, ON_ERROR ignore, LOG_VERBOSITY
verbose);
{"id":"1","v":"10"}
{"id":"2","v":"20"}
{"id":"3","v":"abc"}
{"id":"4","v":"40"}
{"id":"5","v":"50"}
\.
-- REJECT_LIMIT 1 with two bad rows: fails on the second, line 4.
COPY onerr FROM STDIN WITH (FORMAT ndjson, ON_ERROR ignore, REJECT_LIMIT 1);
{"id":"1","v":"10"}
{"id":"2","v":"bad"}
{"id":"3","v":"30"}
{"id":"4","v":"bad"}
\.
-- DEFAULT: a JSON string equal to the DEFAULT option is the marker.
CREATE TABLE def (id int, v int DEFAULT 42, w text DEFAULT 'dw');
COPY def FROM STDIN WITH (FORMAT ndjson, DEFAULT '\D');
{"id":"1","v":"\\D","w":"a"}
{"id":"2","v":"5","w":"\\D"}
\.
SELECT * FROM def ORDER BY id;
-- typmod, converted by core and built by the format (typed).
CREATE TABLE tm (a varchar(3), n numeric(5,2));
COPY tm FROM STDIN WITH (FORMAT ndjson);
{"a":"abcd","n":"1.005"}
\.
COPY tm FROM STDIN WITH (FORMAT ndjson, typed true);
{"a":"abc","n":"1.005"}
{"a":"abcd","n":"1"}
\.
SELECT * FROM tm;
-- SJIS: U+30BD and U+8868 are 0x83 0x5C and 0x95 0x5C, a backslash as
-- the trailing byte. Splitting on \n and converting each record before
-- parsing it works; parsing before converting (scan_raw) does not.
CREATE TABLE sj (id int, s text);
INSERT INTO sj VALUES (1, U&'\30BD'), (2, U&'\8868'), (3, U&'\30BD"\8868' ||
'\x');
CREATE TABLE sj_back (LIKE sj);
COPY sj TO '/tmp/sj.ndjson' WITH (FORMAT ndjson, ENCODING 'SJIS');
COPY sj_back FROM '/tmp/sj.ndjson' WITH (FORMAT ndjson, ENCODING 'SJIS');
SELECT count(*) AS diff FROM (SELECT * FROM sj EXCEPT ALL SELECT * FROM
sj_back) d;
TRUNCATE sj_back;
COPY sj_back FROM '/tmp/sj.ndjson' WITH (FORMAT ndjson, ENCODING 'SJIS',
scan_raw true);
-- CopyFromConvertToServer() rejects a partial character: copy_fixed
-- (0009) slices 'abc' + U+30BD + 'xy' at byte 4, inside the character.
LOAD 'copy_fixed';
COPY (SELECT 'abc' || U&'\30BD' || 'xy') TO '/tmp/split.dat' WITH (FORMAT text,
ENCODING 'SJIS');
CREATE TABLE split (a text, b text);
COPY split FROM '/tmp/split.dat' WITH (FORMAT fixed, widths '4,3', ENCODING
'SJIS');
-- Error context: a malformed record is quoted in UTF8, not in SJIS.
COPY (SELECT '{"id":"1","s":"' || U&'\30BD' || '"')
TO '/tmp/bad_sjis.ndjson' WITH (FORMAT text, ENCODING 'SJIS');
COPY (SELECT '{"id":"1","s":"' || U&'\30BD' || '"') TO '/tmp/bad_utf8.ndjson'
WITH (FORMAT text);
COPY sj_back FROM '/tmp/bad_sjis.ndjson' WITH (FORMAT ndjson, ENCODING 'SJIS');
COPY sj_back FROM '/tmp/bad_utf8.ndjson' WITH (FORMAT ndjson);
-- text quotes the converted line for a record-level error
COPY (SELECT 1, U&'\30BD', 'extra')
TO '/tmp/bad_sjis.txt' WITH (FORMAT text, ENCODING 'SJIS');
COPY sj_back FROM '/tmp/bad_sjis.txt' WITH (FORMAT text, ENCODING 'SJIS');
-- typed: the format builds the Datums itself. Core applies the domain,
-- and ON_ERROR covers it, although copyapi.h says it would have no effect.
CREATE DOMAIN dpos AS int CHECK (VALUE > 0);
CREATE TABLE dom (id int, x dpos);
COPY dom FROM STDIN WITH (FORMAT ndjson, typed true, ON_ERROR ignore);
{"id":"1","x":"5"}
{"id":"2","x":"-1"}
{"id":"3","x":"7"}
\.
SELECT * FROM dom ORDER BY id;
-- Flushing only in CopyToEnd: the whole output stays in the backend.
-- Peak RSS of a fresh backend after ~300 MB of output, per row vs at end.
CREATE UNLOGGED TABLE big AS
SELECT g AS id, repeat('z', 280) AS s FROM generate_series(1, 1000000) g;
\c
LOAD 'ndjson';
COPY big TO '/dev/null' WITH (FORMAT ndjson, flush 'row');
SELECT 'row' AS flush, (regexp_match(pg_read_file('/proc/' || pg_backend_pid()
|| '/status'),
'VmHWM:\s+(\d+) kB'))[1]::int / 1024 AS peak_rss_mb;
\c
LOAD 'ndjson';
COPY big TO '/dev/null' WITH (FORMAT ndjson, flush 'end');
SELECT 'end' AS flush, (regexp_match(pg_read_file('/proc/' || pg_backend_pid()
|| '/status'),
'VmHWM:\s+(\d+) kB'))[1]::int / 1024 AS peak_rss_mb;
-- Over 1 GB of output, flushing only at the end fails.
INSERT INTO big SELECT g, repeat('z', 280) FROM generate_series(1000001,
3600000) g;
COPY big TO '/dev/null' WITH (FORMAT ndjson, flush 'end');