Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/postgresql.js
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,43 @@ PostgreSQL.prototype.buildExpression = function(columnName, operator,
operatorValue);
case 'match':
return new ParameterizedSQL(`to_tsvector(${columnName}) @@ to_tsquery(?)`, [operatorValue]);
// Map the abstract 'jsonContains' operator to PostgreSQL's JSONB containment operator (@>),
// parsing or normalizing string/array inputs to build parameterized clauses connected with OR.
case 'jsonContains':

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to define the public semantics of jsonContains before adding this as a connector operator. Here an array of candidates becomes OR/match-any, while JSON containment of an array in other connectors can mean match-all. Since datasource-juggler #2615 proposes rewriting inq into jsonContains, this risks different results across connectors for the same filter. Can we preserve the inq contract explicitly and establish consistent operator semantics across the relevant connectors?

let values = operatorValue;
if (typeof values === 'string') {
try {
values = JSON.parse(values);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parsing every string with JSON.parse() can silently change identifier types. For example, a legitimate string ID '123' becomes the number 123, and JSONB distinguishes ['123'] from [123], so an existing reference may no longer match. Can we normalize values using the declared element type instead of guessing from string contents? Please add a numeric-looking string ID regression test.

} catch (error) {
values = [values];
}
}
if (!Array.isArray(values)) { values = [values]; }

const itemType = propertyDefinition.type[0];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This path assumes propertyDefinition.type is an array and propertyDefinition.postgresql exists. A model array property does not necessarily declare PostgreSQL-specific metadata, so the later .dataType access can throw a TypeError rather than handling the filter deliberately. Can we validate the supported property types/storage mappings and return a clear error or supported fallback?

const postgresTypeMap = new Map([
[Number, 'INTEGER'],
[String, 'TEXT'],
]);
const arrayItemType = postgresTypeMap.get(itemType);

if (!arrayItemType) {
throw new Error(`Unsupported array item type: ${itemType ? itemType.name : 'unknown'}`);
}
const isArray = propertyDefinition.postgresql.dataType === 'ARRAY';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This native-array detection looks incorrect. The connector already supports native PostgreSQL mappings such as varchar[] (see toColumnValue()), but dataType === 'ARRAY' would not recognize them. They would instead be sent through the JSONB branch, generating an incompatible @> operand type. Can we distinguish actual native array types from JSONB columns and reuse the existing array operators (including containsAnyOf for overlap) where appropriate? Please add native-array execution tests.

const conditions = [];
const params = [];

values.forEach(value => {
if (isArray) {
conditions.push(`${columnName} @> ARRAY[?]::${arrayItemType}[]`);
params.push(value);
} else {
conditions.push(`${columnName} @> CAST(? AS JSONB)`);
params.push(JSON.stringify([value]));
}
});
return new ParameterizedSQL(`(${conditions.join(' OR ')})`, params);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For jsonContains: [], conditions stays empty and this returns (), which is invalid SQL. Empty candidate lists can occur in dynamically generated inq filters. Please define explicit empty-input behavior (typically a false predicate for match-any) and test it.

default:
// invoke the base implementation of `buildExpression`
return this.invokeSuper('buildExpression', columnName, operator,
Expand Down
85 changes: 85 additions & 0 deletions test/postgresql.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,91 @@ describe('postgresql connector', function() {
done();
});
});

context('jsonContains operator', function() {
let ItemWithJson, ItemWithIntegerArray, ItemWithStringArray;

before(function(done) {
db = global.getDataSource();
// Define a test model utilizing a jsonb column type to test JSON containment filters.
ItemWithJson = db.define('ItemWithJson', {
name: {type: String},
tags: {
type: [String],
postgresql: {
dataType: 'jsonb',
},
},
});
ItemWithIntegerArray = db.define('ItemWithIntegerArray', {
name: {type: String},
tags: {
type: [Number],
postgresql: {
dataType: 'jsonb',
},
},
});
ItemWithStringArray = db.define('ItemWithStringArray', {
name: {type: String},
tags: {
type: [String],
postgresql: {
dataType: 'jsonb',
},
},
});
db.automigrate(['ItemWithJson', 'ItemWithIntegerArray', 'ItemWithStringArray'], done);
});

beforeEach(function(done) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The added tests inspect buildWhere() output but do not persist records and execute a find() against PostgreSQL, so they cannot catch type/cast failures or incorrect results. Please add data-backed cases for JSONB, native arrays, multiple candidates, numeric-looking string IDs, empty inputs, and the actual referencesMany flow. Also, this hook only waits for the final destroyAll(done); the preceding two destroyAll() calls are unawaited and may overlap with subsequent tests. Could we await all three operations?

ItemWithJson.destroyAll();
ItemWithIntegerArray.destroyAll();
ItemWithStringArray.destroyAll(done);
});

after(function(done) {
ItemWithJson.destroyAll();
ItemWithIntegerArray.destroyAll();
ItemWithStringArray.destroyAll(done);
});

it('should support unit-level SQL building verification for jsonContains', function() {
const where = db.connector.buildWhere(
'ItemWithJson',
{tags: {jsonContains: ['bar', 'foo']}},
);

where.toJSON().should.eql({
sql: 'WHERE ("tags" @> CAST(? AS JSONB) OR "tags" @> CAST(? AS JSONB))',
params: ['["bar"]', '["foo"]'],
});
});

it('should support unit-level SQL building verification for jsonContains with integer array', function() {
const where = db.connector.buildWhere(
'ItemWithIntegerArray',
{tags: {jsonContains: [1, 2]}},
);

where.toJSON().should.eql({
sql: 'WHERE ("tags" @> CAST(? AS JSONB) OR "tags" @> CAST(? AS JSONB))',
params: ['[1]', '[2]'],
});
});

it('should support unit-level SQL building verification for jsonContains with string array', function() {
const where = db.connector.buildWhere(
'ItemWithStringArray',
{tags: {jsonContains: ['bar', 'foo']}},
);

where.toJSON().should.eql({
sql: 'WHERE ("tags" @> CAST(? AS JSONB) OR "tags" @> CAST(? AS JSONB))',
params: ['["bar"]', '["foo"]'],
});
});
});
});

describe('Serial properties', function() {
Expand Down
Loading