Skip to content

Migrate db logic to service layer - #69

Merged
jlpdeveloper merged 12 commits into
mainfrom
update-products-platforms
May 21, 2026
Merged

Migrate db logic to service layer#69
jlpdeveloper merged 12 commits into
mainfrom
update-products-platforms

Conversation

@jlpdeveloper

@jlpdeveloper jlpdeveloper commented May 21, 2026

Copy link
Copy Markdown
Contributor

Description

Code Rabbit Summary

Summary by CodeRabbit

Release Notes

  • New Features

    • Platform creation now returns the full platform data in the response.
  • Bug Fixes

    • Improved error handling for "not found" scenarios across platform and flow operations.
  • Build & Testing

    • Added Windows support for test coverage reporting.

Review Change Stack

Fixes

Closes #66

Post Deployment Tasks?

@jlpdeveloper jlpdeveloper self-assigned this May 21, 2026
@jlpdeveloper jlpdeveloper added enhancement New feature or request skip-changelog Won't be added to the release notes labels May 21, 2026
@coderabbitai

coderabbitai Bot commented May 21, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@jlpdeveloper has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 47 minutes and 22 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 46183ea6-4d54-4031-8321-7fb9865f4506

📥 Commits

Reviewing files that changed from the base of the PR and between de870ab and 1972c95.

📒 Files selected for processing (3)
  • internal/platform/service.go
  • internal/platform/service_test.go
  • internal/product/service_test.go
📝 Walkthrough

Walkthrough

This pull request refactors the platform, product, and flow packages by migrating sqlc-generated database code to dedicated /db subdirectories, introducing service layers to abstract database error handling from handlers, and removing exported handler interfaces. The changes establish a consistent, layered architecture across three packages.

Changes

Database Service Layer Refactoring and Package Reorganization

Layer / File(s) Summary
SQLC Configuration and DB Package Generation
sqlc.yml, internal/platform/db/*.gen.go, internal/product/db/*.gen.go
sqlc.yml output paths changed to generate code under /db subdirectories. All generated files across both packages update their package declarations from platform/product to db to align with the new directory structure.
Platform Service Layer and SQL Query Update
internal/platform/platforms.sql, internal/platform/request.go, internal/platform/service.go, internal/platform/service_test.go
New postgresService implements platformService interface, wrapping db.Querier calls and normalizing errors. CreatePlatform SQL query updated to return full inserted row (:one with RETURNING *). Request mapping methods return db.CreatePlatformParams and db.UpdatePlatformParams. Service tests cover success and error paths using local mockQuerier.
Platform Handler Refactoring and Interface Removal
internal/platform/handler.go, internal/platform/handler_test.go, internal/platform/interface.go
Handler accepts db.DBTX, constructs postgresService via db.New, and delegates to service methods. Error handling switches from pgx.ErrNoRows to errors.Is(err, internal.NotFoundError{}). CreatePlatform now returns created platform as JSON. Response types use []db.Platform. Exported Handler interface removed. Handler tests refactored to use service-based mock with new types.
Product Service Layer and Request Updates
internal/product/request.go, internal/product/service.go, internal/product/service_test.go
New postgresService implements productService interface, delegating CRUD to db.Querier and normalizing pgx.ErrNoRows to internal.NotFoundError. Request methods return db.CreateProductParams and db.UpdateProductParams. Service tests cover success and error scenarios with mockQuerier.
Product Handler Refactoring and Interface Removal
internal/product/handler.go, internal/product/handler_test.go, internal/product/interface.go
Handler accepts db.DBTX, constructs postgresService, and calls service instead of direct query layer. Error handling switches from pgx.ErrNoRows to errors.Is(err, internal.NotFoundError{}). Response types changed to []db.Product. Exported Handler interface removed. Handler tests completely rewired to use service-based mockProductService with updated assertions.
Flow Package Interface Consolidation
internal/flow/handler.go, internal/flow/handler_test.go, internal/flow/service.go, internal/flow/interface.go
Exported Handler interface removed from interface.go; handler methods added directly to handler.go. NewHandler constructs postgresService (renamed from service). Internal flowService interface introduced. Service and handler tests updated to use postgresService.
Development Tools and Environment Configuration
.gitignore, justfile
.gitignore excludes .junie and coverage.out. justfile test-cover refactored with Windows-specific [windows] variant using PowerShell and filtering packages to exclude /db folders.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • service-atlas/products#60: Adds initial flow sqlc/handler/interface scaffolding; this PR refactors flow handler interface consolidation and postgresService wiring.
  • service-atlas/products#50: Touches platform/product handler layer contracts and wiring; this PR further refactors handlers to use postgresService and removes Handler interfaces.
  • service-atlas/products#16: Adds sqlc.yml and justfile for SQL-to-Go generation; this PR updates sqlc output paths and regenerates code with new package namespaces.

Suggested labels

chore

Poem

🐰 A rabbit hops through packages neat,
DB code now has its own retreat,
Service layers catch the postgres pain,
Errors flow through cleaner lane,
Interfaces consolidate with care—
Refactored code now everywhere! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive Minor out-of-scope changes detected: .gitignore updates for .junie and coverage.out, flow package refactoring (service→postgresService), and Windows-specific justfile recipe addition are not part of issue #66 requirements. While these changes are reasonable housekeeping, clarify whether .gitignore, flow refactoring, and justfile updates should have been included in this PR or addressed separately.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Migrate db logic to service layer' directly summarizes the main objective of moving database logic into service layers for products and platforms packages.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #66: sqlc code moved to /db folders, imports updated, service layers created wrapping db calls, error translation implemented, and handlers updated to use service-layer errors.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch update-products-platforms

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@jlpdeveloper jlpdeveloper added this to the Phase 2: API Endpoints milestone May 21, 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: 3

Caution

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

⚠️ Outside diff range comments (2)
internal/platform/handler_test.go (1)

102-126: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Create success test should assert the JSON payload, not only status.

The endpoint contract changed to return the created platform body on 201, but this test only checks status. Add response body assertions for the success case.

As per coding guidelines, "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request".

🤖 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 `@internal/platform/handler_test.go` around lines 102 - 126, The CreatePlatform
test only checks HTTP status but must also assert the JSON response body on
success (201); update the table-driven test to include an expected response
platform value and modify the mockPlatformService.createPlatform to return that
db.Platform for the success case, then after h.CreatePlatform(rr, req) when
tt.expectedStatus == http.StatusCreated unmarshal rr.Body into a db.Platform and
compare its fields to the expected platform (or deep-equal the struct) to ensure
the handler actually writes the created platform JSON; focus changes around
platformHandler.CreatePlatform test setup and the mock createPlatform return
values.
internal/product/handler_test.go (1)

392-396: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assert GetProductById response payload fields in the success path.

The success test currently validates only status and content type. Since the handler now returns db.Product, add body assertions (e.g., ID, Name) to lock the contract.

Suggested assertion update
 			if tt.expectedStatus == http.StatusOK {
 				if rr.Header().Get("Content-Type") != "application/json" {
 					t.Errorf("expected Content-Type application/json, got %v", rr.Header().Get("Content-Type"))
 				}
+				var got db.Product
+				if err := json.NewDecoder(rr.Body).Decode(&got); err != nil {
+					t.Fatalf("failed to decode response: %v", err)
+				}
+				if got.ID != 1 || got.Name != "Test Product" {
+					t.Errorf("unexpected product payload: %+v", got)
+				}
 			}

As per coding guidelines, **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request".

🤖 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 `@internal/product/handler_test.go` around lines 392 - 396, The success branch
in the test currently only checks status and Content-Type; update the success
path (inside the if tt.expectedStatus == http.StatusOK block in handler_test.go)
to decode rr.Body into a db.Product (or the concrete product struct used by the
handler, e.g., db.Product) using json.Decoder and assert critical fields like ID
and Name (and any other contract fields like Price or SKU) match the expected
values from the test case (e.g., tt.expectedProduct or the fixture used to set
up the mock). Ensure decoding errors are handled with t.Fatalf/t.Errorf and only
run these assertions for the HTTP 200 case so the contract is locked for
GetProductById.
🤖 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 `@internal/platform/service.go`:
- Around line 47-55: The UpdatePlatform (and similarly DeletePlatform) service
should detect pgx.ErrNoRows returned by p.db.UpdatePlatform (and
p.db.DeletePlatform) and map it to an internal.NotFound error instead of
propagating a 500: in postgresService.UpdatePlatform (and DeletePlatform) check
if errors.Is(err, pgx.ErrNoRows) and return internal.NewNotFoundError(id,
"Platform"); otherwise return the original err; keep the existing use of
req.ToParams(id) for UpdatePlatform and ensure you import/errors.Is and pgx
types as needed.

In `@internal/product/service_test.go`:
- Around line 68-186: The tests currently only cover success and NotFound
branches; add additional subtests for GetProductsByPlatform, GetProductById,
UpdateProduct, and DeleteProduct that exercise the non-not-found DB error path
by having the mockQuerier methods (getProductsByPlatform, getProductById,
updateProduct, deleteProduct) return a non-pgx.ErrNoRows error (e.g., a sentinel
errors.New("db error")) and assert the service methods (GetProductsByPlatform,
GetProductById, UpdateProduct, DeleteProduct) propagate that error (use
errors.Is or direct comparison) so the error-pass-through behavior is verified.

In `@justfile`:
- Around line 18-22: The justfile currently defines a Windows-only recipe for
test-cover under the [windows] attribute, removing the default Unix-like recipe
and breaking cross-platform use; add back a default test-cover recipe (name:
test-cover) that runs the equivalent commands for Unix shells (e.g., use a shell
pipeline to list packages excluding /db, run go test with -covermode=count
-coverprofile=coverage.out, then run go tool cover -func=coverage.out), and keep
the existing [windows] test-cover override for Windows-specific PowerShell
syntax so both platforms can run just test-cover.

---

Outside diff comments:
In `@internal/platform/handler_test.go`:
- Around line 102-126: The CreatePlatform test only checks HTTP status but must
also assert the JSON response body on success (201); update the table-driven
test to include an expected response platform value and modify the
mockPlatformService.createPlatform to return that db.Platform for the success
case, then after h.CreatePlatform(rr, req) when tt.expectedStatus ==
http.StatusCreated unmarshal rr.Body into a db.Platform and compare its fields
to the expected platform (or deep-equal the struct) to ensure the handler
actually writes the created platform JSON; focus changes around
platformHandler.CreatePlatform test setup and the mock createPlatform return
values.

In `@internal/product/handler_test.go`:
- Around line 392-396: The success branch in the test currently only checks
status and Content-Type; update the success path (inside the if
tt.expectedStatus == http.StatusOK block in handler_test.go) to decode rr.Body
into a db.Product (or the concrete product struct used by the handler, e.g.,
db.Product) using json.Decoder and assert critical fields like ID and Name (and
any other contract fields like Price or SKU) match the expected values from the
test case (e.g., tt.expectedProduct or the fixture used to set up the mock).
Ensure decoding errors are handled with t.Fatalf/t.Errorf and only run these
assertions for the HTTP 200 case so the contract is locked for GetProductById.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: afa68d24-5165-4f5b-b971-9fd85024f460

📥 Commits

Reviewing files that changed from the base of the PR and between f2fa951 and de870ab.

📒 Files selected for processing (29)
  • .gitignore
  • internal/flow/handler.go
  • internal/flow/handler_test.go
  • internal/flow/interface.go
  • internal/flow/service.go
  • internal/flow/service_test.go
  • internal/platform/db/db.gen.go
  • internal/platform/db/models.gen.go
  • internal/platform/db/platforms.sql.gen.go
  • internal/platform/db/querier.gen.go
  • internal/platform/handler.go
  • internal/platform/handler_test.go
  • internal/platform/interface.go
  • internal/platform/platforms.sql
  • internal/platform/request.go
  • internal/platform/service.go
  • internal/platform/service_test.go
  • internal/product/db/db.gen.go
  • internal/product/db/models.gen.go
  • internal/product/db/products.sql.gen.go
  • internal/product/db/querier.gen.go
  • internal/product/handler.go
  • internal/product/handler_test.go
  • internal/product/interface.go
  • internal/product/request.go
  • internal/product/service.go
  • internal/product/service_test.go
  • justfile
  • sqlc.yml
💤 Files with no reviewable changes (3)
  • internal/product/interface.go
  • internal/platform/interface.go
  • internal/flow/interface.go

Comment thread internal/platform/service.go
Comment thread internal/product/service_test.go
Comment thread justfile
@jlpdeveloper
jlpdeveloper merged commit 3eb68e8 into main May 21, 2026
3 checks passed
@jlpdeveloper
jlpdeveloper deleted the update-products-platforms branch May 21, 2026 01:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request skip-changelog Won't be added to the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate product and platform sqlc to /db folder

1 participant