Skip to content

Pull Request#214

Open
aditisb1212-lab wants to merge 15 commits into
roshankumar0036singh:mainfrom
aditisb1212-lab:main
Open

Pull Request#214
aditisb1212-lab wants to merge 15 commits into
roshankumar0036singh:mainfrom
aditisb1212-lab:main

Conversation

@aditisb1212-lab

@aditisb1212-lab aditisb1212-lab commented Jun 21, 2026

Copy link
Copy Markdown

Checklist

  • I have read and signed the CLA by commenting I have read the CLA and agree to its terms. on this PR.
  • My changes follow the project's coding style.
  • I have tested my changes.

Summary by CodeRabbit

  • New Features
    • Expanded the environment example with explicit database connection variables (host, port, user, password, database).
    • Added connection pool configuration (max open/idle connections and timeout/lifetime settings) plus validation.
    • Updated database initialization to support MySQL and improved diagnostics via database stats and health checks (reachability and pool “near capacity” status).
  • Bug Fixes
    • Cleaned up the FORGOT_RATE_LIMIT_WINDOW value formatting by removing the //ms suffix.
  • Chores
    • Updated the pull request checklist header formatting.

Closes<#187>

@coderabbitai

coderabbitai Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR migrates the database layer from Postgres to MySQL by introducing a DBConfig struct with a LoadDBConfig loader in config.go, rewriting InitDatabase in database.go to build a MySQL DSN, configure GORM with connection pool parameters, and expose a global DB. Two new helpers, GetDBStats and HealthCheckDatabase, are added for runtime pool monitoring. The .env.example is updated with corresponding MySQL and pool variables.

Changes

MySQL Database Configuration and Health

Layer / File(s) Summary
DBConfig struct and LoadDBConfig loader
.env.example, internal/config/config.go
Adds DBConfig struct (host, port, credentials, pool fields), LoadDBConfig() that reads and validates env vars, getEnv/getEnvInt helpers with default fallback and warning on invalid integers, fmt import, and matching MySQL/pool env var definitions in .env.example.
MySQL InitDatabase rewrite and global DB
internal/config/database.go
Rewrites InitDatabase to accept DBConfig, construct a MySQL DSN, open GORM with the MySQL driver, configure all connection pool parameters, ping-verify connectivity, and set the exported var DB *gorm.DB. Removes the prior Postgres-based initializer and AutoMigrate. Adds database/sql import.
GetDBStats and HealthCheckDatabase helpers
internal/config/database.go
Adds GetDBStats returning pool metrics map from the global DB, and HealthCheckDatabase returning a health/message/stats map with nil-check, ping failure, and near-capacity (≥95 open connections) detection.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant LoadDBConfig
    participant InitDatabase
    participant GORM
    participant MySQL

    App->>LoadDBConfig: read env vars
    LoadDBConfig-->>App: DBConfig (validated)
    App->>InitDatabase: InitDatabase(DBConfig)
    InitDatabase->>GORM: gorm.Open(mysql DSN)
    GORM->>MySQL: TCP connect
    MySQL-->>GORM: connection
    InitDatabase->>GORM: configure pool (open/idle/lifetime/idle-time)
    InitDatabase->>MySQL: Ping()
    MySQL-->>InitDatabase: pong
    InitDatabase-->>App: nil (global DB set)

    rect rgba(100, 180, 255, 0.5)
        App->>HealthCheckDatabase: check
        HealthCheckDatabase->>MySQL: Ping()
        HealthCheckDatabase-->>App: healthy/unhealthy + stats
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • roshankumar0036singh/auth-server#196: Directly connected — introduces the same ConnMaxLifetime and ConnMaxIdleTime fields in the config layer and applies them to the connection pool in internal/config/database.go.

Suggested labels

Hard

🐇 A bunny once dug through the code so deep,
Swapped Postgres for MySQL while half asleep!
With pools and pings and a health check too,
GetDBStats knows what the connections do. 🌿
Now .env.example shows the way —
Hop along, the DB's here to stay! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 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 "Pull Request" is vague and generic, providing no meaningful information about the changeset's purpose or main modifications. Replace with a descriptive title that summarizes the main change, such as "Migrate database configuration to MySQL with connection pool settings" or "Add MySQL database configuration and pool management".
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Description check ✅ Passed The PR description matches the required checklist template and includes all required checklist items, with an issue reference added.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@github-actions

github-actions Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA. ✅ Thank you!
Posted by the CLA Assistant Lite bot.

@aditisb1212-lab

Copy link
Copy Markdown
Author

Thank you for your contribution! Before we can merge this PR, we need you to sign our Contributor License Agreement. To sign, please post a comment on this PR with the following exact text: I have read the CLA and agree to its terms

I have read the CLA and agree to its terms.

You can retrigger this bot by commenting recheck in this Pull Request. Posted by the CLA Assistant Lite bot.

I have read the CLA and agree to its terms

@aditisb1212-lab

Copy link
Copy Markdown
Author

