Skip to content

[WEB-3705] improvement: clear local db on version change#6843

Merged
sriramveeraghanta merged 2 commits intopreviewfrom
improvement-local-db-version
Mar 28, 2025
Merged

[WEB-3705] improvement: clear local db on version change#6843
sriramveeraghanta merged 2 commits intopreviewfrom
improvement-local-db-version

Conversation

@prateekshourya29
Copy link
Member

@prateekshourya29 prateekshourya29 commented Mar 28, 2025

Description

This PR adds a check to clear local DB if the stored version differs from the current version to prevent compatibility issues.

Type of Change

  • Improvement (change that would cause existing functionality to not work as expected)

Summary by CodeRabbit

  • Refactor
    • Improved local data management to ensure smoother synchronization between stored data and the application.
    • Enhanced error handling for more reliable fallback when issues occur with local data retrieval.

@makeplane
Copy link

makeplane bot commented Mar 28, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 28, 2025

Walkthrough

The pull request refactors the database storage initialization in the web module. A new private method initializeWorker is introduced in the Storage class to encapsulate the worker setup with Comlink, replacing inline initialization code. The database version constant is updated from 1 to 1.1, and the initialization process now checks for version mismatches, clearing storage when needed. Additionally, error logging is added in the getIssues method to log failures when retrieving work items.

Changes

File(s) Summary
web/.../storage.sqlite.ts - Added private method initializeWorker to encapsulate worker initialization using Comlink
- Updated DB_VERSION from 1 to 1.1 with version mismatch handling
- Added error logging in getIssues for fallback scenarios

Sequence Diagram(s)

sequenceDiagram
    participant S as Storage Instance
    participant WB as Web Worker
    participant W as Window
    S->>S: initialize()
    S->>S: initializeWorker()
    S->>WB: Import DBClass, create & wrap worker via Comlink
    WB-->>S: Worker ready
    W->>S: Window unload event
    S->>WB: Terminate worker
Loading

Possibly related PRs

Suggested labels

🧹chore

Suggested reviewers

  • sriramveeraghanta
  • SatishGandham

Poem

I'm a bunny hopping through lines of code,
New worker paths in a shiny abode.
DB version updated, our schema’s renewed,
With error logs logging each misstep subdued.
Celebrating changes—let the code dance anew! ʕ•ᴥ•ʔ

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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 (3)
web/core/local-db/storage.sqlite.ts (3)

127-143: Well-implemented version check with appropriate logging

The version check logic handles all edge cases (undefined, empty string, non-numeric values) and properly clears storage when a version mismatch is detected. The debugging logs help track the flow during development.

Consider extracting the "DB_VERSION" string into a constant to avoid duplication and improve maintainability.

+const DB_VERSION_KEY = "DB_VERSION";
 // ...
-const dbVersion = await this.getOption("DB_VERSION");
+const dbVersion = await this.getOption(DB_VERSION_KEY);
 // ...
-await this.setOption("DB_VERSION", DB_VERSION.toString());
+await this.setOption(DB_VERSION_KEY, DB_VERSION.toString());

125-143: Consider refining the initialization flow after version mismatch

When a version mismatch is detected, the worker is reinitialized, but then the normal initialization flow continues with createTables() and setting the DB_VERSION again. This might lead to redundant operations.

Consider restructuring the flow to avoid potential redundancy:

 await this.initializeWorker(workspaceSlug);

 const dbVersion = await this.getOption("DB_VERSION");
 log("Stored db version", dbVersion);
 log("Current db version", DB_VERSION);
 // Check if the database version matches the current version
 // If there's a mismatch, clear storage to avoid compatibility issues
 if (
   dbVersion !== undefined &&
   dbVersion !== "" &&
   !isNaN(Number(dbVersion)) &&
   Number(dbVersion) !== DB_VERSION
 ) {
   log("Database version mismatch detected - clearing storage to ensure compatibility");
   await this.clearStorage();
   await this.initializeWorker(workspaceSlug);
+  this.status = "ready";
+  // Your SQLite code here.
+  await createTables();
+  await this.setOption("DB_VERSION", DB_VERSION.toString());
+  return true;
 } else {
   log("Database version matches current version - proceeding with data load");
+  this.status = "ready";
+  // Your SQLite code here.
+  await createTables();
+  await this.setOption("DB_VERSION", DB_VERSION.toString());
+  return true;
 }

