Skip to content

Improve coverage#109

Merged
AlphaOne1 merged 8 commits intomasterfrom
improve_coverage
Mar 8, 2026
Merged

Improve coverage#109
AlphaOne1 merged 8 commits intomasterfrom
improve_coverage

Conversation

@AlphaOne1
Copy link
Copy Markdown
Owner

@AlphaOne1 AlphaOne1 commented Mar 8, 2026

Summary by CodeRabbit

  • Bug Fixes

    • More reliable transaction cleanup to avoid edge-case rollbacks.
    • Migration parsing improved to skip leading comments and correctly detect statement boundaries.
    • Added validations to ensure SQL templates include required placeholders.
  • Tests

    • Expanded tests to use an in-memory DB and added edge-case scenarios (closed DB, canceled context).
  • Chores

    • Updated Go version and bumped indirect dependency versions.
    • Re-enabled and configured linters and updated CI workflow steps.

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
…ups.

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
@AlphaOne1 AlphaOne1 self-assigned this Mar 8, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 8, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Re-enabled a linter, added a linter group, simplified transaction rollback with a universal deferred Rollback, added template "%s" assertions in tests, improved SQL migration line parsing with a regex/newStep approach, bumped several indirect Go modules and Go version, and converted migration tests to in-memory SQLite with new test doubles and edge-case tests.

Changes

Cohort / File(s) Summary
Linter configuration
\.golangci\.yaml
Re-enabled forbidigo; added wsl_v5 linter group disabling decl, err, and leading-whitespace.
Transaction cleanup
dialects.go
Replaced conditional rollback/panic patterns with a universal defer tx.Rollback(); removed explicit tx = nil assignments and simplified rollback handling.
SQL template tests
dialects_test.go
Added runtime assertions that CreateTemplate, AppliedTemplate, and RegisterTemplate each include a %s placeholder.
SQL statement parsing
file_migration.go
Added initialEmptyRegex and newStep tracking to skip leading empty/comment lines only at statement start; adjusted buffer/reset/step logic for statement assembly.
Migration flow tweaks
migration.go
Minor formatting and replaced short-declarations with assignments to avoid variable shadowing; no public API changes.
Tests: in-memory DB & doubles
migration_test.go
Switched tests from file-based DB to in-memory SQLite via openTempSQLite; added okDialect/oneMigration test doubles and new tests for closed DB and canceled context.
Dependency bumps
go.mod
Updated Go version to go 1.25.0; upgraded indirects: golang.org/x/mod, golang.org/x/sync, golang.org/x/sys, golang.org/x/tools, modernc.org/libc.
CI workflow
.github/workflows/security.yml
Swapped/renamed Trivy/GolangCI jobs, changed permissions and checkout depth, adjusted sarif outputs and upload steps, and renamed several steps and conditions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🐰
I nibble through code with a twitchy nose,
Deferred rollbacks tidy tidy rows,
NewStep hops, skipping comments in line,
In-memory tests help edge cases shine,
A rabbit hums — the diff smells fine! 🎉

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Improve coverage' is vague and generic, failing to convey what specific changes or aspects of the codebase are being improved. Replace with a more descriptive title that reflects the main changes, such as 'Add test coverage for dialects and migration edge cases' or 'Refactor transaction handling and improve test infrastructure'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch improve_coverage

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.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
file_migration.go (1)

123-159: ⚠️ Potential issue | 🟠 Major

Blank leading lines now disable comment stripping.

Line 159 flips newStep to false even when the current line is empty, so a step formatted as blank line → -- comment → SQL no longer treats that comment as leading. That can send comments to ExecContext again, which this helper is explicitly trying to avoid.

🔧 Suggested fix
 	for step = 0; scanner.Scan(); {
-		if newStep && strings.HasPrefix(scanner.Text(), "--") {
+		text := scanner.Text()
+		trimmed := strings.TrimSpace(text)
+
+		if newStep && trimmed == "" {
+			continue
+		}
+
+		if newStep && strings.HasPrefix(trimmed, "--") {
 			// skip leading comments
 			continue
 		}
 
-		if scanner.Text() == ";" {
+		if trimmed == ";" {
 			log.Info("migration step",
 				slog.String("migrationID", migrationID),
 				slog.Int("step", step),
@@
 		if buf.Len() > 0 {
 			buf.WriteByte('\n')
 		}
 
-		buf.Write(scanner.Bytes())
+		buf.WriteString(text)
 
 		newStep = false
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@file_migration.go` around lines 123 - 159, The loop that parses migration
steps marks newStep = false whenever it appends any line, but it doesn't skip
empty lines, so a blank line followed by a comment will not be treated as a
leading comment; update the logic around the scanner loop (the newStep variable
handling inside the loop that currently sets newStep = false after
buf.Write(scanner.Bytes())) to ignore empty lines when deciding to flip newStep
to false (i.e., if scanner.Text() is empty or only whitespace, do not set
newStep = false and do not append that blank line to the buffer), keeping the
existing handling for lines starting with "--" and the step termination on ";"
(use the existing variables newStep, step, buf, scanner, and tx.ExecContext to
locate the code to change).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@go.mod`:
- Line 35: Update the pinned module version for modernc.org/libc in go.mod to
v1.67.6 to match modernc.org/sqlite@v1.46.1: replace the modernc.org/libc
v1.69.0 line with v1.67.6, then run `go get modernc.org/libc@v1.67.6` (or `go
mod tidy`) to update go.sum and verify builds; ensure the change is committed.

In `@migration_test.go`:
- Around line 26-32: openTempSQLite currently opens sqlite with ":memory:" which
creates a separate in-memory DB per connection; because *sql.DB is a pool this
causes flaky tests—fix by making the DB use a single connection or a shared
in-memory DSN: after creating the DB in openTempSQLite, either call
db.SetMaxOpenConns(1) and db.SetMaxIdleConns(1) to pin the pool to one
connection, or open with a shared-memory DSN such as
"file::memory:?cache=shared" instead of ":memory:" so all connections see the
same DB; apply the change in the openTempSQLite function where
sql.Open("sqlite", ":memory:") is called and keep the require.NoError and
Cleanup behavior intact.

---

Outside diff comments:
In `@file_migration.go`:
- Around line 123-159: The loop that parses migration steps marks newStep =
false whenever it appends any line, but it doesn't skip empty lines, so a blank
line followed by a comment will not be treated as a leading comment; update the
logic around the scanner loop (the newStep variable handling inside the loop
that currently sets newStep = false after buf.Write(scanner.Bytes())) to ignore
empty lines when deciding to flip newStep to false (i.e., if scanner.Text() is
empty or only whitespace, do not set newStep = false and do not append that
blank line to the buffer), keeping the existing handling for lines starting with
"--" and the step termination on ";" (use the existing variables newStep, step,
buf, scanner, and tx.ExecContext to locate the code to change).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0cf33586-0115-4a14-a178-fb6e66b62ed4

📥 Commits

Reviewing files that changed from the base of the PR and between de5aea4 and 274a43e.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • .golangci.yaml
  • dialects.go
  • dialects_test.go
  • file_migration.go
  • go.mod
  • migration.go
  • migration_test.go

Comment thread go.mod
gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools/gotestsum v1.13.0 // indirect
modernc.org/libc v1.67.6 // indirect
modernc.org/libc v1.69.0 // indirect
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo_libc="$(
  sed -n 's/^[[:space:]]*modernc\.org\/libc[[:space:]]\+\(v[^[:space:]]\+\).*/\1/p' go.mod
)"

sqlite_libc="$(
  curl -fsSL https://proxy.golang.org/modernc.org/sqlite/@v/v1.46.1.mod \
    | sed -n 's/^[[:space:]]*modernc\.org\/libc[[:space:]]\+\(v[^[:space:]]\+\).*/\1/p'
)"

printf 'repo go.mod modernc.org/libc: %s\n' "$repo_libc"
printf 'modernc.org/sqlite@v1.46.1 expects: %s\n' "$sqlite_libc"

test -n "$repo_libc"
test -n "$sqlite_libc"
test "$repo_libc" = "$sqlite_libc"

Repository: AlphaOne1/dmorph

Length of output: 141


Downgrade modernc.org/libc to v1.67.6 to match modernc.org/sqlite@v1.46.1.

The current pinned version v1.69.0 does not match the version required by modernc.org/sqlite@v1.46.1, which expects v1.67.6. Since modernc.org/sqlite documents strict version coupling for this dependency, the mismatch must be resolved before merging.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@go.mod` at line 35, Update the pinned module version for modernc.org/libc in
go.mod to v1.67.6 to match modernc.org/sqlite@v1.46.1: replace the
modernc.org/libc v1.69.0 line with v1.67.6, then run `go get
modernc.org/libc@v1.67.6` (or `go mod tidy`) to update go.sum and verify builds;
ensure the change is committed.

Comment thread migration_test.go
…g with regex.

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
migration_test.go (1)

588-610: Add connection pool settings for consistency.

Unlike openTempSQLite, this test opens an in-memory SQLite database without setting SetMaxOpenConns(1) and SetMaxIdleConns(1). While the current test passes because the context is canceled before any DB operations, adding these settings would maintain consistency and prevent potential flakiness if the test logic evolves.

♻️ Suggested fix
 func TestApplyFailsOnCanceledContext(t *testing.T) {
 	t.Parallel()
 
 	db, err := sql.Open("sqlite", ":memory:")
-
 	require.NoError(t, err)
+	db.SetMaxOpenConns(1)
+	db.SetMaxIdleConns(1)
 
 	logger := slog.New(slog.DiscardHandler)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@migration_test.go` around lines 588 - 610, The test
TestApplyFailsOnCanceledContext opens an in-memory DB without configuring its
connection pool, which differs from openTempSQLite; modify the test to set
DB.SetMaxOpenConns(1) and DB.SetMaxIdleConns(1) right after creating db in
TestApplyFailsOnCanceledContext so the connection pool is consistent with
openTempSQLite and avoids potential flakiness when calling dmorph.Run with the
canceled context.
file_migration.go (1)

119-120: Move regex compilation to package level for efficiency.

The initialEmptyRegex is compiled on every call to applyStepsStream. Since the pattern is constant, compiling it once at package initialization would avoid repeated compilation overhead during migrations.

♻️ Suggested refactor

Add at package level (e.g., after line 19):

// initialEmptyRegex matches empty lines or lines containing only SQL comments.
var initialEmptyRegex = regexp.MustCompile(`^\s*(?:--.*)?$`)

Then remove line 119:

 func applyStepsStream(ctx context.Context, tx *sql.Tx, r io.Reader, migrationID string, log *slog.Logger) error {
 	const InitialScannerBufSize = 64 * 1024
 	const MaxScannerBufSize = 1024 * 1024
 
-	initialEmptyRegex := regexp.MustCompile(`^\s*(?:--.*)?$`)
-
 	buf := bytes.Buffer{}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@file_migration.go` around lines 119 - 120, The regex initialEmptyRegex is
being compiled inside applyStepsStream on every call which wastes CPU; move its
compilation to package initialization by declaring a package-level variable
named initialEmptyRegex (with the same pattern `^\s*(?:--.*)?$`) and remove the
local compilation inside applyStepsStream so the function uses the package-level
initialEmptyRegex instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@file_migration.go`:
- Around line 119-120: The regex initialEmptyRegex is being compiled inside
applyStepsStream on every call which wastes CPU; move its compilation to package
initialization by declaring a package-level variable named initialEmptyRegex
(with the same pattern `^\s*(?:--.*)?$`) and remove the local compilation inside
applyStepsStream so the function uses the package-level initialEmptyRegex
instead.

In `@migration_test.go`:
- Around line 588-610: The test TestApplyFailsOnCanceledContext opens an
in-memory DB without configuring its connection pool, which differs from
openTempSQLite; modify the test to set DB.SetMaxOpenConns(1) and
DB.SetMaxIdleConns(1) right after creating db in TestApplyFailsOnCanceledContext
so the connection pool is consistent with openTempSQLite and avoids potential
flakiness when calling dmorph.Run with the canceled context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c83abc38-171f-4627-b54a-3becd372c463

📥 Commits

Reviewing files that changed from the base of the PR and between 274a43e and f795afe.

📒 Files selected for processing (2)
  • file_migration.go
  • migration_test.go

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
migration_test.go (1)

587-607: Consider removing redundant db.Close() call.

Line 604's db.Close() is unnecessary since openTempSQLite already registers t.Cleanup(func() { _ = db.Close() }) on line 32. While sql.DB.Close() is idempotent and this won't cause issues, removing it improves consistency with other tests in this file.

♻️ Suggested simplification
 	)
 
-	require.NoError(t, db.Close())
 	require.Error(t, err)
 	require.ErrorContains(t, err, "context cancelled")
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@migration_test.go` around lines 587 - 607, The test
TestApplyFailsOnCanceledContext contains a redundant explicit call to db.Close()
after openTempSQLite already registered t.Cleanup to close the database; remove
the require.NoError(t, db.Close()) line so the test relies on openTempSQLite's
cleanup and matches other tests' pattern, leaving the context cancellation and
assertions (dmorph.Run call and require.Error/require.ErrorContains) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@migration_test.go`:
- Around line 587-607: The test TestApplyFailsOnCanceledContext contains a
redundant explicit call to db.Close() after openTempSQLite already registered
t.Cleanup to close the database; remove the require.NoError(t, db.Close()) line
so the test relies on openTempSQLite's cleanup and matches other tests' pattern,
leaving the context cancellation and assertions (dmorph.Run call and
require.Error/require.ErrorContains) unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5e755d63-09b1-484f-94bd-d87ca5e42f01

📥 Commits

Reviewing files that changed from the base of the PR and between f795afe and a6053b6.

📒 Files selected for processing (2)
  • file_migration.go
  • migration_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • file_migration.go

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
Signed-off-by: Alexander Adam <alphaone23@gmail.com>
@codecov-commenter
Copy link
Copy Markdown

⚠️ JUnit XML file not found

The CLI was unable to find any JUnit XML files to upload.
For more help, visit our troubleshooting guide.

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
… jobs, improved permission granularity, and aligned action versions.

Signed-off-by: Alexander Adam <alphaone23@gmail.com>
@github-advanced-security
Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out
the documentation.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/security.yml:
- Around line 95-107: The current printSarif step uses `grep results
govulncheck-results.sarif` which matches empty arrays; update the run script in
the step with id `printSarif` to parse the SARIF JSON
(`govulncheck-results.sarif`) with `jq` and set the `hasResults` output based on
the actual results array length (for example, use a command that computes total
results like `jq '[.runs[].results[]?] | length'` and then `if [ $COUNT -gt 0 ];
then echo "hasResults=true" >> $GITHUB_OUTPUT; else echo "hasResults=false" >>
$GITHUB_OUTPUT; fi`), ensuring `hasResults` drives the downstream upload step
correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eea87cab-625e-400e-bbf1-c48bc41b9a24

📥 Commits

Reviewing files that changed from the base of the PR and between f40f5be and bef9a9b.

📒 Files selected for processing (1)
  • .github/workflows/security.yml

Comment thread .github/workflows/security.yml
@AlphaOne1 AlphaOne1 merged commit d4b55ba into master Mar 8, 2026
19 checks passed
@AlphaOne1 AlphaOne1 deleted the improve_coverage branch March 8, 2026 17:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants