Skip to content

Commit aec7dac

Browse files
committed
fix: add jsonb[] coercion handler in csv-to-pg parser to prevent corrupted SQL output
1 parent 1ba8a0e commit aec7dac

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

packages/csv-to-pg/src/parse.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,39 @@ const getCoercionFunc = (type: string, from: string[], opts: FieldOptions, field
458458
});
459459
return wrapValue(val, opts);
460460
};
461+
case 'jsonb[]':
462+
return (record: Record<string, unknown>): Node => {
463+
const rawValue = record[from[0]];
464+
if (isNullToken(rawValue)) {
465+
return makeNullOrThrow(fieldName, rawValue, type, required, 'value is empty or null');
466+
}
467+
if (Array.isArray(rawValue)) {
468+
if (rawValue.length === 0) {
469+
return makeNullOrThrow(fieldName, rawValue, type, required, 'array is empty');
470+
}
471+
const elements = rawValue.map(el => JSON.stringify(el));
472+
const arrayLiteral = psqlArray(elements);
473+
if (isEmpty(arrayLiteral)) {
474+
return makeNullOrThrow(fieldName, rawValue, type, required, 'failed to format array');
475+
}
476+
const val = nodes.aConst({
477+
sval: ast.string({ sval: String(arrayLiteral) })
478+
});
479+
return wrapValue(val, opts);
480+
}
481+
// If it's a string, try to parse as JSON array
482+
if (typeof rawValue === 'string') {
483+
const parsed = parseJson(cleanseEmptyStrings(rawValue));
484+
if (isEmpty(parsed)) {
485+
return makeNullOrThrow(fieldName, rawValue, type, required, 'value is empty or null');
486+
}
487+
const val = nodes.aConst({
488+
sval: ast.string({ sval: String(parsed) })
489+
});
490+
return wrapValue(val, opts);
491+
}
492+
return makeNullOrThrow(fieldName, rawValue, type, required, 'value is not an array');
493+
};
461494
default:
462495
return (record: Record<string, unknown>): Node => {
463496
const rawValue = record[from[0]];

0 commit comments

Comments
 (0)