fix(Postgres Node): Fix inserting null or undefined in type=json columns (#14672)

This commit is contained in:
Elias Meire
2025-04-16 16:36:23 +02:00
committed by GitHub
parent ff47279b25
commit 3add0b82ba
2 changed files with 42 additions and 28 deletions

View File

@@ -429,15 +429,18 @@ describe('Test PostgresV2, hasJsonDataType', () => {
}); });
describe('Test PostgresV2, convertValuesToJsonWithPgp', () => { describe('Test PostgresV2, convertValuesToJsonWithPgp', () => {
it('should use pgp to properly convert values to JSON', () => {
const pgp = pgPromise(); const pgp = pgPromise();
const pgpJsonSpy = jest.spyOn(pgp.as, 'json'); const pgpJsonSpy = jest.spyOn(pgp.as, 'json');
const schema: ColumnInfo[] = [ const schema: ColumnInfo[] = [
{ column_name: 'data', data_type: 'json', is_nullable: 'YES' }, { column_name: 'data', data_type: 'json', is_nullable: 'YES' },
{ column_name: 'id', data_type: 'integer', is_nullable: 'NO' }, { column_name: 'id', data_type: 'integer', is_nullable: 'NO' },
]; ];
const values = [
beforeEach(() => {
pgpJsonSpy.mockClear();
});
it.each([
{ {
value: { data: [], id: 1 }, value: { data: [], id: 1 },
expected: { data: '[]', id: 1 }, expected: { data: '[]', id: 1 },
@@ -450,15 +453,23 @@ describe('Test PostgresV2, convertValuesToJsonWithPgp', () => {
value: { data: { key: 2 }, id: 1 }, value: { data: { key: 2 }, id: 1 },
expected: { data: '{"key":2}', id: 1 }, expected: { data: '{"key":2}', id: 1 },
}, },
]; {
value: { data: null, id: 1 },
values.forEach((value) => { expected: { data: null, id: 1 },
const data = value.value.data; shouldSkipPgp: true,
},
expect(convertValuesToJsonWithPgp(pgp, schema, value.value)).toEqual(value.expected); {
expect(value.value).toEqual(value.expected); value: { data: undefined, id: 1 },
expected: { data: undefined, id: 1 },
shouldSkipPgp: true,
},
])('should convert $value.data to json correctly', ({ value, expected, shouldSkipPgp }) => {
const data = value.data;
expect(convertValuesToJsonWithPgp(pgp, schema, value)).toEqual(expected);
expect(value).toEqual(expected);
if (!shouldSkipPgp) {
expect(pgpJsonSpy).toHaveBeenCalledWith(data, true); expect(pgpJsonSpy).toHaveBeenCalledWith(data, true);
}); }
}); });
}); });

View File

@@ -414,7 +414,10 @@ export function convertValuesToJsonWithPgp(
values: IDataObject, values: IDataObject,
) { ) {
schema schema
.filter(({ data_type }: { data_type: string }) => data_type === 'json') .filter(
({ data_type, column_name }) =>
data_type === 'json' && values[column_name] !== null && values[column_name] !== undefined,
)
.forEach(({ column_name }) => { .forEach(({ column_name }) => {
values[column_name] = pgp.as.json(values[column_name], true); values[column_name] = pgp.as.json(values[column_name], true);
}); });