Skip to content

chore(db): modernize Drizzle usage, fix query bugs, and drop redundant indexes - #223

Merged
theosiemensrhodes merged 5 commits into
mainfrom
chore/drizzle-db-updates
Nov 24, 2026
Merged

theosiemensrhodes merged 5 commits into
mainfrom
chore/drizzle-db-updates

Conversation

@theosiemensrhodes

@theosiemensrhodes theosiemensrhodes commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Modernizes Drizzle ORM usage for drizzle-orm@0.45.4 / drizzle-kit@0.31.11, fixes DB/query bugs found during audit, and cleans up redundant indexes and schema relations.

Changes

  1. Fix DrizzleQueryError.cause handling for unique violations (6fdc4369, hardened in c537839e)

    • Since drizzle-orm@0.44+ wraps driver errors in DrizzleQueryError with the underlying postgres error on .cause, duplicate-email checks in UserService (createUser, createInstructor, updateInstructor) stopped matching SQLSTATE 23505.
    • Added isUniqueViolation in src/server/db/errors.ts walking .cause (with cycle guard) and treating explicit SQLSTATE code as authoritative rather than matching "unique" substrings.
  2. Modernize Drizzle config, client, view helpers, and typed queries (de654735, refined in c537839e)

    • Extracted runtime migration constants to src/server/db/migration-config.ts so drizzle.config.ts uses defineConfig (strict: true, verbose: true) without pulling drizzle-kit into runtime code; removed stale "drizzle.config.*" from next.config.js outputFileTracingIncludes and added --force to pnpm test:db:push.
    • Switched drizzle(conn, { schema }) to drizzle({ client: conn, schema }) in src/server/db/index.ts and src/test/test-db.ts.
    • Replaced custom getViewColumns (ViewBaseConfig cast) with built-in getViewSelectedFields from drizzle-orm.
    • Added .$onUpdate(() => sql\now()`)toupdatedAt columns on app-updated tables (course, user, notification_preference) so updates stay on Postgres's clock, and dropped the redundant manual updatedAt: new Date()inPreferenceService.setPreference(leaving Better Auth-managed tables inauth.ts` untouched).
    • Replaced raw sql EXISTS / NOT EXISTS subqueries in CoverageService and ShiftService with typed exists(), notExists(), and aliasedTable().
    • Updated eslint-plugin-drizzle drizzleObjectName rules to ["db", "tx"] so transaction updates/deletes are guarded and the inert "ctx.db" entry is removed.
  3. Fix DB/query bugs & add query optimizations (036da941, hardened in c537839e)

    • TermService.createTerm: awaited this.insertHolidays(tx, termId, holidays) inside the transaction.
    • migrate.ts: uses a dedicated max: 1 postgres connection closed in finally and rethrows migration errors on startup instead of swallowing them. Deploy note: instrumentation.ts awaits migrate() at boot, so an unreachable DB or failing migration will now fail startup fast (causing container restart under restart: unless-stopped) rather than serving against a stale schema.
    • Added .mapWith(Number) to count(*) over() queries in UserService, VolunteerService, and CoverageService (Postgres returns int8 as string via postgres-js), and replaced UserService.getVerificationRequestCount with Drizzle's count().
    • ClassService.updateSchedules: match fetched schedules by ID via a Map instead of array index after WHERE id IN (...).
    • searchUtils.ts: iterate columns.slice(1) so the first column (name) is not double-counted in similarity/search expressions. Behavior note: user search ranking/thresholding (gt(similarity, 0.4)) now weights name, lastName, and email equally instead of double-weighting name.
    • Optimization: added empty-array short-circuit guards before inArray(...) queries in ClassService, UserService, VolunteerService, TermService, and CoverageService to skip unnecessary WHERE false round-trips.
  4. Drop redundant indexes, refine relations, and remove dead DB files (e0c10784, extended in c537839e)

    • Removed 7 duplicate/redundant indexes (session_token_index, verification_identifier_index, idx_user_email, shift_schedule_id_index, volunteer_to_schedule_volunteer_user_id_index, instructor_to_schedule_instructor_user_id_index, idx_notification_pref_user) and generated idempotent migration 0011_drop_redundant_indexes.sql (DROP INDEX IF EXISTS).
    • Added explicit relationName to coverageRequestRelations and completed missing reverse relations (account, user, volunteer, schedule, shift).
    • Removed unused commented-out src/server/db/cache.ts and src/server/services/entity/profileService.ts.

Validation

  • pnpm exec dotenv -e .env.test -- drizzle-kit check — passed.
  • SKIP_ENV_VALIDATION=1 npx next typegen && pnpm typecheck — passed (0 errors).
  • vitest run on unit tests (db-errors, search-utils, availability-utils, schedule-fmt, service-unavailable, example) and integration suites (class-service, coverage-queries, job-service, preference-service, shift-service, term-service, user-service) — passed against Postgres with migration 0011 applied (including coverage-queries.test.ts covering notExists + aliasedTable("cr2") + mapWith(Number) + getViewSelectedFields, preference-service.test.ts verifying updated_at advances on upsert, and shift-service.test.ts verifying instructor exists()).

Limitations / Notes

Council review

Rounds: 2

Delegate Round 1 Round 2
antigravity / claude-opus-5-5 (thought_level: high) 8/10 no score
antigravity / gemini-4-neon (thought_level: high) 8/10 9/10
codex / gpt-6.1-sol (reasoningEffort: high) 8/10 9/10
  • Availability note: antigravity / claude-opus-5-5 hit its individual quota during Round 2 (Resets in 4h39m41s) and was not substituted, so Round 2 has 2 of 3 requested members.
  • Round 1 → Round 2 resolution: All in-scope Round 1 findings were resolved in c537839e (authoritative SQLSTATE checking in isUniqueViolation, dedicated max: 1 migrator connection, verification_identifier_index + DROP INDEX IF EXISTS in migration 0011, --force on test:db:push, removing stale drizzle.config.* tracing and dead ctx.db ESLint entry, and adding direct Postgres integration tests for CoverageService, PreferenceService upsert updatedAt, and instructor ShiftService). Out-of-scope pre-existing bugs were verified against existing project items (N05, N06, N08, N11) and newly tracked as N12 and N13.
  • Remaining non-blocking notes from Round 2: Both completing Round 2 delegates found zero blocking or important issues (9/10). Minor optional polish noted (outer-wrapper .code short-circuit in isUniqueViolation, timeout: 5 on migrationClient.end(), and additional negative/volunteer test cases) was left as-is to avoid unnecessary churn.

Signed-off-by: Theo Siemens-Rhodes <112789743+theosiemensrhodes@users.noreply.github.com>
@theosiemensrhodes
theosiemensrhodes marked this pull request as draft November 23, 2026 22:49
…ed queries

Signed-off-by: Theo Siemens-Rhodes <112789743+theosiemensrhodes@users.noreply.github.com>
…uery bugs

Signed-off-by: Theo Siemens-Rhodes <112789743+theosiemensrhodes@users.noreply.github.com>
…db files

Signed-off-by: Theo Siemens-Rhodes <112789743+theosiemensrhodes@users.noreply.github.com>
…ry test coverage

Signed-off-by: Theo Siemens-Rhodes <112789743+theosiemensrhodes@users.noreply.github.com>
@theosiemensrhodes
theosiemensrhodes marked this pull request as ready for review November 24, 2026 01:36
@theosiemensrhodes
theosiemensrhodes merged commit 5b76bee into main Nov 24, 2026
@theosiemensrhodes
theosiemensrhodes deleted the chore/drizzle-db-updates branch November 24, 2026 01:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant