Skip to content

Make bit Besql's ConfigureSqliteSynchronous public (#9819)#9820

Merged
msynk merged 2 commits intobitfoundation:developfrom
yasmoradi:9819
Feb 7, 2025
Merged

Make bit Besql's ConfigureSqliteSynchronous public (#9819)#9820
msynk merged 2 commits intobitfoundation:developfrom
yasmoradi:9819

Conversation

@yasmoradi
Copy link
Member

@yasmoradi yasmoradi commented Feb 7, 2025

closes #9819

Summary by CodeRabbit

  • New Features
    • Added a “Re-create database” button on the weather demo page, allowing users to reset the database state easily.
  • Refactor
    • Updated the database initialization process to perform necessary configuration steps before migration operations.
    • Enhanced service registration to ensure proper asynchronous handling during database setup.

@yasmoradi yasmoradi requested a review from msynk February 7, 2025 13:56
@coderabbitai
Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request removes the inline SQLite connection initialization from the BesqlPooledDbContextFactory class and introduces a new public asynchronous extension method—ConfigureSqliteSynchronous—in a dedicated DatabaseFacadeExtensions class. The service registration in IServiceCollectionBesqlExtentions is updated to invoke the new method before calling the database initializer asynchronously. Additionally, a new "Re-create database" button with its corresponding ReCreateDatabase method is added to the demo Razor page to facilitate database recreation.

Changes

File(s) Changed Summary of Changes
src/Besql/.../BesqlPooledDbContextFactory.cs
src/Besql/.../DatabaseFacadeExtensions.cs
src/Besql/.../IServiceCollectionBesqlExtentions.cs
Removed inline SQLite connection initialization (PRAGMA synchronous) from the DB context factory; added a public async extension method ConfigureSqliteSynchronous for SQLite configuration; updated the service registration to asynchronously configure the database before invoking the initializer.
src/Besql/Demo/.../Weather.razor Added a "Re-create database" button and its associated ReCreateDatabase method, which deletes and recreates the database and clarifies the need for manual configuration when using a pre-populated DB context.

Sequence Diagram(s)

sequenceDiagram
    participant SP as Service Provider
    participant SC as AddBesqlDbContextFactory
    participant DBF as ConfigureSqliteSynchronous
    participant DI as dbContextInitializer

    SP->>SC: Invoke service registration
    SC->>DBF: Asynchronously configure SQLite connection
    DBF-->>SC: Return configured DatabaseFacade
    SC->>DI: Invoke dbContext initializer
    DI-->>SC: Initialize database context
    SC-->>SP: Return registered service
Loading
sequenceDiagram
    participant U as User
    participant R as Weather.razor
    participant DB as Database

    U->>R: Click "Re-create database" button
    R->>DB: Delete existing database
    R->>DB: Recreate database (migrate/ensure created)
    R->>DB: Apply SQLite synchronous configuration
    DB-->>R: Database configured and ready
    R-->>U: Update UI
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure ConfigureSqliteSynchronous is public [#9819]

Poem

Hopping through the code with delight,
I’ve ditched old paths for something bright.
A new extension makes SQLite sing,
And async magic now takes wing.
Carrots and code, I hop with glee! 🥕🐇


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

@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: 0

🧹 Nitpick comments (4)
src/Besql/Bit.Besql/DatabaseFacadeExtensions.cs (2)

8-11: Enhance XML documentation with parameter and return value details.

Add parameter and return value documentation to make the API more discoverable.

 /// <summary>
 /// This method must be called before invoking Database.MigrateAsync or Database.EnsureCreatedAsync, to ensure proper functionality of bit Besql.
 /// </summary>
+/// <param name="database">The database facade to configure.</param>
+/// <returns>The same database facade instance for method chaining.</returns>
+/// <exception cref="InvalidOperationException">Thrown when the database is not SQLite.</exception>

22-22: Consider extracting the PRAGMA command as a constant.

For better maintainability and reusability, consider extracting the SQL command text.

+    private const string SetSynchronousFullCommand = "PRAGMA synchronous = FULL;";
+
     public static async Task<DatabaseFacade> ConfigureSqliteSynchronous(this DatabaseFacade database)
     {
         // ...
-        command.CommandText = "PRAGMA synchronous = FULL;";
+        command.CommandText = SetSynchronousFullCommand;
         // ...
src/Besql/Bit.Besql/IServiceCollectionBesqlExtentions.cs (1)

20-24: Consider adding error handling in the async lambda.

While the implementation is correct, consider adding error handling to ensure database configuration failures are properly handled.

     services.AddSingleton(async (IServiceProvider sp, TDbContext dbContext) =>
     {
-        await dbContext.Database.ConfigureSqliteSynchronous();
-        await dbContextInitializer(sp, dbContext);
+        try
+        {
+            await dbContext.Database.ConfigureSqliteSynchronous();
+            await dbContextInitializer(sp, dbContext);
+        }
+        catch (Exception ex)
+        {
+            throw new InvalidOperationException("Failed to initialize database context.", ex);
+        }
     });
src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (1)

102-113: Consider adding user feedback for database operations.

The implementation is correct, but consider adding loading states and success/error notifications for a better user experience.

+    private bool isRecreating = false;
+
     private async Task ReCreateDatabase()
     {
+        if (isRecreating) return;
+        isRecreating = true;
+
         await using var dbContext = await DbContextFactory.CreateDbContextAsync();
+        try
+        {
+            await dbContext.Database.EnsureDeletedAsync();
+            await dbContext.Database.ConfigureSqliteSynchronous();
+            await dbContext.Database.MigrateAsync();
+            await ReadDataSample(); // Refresh the count
+        }
+        catch (Exception ex)
+        {
+            Console.Error.WriteLine($"Failed to recreate database: {ex}");
+            throw;
+        }
+        finally
+        {
+            isRecreating = false;
+        }
     }

And update the button:

-<button class="btn btn-primary" @onclick="ReCreateDatabase">Re-create database</button>
+<button class="btn btn-primary" @onclick="ReCreateDatabase" disabled="@isRecreating">
+    @if (isRecreating)
+    {
+        <span>Recreating...</span>
+    }
+    else
+    {
+        <span>Re-create database</span>
+    }
+</button>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c047bc7 and 120412f.

📒 Files selected for processing (4)
  • src/Besql/Bit.Besql/BesqlPooledDbContextFactory.cs (0 hunks)
  • src/Besql/Bit.Besql/DatabaseFacadeExtensions.cs (1 hunks)
  • src/Besql/Bit.Besql/IServiceCollectionBesqlExtentions.cs (1 hunks)
  • src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (3 hunks)
💤 Files with no reviewable changes (1)
  • src/Besql/Bit.Besql/BesqlPooledDbContextFactory.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (3)
src/Besql/Bit.Besql/DatabaseFacadeExtensions.cs (2)

13-14: LGTM! Robust error handling.

The null check with string comparison and clear error message is well implemented.


19-24: LGTM! Proper connection and command management.

Good use of:

  • await using for automatic disposal
  • ConfigureAwait(false) for performance
  • Async operations throughout
src/Besql/Demo/Bit.Besql.Demo.Client/Pages/Weather.razor (1)

18-18: LGTM! Consistent button implementation.

The new button follows the same style and pattern as other buttons in the component.

@msynk msynk merged commit 3b8a09c into bitfoundation:develop Feb 7, 2025
3 checks passed
@yasmoradi yasmoradi deleted the 9819 branch February 8, 2025 11:34
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.

bit Besql's ConfigureSqliteSynchronous is not public

2 participants