Skip to content

feat(db): migration runner and core schema#7

Merged
thewrz merged 4 commits into
mainfrom
feat/db-migrations
May 8, 2026
Merged

feat(db): migration runner and core schema#7
thewrz merged 4 commits into
mainfrom
feat/db-migrations

Conversation

@thewrz

@thewrz thewrz commented May 8, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Installs node-pg-migrate@8.0.4 as dev dependency
  • Implements pnpm migrate and pnpm migrate:down (previously stubs that echoed and exited)
  • Creates 4 reversible TypeScript migrations: csi_sections, specs, paragraphs, paragraph_versions with FK constraints, CASCADE deletes, and indexes
  • Fixes pre-existing bug in src/db/index.test.ts: static import of ./index.js triggered env validation → process.exit(1) during unit tests; fixed by mocking ../lib/env.js via vi.mock (hoisted before static imports)

Deviations from plan

node-pg-migrate v8 changed the CLI API. The plan specified --ts-runner tsx --migration-file-language ts but v8 uses --tsx (boolean flag). Updated scripts accordingly.

Test plan

  • DATABASE_URL=postgres://specr:specr@localhost:5432/specr pnpm migrate — expect "Migrations complete!" after running all 4
  • DATABASE_URL=postgres://specr:specr@localhost:5432/specr pnpm migrate:down — rolls back 004_create_paragraph_versions only
  • Re-run pnpm migrate — re-applies 004 cleanly
  • pnpm lint — ESLint + tsc + prettier all pass
  • pnpm test — 5 test files, 15 tests, all pass
  • CI green

Summary by CodeRabbit

  • New Features

    • Added database migrations to create tables for sections, specs, paragraphs, and paragraph versioning.
  • Tests

    • Made database connection tests deterministic with improved mocking and consistent error handling.
  • Chores

    • Replaced placeholder migration commands with real migration CLI invocations and added the migration tool to dev dependencies; expanded pnpm config formatting.

- Install node-pg-migrate@8.0.4 as devDependency
- Implement pnpm migrate and pnpm migrate:down (previously stubs)
  using --tsx flag for TypeScript migration files
- Create 4 reversible TypeScript migrations: csi_sections, specs,
  paragraphs, paragraph_versions with FK constraints and indexes
- Fix db/index.test.ts: mock env module to prevent process.exit(1)
  during unit test module evaluation (pre-existing test bug)

Deviations from plan: node-pg-migrate v8 uses --tsx boolean flag
instead of --ts-runner tsx --migration-file-language ts (v8 API).
@coderabbitai

coderabbitai Bot commented May 8, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Rate limit exceeded

@thewrz has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 32 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Free

Run ID: 394e0bd5-bc0f-43df-b00b-04c2cd94b5f3

📥 Commits

Reviewing files that changed from the base of the PR and between c03391c and 1bfb8cb.

📒 Files selected for processing (1)
  • vitest.config.ts
📝 Walkthrough

Walkthrough

Adds node-pg-migrate CLI scripts, four reversible DB migrations (csi_sections, specs, paragraphs, paragraph_versions), and refactors DB test mocks to use a hoisted pg.Pool mock and shared mocked pool for pingDatabase tests.

Changes

Database Schema Migrations & Setup

