drizzle-graphql icon indicating copy to clipboard operation
drizzle-graphql copied to clipboard

Add aggregations?

Open anthonyhoegberg opened this issue 1 year ago • 2 comments

Hello, Thank you for your hard work. Maybe it would be a good idea to add some kind of aggregation api? https://orm.drizzle.team/docs/select#aggregations

As an example: There are times when we need to count the number of rows without actually requesting the data as well (pagination, etc) https://orm.drizzle.team/learn/guides/count-rows

Could count rows etc, be implemented with the use of the existing filters using the above? That way we can execute a query and get number of items that match it without doing a more costly operation.

anthonyhoegberg avatar Jun 14 '24 00:06 anthonyhoegberg

Row count could be done by just adding the extra field to each type and then modifying query with count(*) if it is requested (no data should be requested from DB in case you didn't select columns), expect that feature very soon. As for aggregation though, I am once again powerless because of current RQB limitations, however I'm all for it the moment RQB rolls out the required functionality.

UPD: Sorry for the unintended deception, but it turned out that row count too is not supported by current version of RQB, so we'll have to wait until V2 on yet another matter.

Sukairo-02 avatar Jun 14 '24 09:06 Sukairo-02

What if I wanted to extend a query with a related entity count? Say I have a Project entity with a relation to an Institution one, can I extend the FamilySelectItem query to include an institutionCount field?

Right now I'm doing something like this:

import { buildSchema } from 'drizzle-graphql';
import { sql } from 'drizzle-orm';

export function createGraphQLSchema(db) {
    // Get the schema from drizzle-graphql
    const drizzleResult = buildSchema(db, {
        relationsDepthLimit: 3
    });

    // Add our custom resolver to the existing ProjectSelectItem resolvers
    drizzleResult.schema._typeMap.ProjectSelectItem._fields.institutionsCount = {
        name: 'institutionsCount',
        type: drizzleResult.schema._typeMap.Int,
        resolve: async (parent) => {
            const result = await db.run(sql`SELECT COUNT(1) AS count FROM institutions WHERE project_id = ${parent.id}`);
            return Number(result.rows[0]['count'] ?? 0);
        },
        args: [],
        extensions: {},
        astNode: undefined
    };

    return { schema: drizzleResult.schema, resolvers: drizzleResult.resolvers };
} 

but this results in an initial query to get all the projects, plus a query for each project to get its related institutions. Can I somehow integrate it?

fenicento avatar Mar 05 '25 14:03 fenicento