diff --git a/lib/query/method-constants.js b/lib/query/method-constants.js index 2b939d5b3e..ab637c8931 100644 --- a/lib/query/method-constants.js +++ b/lib/query/method-constants.js @@ -9,6 +9,7 @@ module.exports = [ 'column', 'from', 'fromJS', + 'fromRaw', 'into', 'withSchema', 'table', diff --git a/lib/query/querybuilder.js b/lib/query/querybuilder.js index 317379001c..ee05a4af1b 100644 --- a/lib/query/querybuilder.js +++ b/lib/query/querybuilder.js @@ -1266,6 +1266,11 @@ class Builder extends EventEmitter { return this; } + fromRaw(sql, bindings) { + const raw = sql.isRawInstance ? sql : this.client.raw(sql, bindings); + return this.from(raw); + } + // Passes query to provided callback function, useful for e.g. composing // domain-specific helpers modify(callback) { diff --git a/test/unit/query/builder.js b/test/unit/query/builder.js index 99655e9500..abe7c34bed 100644 --- a/test/unit/query/builder.js +++ b/test/unit/query/builder.js @@ -8421,6 +8421,15 @@ describe('QueryBuilder', () => { ); }); + it('uses fromRaw api, #1767', () => { + testsql(qb().select('*').fromRaw('(select * from users where age > 18)'), { + mysql: 'select * from (select * from users where age > 18)', + mssql: 'select * from (select * from users where age > 18)', + pg: 'select * from (select * from users where age > 18)', + 'pg-redshift': 'select * from (select * from users where age > 18)', + }); + }); + it('has a modify method which accepts a function that can modify the query', () => { // arbitrary number of arguments can be passed to `.modify(queryBuilder, ...)`, // builder is bound to `this` diff --git a/types/index.d.ts b/types/index.d.ts index a726ed3fcf..bb32ecd972 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -491,6 +491,7 @@ export declare namespace Knex { column: Select; hintComment: HintComment; from: Table; + fromRaw: Table; into: Table; table: Table; distinct: Distinct;