From e1a6bcbd42b6473ba06e9b7db5b32c252a6426ff Mon Sep 17 00:00:00 2001 From: Stanislav Mishchyshyn Date: Mon, 12 Aug 2024 19:30:31 +0300 Subject: [PATCH] fix(ilc-registry/server): optimize versioning query --- registry/server/db/versioning.ts | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/registry/server/db/versioning.ts b/registry/server/db/versioning.ts index 038877d1..e56b1a9a 100644 --- a/registry/server/db/versioning.ts +++ b/registry/server/db/versioning.ts @@ -38,13 +38,20 @@ export interface VersionedKnex extends function selectVersionedRows(knex: VersionedKnex) { return function (table: string, key: string, entityType: EntityTypes, columns: ColumnDescriptor[]) { - const versionIdQuery = knex - .table(Tables.Versioning) - .max('id') - .as('versionId') - .where('entity_id', knex.raw(`cast(${table}.${key} as char(255))`)) - .andWhere('entity_type', entityType); - return knex.select.call(knex, columns.concat([versionIdQuery])); + return knex + .leftJoin( + knex + .select('entity_id') + .from(Tables.Versioning) + .max('id', { as: 'versionId' }) + .where({ entity_type: entityType }) + .groupBy('entity_id') + .as('v'), + 'v.entity_id', + // only such syntax works in all sqlite,mysql,postgresql + knex.raw(`CAST(${table}.${key} AS char(255))`), + ) + .select([...columns, 'versionId']); }; }