Skip to content

feat(database): introduce *Client surface - #1191

Merged
kalbasit merged 1 commit into
mainfrom
feat-database-introduce-client-surface
May 22, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-database-introduce-client-surface

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Lays the foundation for §10 of migrate-to-ent-and-atlas — replacing
the sqlc-generated Querier interface with an Ent-backed
*database.Client.

What lands:

  • pkg/database/client.go defines *Client (wraps *ent.Client,
    the underlying *sql.DB, and the dialect Type) plus a small set
    of accessors (Ent, DB, Type, Close).
  • WithTransaction(ctx, name, fn func(*ent.Tx) error) error is the
    Ent-native replacement for the legacy
    *Cache.executeTransaction helper: begin → fn → commit on
    success, rollback on error, defer-rollback on panic (with a new
    ErrTransactionPanic sentinel callers can errors.Is against).
    Operation name flows into every wrapped lifecycle error so logs
    and telemetry can attribute failures back to the originating
    call.
  • NewClient(*sql.DB, Type) constructs the wrapper from a
    caller-owned *sql.DB. The migrate package already opens its
    own *sql.DB for goose, so this keeps that lifecycle untouched.
  • EntDialectFor(Type) exports the existing local mapping so the
    migrate package and future callers share one source of truth.
  • pkg/database/client_test.go exercises commit, rollback,
    panic-rollback, begin-error wrap, accessors, Close, and the
    dialect mapping.

Why split §10.1 from the Open signature swap:

The task list literally says "Replace database.Querier return type
with *database.Client ... in database.Open", but 22 caller files
hold database.Querier. Swapping Open here would leave the build
red until §11 (caller migration) lands. The autonomous-drive rule
this stack follows ("make sure tests are passing" after every group)
forbids that. §10 therefore introduces the new surface in parallel;
§11 will rewire Open and migrate all callers in one coherent
commit.

§10.3 — DetectFromDatabaseURL and PoolConfig — is satisfied by
inspection: nothing in this commit touches them, and their existing
tests (url_test.go, url_internal_test.go, backends_test.go)
still pass under -race against all three engines.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels May 21, 2026
@kalbasit

kalbasit commented May 21, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

This was referenced May 21, 2026
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from cdb72af to ea9a362 Compare May 22, 2026 07:05
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 879737b to f63c649 Compare May 22, 2026 15:03
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from ea9a362 to d3f709e Compare May 22, 2026 15:03
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from f63c649 to 2093b97 Compare May 22, 2026 15:17
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from d3f709e to 0e98990 Compare May 22, 2026 15:17
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 2093b97 to 6837f3b Compare May 22, 2026 15:33
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 0e98990 to 0c33483 Compare May 22, 2026 15:33
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 6837f3b to 96c0213 Compare May 22, 2026 15:47
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 0c33483 to 5b0de30 Compare May 22, 2026 15:47
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added database client abstraction with support for multiple database dialects (SQLite, PostgreSQL, MySQL) and transaction management with error recovery handling.
  • Tests

    • Comprehensive test coverage for database client functionality including transaction commits, rollbacks, panic recovery, and dialect validation.

Walkthrough

This PR implements a new Ent-backed database Client type in pkg/database/client.go that wraps an already-opened *sql.DB. It provides initialization, dialect mapping, transaction handling with panic recovery, and comprehensive test coverage with schema setup helpers.

Changes

Ent Client Wrapper Implementation

Layer / File(s) Summary
Error contracts and Client structure
pkg/database/client.go
Sentinel errors for nil DB input, unknown dialect, and transaction panics; Client struct holds Ent client, raw *sql.DB, and dialect type.
Client initialization and utilities
pkg/database/client.go
NewClient constructor validates non-nil DB and initializes Client with Ent driver; EntDialectFor maps database types (SQLite, PostgreSQL, MySQL) to Ent dialect strings; accessor methods expose Ent client, raw DB, and dialect; Close shuts down client and wraps errors.
Transaction handling with panic recovery
pkg/database/client.go
WithTransaction begins Ent transaction, defers panic recovery via recover() to capture panics, rolls back on callback errors (wrapping both callback and rollback failures), commits on success, and returns all lifecycle errors with contextual operation names.
Test coverage and schema setup
pkg/database/client_test.go
Tests validate NewClient input validation (nil DB, unknown dialect) and accessor behavior; WithTransaction tests verify commit success, error rollback, panic recovery with wrapped ErrTransactionPanic, and begin-error handling; Close tests confirm DB shutdown; EntDialectFor table-driven tests cover dialect mapping including error case; freshSchemaSQLite helper creates isolated temporary SQLite test databases with Ent migrations using process-wide mutex.

