From 772fdbec25d86dd001a229cadb2107248280efdb Mon Sep 17 00:00:00 2001 From: nikugogoi Date: Wed, 9 Nov 2022 13:31:26 +0530 Subject: [PATCH] Add unique entities query without checking pruned block (#218) --- packages/graph-node/src/database.ts | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/packages/graph-node/src/database.ts b/packages/graph-node/src/database.ts index 8fc9deca..a306e2f2 100644 --- a/packages/graph-node/src/database.ts +++ b/packages/graph-node/src/database.ts @@ -45,6 +45,7 @@ export enum ENTITY_QUERY_TYPE { GROUP_BY, GROUP_BY_WITHOUT_PRUNED, UNIQUE, + UNIQUE_WITHOUT_PRUNED } interface CachedEntities { @@ -381,6 +382,10 @@ export class Database { entities = await this.getEntitiesUnique(queryRunner, entity, block, where, queryOptions); break; + case ENTITY_QUERY_TYPE.UNIQUE_WITHOUT_PRUNED: + entities = await this.getEntitiesUniqueWithoutPruned(queryRunner, entity, block, where, queryOptions); + break; + case ENTITY_QUERY_TYPE.DISTINCT_ON: entities = await this.getEntitiesDistinctOn(queryRunner, entity, block, where, queryOptions); break; @@ -757,6 +762,52 @@ export class Database { return entities as Entity[]; } + async getEntitiesUniqueWithoutPruned ( + queryRunner: QueryRunner, + entity: new () => Entity, + block: BlockHeight, + where: Where = {}, + queryOptions: QueryOptions = {} + ): Promise { + const repo = queryRunner.manager.getRepository(entity); + const { tableName } = repo.metadata; + let selectQueryBuilder = repo.createQueryBuilder(tableName); + + if (block.hash) { + const { canonicalBlockNumber, blockHashes } = await this._baseDatabase.getFrothyRegion(queryRunner, block.hash); + + selectQueryBuilder = selectQueryBuilder + .andWhere(new Brackets(qb => { + qb.where(`${tableName}.block_hash IN (:...blockHashes)`, { blockHashes }) + .orWhere(`${tableName}.block_number <= :canonicalBlockNumber`, { canonicalBlockNumber }); + })); + } + + if (block.number) { + selectQueryBuilder = selectQueryBuilder.andWhere(`${tableName}.block_number <= :blockNumber`, { blockNumber: block.number }); + } + + selectQueryBuilder = this._baseDatabase.buildQuery(repo, selectQueryBuilder, where); + + if (queryOptions.orderBy) { + selectQueryBuilder = this._baseDatabase.orderQuery(repo, selectQueryBuilder, queryOptions); + } + + selectQueryBuilder = this._baseDatabase.orderQuery(repo, selectQueryBuilder, { ...queryOptions, orderBy: 'id' }); + + if (queryOptions.skip) { + selectQueryBuilder = selectQueryBuilder.offset(queryOptions.skip); + } + + if (queryOptions.limit) { + selectQueryBuilder = selectQueryBuilder.limit(queryOptions.limit); + } + + const entities = await selectQueryBuilder.getMany(); + + return entities as Entity[]; + } + async loadEntitiesRelations ( queryRunner: QueryRunner, block: BlockHeight,