Skip to content

feat(cache): convert populateNarInfoFromDatabase to Ent - #1198

Merged
kalbasit merged 1 commit into
mainfrom
feat-cache-populate-narinfo-ent
May 22, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-cache-populate-narinfo-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.2 continuation. Switches the cache's central narinfo-read
helper from the qtx-style Querier closures (sqlc shape: row
fields are sql.Null*, references/signatures fetched in
separate queries by ID) to the Ent fluent API (row fields are
*string/*int64 pointers, references and signatures eager-loaded
in one round-trip via WithReferences() / WithSignatures()).

Specifically:

  • populateNarInfoFromDatabase(ctx, tx *ent.Tx, hash, touch):

    • tx.NarInfo.Query().Where(HashEQ(hash)).WithReferences() .WithSignatures().Only(ctx) replaces three separate
      Querier calls (GetNarInfoByHash + GetNarInfoReferences +
      GetNarInfoSignatures). One query, one round-trip.
    • ent.IsNotFound(err) replaces database.IsNotFoundError.
    • sql.NullString/NullInt64 reads (x.URL.Valid, x.URL.String,
      x.FileSize.Int64, …) become pointer dereferences via
      derefStringPtr/derefInt64Ptr helpers introduced in this
      commit. parseValidHashPtr is the *string counterpart to
      parseValidHash and replaces it (the sql.NullString
      version was the helper's only caller, so removed).
    • Touch logic (if time.Since(LastAccessedAt) > recordAgeIgnoreTouch) now reads *time.Time directly and
      calls tx.NarInfo.Update().Where(HashEQ(hash)) .SetLastAccessedAt(time.Now()).Save(ctx) instead of the
      sqlc-generated TouchNarInfo.
  • The one caller getNarInfoFromDatabase switches from
    c.withTransaction(ctx, op, func(qtx database.Querier)) to
    c.withEntTransaction(ctx, op, func(tx *ent.Tx)), the helper
    added in feat-cache-with-ent-transaction.

Both parseValidHashPtr and the deref helpers are written to
be reusable for upcoming §11 conversions (PutNarInfo,
GetNarFile, fsck) that face the same null-shape translation.

Behaviour-preserving by construction:

  • The eager-load result iteration order matches sqlc's. For
    references it's narinfo_references.id ASC because the join
    uses the row order; the prior GetNarInfoReferences query
    ordered by reference's PRIMARY KEY (id) too, so the slice
    is identical.
  • Touch is gated by the same recordAgeIgnoreTouch threshold
    and emits an UPDATE only when stale.
  • "Stub" narinfos (URL NULL/empty) still return
    storage.ErrNotFound.

Verified by go test -race ./pkg/cache/... against SQLite +
Postgres + MySQL + Redis. Lint clean.

@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 refactor-testhelper-use-migrate-up branch from 7476f56 to d47e51b Compare May 22, 2026 05:33
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 215d89f to 52a4512 Compare May 22, 2026 05:33
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from d47e51b to 6caee71 Compare May 22, 2026 05:46
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 52a4512 to 0e52ed8 Compare May 22, 2026 05:46
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from 6caee71 to b63df34 Compare May 22, 2026 05:59
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 0e52ed8 to 17f74d6 Compare May 22, 2026 05:59
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from b63df34 to 7eb0409 Compare May 22, 2026 06:47
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 17f74d6 to d8ee4c7 Compare May 22, 2026 06:47
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from 7eb0409 to 69fd9fc Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from d8ee4c7 to b1c416c Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from 69fd9fc to 756cb1b Compare May 22, 2026 18:07
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from b1c416c to 3724df5 Compare May 22, 2026 18:07
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6518a214-2c09-4c4e-a8bf-96fa0bf5e0b1

📥 Commits

Reviewing files that changed from the base of the PR and between d394450 and 6589260.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

📝 Walkthrough

Summary by CodeRabbit

  • Refactor
    • Optimized cache database query efficiency through improved data retrieval and field handling.

Walkthrough

This PR migrates getNarInfoFromDatabase from a legacy multi-query row-fetch pattern to a single Ent-backed eager-loading query. The entry point now delegates through withEntTransaction to a new populateNarInfoFromDatabase helper that consolidates reference and signature queries, dereferences nullable Ent fields, and updates the touch-record path to use Ent's update builder.

Changes

NarInfo Ent Migration

Layer / File(s) Summary
NarInfo query and record touch via Ent
pkg/cache/cache.go
getNarInfoFromDatabase entry point switches to withEntTransaction and delegates to new populateNarInfoFromDatabase. The helper executes a single Ent query with eager-loaded references and signatures, returns storage.ErrNotFound for nil/empty stored URLs, dereferences nullable Ent fields to build narinfo.NarInfo, parses nullable hashes via pointer-aware parsing, and converts signature edges. Touch-record path updates LastAccessedAt through Ent's update builder with nil and stale-timestamp handling. Minor nolint cleanup.
Ent nullable field helpers
pkg/cache/cache.go
New parseValidHashPtr, derefStringPtr, and derefInt64Ptr helpers support dereferencing Ent nullable field shapes. Legacy parseValidHash(sql.NullString, ...) removed.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant getNarInfoFromDatabase
  participant withEntTransaction
  participant populateNarInfoFromDatabase
  participant EntClient
  participant EntUpdate
  Caller->>getNarInfoFromDatabase: request narinfo
  getNarInfoFromDatabase->>withEntTransaction: begin Ent tx
  withEntTransaction->>populateNarInfoFromDatabase: call with *ent.Tx
  populateNarInfoFromDatabase->>EntClient: Ent query (eager-load refs & sigs)
  EntClient-->>populateNarInfoFromDatabase: Ent entity + edges
  populateNarInfoFromDatabase->>populateNarInfoFromDatabase: deref nullable fields, parse hashes, parse signatures
  alt touch enabled
    populateNarInfoFromDatabase->>EntUpdate: Ent update LastAccessedAt (nil or stale handling)
    EntUpdate-->>populateNarInfoFromDatabase: update result
  end
  populateNarInfoFromDatabase-->>withEntTransaction: return NarInfo
  withEntTransaction-->>getNarInfoFromDatabase: commit/return
  getNarInfoFromDatabase-->>Caller: NarInfo or ErrNotFound
Loading

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

  • kalbasit/ncps#1194: Introduced withEntTransaction wrapper that this PR now routes getNarInfoFromDatabase through, enabling the Ent-based transaction and eager-loading query migration.
  • kalbasit/ncps#1191: Related Ent transaction surface changes (Client.WithTransaction) that tie into this PR's use of Ent transactions.
  • kalbasit/ncps#1193: Other conversions of narinfo retrieval to Ent queries; part of the same Ent-based refactor.

Suggested Labels

size:M

🐰 I hopped through rows and swapped old calls for new,
One eager query now from what once were two,
Nullable pointers gently deref'd with care,
Signatures parsed and touched timestamps fair,
A rabbit's nibble turned the DB anew.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: converting populateNarInfoFromDatabase to use Ent instead of the prior qtx/sqlc-style Querier approach, which is the central objective of this PR.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the migration from Querier to Ent API, specific function signatures, query consolidation, null-type handling, and behavior preservation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 refactor-testhelper-use-migrate-up branch from 756cb1b to 7f0de59 Compare May 22, 2026 19:02
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 3724df5 to 1a69830 Compare May 22, 2026 19:02
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from 7f0de59 to d963c81 Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 1a69830 to d394450 Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the refactor-testhelper-use-migrate-up branch from d963c81 to 196e69e Compare May 22, 2026 20:51
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from d394450 to dfd6326 Compare May 22, 2026 20:51
Base automatically changed from refactor-testhelper-use-migrate-up to main May 22, 2026 21:04
§11.2 continuation. Switches the cache's central narinfo-read
helper from the qtx-style Querier closures (sqlc shape: row
fields are sql.Null*, references/signatures fetched in
separate queries by ID) to the Ent fluent API (row fields are
*string/*int64 pointers, references and signatures eager-loaded
in one round-trip via `WithReferences()` / `WithSignatures()`).

Specifically:

- `populateNarInfoFromDatabase(ctx, tx *ent.Tx, hash, touch)`:
  - `tx.NarInfo.Query().Where(HashEQ(hash)).WithReferences()
    .WithSignatures().Only(ctx)` replaces three separate
    Querier calls (GetNarInfoByHash + GetNarInfoReferences +
    GetNarInfoSignatures). One query, one round-trip.
  - `ent.IsNotFound(err)` replaces `database.IsNotFoundError`.
  - sql.NullString/NullInt64 reads (`x.URL.Valid`, `x.URL.String`,
    `x.FileSize.Int64`, …) become pointer dereferences via
    `derefStringPtr`/`derefInt64Ptr` helpers introduced in this
    commit. `parseValidHashPtr` is the *string counterpart to
    `parseValidHash` and replaces it (the sql.NullString
    version was the helper's only caller, so removed).
  - Touch logic (`if time.Since(LastAccessedAt) >
    recordAgeIgnoreTouch`) now reads `*time.Time` directly and
    calls `tx.NarInfo.Update().Where(HashEQ(hash))
    .SetLastAccessedAt(time.Now()).Save(ctx)` instead of the
    sqlc-generated `TouchNarInfo`.

- The one caller `getNarInfoFromDatabase` switches from
  `c.withTransaction(ctx, op, func(qtx database.Querier))` to
  `c.withEntTransaction(ctx, op, func(tx *ent.Tx))`, the helper
  added in `feat-cache-with-ent-transaction`.

Both `parseValidHashPtr` and the deref helpers are written to
be reusable for upcoming §11 conversions (PutNarInfo,
GetNarFile, fsck) that face the same null-shape translation.

Behaviour-preserving by construction:

- The eager-load result iteration order matches sqlc's. For
  references it's narinfo_references.id ASC because the join
  uses the row order; the prior GetNarInfoReferences query
  ordered by reference's PRIMARY KEY (id) too, so the slice
  is identical.
- Touch is gated by the same recordAgeIgnoreTouch threshold
  and emits an UPDATE only when stale.
- "Stub" narinfos (URL NULL/empty) still return
  storage.ErrNotFound.

Verified by `go test -race ./pkg/cache/...` against SQLite +
Postgres + MySQL + Redis. Lint clean.
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from dfd6326 to 6589260 Compare May 22, 2026 21:04
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 21:05
@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.68%. Comparing base (5e92e11) to head (6589260).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1198   +/-   ##
=====================================
  Coverage   5.68%   5.68%           
=====================================
  Files          6       6           
  Lines        387     387           
=====================================
  Hits          22      22           
  Misses       361     361           
  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 merged commit 7c26ac7 into main May 22, 2026
16 checks passed
@kalbasit
kalbasit deleted the feat-cache-populate-narinfo-ent branch May 22, 2026 21:16
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