Skip to content

Commit

Permalink
fix(query-builder): respect preferReadReplicas in QueryBuilder
Browse files Browse the repository at this point in the history
Closes #4847
  • Loading branch information
B4nan committed Oct 21, 2023
1 parent 41425cb commit 22e140e
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
3 changes: 2 additions & 1 deletion packages/knex/src/query/QueryBuilder.ts
Expand Up @@ -640,7 +640,8 @@ export class QueryBuilder<T extends object = AnyEntity> {
return cached.data;
}

const type = this.connectionType || (method === 'run' ? 'write' : 'read');
const write = method === 'run' || !this.platform.getConfig().get('preferReadReplicas');
const type = this.connectionType || (write ? 'write' : 'read');
const res = await this.driver.getConnection(type).execute(query.sql, query.bindings as any[], method, this.context);
const meta = this.mainAlias.metadata;

Expand Down
4 changes: 2 additions & 2 deletions tests/features/read-replicas.test.ts
Expand Up @@ -143,10 +143,10 @@ describe('read-replicas', () => {
orm.em.clear();
author = (await orm.em.findOne(Author2, author))!;
await orm.em.findOne(Author2, author, { refresh: true });
await orm.em.findOne(Author2, author, { refresh: true });
await orm.em.qb(Author2).where({ id: author.id }).limit(1).execute();
expect(mock.mock.calls[4][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/);
expect(mock.mock.calls[5][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/);
expect(mock.mock.calls[6][0]).toMatch(/select `a0`\.\*, `a1`\.`author_id` as `address_author_id` from `author2` as `a0` left join `address2` as `a1` on `a0`\.`id` = `a1`\.`author_id` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/);
expect(mock.mock.calls[6][0]).toMatch(/select `a0`\.\* from `author2` as `a0` where `a0`.`id` = \? limit \?.*via write connection '127\.0\.0\.1'/);

author.name = 'Jon Blow';
await orm.em.flush();
Expand Down

0 comments on commit 22e140e

Please sign in to comment.