MCPcopy Create free account
hub / github.com/zenstackhq/zenstack / buildCountJson

Function buildCountJson

packages/orm/src/client/crud/dialects/base-dialect.ts:1473–1529  ·  view source on GitHub ↗
(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any)

Source from the content-addressed store, hash-verified

1471 }
1472
1473 buildCountJson(model: string, eb: ExpressionBuilder<any, any>, parentAlias: string, payload: any) {
1474 const modelDef = requireModel(this.schema, model);
1475 const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
1476
1477 const selections =
1478 payload === true
1479 ? {
1480 select: toManyRelations.reduce(
1481 (acc, [field]) => {
1482 acc[field] = true;
1483 return acc;
1484 },
1485 {} as Record<string, boolean>,
1486 ),
1487 }
1488 : payload;
1489
1490 const jsonObject: Record<string, Expression<any>> = {};
1491
1492 for (const [field, value] of Object.entries(selections.select)) {
1493 const fieldDef = requireField(this.schema, model, field);
1494 const fieldModel = fieldDef.type as GetModels<Schema>;
1495 let fieldCountQuery: SelectQueryBuilder<any, any, any>;
1496
1497 // Use a unique alias for the subquery to avoid ambiguous references when
1498 // fieldModel === model (self-referential relation on a delegate model)
1499 const subQueryAlias = tmpAlias(`${parentAlias}$_${field}$count`);
1500
1501 // join conditions
1502 const m2m = getManyToManyRelation(this.schema, model, field);
1503 if (m2m) {
1504 // many-to-many relation, count the join table
1505 fieldCountQuery = this.buildModelSelect(fieldModel, subQueryAlias, value as any, false)
1506 .innerJoin(m2m.joinTable, (join) =>
1507 join
1508 .onRef(`${m2m.joinTable}.${m2m.otherFkName}`, '=', `${subQueryAlias}.${m2m.otherPKName}`)
1509 .onRef(`${m2m.joinTable}.${m2m.parentFkName}`, '=', `${parentAlias}.${m2m.parentPKName}`),
1510 )
1511 .select(eb.fn.countAll().as(`_count$${field}`));
1512 } else {
1513 // build a nested query to count the number of records in the relation
1514 fieldCountQuery = this.buildModelSelect(fieldModel, subQueryAlias, value as any, false).select(
1515 eb.fn.countAll().as(`_count$${field}`),
1516 );
1517
1518 // join conditions
1519 const joinPairs = buildJoinPairs(this.schema, model, parentAlias, field, subQueryAlias);
1520 for (const [left, right] of joinPairs) {
1521 fieldCountQuery = fieldCountQuery.whereRef(left, '=', right);
1522 }
1523 }
1524
1525 jsonObject[field] = fieldCountQuery;
1526 }
1527
1528 return this.buildJsonObject(jsonObject);
1529 }
1530

Callers

nothing calls this directly

Calls 6

requireModelFunction · 0.90
requireFieldFunction · 0.90
tmpAliasFunction · 0.90
getManyToManyRelationFunction · 0.90
buildJoinPairsFunction · 0.90
buildJsonObjectMethod · 0.45

Tested by

no test coverage detected