I have read the CLA and agree to its terms

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 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 @.env.example:
- Line 70: The FORGOT_RATE_LIMIT_WINDOW environment variable on line 70 contains
an inline comment `//ms` that is being parsed as part of the numeric value,
causing integer parsing with strconv.Atoi to fail. Remove the inline `//ms`
comment from the FORGOT_RATE_LIMIT_WINDOW value so that only the numeric value
`3600000` remains, or if documentation is needed, add the comment on a separate
line outside the variable assignment to prevent it from interfering with the
integer parsing logic.

In `@internal/config/config.go`:
- Around line 139-145: The getEnv function is declared twice in the same package
(at lines 140-145 and 274-279), which causes a Go compilation error since
duplicate function declarations are not allowed. Identify both getEnv function
declarations in the file, determine which implementation is correct for your use
case (the first uses os.LookupEnv to distinguish between missing and
empty-valued variables, while the second uses os.Getenv which treats them
identically), keep the correct implementation, and delete the duplicate
declaration.

In `@internal/config/database.go`:
- Around line 15-16: The InitDatabase function signature returns only error, but
the calling code in main() at line 46 assigns the return value to a database
connection variable (db) and then passes it to config.AutoMigrate at line 59.
Modify the InitDatabase function signature to return both the database
connection and an error value (e.g., returning a tuple or struct containing the
connection alongside the error), then update the function implementation to
properly initialize and return the database connection object along with any
initialization errors.
- Around line 128-133: The capacity health threshold at line 128 is hardcoded to
95, assuming a fixed 100-connection pool, but this does not account for the
actual MaxOpenConns value from cfg.Database.PoolMax configured at line 50. Since
sql.DBStats does not expose MaxOpenConnections, store the configured
MaxOpenConns value in a package-scoped variable (initialized when the database
is configured) or pass it as a parameter to HealthCheckDatabase(). Then replace
the hardcoded threshold of 95 with a dynamic calculation that computes the
threshold as a percentage of the actual configured pool size, so the health
check in the condition at line 128 accurately reflects the actual capacity
limits.
- Around line 93-94: The code at lines 93-94 and 116-117 ignores the error
returned by DB.DB(), which can be nil if the method fails. This causes a panic
when calling Stats() and Ping() on a nil sqlDB. Check the error returned by
DB.DB() and handle it appropriately (such as logging the error and returning
early) before attempting to call Stats() or Ping() on the sqlDB object. Apply
this error handling fix to both occurrences in the file.
- Around line 41-80: In the InitDatabase function that accepts dbConfig as a
parameter, replace all references to cfg.Database with dbConfig throughout the
connection pool configuration section. Additionally, replace the log.Fatal call
with a proper error return statement using fmt.Errorf to handle the ping failure
appropriately. Finally, add the missing SetMaxOpenConns and SetMaxIdleConns
configuration calls to the corrected configuration block along with their
corresponding log statements to ensure all pool settings are consistently
applied.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b5843e28-c1a1-4f39-8cf6-463b4647edf0

📥 Commits

Reviewing files that changed from the base of the PR and between d61168a and 6b94797.

📒 Files selected for processing (4)
  • .env.example
  • .github/pull_request_template.md
  • internal/config/config.go
  • internal/config/database.go

Comment thread .env.example Outdated
Comment thread internal/config/config.go
Comment thread internal/config/database.go
Comment thread internal/config/database.go Outdated
Comment thread internal/config/database.go
Comment thread internal/config/database.go Outdated
@roshankumar0036singh

Copy link
Copy Markdown
Owner

resolev all the issues marked by sonar and coderabbit

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/config/database.go`:
- Line 29: In the InitDatabase function, the Logger field configuration
references an undefined variable logLevel that does not exist as a function
parameter, package-level variable, or in the codebase. Replace the logLevel
variable in the LogMode method call with an appropriate logger level constant
such as logger.Info, logger.Warn, or logger.Error depending on the desired
logging verbosity for the database connection.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 755b4e46-bbde-4d40-baac-8dfd83729486

📥 Commits

Reviewing files that changed from the base of the PR and between 6b94797 and 8664ba0.

📒 Files selected for processing (1)
  • internal/config/database.go

Comment thread internal/config/database.go Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.env.example:
- Line 70: The FORGOT_RATE_LIMIT_WINDOW environment variable assignment has
trailing whitespace after the value 3600000 that should be removed to comply
with style conventions and prevent unnecessary diffs. Simply delete the
whitespace characters at the end of the line after the numeric value.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6959ac0b-9210-425e-b686-6fdc9f88fba9

📥 Commits

Reviewing files that changed from the base of the PR and between 8664ba0 and a6ac9fe.

📒 Files selected for processing (3)
  • .env.example
  • internal/config/config.go
  • internal/config/database.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/config/config.go
  • internal/config/database.go

Comment thread .env.example Outdated
@sonarqubecloud

Copy link
Copy Markdown

@aditisb1212-lab

aditisb1212-lab commented Jun 27, 2026

Copy link
Copy Markdown
Author

@roshankumar0036singh I have submitted the commits. Please review and merge when you have a moment!

@aditisb1212-lab

Copy link
Copy Markdown
Author

Sir please check again and review i have done all

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.

2 participants