Invalid usage of operation "next" in the FETCH statement
bmitchinson opened this issue · comments
Hello, would appreciate any debugging advice, apologies in advance if I've missed something.
I'm running the following knex query:
getPrompts(companyId: number, currentPage: number, pageSize: number) {
const knex = this.databaseService.getConnection()
return knex("prompts")
.where("company_id", companyId)
.paginate<Prompt[]>({
currentPage: currentPage,
perPage: pageSize,
isLengthAware: true
})
}
And calling getPrompts
with getPrompts(1, 2, 2)
results in the query:
select * from [prompts] where [company_id] = ? offset ? rows fetch next ? rows only trx3
Which throws the knex error: [ExceptionsHandler] select * from [prompts] where [company_id] = @p0 offset @p1 rows fetch next @p2 rows only - Invalid usage of the option next in the FETCH statement.
Is there something happening wrong syntax wise in the query builder? Not sure why the next option is used. I'm using a mysql database connection.
Additionally:
This is similar to trying to extend a .paginate
off of an existing lookup method. I've noticed you have a "getById" method in your test, but it's not referenced anywhere. Maybe after solving this I could write a PR that tests for this?
Solution within 5 minutes of posting 😅
Adding a .orderBy("id")
before the .pagination
call fixed the issue, why is that?
To reiterate, using a method like this worked instead:
getPrompts(companyId: number, currentPage: number, pageSize: number) {
const knex = this.databaseService.getConnection();
return knex('prompts').where('company_id', companyId).orderBy('id').paginate<Prompt[]>({
currentPage: currentPage,
perPage: pageSize,
isLengthAware: true,
});
}
Hi,
I'm not sure how your error is related to the lib...
What kind of DB are you using? Looks like your DB is throwing when there is a usage of offset
without order.
To verify this, please try to run
await knex('prompts').where('company_id', companyId).offset(1);
Yeah, this failed, due to not having an order! Thanks for clarity on this. I'm using a MSSQL DB.