PrismaP
Prisma5mo ago
6 replies
Max

Duplicate joins & offsets in count expression

Hi! I'm doing some complex count operations and the query builder is making some decisions that I do not understand.

Essentially, I'm doing this query:

prisma.table.count({
  where: {
    OR: flag1
            ? undefined
            : [
                  {
                      fKey1: id
                  },
                  {
                      foreignTable1: { // Foreign key 1 points to this table
                          parentId: id
                      }
                  }
              ],
        tenantId: user.tenantId ?? undefined,
        fKey2: flag1 ? id : undefined,
        AND:
            aPermissionsCondition
                ? [
                      {
                          OR: [
                              {foreignTable3: {visibility: Visibility.PUBLIC}},
                              {foreignTable3: {visibility: Visibility.CREATOR_ONLY, userId: user.id}},
                              {fKey3: null}
                          ]
                      }
                  ]
                : [],
        anotherProperty: {
            in: anArray
        }
  }
})


Very complex query, so I'd expect the count op to be complex, but I feel its a little un-optimized.

This generates the following SQL (flag1 = false, so it's filtering based on foreignTable1):
Was this page helpful?