Commit02aa828
fix(db): cast every selected count() to ::int — bigint arrives as a string
fix(db): cast every selected count() to ::int — bigint arrives as a string Postgres count() returns bigint and the driver hands it back as a STRING. Drizzle's `sql<number>` is a compile-time cast only, so `sql<number>`count(*)`` yields "0", not 0. Every consumer comparing with === or doing arithmetic was silently wrong. The codebase already used `count(*)::int` at 100+ sites; these were the stragglers. Reached-and-broken paths this fixes: - onboarding.tsx: `repoCount === 0` was "0" === 0 → false, so the entire first-run branch was unreachable and a brand-new user never saw the getting-started flow. - notifications.tsx: `unreadCount === 0` likewise, so "You are all caught up" could never render. - inbox.tsx: GET /api/inbox/count returned a JSON string, diverging from /api/notifications/count which returns a number. - pulls.tsx / issues.tsx: the open/draft/closed/merged tab counters. Note 8102dd4 fixed the "0"+"0"+"0" = "000" rendering in this same file but left these four `count(*) filter (...)` aggregates uncast. - gists.tsx, projects.tsx: per-row file/star/column/item counts via scalar subqueries. - health-score.ts, merge-queue.ts, notify.ts, orgs.tsx. The regression test is deliberately broader than the reported sites: it flags any `sql<number>` wrapping count()/sum() without a cast. That is what caught the 13 additional instances above — `count(*) filter (...)` and `(SELECT count(*) ...)` shapes that a search for bare `count(*)` misses. ORDER BY aggregates are left uncast on purpose: sorting on bigint is correct, and only selected values cross into JS. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
12 files changed+124−2602aa828ce1861de20224c2b16ba4bdfe78e44996
12 changed files+124−26
Addedsrc/__tests__/count-bigint.test.ts+98−0View fileUnifiedSplit
@@ -0,0 +1,98 @@
1/**
2 * Postgres count() returns bigint, which the driver hands back as a STRING.
3 *
4 * Drizzle's `sql<number>` is a compile-time cast only — it does not coerce at
5 * runtime — so `sql<number>`count(*)`` yields "0", not 0. Every consumer that
6 * compared with === or did arithmetic was silently broken:
7 *
8 * - onboarding.tsx: `repoCount === 0` is "0" === 0 → false, so the entire
9 * first-run branch was unreachable and brand-new users never saw the
10 * getting-started flow.
11 * - notifications.tsx: `unreadCount === 0` → the "You are all caught up"
12 * state could never render.
13 * - inbox.tsx: GET /api/inbox/count returned a JSON string, diverging from
14 * /api/notifications/count which returns a number.
15 * - pulls.tsx previously rendered "0"+"0"+"0" as "000" (fixed earlier).
16 *
17 * The established fix in this codebase is `count(*)::int` — already used at
18 * 100+ sites. These stragglers are now consistent with it.
19 */
20
21import { describe, expect, it } from "bun:test";
22import { readdirSync, readFileSync, statSync } from "fs";
23import { join } from "path";
24
25function walk(dir: string): string[] {
26 const out: string[] = [];
27 for (const e of readdirSync(dir)) {
28 const p = join(dir, e);
29 if (statSync(p).isDirectory()) {
30 if (e === "__tests__") continue;
31 out.push(...walk(p));
32 } else if (e.endsWith(".ts") || e.endsWith(".tsx")) out.push(p);
33 }
34 return out;
35}
36
37const FILES = walk("src");
38
39describe("no uncast bigint aggregates typed as number", () => {
40 it("every sql<number>count(*) casts to ::int", () => {
41 const offenders: string[] = [];
42 for (const f of FILES) {
43 const src = readFileSync(f, "utf8");
44 src.split("\n").forEach((line, i) => {
45 // Typed as number but no cast — the exact bug shape.
46 if (/sql<number>`\s*count\(\*\)\s*`/.test(line)) {
47 offenders.push(`${f.replace(/\\/g, "/")}:${i + 1}`);
48 }
49 });
50 }
51 expect(offenders).toEqual([]);
52 });
53
54 it("no sql<number> wraps count()/sum() of a column without a cast either", () => {
55 const offenders: string[] = [];
56 for (const f of FILES) {
57 const src = readFileSync(f, "utf8");
58 src.split("\n").forEach((line, i) => {
59 const m = line.match(/sql<number>`([^`]*)`/);
60 if (!m) return;
61 const expr = m[1];
62 if (!/\b(count|sum)\s*\(/i.test(expr)) return;
63 if (expr.includes("::")) return; // cast present
64 offenders.push(`${f.replace(/\\/g, "/")}:${i + 1} → ${expr.trim()}`);
65 });
66 }
67 expect(offenders).toEqual([]);
68 });
69});
70
71describe("the specific consumers that were broken", () => {
72 it("onboarding's first-run branch can now be reached", () => {
73 const src = readFileSync("src/routes/onboarding.tsx", "utf8");
74 expect(src).toContain("count(*)::int");
75 // The comparison itself is fine once the value is a real number.
76 expect(src).toContain("repoCount === 0");
77 });
78
79 it("notifications' all-caught-up branch can now be reached", () => {
80 const src = readFileSync("src/routes/notifications.tsx", "utf8");
81 expect(src).toContain("count(*)::int");
82 expect(src).toContain("unreadCount === 0");
83 });
84
85 it("inbox's count endpoint returns a number", () => {
86 const src = readFileSync("src/routes/inbox.tsx", "utf8");
87 expect(src).toContain("count(*)::int");
88 });
89});
90
91describe("ORDER BY aggregates are deliberately left alone", () => {
92 it("bare sql`count(*)` in an orderBy is not flagged", () => {
93 // Sorting on bigint is correct; only *selected* values reach JS and need
94 // the cast. Keeping these uncast avoids churn with no behaviour change.
95 const pulls = readFileSync("src/routes/pulls.tsx", "utf8");
96 expect(pulls).toContain("desc(sql`count(*)`)");
97 });
98});
Modifiedsrc/lib/health-score.ts+1−1View fileUnifiedSplit
@@ -41,7 +41,7 @@ export async function computeHealthScore(repoId: string): Promise<HealthScore> {
4141 db
4242 .select({
4343 total: count(),
44 passed: sql<number>`count(*) filter (where ${gateRuns.status} in ('passed','repaired'))`,
44 passed: sql<number>`(count(*) filter (where ${gateRuns.status} in ('passed','repaired')))::int`,
4545 })
4646 .from(gateRuns)
4747 .where(and(eq(gateRuns.repositoryId, repoId), gte(gateRuns.createdAt, since30d)))
Modifiedsrc/lib/merge-queue.ts+1−1View fileUnifiedSplit
@@ -247,7 +247,7 @@ export async function queueDepth(
247247): Promise<number> {
248248 try {
249249 const rows = await db
250 .select({ n: sql<number>`COUNT(*)` })
250 .select({ n: sql<number>`COUNT(*)::int` })
251251 .from(mergeQueueEntries)
252252 .where(
253253 and(
Modifiedsrc/lib/notify.ts+1−1View fileUnifiedSplit
@@ -45,7 +45,7 @@ export async function createNotification(params: {
4545export async function getUnreadCount(userId: string): Promise<number> {
4646 try {
4747 const [row] = await db
48 .select({ count: sql<number>`count(*)` })
48 .select({ count: sql<number>`count(*)::int` })
4949 .from(notificationsExt)
5050 .where(and(eq(notificationsExt.userId, userId), eq(notificationsExt.isRead, false)));
5151 return Number(row?.count ?? 0);
Modifiedsrc/routes/gists.tsx+4−4View fileUnifiedSplit
@@ -577,8 +577,8 @@ gistRoutes.get("/gists", softAuth, async (c) => {
577577 .select({
578578 g: gists,
579579 owner: { username: users.username },
580 fileCount: sql<number>`(SELECT count(*) FROM gist_files WHERE gist_id = ${gists.id})`,
581 starCount: sql<number>`(SELECT count(*) FROM gist_stars WHERE gist_id = ${gists.id})`,
580 fileCount: sql<number>`(SELECT count(*) FROM gist_files WHERE gist_id = ${gists.id})::int`,
581 starCount: sql<number>`(SELECT count(*) FROM gist_stars WHERE gist_id = ${gists.id})::int`,
582582 })
583583 .from(gists)
584584 .innerJoin(users, eq(gists.ownerId, users.id))
@@ -898,7 +898,7 @@ gistRoutes.get("/gists/:slug", softAuth, async (c) => {
898898 .where(eq(gistFiles.gistId, gist.g.id))
899899 .orderBy(gistFiles.filename);
900900 const [cnt] = await db
901 .select({ n: sql<number>`count(*)` })
901 .select({ n: sql<number>`count(*)::int` })
902902 .from(gistStars)
903903 .where(eq(gistStars.gistId, gist.g.id));
904904 starCount = Number(cnt?.n || 0);
@@ -1477,7 +1477,7 @@ gistRoutes.get("/:username/gists", softAuth, async (c) => {
14771477 rows = await db
14781478 .select({
14791479 g: gists,
1480 fileCount: sql<number>`(SELECT count(*) FROM gist_files WHERE gist_id = ${gists.id})`,
1480 fileCount: sql<number>`(SELECT count(*) FROM gist_files WHERE gist_id = ${gists.id})::int`,
14811481 })
14821482 .from(gists)
14831483 .where(
Modifiedsrc/routes/inbox.tsx+1−1View fileUnifiedSplit
@@ -859,7 +859,7 @@ async function loadAutoMergeEvents(repoIds: string[]): Promise<InboxRow[]> {
859859async function getUnreadNotifCount(userId: string): Promise<number> {
860860 try {
861861 const [r] = await db
862 .select({ count: sql<number>`count(*)` })
862 .select({ count: sql<number>`count(*)::int` })
863863 .from(notifTable)
864864 .where(and(eq(notifTable.userId, userId), eq(notifTable.isRead, false)));
865865 return r?.count ?? 0;
Modifiedsrc/routes/issues.tsx+2−2View fileUnifiedSplit
@@ -1037,8 +1037,8 @@ issueRoutes.get("/:owner/:repo/issues", softAuth, requireRepoAccess("read"), asy
10371037 // Count open/closed
10381038 const [counts] = await db
10391039 .select({
1040 open: sql<number>`count(*) filter (where ${issues.state} = 'open')`,
1041 closed: sql<number>`count(*) filter (where ${issues.state} = 'closed')`,
1040 open: sql<number>`(count(*) filter (where ${issues.state} = 'open'))::int`,
1041 closed: sql<number>`(count(*) filter (where ${issues.state} = 'closed'))::int`,
10421042 })
10431043 .from(issues)
10441044 .where(eq(issues.repositoryId, repo.id));
Modifiedsrc/routes/notifications.tsx+5−5View fileUnifiedSplit
@@ -533,21 +533,21 @@ notificationRoutes.get("/notifications", softAuth, requireAuth, async (c) => {
533533 let mentionsCount = 0;
534534 try {
535535 const [r1] = await db
536 .select({ count: sql<number>`count(*)` })
536 .select({ count: sql<number>`count(*)::int` })
537537 .from(notifications)
538538 .where(and(eq(notifications.userId, user.id), eq(notifications.isRead, false)));
539539 unreadCount = r1?.count ?? 0;
540540 } catch { /* table may not exist */ }
541541 try {
542542 const [r2] = await db
543 .select({ count: sql<number>`count(*)` })
543 .select({ count: sql<number>`count(*)::int` })
544544 .from(notifications)
545545 .where(eq(notifications.userId, user.id));
546546 totalCount = r2?.count ?? 0;
547547 } catch { /* table may not exist */ }
548548 try {
549549 const [r3] = await db
550 .select({ count: sql<number>`count(*)` })
550 .select({ count: sql<number>`count(*)::int` })
551551 .from(notifications)
552552 .where(
553553 and(
@@ -560,7 +560,7 @@ notificationRoutes.get("/notifications", softAuth, requireAuth, async (c) => {
560560 } catch { /* table may not exist */ }
561561 try {
562562 const [r4] = await db
563 .select({ count: sql<number>`count(*)` })
563 .select({ count: sql<number>`count(*)::int` })
564564 .from(notifications)
565565 .where(and(eq(notifications.userId, user.id), eq(notifications.type, "mention")));
566566 mentionsCount = r4?.count ?? 0;
@@ -794,7 +794,7 @@ notificationRoutes.get("/api/notifications/count", softAuth, async (c) => {
794794
795795 try {
796796 const [result] = await db
797 .select({ count: sql<number>`count(*)` })
797 .select({ count: sql<number>`count(*)::int` })
798798 .from(notifications)
799799 .where(and(eq(notifications.userId, user.id), eq(notifications.isRead, false)));
800800 const unread = Number(result?.count ?? 0);
Modifiedsrc/routes/onboarding.tsx+3−3View fileUnifiedSplit
@@ -462,19 +462,19 @@ const gettingStartedHandler = async (c: any) => {
462462
463463 try {
464464 const [repos] = await db
465 .select({ count: sql<number>`count(*)` })
465 .select({ count: sql<number>`count(*)::int` })
466466 .from(repositories)
467467 .where(eq(repositories.ownerId, user.id));
468468 repoCount = repos?.count ?? 0;
469469
470470 const [keys] = await db
471 .select({ count: sql<number>`count(*)` })
471 .select({ count: sql<number>`count(*)::int` })
472472 .from(sshKeys)
473473 .where(eq(sshKeys.userId, user.id));
474474 hasKeys = (keys?.count ?? 0) > 0;
475475
476476 const [tokens] = await db
477 .select({ count: sql<number>`count(*)` })
477 .select({ count: sql<number>`count(*)::int` })
478478 .from(apiTokens)
479479 .where(eq(apiTokens.userId, user.id));
480480 hasTokens = (tokens?.count ?? 0) > 0;
Modifiedsrc/routes/orgs.tsx+2−2View fileUnifiedSplit
@@ -522,7 +522,7 @@ orgRoutes.get("/orgs", softAuth, requireAuth, async (c) => {
522522 let repoCount = 0;
523523 try {
524524 const [m] = await db
525 .select({ count: sql<number>`count(*)` })
525 .select({ count: sql<number>`count(*)::int` })
526526 .from(orgMembers)
527527 .where(eq(orgMembers.orgId, r.org.id));
528528 memberCount = Number(m?.count ?? 0);
@@ -538,7 +538,7 @@ orgRoutes.get("/orgs", softAuth, requireAuth, async (c) => {
538538 .limit(1);
539539 if (u) {
540540 const [rc] = await db
541 .select({ count: sql<number>`count(*)` })
541 .select({ count: sql<number>`count(*)::int` })
542542 .from(repositories)
543543 .where(eq(repositories.ownerId, u.id));
544544 repoCount = Number(rc?.count ?? 0);
Modifiedsrc/routes/projects.tsx+2−2View fileUnifiedSplit
@@ -597,8 +597,8 @@ projectRoutes.get("/:owner/:repo/projects", softAuth, async (c) => {
597597 rows = await db
598598 .select({
599599 p: projects,
600 columnCount: sql<number>`(SELECT count(*) FROM project_columns WHERE project_id = ${projects.id})`,
601 itemCount: sql<number>`(SELECT count(*) FROM project_items WHERE project_id = ${projects.id})`,
600 columnCount: sql<number>`(SELECT count(*) FROM project_columns WHERE project_id = ${projects.id})::int`,
601 itemCount: sql<number>`(SELECT count(*) FROM project_items WHERE project_id = ${projects.id})::int`,
602602 })
603603 .from(projects)
604604 .where(eq(projects.repositoryId, repo.id))
Modifiedsrc/routes/pulls.tsx+4−4View fileUnifiedSplit
@@ -2687,10 +2687,10 @@ pulls.get("/:owner/:repo/pulls", softAuth, requireRepoAccess("read"), async (c)
26872687
26882688 const [counts] = await db
26892689 .select({
2690 open: sql<number>`count(*) filter (where ${pullRequests.state} = 'open')`,
2691 draft: sql<number>`count(*) filter (where ${pullRequests.state} = 'open' and ${pullRequests.isDraft} = true)`,
2692 closed: sql<number>`count(*) filter (where ${pullRequests.state} = 'closed')`,
2693 merged: sql<number>`count(*) filter (where ${pullRequests.state} = 'merged')`,
2690 open: sql<number>`(count(*) filter (where ${pullRequests.state} = 'open'))::int`,
2691 draft: sql<number>`(count(*) filter (where ${pullRequests.state} = 'open' and ${pullRequests.isDraft} = true))::int`,
2692 closed: sql<number>`(count(*) filter (where ${pullRequests.state} = 'closed'))::int`,
2693 merged: sql<number>`(count(*) filter (where ${pullRequests.state} = 'merged'))::int`,
26942694 })
26952695 .from(pullRequests)
26962696 .where(eq(pullRequests.repositoryId, resolved.repo.id));
26972697