/*------------------------------------------------------------------------- * * 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); }