-this.status = "ready";
-// Your SQLite code here.
-await createTables();
-
-await this.setOption("DB_VERSION", DB_VERSION.toString());
-return true;

127-143:

Details

❓ Verification inconclusive

Add version comparison for future maintainability

As the application evolves, you might need more complex version comparisons. Consider using a semantic versioning approach for better future-proofing.


🌐 Web query:

How to implement semantic versioning comparison in TypeScript?

💡 Result:

To implement semantic versioning comparison in TypeScript, you can either use existing libraries or create a custom parser. Here are two robust approaches:

1. Using Established Libraries

Recommended solution: Use the compare-versions package ([source][11]):

import compareVersions from 'compare-versions';

// Basic comparison returns -1, 0, or 1
console.log(compareVersions('2.2.0', '2.2.1')); // -1

// Direct boolean checks
console.log(compareVersions.gt('3.1.0', '3.0.5')); // true
console.log(compareVersions.satisfies('4.7.2', '^4.6')); // true

This library handles:

  • Standard SemVer format (MAJOR.MINOR.PATCH)
  • Pre-release versions (3.0.0-beta.1)
  • Build metadata (2.1.0+20230328)

2. Custom Implementation (Basic)

For simple comparisons without prerelease/build metadata:

function semverCompare(a: string, b: string): -1 | 0 | 1 {
  const partsA = a.split('.').map(Number);
  const partsB = b.split('.').map(Number);

  for (let i = 0; i < 3; i++) {
    if (partsA[i] > partsB[i]) return 1;
    if (partsA[i] < partsB[i]) return -1;
  }
  
  return 0;
}
  
// Usage
semverCompare('2.1.9', '2.2.0'); // -1

Key considerations:

  • Always validate version strings first
  • Handle edge cases like missing segments (22.0.0)
  • Use zero-padding for comparisons (2.12.1.0)
  • Consider using [semver.org]'s official regex for validation[8]

Comparison Table

Approach Pros Cons
compare-versions Full spec compliance, pre-release support Adds 1.4kB dependency
Custom Implementation No dependencies Lacks advanced feature support

For most projects, we recommend using compare-versions due to its robust handling of edge cases and compliance with the official SemVer specification[8]. The custom solution works for basic comparisons but misses critical features like pre-release version handling[11].

Citations:


Action Required: Transition to Semantic Versioning Comparison in DB Version Check

  • Location: web/core/local-db/storage.sqlite.ts (Lines: 127–143)
  • Context: The current implementation compares numerical values of versions. While sufficient for numeric versions, this approach won’t scale if version strings evolve to Semantic Versioning.
  • Suggestion:
    • For better future-proofing, implement a semantic version comparator. Consider using the compare-versions package, which offers robust comparison (including handling pre-release and build metadata), or, if requirements are minimal, a custom semver parser.
    • Refactor the version check to validate and compare semantic version strings (e.g., using compareVersions.gt(dbVersion, DB_VERSION) or similar) rather than converting to a number.
    • This change will help prevent compatibility issues as your versioning scheme becomes more complex over time.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e877951 and 10672af.

📒 Files selected for processing (1)
  • web/core/local-db/storage.sqlite.ts (4 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
web/core/local-db/storage.sqlite.ts (1)
web/core/local-db/utils/utils.ts (1)
  • log (7-11)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (python)
🔇 Additional comments (4)
web/core/local-db/storage.sqlite.ts (4)

22-22: Version update to trigger DB clearing logic

The DB_VERSION is updated from 1 to 1.1, which will trigger the new version checking logic to clear local storage when users update their application. This is a good approach to prevent compatibility issues between database versions.


72-89: Good refactoring of worker initialization logic

Moving the worker initialization code into a separate private method improves code organization and enables reuse in the version mismatch handling path.


125-125: Clean replacement of inline worker initialization

The refactored method is correctly called here to initialize the worker.


339-339: Enhanced error logging for database fallback

Adding this log statement helps developers understand when the system is falling back to the server due to local database issues, which is valuable for debugging.

@sriramveeraghanta sriramveeraghanta merged commit fed0ef6 into preview Mar 28, 2025
5 of 6 checks passed
@sriramveeraghanta sriramveeraghanta deleted the improvement-local-db-version branch March 28, 2025 09:42
lifeiscontent pushed a commit that referenced this pull request Aug 18, 2025
* [WEB-3705] improvement: clear local db on version change

* chore: remove console.log
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