Sequence Diagram

sequenceDiagram
  participant Caller
  participant Client
  participant Transaction
  participant Callback
  Caller->>Client: WithTransaction(ctx, name, fn)
  Client->>Transaction: Begin()
  alt Begin succeeds
    Client->>Callback: fn(tx)
    alt Callback succeeds
      Callback-->>Client: nil
      Client->>Transaction: Commit()
      Transaction-->>Client: success
      Client-->>Caller: nil
    else Callback returns error
      Callback-->>Client: error
      Client->>Transaction: Rollback()
      Transaction-->>Client: rollback result
      Client-->>Caller: wrapped error
    else Callback panics
      Callback-->>Client: panic
      Client->>Client: recover()
      Client->>Transaction: Rollback()
      Transaction-->>Client: rollback result
      Client-->>Caller: ErrTransactionPanic + panic details
    end
  else Begin fails
    Transaction-->>Client: error
    Client-->>Caller: wrapped begin error (callback not invoked)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:XL

Poem

🐰 A wrapper neat wraps Ent and DB with care,
Transaction flows with panic guarded fair,
Dial a type, begin the dance, commit or roll,
Tests ensure each error finds its goal! 🗄️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: introducing a new *Client surface in the database package as part of the Ent migration.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the purpose, implementation details, and rationale for introducing the *Client surface.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 96c0213 to d2afd47 Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 5b0de30 to 4a223d0 Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from d2afd47 to cf004cf Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 4a223d0 to a0fa1f8 Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from cf004cf to 96afbbf Compare May 22, 2026 16:27
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from a0fa1f8 to 7e75e62 Compare May 22, 2026 16:27
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 96afbbf to ef67ddd Compare May 22, 2026 16:42
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 7e75e62 to 969f6e1 Compare May 22, 2026 16:42
Base automatically changed from gs-comments-1178-1188 to main May 22, 2026 16:56
Lays the foundation for §10 of migrate-to-ent-and-atlas — replacing
the sqlc-generated `Querier` interface with an Ent-backed
`*database.Client`.

What lands:

- `pkg/database/client.go` defines `*Client` (wraps `*ent.Client`,
  the underlying `*sql.DB`, and the dialect Type) plus a small set
  of accessors (`Ent`, `DB`, `Type`, `Close`).
- `WithTransaction(ctx, name, fn func(*ent.Tx) error) error` is the
  Ent-native replacement for the legacy
  `*Cache.executeTransaction` helper: begin → fn → commit on
  success, rollback on error, defer-rollback on panic (with a new
  `ErrTransactionPanic` sentinel callers can `errors.Is` against).
  Operation name flows into every wrapped lifecycle error so logs
  and telemetry can attribute failures back to the originating
  call.
- `NewClient(*sql.DB, Type)` constructs the wrapper from a
  caller-owned `*sql.DB`. The migrate package already opens its
  own `*sql.DB` for goose, so this keeps that lifecycle untouched.
- `EntDialectFor(Type)` exports the existing local mapping so the
  migrate package and future callers share one source of truth.
- `pkg/database/client_test.go` exercises commit, rollback,
  panic-rollback, begin-error wrap, accessors, Close, and the
  dialect mapping.

Why split §10.1 from the `Open` signature swap:

The task list literally says "Replace `database.Querier` return type
with `*database.Client` ... in `database.Open`", but 22 caller files
hold `database.Querier`. Swapping `Open` here would leave the build
red until §11 (caller migration) lands. The autonomous-drive rule
this stack follows ("make sure tests are passing" after every group)
forbids that. §10 therefore introduces the new surface in parallel;
§11 will rewire `Open` and migrate all callers in one coherent
commit.

§10.3 — `DetectFromDatabaseURL` and `PoolConfig` — is satisfied by
inspection: nothing in this commit touches them, and their existing
tests (`url_test.go`, `url_internal_test.go`, `backends_test.go`)
still pass under -race against all three engines.
@kalbasit
kalbasit force-pushed the feat-database-introduce-client-surface branch from 969f6e1 to 08ae130 Compare May 22, 2026 16:56
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 16:57
coderabbitai[bot]
coderabbitai Bot previously requested changes May 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/database/client_test.go (1)

215-224: 💤 Low value

Consider using subtests for better test isolation and reporting.

Table-driven tests benefit from t.Run subtests: clearer failure messages identifying which case failed, parallel execution of individual cases, and proper test isolation.