Layer / File(s) Summary
Migration Tooling Configuration
package.json
Adds node-pg-migrate ^8.0.4 to devDependencies; replaces placeholder migration scripts with node-pg-migrate CLI invocations targeting --migrations-dir src/db/migrations; reformats pnpm.onlyBuiltDependencies.
Base Table Definitions
src/db/migrations/001_create_csi_sections.ts, src/db/migrations/002_create_specs.ts
Creates csi_sections (UUID id, unique section_number, title, division, created_at, index on division) and specs (UUID id, section, source, title, created_at, updated_at) with down migrations.
Paragraph Hierarchy
src/db/migrations/003_create_paragraphs.ts
Creates paragraphs table with UUID id, spec_id FK (CASCADE), optional parent_id self-FK, metadata/content fields (node_type, text, position, vanish, revit_param, base_version), timestamps, and indexes; includes down migration.
Paragraph Version Tracking
src/db/migrations/004_create_paragraph_versions.ts
Creates paragraph_versions table with UUID id, paragraph_id FK (CASCADE), version, text, node_type, snapshot_at, and unique index on (paragraph_id, version); includes down migration.
Test Mocking & Verification
src/db/index.test.ts
Mocks environment variables before module evaluation; adds a top-level vi.mock('pg') returning a shared mocked Pool with query/end/on spies; introduces getPool() helper and updates tests to reuse the shared mock and assert SELECT 1, error mapping to DatabaseError, and cause preservation.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit hops through migrations neat,
Four tables set in tidy rows,
Tools in paw to make them meet,
Tests that mock where river flows.
Hooray — the schema softly grows! 🐰✨


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

thewrz added 3 commits May 7, 2026 22:37
Migrations:
- 002_create_specs: add notNull to section, title, source columns
- 003_create_paragraphs: add onDelete CASCADE to parent_id FK
- 004_create_paragraph_versions: make (paragraph_id, version) index UNIQUE
- all down migrations: add { cascade: true } to dropTable calls

Tests:
- Remove MockPool.prototype mutation; use vi.fn(function(){}) constructor
- Remove as unknown as casts; access mock pool via vi.mocked(Pool).mock.results
@thewrz
thewrz merged commit 07cc2b5 into main May 8, 2026
5 checks passed
@thewrz
thewrz deleted the feat/db-migrations branch May 9, 2026 04:55
thewrz added a commit that referenced this pull request Jun 17, 2026
…hed (#204)

Clears four dev-only Dependabot advisories via pnpm-workspace.yaml
overrides — no source or runtime deps touched:

  esbuild  >=0.28.1  GHSA-gv7w-rqvm-qjhr (high), -g7r4-m6w7-qqqr  (#7, #8)
  dompurify >=3.4.9  GHSA-vxr8-fq34-vvx9                          (#13)
  js-yaml   >=4.2.0  GHSA-h67p-54hq-rp68 (eslint's 4.x line)      (#11)

None ship in dist/ or run in prod: esbuild is a vitest/tsx test-runner
internal, dompurify lives in redoc's docs preview. Overrides applied
surgically — fast-xml-parser and all other runtime deps stay pinned.

Deferred (dev-only, not reachable): vite #9/#10 (Windows-only vite dev
server we never run; bumping it needs a full lockfile regen that also
trips an XMLValidator deprecation) → #203. depcheck's js-yaml@3.x is a
different major the 4.2.0 fix doesn't apply to.

Closes #200

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
thewrz added a commit that referenced this pull request Jul 8, 2026
Address two CodeRabbit nitpicks on PR #423 and record a third as deferred:

- #8 (logger.ts): the pino-roll file transport runs on a worker thread that
  buffers writes, so the bare process.exit(0) in shutdown() could kill it
  before the buffer flushed — dropping the final JSONL lines the corpus
  fix-loop reads back. Build the transport explicitly so we hold its handle,
  and drain it via closeLogger() (awaited in index.ts shutdown, guarded to
  always terminate). No-op when logging to stdout. Pinned by a unit test.

- #7 (ADR-056): document the retention/redaction posture now that the
  user-supplied filename lands in durable JSONL — bounded by pino-roll
  rotation, namespaced under an app-controlled `doc` key, not redacted by
  default (spec filenames are not secrets), with a redact path noted for
  deployments that disagree.

- #3 (ADR-056 P2): recorded as the first deferred item — carry the caught
  error's cause/detail on ParseWarning so core-metadata-unreadable surfaces
  *why* it failed, not just *that* it did. Deferred as an AST/contract change
  beyond this PR's boundary-only scope.

The other 6 nitpicks are correctly skippable (one, the error.ts `declare
override`, does not compile under useDefineForClassFields — the load-bearing
`= undefined` initializer is documented in the Task 4 gotcha).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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