Repository navigation
feat(database): introduce *Client surface - #1191
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
cdb72af to
ea9a362
Compare
879737b to
f63c649
Compare
ea9a362 to
d3f709e
Compare
f63c649 to
2093b97
Compare
d3f709e to
0e98990
Compare
2093b97 to
6837f3b
Compare
0e98990 to
0c33483
Compare
6837f3b to
96c0213
Compare
0c33483 to
5b0de30
Compare
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR implements a new Ent-backed database ChangesEnt Client Wrapper Implementation
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
96c0213 to
d2afd47
Compare
5b0de30 to
4a223d0
Compare
d2afd47 to
cf004cf
Compare
4a223d0 to
a0fa1f8
Compare
cf004cf to
96afbbf
Compare
a0fa1f8 to
7e75e62
Compare
96afbbf to
ef67ddd
Compare
7e75e62 to
969f6e1
Compare
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.
969f6e1 to
08ae130
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/database/client_test.go (1)
215-224: 💤 Low valueConsider using subtests for better test isolation and reporting.
Table-driven tests benefit from
t.Runsubtests: 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 callt.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
📒 Files selected for processing (3)
openspec/changes/migrate-to-ent-and-atlas/tasks.mdpkg/database/client.gopkg/database/client_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
I want to just merge this right now...
…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]>
Lays the foundation for §10 of migrate-to-ent-and-atlas — replacing
the sqlc-generated
Querierinterface with an Ent-backed*database.Client.What lands:
pkg/database/client.godefines*Client(wraps*ent.Client,the underlying
*sql.DB, and the dialect Type) plus a small setof accessors (
Ent,DB,Type,Close).WithTransaction(ctx, name, fn func(*ent.Tx) error) erroris theEnt-native replacement for the legacy
*Cache.executeTransactionhelper: begin → fn → commit onsuccess, rollback on error, defer-rollback on panic (with a new
ErrTransactionPanicsentinel callers canerrors.Isagainst).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 acaller-owned
*sql.DB. The migrate package already opens itsown
*sql.DBfor goose, so this keeps that lifecycle untouched.EntDialectFor(Type)exports the existing local mapping so themigrate package and future callers share one source of truth.
pkg/database/client_test.goexercises commit, rollback,panic-rollback, begin-error wrap, accessors, Close, and the
dialect mapping.
Why split §10.1 from the
Opensignature swap:The task list literally says "Replace
database.Querierreturn typewith
*database.Client... indatabase.Open", but 22 caller fileshold
database.Querier. SwappingOpenhere would leave the buildred 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
Openand migrate all callers in one coherentcommit.
§10.3 —
DetectFromDatabaseURLandPoolConfig— is satisfied byinspection: 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.