♻️ Suggested refactor using subtests
 	for _, tc := range tests {
+		t.Run(tc.in.String(), func(t *testing.T) {
+			t.Parallel()
+
-		got, err := database.EntDialectFor(tc.in)
-		if tc.err {
-			require.Error(t, err)
-			assert.ErrorIs(t, err, database.ErrUnknownDialect)
-		} else {
-			require.NoError(t, err)
-			assert.Equal(t, tc.want, got)
-		}
+			got, err := database.EntDialectFor(tc.in)
+			if tc.err {
+				require.Error(t, err)
+				assert.ErrorIs(t, err, database.ErrUnknownDialect)
+			} else {
+				require.NoError(t, err)
+				assert.Equal(t, tc.want, got)
+			}
+		})
 	}

As per coding guidelines: "All tests and subtests (t.Run) must call t.Parallel() unless the test cannot be parallelized."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/database/client_test.go` around lines 215 - 224, The table-driven loop in
the test should use t.Run subtests with proper parallelization and loop-variable
capture: wrap each case in t.Run(tc.name, func(t *testing.T) { t.Parallel(); tc
:= tc; got, err := database.EntDialectFor(tc.in); if tc.err { require.Error(t,
err); assert.ErrorIs(t, err, database.ErrUnknownDialect) } else {
require.NoError(t, err); assert.Equal(t, tc.want, got) } }) so failures report
the case name and each subtest runs in parallel and is isolated; ensure you
reference the existing tests slice and functions EntDialectFor and
ErrUnknownDialect and capture tc before using it in the goroutine.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openspec/changes/migrate-to-ent-and-atlas/tasks.md`:
- Line 110: The task checkbox for "10.1 Replace `database.Querier` return type
with `*database.Client`" is inconsistent with its note that the `database.Open`
signature swap is deferred to §11; update the tasks list so progress is accurate
by either unchecking the 10.1 checkbox or splitting 10.1 into two items (e.g.,
"10.1a Add parallel surface in §10" — checked, and "10.1b Swap `database.Open`
signature to return `*database.Client` (deferred to §11)" — unchecked), and
ensure the task text references `database.Open`, `database.Querier`,
`*database.Client`, and sections §10/§11 to keep intent clear.

---

Nitpick comments:
In `@pkg/database/client_test.go`:
- Around line 215-224: The table-driven loop in the test should use t.Run
subtests with proper parallelization and loop-variable capture: wrap each case
in t.Run(tc.name, func(t *testing.T) { t.Parallel(); tc := tc; got, err :=
database.EntDialectFor(tc.in); if tc.err { require.Error(t, err);
assert.ErrorIs(t, err, database.ErrUnknownDialect) } else { require.NoError(t,
err); assert.Equal(t, tc.want, got) } }) so failures report the case name and
each subtest runs in parallel and is isolated; ensure you reference the existing
tests slice and functions EntDialectFor and ErrUnknownDialect and capture tc
before using it in the goroutine.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 43a54b55-db85-474c-84be-d6b8f7358bc2

📥 Commits

Reviewing files that changed from the base of the PR and between 40afcbb and 08ae130.

📒 Files selected for processing (3)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/database/client.go
  • pkg/database/client_test.go

@codecov

codecov Bot commented May 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (40afcbb) to head (08ae130).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1191   +/-   ##
=====================================
  Coverage   5.04%   5.04%           
=====================================
  Files          6       6           
  Lines        436     436           
=====================================
  Hits          22      22           
  Misses       410     410           
  Partials       4       4           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kalbasit
kalbasit dismissed coderabbitai[bot]’s stale review May 22, 2026 17:17

I want to just merge this right now...

@kalbasit
kalbasit merged commit 57b22af into main May 22, 2026
16 checks passed
@kalbasit
kalbasit deleted the feat-database-introduce-client-surface branch May 22, 2026 17:17
kalbasit added a commit that referenced this pull request May 24, 2026
…1251)

## Summary

Consolidation branch addressing unresolved reviewer threads left open
across
merged PRs #1179–#1246. Each fix has its own atomic commit referencing
the
source PR and thread ID; all threads are resolved on GitHub after each
change.

### Bug fixes

- **cache:** touch `nar_file` by fetched row ID, not by narURL fields —
`getNarFileFromDB` can return a `compression=none` fallback whose key
differs
from `narURL`, causing stale `last_accessed_at` and LRU regressions
(#1206)
- **cache:** fail fast on `nil` eager-loaded chunk edges in
`streamCompleteChunks`
and `streamProgressiveChunks` instead of silently `continue`-ing, which
caused
  count mismatches or infinite re-streaming (#1207)
- **cache:** include `narURLsToRemove` in the LRU early-return guard so
orphaned
`NarFile` blobs are passed to `parallelDeleteFromStores` instead of
being
  silently leaked in storage (#1215)
- **cache:** log a warning when LRU candidate fetch hits the
`maxFetchRows` cap
  so operators know eviction scanned only a partial window (#1206)
- **cache/relink:** lower `relinkBatchSize` from 500 → 499 to stay under
SQLite's 999-placeholder limit (500 rows × 2 binds = 1000 > 999) (#1208)
- **database:** close `*sql.DB` in `Open()` when `NewClient` fails
(#1208)
- **migrate/adopt:** use `ErrUnknownState` (not `ErrUnknownDialect`) for
unrecognised `State` values — fixes false-positive `errors.Is` checks
(#1188)
- **generate-migrations:** `parseSkip` validates dialect names,
returning an error
on unknown values like `"myslq"` instead of silently skipping them
(#1187)
- **generate-migrations:** `--sql-only` path now calls `ensureAtlasSum`
after
  writing the stub so `atlas.sum` stays in sync (#1187)
- **generate-migrations:** `runDialect` now returns the generated file
path and
prints it to stdout; `main()` warns when a second boundary falls between
dialect runs so callers know to re-run for a consistent timestamp set
(#1215)
- **generate-migrations:** add `"empty"` to `validateName` reject list
(#1185)
- **nix/ent-lint-check:** add `set -o pipefail` so `ent-lint | tee`
propagates
  a non-zero exit through the pipeline (#1221)
- **e2e:** fix docstring path (`var/ncps/e2e-results/` →
`.e2e-results/`);
`mc mb` and `redis-cli flushall` now use `check=True` so reset failures
  abort the test immediately (#1233)
- **e2e:** `stop_ncps` now verifies the port closes within timeout;
`wait_ready`
  exits early if the child process dies before becoming ready (#1233)
- **run.py:** guard `dbmate` usage with a `shutil.which` check so a
missing
binary fails fast with a clear message instead of an obscure error
(#1234)
- **CI:** pin all external GitHub Action refs to immutable commit SHAs
to
  prevent supply-chain mutation (#1223)
- **CI:** remove `release-*` from pull_request/push triggers; add
`go.mod` and
  `go.sum` to the ent paths-filter (#1235)
- **docs:** replace distroless-incompatible `wget` healthcheck in Docker
Compose
  example with `garage status` (#1223)

### Test fixes

- Replace non-fatal `assert.Len` → `require.Len` before indexing
`stamps[0..2]`
  in `generate-migrations` tests (#1185)
- Add 60 s timeout to the one-time `go build` in the test setup (#1241)
- Fix `cache_prefetch_test.go` to look up `nar_file` by `(hash,
compression,
  query)` instead of hard-coded `id=1` (#1218)
- Apply `NarSize` fallback when `FileSize == 0` in
`testhelper/sqlite.go` to
avoid impossible `file_size=0` fixture rows for `compression=none`
narinfos (#1218)
- Increase `chunkingDelay` from 500 ms → 1 s in `cdc_test.go` to reduce
  flakiness on slow CI machines (#1217)
- Replace `Lock`-with-timeout with `TryLock` in
`cache_distributed_test.go` to
  avoid spurious failures when the lock-hold window is tight (#1217)

### Docs / skills

- Quote PostgreSQL DSNs in shell-command examples to prevent `?`-glob
expansion
  by shells (#1234)
- `migrate-new/SKILL.md`: ent-lint checks A1, A2, A4 — not all five
invariants
  as previously stated (#1225)
- `migrate-down/SKILL.md`: clarify that `DROP COLUMN` is
sensitive/forbidden DDL
per the migration spec and is only permissible as the terminal
expand-contract
step; add the missing "deploy code that always writes non-null" step to
the
  NOT NULL recipe (#1225)
- `openspec/changes/archive/2026-05-23-less-tests/`: fix stale paths,
add `bash`
fence tag, replace "branch coverage" with "statement/block coverage"
(#1245)
- `openspec/specs/test-suite-efficiency/spec.md`: same coverage
terminology
  fix (#1245)
-
`openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/design.md`:
  add language tag to decision-tree fence block; fix grammar (#1186)
-
`openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/tasks.md`:
update §10.1/§11.1 notes to reflect that `*database.Client` threading
was
  completed in §11, not deferred (#1191, #1192)

## Test plan

- [x] `nix flake check` (includes all unit + integration tests, lint,
ent-lint,
  atlas-sum, helm-unittest, schema-equivalence)
- [x] `go test -race ./...` locally with `eval
"$(enable-integration-tests)"`
- [x] Verify all referenced GitHub threads are marked resolved

🤖 Generated with [Claude Code](https://claude.ai/claude-code)

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant