You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is more a question than an issue, but how can I build a CTE (with) with TypeORM ? Is there a built in feature to do this, or should I use the raw sql query builder ?
Thanks.
Reacted by Daniel Luz, Chris Marx, ejose19, Glen, Michał Wadas, patryk-sienkiewicz-bi, Martin Hasoň, Matt, Juraj Mäsiar, generalpiston and 17 more
Sorry but I can't imagine how this can be integrated into typeorm's query builder semantics. TypeORM's QueryBuilder purpose is to select some model and return it. Can you create a feature proposal on how this can be implemented in our QueryBuilder and how it will work.
I have a use case where a with CTE would be useful and I think it could work with the existing API. What I'm trying to do is get a list of items by ids and return the results in the order of the ids. The following raw query works with postgres 9.6+.
with x (id_list) as (
values (array[42,48,43])
)
select c.*from comments c, x
where id = any (x.id_list)
order by array_position(x.id_list, c.id);
However I'd ideally want to avoid using raw queries due to the lack of type-safety and the difficulty in mapping the results back to entities. What I'd like to do is to use an API similar to below.
However I'd like not to send the array of ids twice especially if there is a large number of them. A possible API for with could be similar to Knex and be with(alias: string, query: ((qb: this) => string) | string): this. Some other examples from Knex would be written as:
Knex
knex.with('with_alias',knex.raw('select * from "books" where "author" = ?','Test')).select('*').from('with_alias')
TypeORM
constbooks=awaitgetRepository(Book).createQueryBuilder().with('with_alias','select * from "books" where "author" = :author').select().from('with_alias').setParameter('author','Test').getMany();
Can we have a querybuilder that takes at a top level, any WITHs and then an array of UNION or UNION ALL subqueries? That can be a SuperSelectQueryBuilder that has like with, addWith, union, addUnion or similar. Then redesign SelecQueryBuilder to take a scopeIndex parameter, such that the param names become (in mssql for example) @<scopeIndex>_<paramIndex>. Then we have a model that includes a way to combine multiple queries and their parameters as UNION or UNION ALL, plus the WITHs. Having SelectQueryBuilder not aware that its parameters need to be scoped is too limiting. Thanks.
For that matter, scopes could be recursive, if necessary. So SelectQueryBuilder takes an array of scope indexes when it produces the actual SQL and parameters. This would be great, since it would mean that params in subqueries wouldn't have to be registered manually in the parent query. Just use nested scopes to produce the actual parameter names. Visitor pattern.
To make it work properly with native TypeORM's queryBuilder for all methods (which may call getQuery deeply nested) i found out that it is necessary to patch it. Also, in order to make commonTableExpressions be encapsulated separately for each specific query, it is necessary to patch QueryExpressionMap.
Note Since [email protected] it is already implemented ability to use CTE, still for other versions this will be useful.
So the solution which works for me for all native methods such as getManyAndCount etc:
// patchTypeOrmQueryBuilderAddCommonTableExpressionsSupport.tsimport{SelectQueryBuilder,UpdateQueryBuilder,DeleteQueryBuilder,InsertQueryBuilder,RelationQueryBuilder}from'typeorm';import{QueryExpressionMap}from'typeorm/query-builder/QueryExpressionMap';exportfunctionpatchTypeOrmQueryBuilderAddCommonTableExpressionsSupport(queryBuilder: OptionableQueryBuilder=require('typeorm').SelectQueryBuilder,): void{constqueryExpressionMap: typeofQueryExpressionMap=require('typeorm/query-builder/QueryExpressionMap').QueryExpressionMap;constqueryExpressionMapPrototype=queryExpressionMap.prototype;constoriginalClone=queryExpressionMapPrototype.clone;constqbPrototype=queryBuilder.prototype;constoriginalGetQuery=qbPrototype.getQuery;Object.defineProperty(queryExpressionMapPrototype,'clone',{value: functionclone(){constcontext=thisasQueryExpressionMap;// For typization onlyconstresult=originalClone.call(context);result.commonTableExpressions={ ...context.commonTableExpressions};returnresult;},});Object.defineProperty(qbPrototype,'getQuery',{value: functiongetQuery(): string{constcontext=thisasSelectQueryBuilder<unknown>;// For typization onlyconstctes=Object.entries(context.expressionMap.commonTableExpressions??{});if(ctes.length&&!context.expressionMap.subQuery){return['WITH',ctes.map(([name,expression])=>`${context.escape(name)} AS (${expression})`).join(', '),originalGetQuery.call(context),].join(' ');}returnoriginalGetQuery.call(context);},});Object.defineProperty(qbPrototype,'addCommonTableExpression',{value: functionaddCommonTableExpression<T>(expression: CommonTableExpression<T>,name: string){constcontext=thisasSelectQueryBuilder<unknown>;// For typization onlyif(!context.expressionMap.commonTableExpressions)context.expressionMap.commonTableExpressions={};if(typeofexpression==='function'){constsubQueryBuilder=expression(context.subQuery());context.setParameters(subQueryBuilder.getParameters());context.expressionMap.commonTableExpressions[name]=subQueryBuilder.getQuery();}else{context.expressionMap.commonTableExpressions[name]=expression;}returncontext;},});}typeOptionableQueryBuilder=typeofSelectQueryBuilder|typeofUpdateQueryBuilder|typeofDeleteQueryBuilder|typeofInsertQueryBuilder|typeofRelationQueryBuilder;typeCommonTableExpression<T>=string|((qb: SelectQueryBuilder<T>)=>SelectQueryBuilder<T>);exportinterfaceIQueryBuilderWithCommonTableExpressions<Entity>{addCommonTableExpression<T=Entity>(expression: CommonTableExpression<T>,name: string): this;getQuery(): string;}declare module 'typeorm'{exportinterfaceSelectQueryBuilder<Entity>extendsIQueryBuilderWithCommonTableExpressions<Entity>{}}declare module 'typeorm/query-builder/QueryExpressionMap'{exportinterfaceQueryExpressionMap{commonTableExpressions: Record<string,string>;}}
Usage
call patchTypeOrmQueryBuilderAddCommonTableExpressionsSupport some where at application startUp, to fully patch TypeORM's SelectQueryBuilder.
patchTypeOrmQueryBuilderAddCommonTableExpressionsSupport();// This will patch SelectQueryBuilder as default
Use someWhere/at/some/repository.ts
qb.addCommonTableExpression(`SELECT * FROM some_table`,'some_cte').addSelect(/* ... */)
Activity
pleerock commentedon Oct 30, 2017
Hi, no, there is no, you probably need to execute raw sql query using
querymethod. But if orm would have such functionality, how do you see it there?sylvainlap commentedon Oct 31, 2017
Knex, for example, allows to build CTE thanks to
.with(): http://knexjs.org/#Builder-withpleerock commentedon Nov 1, 2017
Sorry but I can't imagine how this can be integrated into typeorm's query builder semantics. TypeORM's QueryBuilder purpose is to select some model and return it. Can you create a feature proposal on how this can be implemented in our QueryBuilder and how it will work.
pleerock commentedon Nov 20, 2017
@sylvainlap did you have a chance to take a look on this issue deeply?
sylvainlap commentedon Nov 20, 2017
Actually, it was more a question than a feature request. I can close the issue.
jtmthf commentedon Nov 29, 2017
I have a use case where a
withCTE would be useful and I think it could work with the existing API. What I'm trying to do is get a list of items by ids and return the results in the order of the ids. The following raw query works with postgres 9.6+.However I'd ideally want to avoid using raw queries due to the lack of type-safety and the difficulty in mapping the results back to entities. What I'd like to do is to use an API similar to below.
Understandably this is also possible with the following simpler query builder expression:
However I'd like not to send the array of ids twice especially if there is a large number of them. A possible API for
withcould be similar to Knex and bewith(alias: string, query: ((qb: this) => string) | string): this. Some other examples from Knex would be written as:Knex
TypeORM
Knex
TypeORM
12 remaining items
dustin-rcg commentedon Jan 30, 2021
Can we have a querybuilder that takes at a top level, any
WITHs and then an array ofUNIONorUNION ALLsubqueries? That can be a SuperSelectQueryBuilder that has likewith,addWith,union,addUnionor similar. Then redesign SelecQueryBuilder to take ascopeIndexparameter, such that the param names become (in mssql for example)@<scopeIndex>_<paramIndex>. Then we have a model that includes a way to combine multiple queries and their parameters as UNION or UNION ALL, plus the WITHs. Having SelectQueryBuilder not aware that its parameters need to be scoped is too limiting. Thanks.For that matter, scopes could be recursive, if necessary. So SelectQueryBuilder takes an array of scope indexes when it produces the actual SQL and parameters. This would be great, since it would mean that params in subqueries wouldn't have to be registered manually in the parent query. Just use nested scopes to produce the actual parameter names. Visitor pattern.
dustin-rcg commentedon May 19, 2021
Here's an implementation I have working. Subclassing SelectQueryBuilder works fine it seems.
feat: support for Common Table Expressions (#8534)
timfrans commentedon Apr 6, 2022
@Ginden
Are there any plans to make this available for 0.2.x versions?
Ginden commentedon Apr 6, 2022
@timfrans No.
mopcweb commentedon Apr 21, 2022
@dustin-rcg thx so much for your approach.
To make it work properly with native TypeORM's queryBuilder for all methods (which may call
getQuerydeeply nested) i found out that it is necessary to patch it. Also, in order to makecommonTableExpressionsbe encapsulated separately for each specific query, it is necessary to patch QueryExpressionMap.Note Since
[email protected]it is already implemented ability to use CTE, still for other versions this will be useful.So the solution which works for me for all native methods such as
getManyAndCountetc:Usage
call
patchTypeOrmQueryBuilderAddCommonTableExpressionsSupportsome where at application startUp, to fully patch TypeORM's SelectQueryBuilder.Use someWhere/at/some/repository.ts
mopcweb commentedon Apr 21, 2022
@timfrans u could try to use solution above
67726e commentedon Nov 11, 2022
@mopcweb What version is this meant to work against? I've tried on
0.2.xand0.3.xand in all cases it results in an error.ab958 commentedon Sep 19, 2023
any update on that?
Ginden commentedon Sep 19, 2023
https://typeorm.io/select-query-builder#common-table-expressions
revskill10 commentedon Feb 21, 2024
@Ginden How do we know if it supports a driver ?
I'm using SQL server.
Ginden commentedon Feb 21, 2024
@revskill10 SQL Server is partially supported - https://github.com/typeorm/typeorm/blob/master/src/driver/sqlserver/SqlServerDriver.ts#L239
I wasn't able to implement writable CTEs, because of issues with non-standard OUTPUT clause.