Skip to content

chore(database): finish sqlc removal and Ent test migration - #1218

Merged
kalbasit merged 3 commits into
mainfrom
chore-delete-sqlc-finish-ent-migration
May 23, 2026
Merged

kalbasit merged 3 commits into
mainfrom
chore-delete-sqlc-finish-ent-migration

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§12: the final cleanup. All production code already runs through
*database.Client + Ent (see prior commits in this stack); this commit
deletes the rest of the sqlc surface and finishes converting test
fixtures that still spoke the legacy Querier API.

Deletions:

  • pkg/database/generated_*.go (sqlc-multi-db generated wrappers)
  • pkg/database/{sqlitedb,postgresdb,mysqldb}/ (per-engine adapters)
  • pkg/database/contract_test.go and ent_schema_parity_test.go
    (obsolete contract suite that compared sqlc vs Ent shapes)
  • pkg/database/schema_parity_test.go (rolled into migrations/)
  • pkg/database/backends_test.go

Code changes:

  • database.Open now returns *Client directly (no Querier).
  • pkg/analytics, pkg/cache, pkg/ncps, pkg/server: all test fixtures
    drop the Querier parameter and rely on dbClient.Ent() + dbClient.DB()
    for the raw SQL escape hatch.
  • testhelper/{sqlite,postgres,mysql}.go: helpers take *database.Client
    and use Ent fluent API.
  • *Cache.db field and its New() parameter removed (production code
    has not touched it for several commits already).
  • pkg/ncps/serve.go: createDatabaseQuerier now returns just
    *database.Client; renamed locally to the legacy name to keep the
    stack diff small but the signature is single-return.
  • cache_internal_test.go: the testStoreInDatabaseTransactionSafety
    scenario already uses dbClient.WithTransaction + Ent OnConflict.

Test fixtures still use dbClient.DB() for raw SQL where the test is
specifically exercising the schema (e.g. UPDATE nar_files SET
chunking_started_at = ?), which is appropriate -- they aren't
exercising Ent code paths.

Full -race sweep against SQLite + Postgres + MySQL + MinIO + Redis is
green across all 29 packages.

Co-Authored-By: Claude Opus 4.7 [email protected]

This was referenced 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.

kalbasit added a commit that referenced this pull request May 22, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from 93b30ab to 0875a49 Compare May 22, 2026 23:02
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from 398574b to 4394d44 Compare May 22, 2026 23:02
kalbasit added a commit that referenced this pull request May 22, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from 0875a49 to d0503b2 Compare May 22, 2026 23:16
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from 4394d44 to e418c9c Compare May 22, 2026 23:16
kalbasit added a commit that referenced this pull request May 22, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from d0503b2 to a8527e0 Compare May 22, 2026 23:28
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from e418c9c to 8684336 Compare May 22, 2026 23:28
kalbasit added a commit that referenced this pull request May 22, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from a8527e0 to 09d8642 Compare May 22, 2026 23:54
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from 8684336 to ab3d67e Compare May 22, 2026 23:54
kalbasit added a commit that referenced this pull request May 22, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from 09d8642 to c6697fa Compare May 23, 2026 00:07
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from ab3d67e to 3d1c72f Compare May 23, 2026 00:07
kalbasit added a commit that referenced this pull request May 23, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from c6697fa to 86956f6 Compare May 23, 2026 00:36
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from 3d1c72f to 83cf39d Compare May 23, 2026 00:36
kalbasit added a commit that referenced this pull request May 23, 2026
The previous wording referenced a "well-known Ent sentinel below" that
doesn't exist in this file — IsNotFoundError simply delegates to
isEntNotFound (declared in ent_errors.go) which keeps the ent import
isolated to a single file.

Addresses gemini-code-assist comment on PR #1218 (PRRT_kwDONV6tZs6D3WsX).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-analytics-to-ent branch from 86956f6 to d6fd28a Compare May 23, 2026 03:31
@kalbasit
kalbasit force-pushed the chore-delete-sqlc-finish-ent-migration branch from 83cf39d to 8e432aa Compare May 23, 2026 03:31
Comment thread pkg/server/security_test.go Dismissed
kalbasit and others added 3 commits May 22, 2026 23:36
§12: the final cleanup. All production code already runs through
*database.Client + Ent (see prior commits in this stack); this commit
deletes the rest of the sqlc surface and finishes converting test
fixtures that still spoke the legacy Querier API.

Deletions:
- pkg/database/generated_*.go (sqlc-multi-db generated wrappers)
- pkg/database/{sqlitedb,postgresdb,mysqldb}/ (per-engine adapters)
- pkg/database/contract_test.go and ent_schema_parity_test.go
  (obsolete contract suite that compared sqlc vs Ent shapes)
- pkg/database/schema_parity_test.go (rolled into migrations/)
- pkg/database/backends_test.go

Code changes:
- database.Open now returns *Client directly (no Querier).
- pkg/analytics, pkg/cache, pkg/ncps, pkg/server: all test fixtures
  drop the Querier parameter and rely on dbClient.Ent() + dbClient.DB()
  for the raw SQL escape hatch.
- testhelper/{sqlite,postgres,mysql}.go: helpers take *database.Client
  and use Ent fluent API.
- *Cache.db field and its New() parameter removed (production code
  has not touched it for several commits already).
- pkg/ncps/serve.go: createDatabaseQuerier now returns just
  *database.Client; renamed locally to the legacy name to keep the
  stack diff small but the signature is single-return.
- cache_internal_test.go: the testStoreInDatabaseTransactionSafety
  scenario already uses dbClient.WithTransaction + Ent OnConflict.

Test fixtures still use dbClient.DB() for raw SQL where the test is
specifically exercising the schema (e.g. UPDATE nar_files SET
chunking_started_at = ?), which is appropriate -- they aren't
exercising Ent code paths.

Full -race sweep against SQLite + Postgres + MySQL + MinIO + Redis is
green across all 29 packages.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The parent commit deletes the sqlc-generated query.<dialect>.sql.go
trees, shrinking the limited (ncps) fileset's vendor down to the
ent-only set. But the golangci-lint-check check that overrides
ncps with `src = ../../.` still sees `cmd/generate-migrations`,
which transitively pulls in modernc.org/sqlite — a dep the
shrunken limited fileset no longer needs. The two derivations
end up wanting different vendorHashes for the same attribute.

Bring `cmd/` into the ncps limited fileset so both derivations
share the same vendor and the single vendorHash satisfies both.
The exclude in #1220's source-list cleanup becomes a no-op for
cmd/ but still removes db/migrations and db/schema cleanly.
sqlc.yml still existed, causing CI to regenerate the deleted per-engine
adapters (sqlitedb/, postgresdb/, mysqldb/) and generated_*.go wrappers
and auto-commit them back onto every PR that touched pkg/database/**.

- Delete sqlc.yml (no longer needed post-Ent migration)
- Remove "Generate Database Code" (sqlc generate) step from generate job
- Remove "Generate Go Code" (go generate ./pkg/database) step — no
  //go:generate directives remain in pkg/database/
- Remove "Format Code" + auto-commit steps that were gated on database filter
- Remove the now-unused database filter output from the filter job

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)

572-589: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject a nil dbClient in New.

After removing the legacy db parameter, this constructor has no database fallback. Passing nil here will still build a Cache and then fail later in initialization or callbacks instead of returning a normal constructor error.

Suggested fix
 var (
 	// ErrHostnameRequired is returned if the given hostName to New is not given.
 	ErrHostnameRequired = errors.New("hostName is required")
+	ErrDBClientRequired = errors.New("dbClient is required")
@@
 func New(
 	ctx context.Context,
 	hostName string,
 	dbClient *database.Client,
@@
 ) (*Cache, error) {
+	if dbClient == nil {
+		return nil, ErrDBClientRequired
+	}
+
 	c := &Cache{
🤖 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/cache/cache.go` around lines 572 - 589, The constructor New accepts a nil
dbClient which later causes runtime failures; add an explicit nil-check at the
start of New and return a clear error if dbClient == nil instead of constructing
a Cache. Place the guard before allocating the Cache struct (referencing the New
function and the Cache type and dbClient parameter) and return an appropriate
error value (e.g., fmt.Errorf or errors.New) so callers fail fast.
🧹 Nitpick comments (1)
pkg/cache/cache_test.go (1)

3640-3643: ⚡ Quick win

Close the database.Client here.

This test now creates a *database.Client, so tearing down only dbClient.DB() bypasses the client-level close path and can drift from the rest of the suite's cleanup behavior.

Suggested fix
-defer dbClient.DB().Close()
+defer dbClient.Close()
🤖 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/cache/cache_test.go` around lines 3640 - 3643, The test currently defers
only dbClient.DB().Close(), which bypasses the database.Client-level shutdown;
change the teardown to call the client Close method instead by replacing the
defer dbClient.DB().Close() with defer dbClient.Close() so the database.Client
(dbClient) is closed properly.
🤖 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 `@pkg/cache/cache_prefetch_test.go`:
- Around line 180-191: Replace the hard-coded NarFile ID used in the chunk query
(entnarfilechunk.NarFileIDEQ(1)) by first resolving the corresponding nar_files
row via the NarFile query (use dbClient.Ent().NarFile.Query().Where(...) with
the nar hash, compression and query values), require the returned nar file
exists, then use that nar file's ID when loading chunks with
dbClient.Ent().NarFileChunk.Query(); also assert that at least two chunks are
returned before deleting the second chunk so the test reliably exercises the
missing-chunk path.
- Around line 63-65: Replace the unsafe testing.T usage in
BenchmarkStreamCompleteChunks_WithPrefetch by changing setupSQLiteFactory to
accept testing.TB (or add a benchmark-specific helper) and pass b into
setupSQLiteFactory so Helper/failure/cleanup semantics work correctly instead of
constructing t := &testing.T{}; and in TestPrefetchErrorPropagation stop
assuming NarFile ID 1 — after creating the nar file for nu, query the nar_files
table (by its hash/compression or other unique fields) to obtain the actual ID
and use that value in the entnarfilechunk.NarFileIDEQ(...) filter rather than
hardcoding 1.

In `@pkg/cache/cdc_test.go`:
- Around line 247-253: The two db count operations currently ignore errors
(count1, _ := dbClient.Ent().Chunk.Query().Count(ctx) and count2, _ :=
dbClient.Ent().Chunk.Query().Count(ctx)), which can mask DB failures; replace
the ignored errors by checking them with require.NoError so the test fails
immediately on DB issues (e.g., assign the error returned from
Chunk.Query().Count(ctx) to a variable and call require.NoError(t, err) after
each call before using count1/count2).

In `@testhelper/sqlite.go`:
- Around line 113-123: The test currently passes the optional ni.FileSize into
getOrCreateNarFile which causes zero-size nar_files rows when Compression is
none; instead derive the effective size from the parsed nar URL and pass that to
getOrCreateNarFile (use the parsed narURL's size field, e.g. narURL.NarSize or
equivalent) after calling nar.ParseURL, so replace the ni.FileSize argument with
the parsed URL's effective size when calling getOrCreateNarFile.

---

Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 572-589: The constructor New accepts a nil dbClient which later
causes runtime failures; add an explicit nil-check at the start of New and
return a clear error if dbClient == nil instead of constructing a Cache. Place
the guard before allocating the Cache struct (referencing the New function and
the Cache type and dbClient parameter) and return an appropriate error value
(e.g., fmt.Errorf or errors.New) so callers fail fast.

---

Nitpick comments:
In `@pkg/cache/cache_test.go`:
- Around line 3640-3643: The test currently defers only dbClient.DB().Close(),
which bypasses the database.Client-level shutdown; change the teardown to call
the client Close method instead by replacing the defer dbClient.DB().Close()
with defer dbClient.Close() so the database.Client (dbClient) is closed
properly.
🪄 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: 5a084d34-d5a9-4ea2-ad94-cd1dfcb56f17

📥 Commits

Reviewing files that changed from the base of the PR and between 2c99e04 and 3a81d05.

📒 Files selected for processing (39)
  • nix/packages/ncps/default.nix
  • pkg/cache/cache.go
  • pkg/cache/cache_distributed_test.go
  • pkg/cache/cache_internal_test.go
  • pkg/cache/cache_prefetch_test.go
  • pkg/cache/cache_test.go
  • pkg/cache/cdc_test.go
  • pkg/cache/healthcheck/healthcheck_test.go
  • pkg/cache/upload_only_test.go
  • pkg/config/config_test.go
  • pkg/database/backends_test.go
  • pkg/database/contract_test.go
  • pkg/database/database.go
  • pkg/database/ent_errors.go
  • pkg/database/ent_schema_parity_test.go
  • pkg/database/errors.go
  • pkg/database/generated_errors.go
  • pkg/database/generated_models.go
  • pkg/database/generated_querier.go
  • pkg/database/generated_wrapper_mysql.go
  • pkg/database/generated_wrapper_postgres.go
  • pkg/database/generated_wrapper_sqlite.go
  • pkg/database/mysqldb/adapter.go
  • pkg/database/postgresdb/adapter.go
  • pkg/database/schema_parity_test.go
  • pkg/database/sqlitedb/adapter.go
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_test.go
  • pkg/ncps/migrate_nar_to_chunks.go
  • pkg/ncps/migrate_nar_to_chunks_test.go
  • pkg/ncps/migrate_narinfo.go
  • pkg/ncps/migrate_narinfo_test.go
  • pkg/ncps/serve.go
  • pkg/server/security_test.go
  • pkg/server/server_internal_test.go
  • pkg/server/server_test.go
  • testhelper/mysql.go
  • testhelper/postgres.go
  • testhelper/sqlite.go
💤 Files with no reviewable changes (13)
  • pkg/database/sqlitedb/adapter.go
  • pkg/database/ent_schema_parity_test.go
  • pkg/database/generated_errors.go
  • pkg/database/mysqldb/adapter.go
  • pkg/database/schema_parity_test.go
  • pkg/database/postgresdb/adapter.go
  • pkg/database/generated_querier.go
  • pkg/database/contract_test.go
  • pkg/database/backends_test.go
  • pkg/database/generated_wrapper_sqlite.go
  • pkg/database/generated_wrapper_postgres.go
  • pkg/database/generated_wrapper_mysql.go
  • pkg/database/generated_models.go

Comment thread pkg/cache/cache_prefetch_test.go Resolved
Comment thread pkg/cache/cache_prefetch_test.go Resolved
Comment thread pkg/cache/cdc_test.go Resolved
Comment thread testhelper/sqlite.go Resolved
Comment thread testhelper/sqlite.go Resolved
@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.50%. Comparing base (2c99e04) to head (952da54).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff            @@
##            main   #1218      +/-   ##
========================================
- Coverage   5.68%   5.50%   -0.19%     
========================================
  Files          6       6              
  Lines        387     400      +13     
========================================
  Hits          22      22              
- Misses       361     374      +13     
  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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants