Skip to content

Commit

Permalink
feat(sql): add qb.raw() to allow using raw snippets in QB
Browse files Browse the repository at this point in the history
Allows to do things like `qb.update({ price: qb.raw('price + 1') }).where({ uuid: '123' });`.

Related: #598
  • Loading branch information
B4nan committed Aug 9, 2020
1 parent 47f899e commit c09a5b6
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 1 deletion.
13 changes: 13 additions & 0 deletions docs/docs/query-builder.md
Expand Up @@ -280,6 +280,18 @@ console.log(qb4.getQuery());
// select `a`.* from `author2` as `a` where (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) = ?
```

## Referring to column in update queries

You can use `qb.raw()` to insert raw SQL snippets like this:

```typescript
const qb = orm.em.createQueryBuilder(Book);
qb.update({ price: qb.raw('price + 1') }).where({ uuid: '123' });

console.log(qb.getQuery());
// update `book` set `price` = price + 1 where `uuid_pk` = ?
```

## Locking support

```typescript
Expand Down Expand Up @@ -318,5 +330,6 @@ qb.getSingleResult<T>(): T;
qb.setLockMode(mode: LockMode): QueryBuilder;
qb.getQuery(): string;
qb.getParams(): any[];
qb.raw(sql): Raw;
qb.clone(): QueryBuilder;
```
4 changes: 4 additions & 0 deletions packages/knex/src/query/QueryBuilder.ts
Expand Up @@ -182,6 +182,10 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {
return this.knex.ref(field);
}

raw(sql: string): Raw {
return this.knex.raw(sql);
}

limit(limit?: number, offset = 0): this {
this._limit = limit;

Expand Down
2 changes: 1 addition & 1 deletion packages/knex/src/query/QueryBuilderHelper.ts
Expand Up @@ -70,7 +70,7 @@ export class QueryBuilderHelper {
return;
}

if (!prop.customType && (Array.isArray(data[k]) || Utils.isObject(data[k], [Date]))) {
if (!prop.customType && (Array.isArray(data[k]) || Utils.isPlainObject(data[k]))) {
data[k] = JSON.stringify(data[k]);
}

Expand Down
7 changes: 7 additions & 0 deletions tests/QueryBuilder.test.ts
Expand Up @@ -1062,6 +1062,13 @@ describe('QueryBuilder', () => {
expect(qb.getParams()).toEqual(['test 123', PublisherType.GLOBAL, 123, PublisherType.LOCAL]);
});

test('update query with column reference', async () => {
const qb = orm.em.createQueryBuilder(Book2);
qb.update({ price: qb.raw('price + 1') }).where({ uuid: '123' });
expect(qb.getQuery()).toEqual('update `book2` set `price` = price + 1 where `uuid_pk` = ?');
expect(qb.getParams()).toEqual(['123']);
});

test('update query with auto-joining', async () => {
const qb = orm.em.createQueryBuilder(Publisher2);
qb.update({ name: 'test 123', type: PublisherType.GLOBAL }).where({ books: { author: 123 } });
Expand Down

0 comments on commit c09a5b6

Please sign in to comment.