Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [#358] add logger for DB #908

Merged
merged 8 commits into from
Feb 22, 2025
Merged

feat: [#358] add logger for DB #908

merged 8 commits into from
Feb 22, 2025

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Feb 21, 2025

📑 Description

goravel/goravel#358

Summary by CodeRabbit

  • New Features

    • Introduced context-aware database operations to better manage timeouts and cancellations.
    • Added functionality to generate SQL output for improved debugging.
  • Enhanced Logging

    • Upgraded the logging interface with adjustable levels (e.g., Silent, Error, Warn, Info) for clearer visibility.
    • Improved trace logging to capture query execution details and error information.
  • Refactor

    • Streamlined database initialization and query handling by integrating context management and logging.
    • Increased test robustness to ensure consistent behavior and reliability.

✅ Checks

  • Added test cases for my code

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Warning

Rate limit exceeded

@hwbrzzl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 58 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 6e12a21 and e1251f2.

📒 Files selected for processing (15)
  • contracts/database/db/db.go (1 hunks)
  • contracts/database/driver/driver.go (1 hunks)
  • contracts/database/logger/logger.go (1 hunks)
  • database/db/db.go (2 hunks)
  • database/db/db_test.go (2 hunks)
  • database/db/query.go (8 hunks)
  • database/db/query_test.go (11 hunks)
  • database/logger/logger.go (6 hunks)
  • database/logger/logger_test.go (6 hunks)
  • database/service_provider.go (1 hunks)
  • mocks/database/db/DB.go (2 hunks)
  • mocks/database/driver/Driver.go (1 hunks)
  • mocks/database/logger/Logger.go (1 hunks)
  • support/carbon/carbon.go (2 hunks)
  • tests/query.go (2 hunks)

Walkthrough

This pull request introduces context support and enhanced logging across the database stack. It adds a new WithContext method to the DB interface and its implementations, enabling context-aware operations. Additionally, it adds an Explain method to the Driver interface for SQL explanation, restructures logger functionality to better integrate with GORM, and updates the query components to include context, driver, and logger fields. The changes also extend to test cases and mocks, ensuring that context and logging are properly handled across all layers.

Changes

File(s) Change Summary
contracts/database/db/db.go, database/db/db.go, database/service_provider.go Added WithContext(ctx context.Context) DB to the DB interface; updated DB struct to include ctx, driver, and logger fields; updated constructors and BuildDB call in ServiceProvider to pass logger.
contracts/database/driver/driver.go, mocks/database/driver/Driver.go Added Explain(sql string, vars ...any) string to the Driver interface and mock implementation for generating SQL explanations.
contracts/database/logger/logger.go, database/logger/logger.go, database/logger/logger_test.go, mocks/database/logger/Logger.go Introduced a new Logger interface with custom log levels, trace logging, and GORM integration; updated method names and return types; added corresponding tests and a mock logger.
database/db/query.go, database/db/query_test.go Enhanced the Query struct by adding ctx, driver, and logger fields; added placeholderFormat and trace methods for SQL building and logging; updated tests to pass context and verify logging.
database/db/db_test.go, tests/query.go Updated test cases to enforce stricter mock expectations and revised function parameters to include the new logger and context support.
mocks/database/db/DB.go Added a new WithContext method to the mock DB along with associated call types and helper methods for context-aware testing.
support/carbon/carbon.go Modified the Clock struct for test time management by adding testNow and testTime fields; updated associated functions accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant SP as ServiceProvider
    participant Log as Logger
    participant DB as Database
    App->>SP: Call Register()
    SP->>Log: Call app.MakeLog()
    Log-->>SP: Return Logger instance
    SP->>DB: Call BuildDB(config, log, connection)
    DB->>DB: Initialize with ctx, driver, logger, builder
    DB-->>SP: Return new DB instance with context
Loading
sequenceDiagram
    participant Caller as Client
    participant Q as Query
    participant D as Driver
    participant L as Logger
    Caller->>Q: Invoke Query operation (e.g., Get, Insert)
    Q->>D: Retrieve placeholder format via driver
    Q->>L: Call trace(sql, args, rowsAffected, err)
    L-->>Q: Log the SQL execution details
    Q-->>Caller: Return query result
Loading

Possibly related PRs

Suggested reviewers

  • devhaozi

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Feb 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 68.01%. Comparing base (0fdfcff) to head (e1251f2).
Report is 3 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #908   +/-   ##
=======================================
  Coverage   68.01%   68.01%           
=======================================
  Files         154      154           
  Lines       10191    10192    +1     
=======================================
+ Hits         6931     6932    +1     
  Misses       2934     2934           
  Partials      326      326           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@hwbrzzl hwbrzzl changed the title feat: [#358] add more methods feat: [#358] add logger for DB Feb 22, 2025
@hwbrzzl hwbrzzl marked this pull request as ready for review February 22, 2025 08:38
@hwbrzzl hwbrzzl requested a review from a team as a code owner February 22, 2025 08:38
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The test now function of carbon generates a new Carbon struct when calling carbon.Now(), it's different with the test carbon, it's difficult to test. So revert it to our self test now function.

s.mockDriver.EXPECT().Config().Return(database.Config{}).Once()
s.mockBuilder.EXPECT().Exec("DELETE FROM users WHERE name = ? AND id = ?", "John", 1).Return(mockResult, nil).Once()
s.mockDriver.EXPECT().Explain("DELETE FROM users WHERE name = ? AND id = ?", "John", 1).Return("DELETE FROM users WHERE name = \"John\" AND id = 1").Once()
s.mockLogger.EXPECT().Trace(s.ctx, s.now, "DELETE FROM users WHERE name = \"John\" AND id = 1", int64(1), nil).Return().Once()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's hard to test now when using carbon's test now function.

@hwbrzzl hwbrzzl merged commit d607bf6 into master Feb 22, 2025
11 of 13 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#358-3 branch February 22, 2025 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant