Skip to content

Conversation

@isasmendiagus
Copy link
Contributor

@isasmendiagus isasmendiagus commented Jan 27, 2026

  • Add DBVersionModel to query the db_version table for schema version, package name, release, and creation date
  • Handle databases that don't have the db_version table by checking sqlite_master before querying, returning ErrTableNotFound sentinel error
  • Truncate created_at to date-only resolution (time.DateOnly) since time precision is not needed
  • Add shared errors.go with ErrTableNotFound and tableExists helper

Summary by CodeRabbit

  • New Features

    • Added database version tracking to monitor schema versions and release information.
  • Tests

    • Added comprehensive test coverage for version retrieval, including scenarios for missing tables and empty data states.

✏️ Tip: You can customize this high-level summary in your review settings.

@isasmendiagus isasmendiagus requested a review from eeisegn January 27, 2026 17:27
@coderabbitai
Copy link

coderabbitai bot commented Jan 27, 2026

Warning

Rate limit exceeded

@isasmendiagus has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 44 seconds before requesting another review.

⌛ 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.

📝 Walkthrough

Walkthrough

Introduces a new database version model and related infrastructure. Adds a DBVersionModel type for querying database version information, an error sentinel for missing tables, a table existence helper function, SQL seed data, comprehensive test coverage, and integrates the new model into the existing Models package.

Changes

Cohort / File(s) Summary
Test Data & SQL
internal/testutils/mock/db_version.sql
New SQL seed script defining db_version table with four text columns (package_name, schema_version, created_at, db_release) and inserting a base version row
Model Implementation
pkg/models/db_version.go, pkg/models/errors.go
Introduces DBVersionModel and DBVersion types; GetCurrentVersion method queries db_version table with table existence check and timestamp normalization; adds ErrTableNotFound error sentinel and tableExists helper utility
Model Tests
pkg/models/db_version_test.go
Three test functions covering successful version retrieval, missing table error handling, and empty table scenarios; configures test database and validates error behavior
Package Integration
pkg/models/models.go, pkg/models/models_test.go
Adds DBVersion field to Models struct; initializes via NewDBVersionModel; extends TestNewDB with assertion for DBVersion initialization

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A version table hops into view,
With schemas tracked and tables new,
Test data seeds the fertile ground,
Where database truths are safely found!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the primary change: introducing a DBVersion model with table existence checking functionality.

✏️ 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 feat/SP-3636/add-db-version-model

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

@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

🤖 Fix all issues with AI agents
In `@pkg/models/db_version_test.go`:
- Around line 54-55: The test assertion message is wrong: it checks that
version.PackageName == "base" but the error text says "want components"; update
the failure message in pkg/models/db_version_test.go so the t.Errorf for the
version.PackageName check reads that it wants "base" (or otherwise matches the
expected value) to reflect the actual expectation when
DBVersionModel.GetCurrentVersion() fails.

In `@pkg/models/errors.go`:
- Around line 31-36: Change tableExists to return (bool, error) instead of
masking all query errors as "table not found": have tableExists(ctx, db
*sqlx.DB, tableName string) perform the QueryRowContext call, return exists and
err (nil on success) so callers can distinguish missing table vs DB/context
errors; then update DBVersionModel.GetCurrentVersion to call tableExists,
propagate any non-nil error to the caller (instead of converting all failures
into ErrTableNotFound), and only return ErrTableNotFound when tableExists
reports false with no underlying error.
🧹 Nitpick comments (1)
pkg/models/db_version.go (1)

60-61: Make “current version” deterministic.

LIMIT 1 without ORDER BY can return an arbitrary row if multiple entries exist. Consider ordering by created_at (or a version column) to ensure you always get the latest record.

♻️ Suggested tweak
-	err := m.db.QueryRowxContext(ctx,
-		"SELECT package_name, schema_version, created_at, db_release FROM db_version LIMIT 1").StructScan(&dbVersion)
+	err := m.db.QueryRowxContext(ctx,
+		"SELECT package_name, schema_version, created_at, db_release FROM db_version ORDER BY created_at DESC LIMIT 1").StructScan(&dbVersion)

Comment on lines +54 to +55
if version.PackageName != "base" {
t.Errorf("DBVersionModel.GetCurrentVersion() package_name = %v, want components", version.PackageName)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix the assertion message to match expected value.

The check expects base, but the failure message says “components”.

💚 Proposed fix
-	if version.PackageName != "base" {
-		t.Errorf("DBVersionModel.GetCurrentVersion() package_name = %v, want components", version.PackageName)
-	}
+	if version.PackageName != "base" {
+		t.Errorf("DBVersionModel.GetCurrentVersion() package_name = %v, want base", version.PackageName)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if version.PackageName != "base" {
t.Errorf("DBVersionModel.GetCurrentVersion() package_name = %v, want components", version.PackageName)
if version.PackageName != "base" {
t.Errorf("DBVersionModel.GetCurrentVersion() package_name = %v, want base", version.PackageName)
}
🤖 Prompt for AI Agents
In `@pkg/models/db_version_test.go` around lines 54 - 55, The test assertion
message is wrong: it checks that version.PackageName == "base" but the error
text says "want components"; update the failure message in
pkg/models/db_version_test.go so the t.Errorf for the version.PackageName check
reads that it wants "base" (or otherwise matches the expected value) to reflect
the actual expectation when DBVersionModel.GetCurrentVersion() fails.

Comment on lines +31 to +36
func tableExists(ctx context.Context, db *sqlx.DB, tableName string) bool {
var exists bool
err := db.QueryRowContext(ctx,
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)",
tableName).Scan(&exists)
return err == nil && exists
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don’t mask DB errors as “table not found”.

tableExists treats any query error as “missing table,” which can hide connection/context failures and mislead callers. Return the error and let the caller decide.

🐛 Proposed fix
-func tableExists(ctx context.Context, db *sqlx.DB, tableName string) bool {
-	var exists bool
-	err := db.QueryRowContext(ctx,
-		"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)",
-		tableName).Scan(&exists)
-	return err == nil && exists
-}
+func tableExists(ctx context.Context, db *sqlx.DB, tableName string) (bool, error) {
+	var exists bool
+	err := db.QueryRowContext(ctx,
+		"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)",
+		tableName).Scan(&exists)
+	if err != nil {
+		return false, err
+	}
+	return exists, nil
+}

Update DBVersionModel.GetCurrentVersion to propagate the error instead of returning ErrTableNotFound on query failures.

🤖 Prompt for AI Agents
In `@pkg/models/errors.go` around lines 31 - 36, Change tableExists to return
(bool, error) instead of masking all query errors as "table not found": have
tableExists(ctx, db *sqlx.DB, tableName string) perform the QueryRowContext
call, return exists and err (nil on success) so callers can distinguish missing
table vs DB/context errors; then update DBVersionModel.GetCurrentVersion to call
tableExists, propagate any non-nil error to the caller (instead of converting
all failures into ErrTableNotFound), and only return ErrTableNotFound when
tableExists reports false with no underlying error.

Signed-off-by: Agustin Isasmendi <agustin.isasmendi@scanoss.com>
Signed-off-by: Agustin Isasmendi <agustin.isasmendi@scanoss.com>
@isasmendiagus isasmendiagus force-pushed the feat/SP-3636/add-db-version-model branch from 6395346 to 48c9ad5 Compare January 30, 2026 15:49
@isasmendiagus isasmendiagus merged commit f1d3b1f into main Jan 30, 2026
2 checks passed
@isasmendiagus isasmendiagus deleted the feat/SP-3636/add-db-version-model branch January 30, 2026 15:51
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