Skip to content

Commit

Permalink
Support string json in json values (#4988)
Browse files Browse the repository at this point in the history
  • Loading branch information
OlivierCavadenti committed Jan 31, 2022
1 parent f9f6a38 commit 2986f8c
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/query/querycompiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -1076,10 +1076,14 @@ class QueryCompiler {
}

_jsonWrapValue(jsonValue) {
if (this.builder._isJsonObject(jsonValue)) {
return JSON.stringify(jsonValue);
if (!this.builder._isJsonObject(jsonValue)) {
try {
return JSON.stringify(JSON.parse(jsonValue.replace(/\n|\t/g, '')));
} catch (e) {
return jsonValue;
}
}
return jsonValue;
return JSON.stringify(jsonValue);
}

_jsonValueClause(statement) {
Expand Down
34 changes: 34 additions & 0 deletions test/integration2/query/select/where.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,22 @@ describe('Where', function () {
});
});

it('where json object with string object', async () => {
const result = await knex('cities')
.select('name')
.whereJsonObject(
'descriptions',
`{
"type": "bigcity",
"short": "beautiful city",
"long": "beautiful and dirty city"
}`
);
expect(result[0]).to.eql({
name: 'Paris',
});
});

it('where not json object', async () => {
const result = await knex('cities')
.select('name')
Expand Down Expand Up @@ -708,6 +724,24 @@ describe('Where', function () {
]);
});

it('where json superset of with string', async function () {
if (!(isPostgreSQL(knex) || isMysql(knex))) {
this.skip();
}
const result = await knex('cities')
.select('name')
.whereJsonSupersetOf('descriptions', '{"type": "bigcity"}');
expect(result.length).to.equal(2);
assertJsonEquals(result, [
{
name: 'Paris',
},
{
name: 'Milan',
},
]);
});

it('where json subset of', async function () {
if (!(isPostgreSQL(knex) || isMysql(knex))) {
this.skip();
Expand Down
20 changes: 20 additions & 0 deletions test/unit/query/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -10924,6 +10924,26 @@ describe('QueryBuilder', () => {
);
});

it('where a json column is a superset of value', async function () {
testsql(
qb().select().from('users').whereJsonSupersetOf('address', 'test'),
{
pg: {
sql: 'select * from "users" where "address" @> ?',
bindings: ['test'],
},
mysql: {
sql: 'select * from `users` where json_contains(`address`,?)',
bindings: ['test'],
},
cockroachdb: {
sql: 'select * from "users" where "address" @> ?',
bindings: ['test'],
},
}
);
});

it('where a json column is not a superset of value', async function () {
testsql(
qb()
Expand Down

0 comments on commit 2986f8c

Please sign in to comment.