Repository navigation
Closed
Description
Hi all,
I'm getting the following error when using the QueryBuilder functionality.
[Nest] 6940 - 2017-8-8 12:14:18 [ExceptionsHandler] Cannot read property 'databaseName' of undefined
TypeError: Cannot read property 'databaseName' of undefined
at /Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1220:91
at Array.map (native)
at SelectQueryBuilder.createOrderByCombinedWithSelectExpression (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1216:14)
at SelectQueryBuilder.<anonymous> (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1130:35)
at step (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:42:23)
at Object.next (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:23:53)
at /Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:17:71
at Promise (<anonymous>)
at __awaiter (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:13:12)
at SelectQueryBuilder.executeEntitiesAndRawResults (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1106:16)
My side of the code:
1. Function that makes the query
public async getPopular(): Promise<Industry[]>{
return await (await this.repository).createQueryBuilder('industry')
.orderBy('industry.counter', 'DESC')
.take(10).getMany();
}
2. The (await this.repository) part.
private get repository(): Promise<Repository<Industry>> {
return this.databaseService.getRepository(Industry);
}
3. The database service function that picks the repository.
public async getRepository<T>(entityClassOrName: ObjectType<T> | string): Promise<Repository<T>> {
return (await this.connection).getRepository<T>(entityClassOrName);
}
It seems that the SelectQueryBuilder cannot fetch the column.databaseName (the name in the database for that column. The error seems to come from the entityMetadata section, as it didn't load the metadata correctly (or it cannot find it?).
Any thoughts would be nice. 👍
Metadata
Metadata
Assignees
Labels
No labels
Activity
popovicidinu commentedon Aug 8, 2017
After some debugging it seems there's an error with the following lines of code:
If I change that to:
findColumnWithDatabaseNameit seems to work and executes the query builder correctly.Is this is a bug in SelectQueryBuilder class, or a bug with the
findColumnwithPropertyName()function from EntityMetadata ?pleerock commentedon Aug 10, 2017
Please provide a minimal reproduction code without any boilerplate code. entity and few lines of code which reproduce this issue.
popovicidinu commentedon Aug 11, 2017
@pleerock Fixed this after testing my code again. You can close it off since this isn't a bug.
Thanks for the help and the great work!!
mentos1386 commentedon Sep 17, 2017
@popovicidinu hey, i'm having the same problem. How did you fix it?
d-bechtel commentedon Dec 4, 2017
i have the same error with this query:
let query = this.activityRepository.createQueryBuilder('activity')
.select()
.addSelect('user.email as email')
.innerJoinAndSelect('activity.user', 'user')
.skip(0)
.take(10)
.orderBy('activity.end_date', 'DESC')
.where('user.email = :email').setParameter('email', userProfile.email);
let activities = await query.getMany();
if i use .limit(10) instead of .take(10), it works, but query returns duplicates.
if i remove the orderBy clause it works, too. So i think the bug exists in combination of take and orderBy.
pleerock commentedon Dec 6, 2017
@d-bechtel I need more info, create a failing test with issue reproduction so I can take alook
RDeluxe commentedon Jul 26, 2018
I'm encountering the same issue.
I have a somewhat complex query to build (I want to be able to order by relations keys )
The SQL query is fine. But I have this error:
The generated query :
Removing the orderBy clause resolves the problem, as others said before me.
RDeluxe commentedon Jul 26, 2018
Ok, to answer my own problem:
qb = qb.addOrderBy(${qb.alias}."${k}", opt);has to be changed into
qb = qb.addOrderBy(${qb.alias}.${k}, opt);ShepelievD commentedon Sep 15, 2018
@popovicidinu @d-bechtel @mentos1386 guys, looks like you have different columns names (I had the issue), for example:
in a model you have
createdAt, but in a database it iscreated_atjnnkky commentedon Nov 19, 2018
I can confirm there is an issue here with the combination of take and orderBy. The query executes fine on the db directly but with TypeORM it fails.
Also this is not the case for me as I am already escaping my column name, which also is not all lowercase in my failing example.
benfavre commentedon Jan 11, 2019
Can you have a look a this please ?
I get
If I specify any type of orderBy
pleerock commentedon Jan 13, 2019
as @ShepelievD pointed this error usually happen when invalid names are specified. Everybody encouraged this issue should check names they are using in queries.
benfavre commentedon Jan 13, 2019
I did see that, and have been trying multiple combinations of names, ...
The error message simply isn't helpfull and debugging is painfull.
Maybe something can be done to hint on the wrong name usage ?
benfavre commentedon Mar 4, 2019
For future me, comming back to this post again, please check the spelling on the orderby column name.
1 remaining item
jtushman commentedon Mar 22, 2019
@jannikkeye did you find a work around? I also have my names escaped, and have this issue with take combined with orderBy
victordidenko commentedon Mar 25, 2019
@pleerock How about null-checking for
column, instead of doingcolumn!.databaseName? And if column is null/undefined — throw valid database exception, instead of generic TypeError?m-shev commentedon May 12, 2019
I solved this problem by removing double quotes around sort key
works:
qb.orderBy(${Table.SelectionResource}.createTime, SortOrder.DESC);error:
qb.orderBy(${Table.SelectionResource}."createTime", SortOrder.DESC);v1d3rm3 commentedon Jun 5, 2019
I get this error when i'm using
leftJoinMapSelectwithorderByin a embedded field.ahmedosama94 commentedon Aug 8, 2019
After tinkering around for a while I found that
orderByworks by providing the${alias}.${propertyName}, not the expected${alias}.${columnName}. I set up my models so that their properties are camelCase and the database tables' columns are in snake_case. I found out the hard way that theorderByfunction expects thepropertyNameinstead of thecolumnName.My specific example was as follows:
query.orderBy('conversations.created_at')throws an error.query.orderBy('conversations.createdAt')does not.Note:
This indeed only happens when using
takealongsideorderByand I can confirm that this does not happen when usinglimitinstead oftake, however,limitshould not be used when performing joins as indicated in the function's documentation.michael-golden commentedon Dec 10, 2019
I get this error when using
leftJoinMapSelectandorderBy, combined withskip()andtake()This works:
This does NOT work:
The difference being the .orderBy() lines.
I believe the issue stems from the sort string referencing an alias.
Version: 0.2.19
antowkabond commentedon Oct 27, 2020
I have the same issues.
As for me, it helps
In QueryBuilder use
qb.orderBy('categories.name', filter.orderDirection);Instead of column name from database.
qb.orderBy('categories.my_name', filter.orderDirection);hypeofpipe commentedon Nov 13, 2020
I had the same issue. The problem was that we had one private npm package exposing
typeormand anothertypeormpackage installed. I had to use only one package, that was exposing thetypeorm.Rare case, but maybe would help someone
vthanghq1 commentedon Jun 10, 2021
thanks. it works like a charm.
kmordan24 commentedon Jan 20, 2022
Thank you!!! This is it right here!! Hours of tinkering and searching threads, and all I had to do was change my
orderByto either:orderBy('table_name:columnName')orI tried both
orderBy('table_name.column_name'andorderBy('table_name_column_name')and it failed to add the columns to the DISTINCT clause so it would give a SQL syntax error or the ORDERBY would always fail because the column was not part of the DISTINCT column set.It appears this bug has existed for years now... the TypeORM docs could at least have a note added about this specific case and the required naming pattern workaround until a fix is complete (which might be a while judging from other thread responses indicating the complexity and required testing).
Razzwan commentedon May 15, 2023
But still problem with error message. Not
databaseNameis wrong, butcolumnNameGrizley56 commentedon Jan 28, 2024
In cases when you want to add custom orderBy logic to your query, and still be able to use .take() in the query, then you can write
for example:
instead of
Niklas-Mezynski commentedon Jan 30, 2024
Can confirm what @Grizley56 said.
If you have any custom logic in your order by, the aliasing mechanism seems to fail. In my case I had a boolean check to filter some fields to come first.
As workaround, I have changed this:
to this:
crazyoptimist commentedon Sep 3, 2024
Thank you @michael-golden for the investigation. This is very stupid thing(or maybe a bug?) that is not documented properly. Not fixed to date as of Sep 2024.
mengtongun commentedon Sep 25, 2024
Thanks it work and solve my current problem.