Skip to content

Commit

Permalink
feat(query-builder): allow passing raw query bindings via qb.raw()
Browse files Browse the repository at this point in the history
Closes #1654
  • Loading branch information
B4nan committed Apr 9, 2021
1 parent 1d7c123 commit aa423a5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
6 changes: 3 additions & 3 deletions packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QueryBuilder as KnexQueryBuilder, Raw, Transaction, Value } from 'knex';
import { QueryBuilder as KnexQueryBuilder, Raw, RawBinding, Transaction, Value, ValueDict } from 'knex';
import {
AnyEntity,
Dictionary,
Expand Down Expand Up @@ -258,8 +258,8 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
return this.knex.ref(field);
}

raw(sql: string): Raw {
const raw = this.knex.raw(sql);
raw(sql: string, bindings: RawBinding[] | ValueDict = []): Raw {
const raw = this.knex.raw(sql, bindings);
(raw as Dictionary).__raw = true; // tag it as there is now way to check via `instanceof`

return raw;
Expand Down
12 changes: 9 additions & 3 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1176,10 +1176,16 @@ describe('QueryBuilder', () => {

test('update query with JSON type and raw value', async () => {
const qb = orm.em.createQueryBuilder(Book2);
const raw = qb.raw(`jsonb_set(payload, '$.{consumed}', 123)`);
const raw = qb.raw(`jsonb_set(payload, '$.{consumed}', ?)`, [123]);
qb.update({ meta: raw }).where({ uuid: '456' });
expect(qb.getQuery()).toEqual('update `book2` set `meta` = jsonb_set(payload, \'$.{consumed}\', 123) where `uuid_pk` = ?');
expect(qb.getParams()).toEqual(['456']);
expect(qb.getFormattedQuery()).toEqual('update `book2` set `meta` = jsonb_set(payload, \'$.{consumed}\', 123) where `uuid_pk` = \'456\'');
});

test('qb.raw() with named bindings', async () => {
const qb = orm.em.createQueryBuilder(Book2);
const raw = qb.raw(`jsonb_set(payload, '$.{consumed}', :val)`, { val: 123 });
qb.update({ meta: raw }).where({ uuid: '456' });
expect(qb.getFormattedQuery()).toEqual('update `book2` set `meta` = jsonb_set(payload, \'$.{consumed}\', 123) where `uuid_pk` = \'456\'');
});

test('update query with auto-joining', async () => {
Expand Down

0 comments on commit aa423a5

Please sign in to comment.