Skip to content

perf: add indexes to improve query speed - #1613

Merged
MrgSub merged 1 commit into
Mail-0:stagingfrom
devsargam:index
Jul 4, 2025
Merged

MrgSub merged 1 commit into
Mail-0:stagingfrom
devsargam:index

Conversation

@devsargam

@devsargam devsargam commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Currently, a lot of relations in schema.ts are missing indexes which increases the query time in the db.

This PR addresses the problem and improves query speed.
Also, adds cascase


Type of Change

Please delete options that are not relevant.

  • ⚡ Performance improvement

Areas Affected

Please check all that apply:

  • Data Storage/Management

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • New Features

    • Improved database performance with new indexes on frequently queried fields.
    • Enhanced data integrity by enabling cascading deletes for related user data.
  • Chores

    • Updated database schema and migration files to reflect new indexing and foreign key behaviors.

@coderabbitai

coderabbitai Bot commented Jul 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces a new database migration that enhances referential integrity and query performance for the "mail0" tables. It adds cascading delete behaviors to foreign keys, defines explicit indexes on frequently queried columns, and updates the schema definitions and migration snapshots to reflect these optimizations.

Changes

File(s) Change Summary
apps/server/src/db/migrations/0035_uneven_shiva.sql Migration script: Drops and re-adds foreign keys with "ON DELETE cascade" for several tables, adds a new foreign key, and creates multiple indexes on columns across the "mail0" tables.
apps/server/src/db/migrations/meta/0035_snapshot.json New migration snapshot: Defines the full schema for all "mail0" tables, including columns, indexes, foreign keys, unique constraints, and default values, reflecting the new cascading behaviors and indexes.
apps/server/src/db/migrations/meta/_journal.json Migration journal: Adds entry for migration 35 with version, timestamp, tag, and breakpoints flag.
apps/server/src/db/schema.ts Refactors table definitions to use explicit index declarations and cascading foreign key constraints; adds indexes on foreign keys, timestamps, JSONB columns, and frequently queried fields for all relevant tables.

Poem

In the warren where data flows,
Cascading deletes now prune what grows.
Indexes sprout on every row,
Making queries quick as a rabbit’s toe!
With foreign keys strong and referential might,
The schema hops forward—oh, what a sight!
🐇✨

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@greptile-apps greptile-apps 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.

PR Summary

Comprehensive database performance optimization through strategic index additions and foreign key modifications in the Mail-0/Zero schema.

  • Added migration apps/server/src/db/migrations/0035_uneven_shiva.sql implementing btree indexes for frequently queried columns like user_id and expiration timestamps
  • Modified foreign key constraints with CASCADE delete behavior in schema.ts to ensure proper cleanup of related records
  • Added composite indexes for commonly joined fields to optimize query patterns
  • Improved query performance for session management and OAuth operations through strategic index placement

4 files reviewed, 2 comments
Edit PR Review Bot Settings | Greptile

Comment on lines +1527 to +1531
"connectionId": {
"name": "connectionId",
"type": "text",
"primaryKey": false,
"notNull": true

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.

style: Column name should be snake_case (connection_id) to maintain consistency with other tables

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

no bro it's fine

Comment on lines +1545 to +1549
"updatedAt": {
"name": "updatedAt",
"type": "timestamp",
"primaryKey": false,
"notNull": true,

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.

style: Column name should be snake_case (updated_at) to maintain consistency with other tables

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

nahhh

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

🧹 Nitpick comments (1)
apps/server/src/db/migrations/0035_uneven_shiva.sql (1)

42-43: Consider GIN indexes for JSONB columns

While btree indexes on JSONB columns are valid for equality comparisons, consider using GIN indexes if you need to query inside the JSON structure (e.g., containment queries with @> operator).

Example:

CREATE INDEX "user_hotkeys_shortcuts_gin_idx" ON "mail0_user_hotkeys" USING gin ("shortcuts");

Also applies to: 46-46

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 142bbaa and 9a4b39f.

📒 Files selected for processing (4)
  • apps/server/src/db/migrations/0035_uneven_shiva.sql (1 hunks)
  • apps/server/src/db/migrations/meta/0035_snapshot.json (1 hunks)
  • apps/server/src/db/migrations/meta/_journal.json (1 hunks)
  • apps/server/src/db/schema.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/server/src/db/schema.ts (1)
apps/server/src/lib/schemas.ts (1)
  • defaultUserSettings (137-151)
🔇 Additional comments (5)
apps/server/src/db/migrations/meta/_journal.json (1)

257-263: LGTM!

The new migration journal entry follows the established pattern and correctly tracks the performance optimization migration.

apps/server/src/db/migrations/0035_uneven_shiva.sql (2)

17-46: Excellent indexing strategy for query optimization!

The indexes cover all the critical query patterns:

  • Foreign key columns for JOIN operations
  • Timestamp columns for time-based queries and cleanup operations
  • Boolean flags for filtering
  • Composite indexes for multi-column queries

11-16: Fix missing statement breakpoints between ALTER TABLE statements

The ALTER TABLE statements are concatenated without proper statement breakpoints, which could cause SQL execution errors.

Apply this diff to add the missing statement breakpoints:

-ALTER TABLE "mail0_account" ADD CONSTRAINT "mail0_account_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-ALTER TABLE "mail0_connection" ADD CONSTRAINT "mail0_connection_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-ALTER TABLE "mail0_session" ADD CONSTRAINT "mail0_session_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-ALTER TABLE "mail0_summary" ADD CONSTRAINT "mail0_summary_connection_id_mail0_connection_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."mail0_connection"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-ALTER TABLE "mail0_user_hotkeys" ADD CONSTRAINT "mail0_user_hotkeys_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-ALTER TABLE "mail0_user_settings" ADD CONSTRAINT "mail0_user_settings_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "mail0_account" ADD CONSTRAINT "mail0_account_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "mail0_connection" ADD CONSTRAINT "mail0_connection_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "mail0_session" ADD CONSTRAINT "mail0_session_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "mail0_summary" ADD CONSTRAINT "mail0_summary_connection_id_mail0_connection_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."mail0_connection"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "mail0_user_hotkeys" ADD CONSTRAINT "mail0_user_hotkeys_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "mail0_user_settings" ADD CONSTRAINT "mail0_user_settings_user_id_mail0_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."mail0_user"("id") ON DELETE cascade ON UPDATE no action;

Likely an incorrect or invalid review comment.

apps/server/src/db/migrations/meta/0035_snapshot.json (1)

1-1610: Schema snapshot correctly reflects the migration changes

The snapshot properly captures:

  • All new indexes for query optimization
  • Cascading delete behavior on foreign keys
  • Complete table structures with appropriate constraints
apps/server/src/db/schema.ts (1)

10-10: Schema definitions properly updated with indexes and cascading deletes

The refactoring to explicit index definitions and cascading foreign keys is well-implemented:

  • All indexes match the migration script
  • Cascading deletes ensure referential integrity
  • Index naming convention is consistent and descriptive

Also applies to: 30-303

@MrgSub
MrgSub merged commit 9ff981c into Mail-0:staging Jul 4, 2025
@devsargam
devsargam deleted the index branch July 5, 2025 03:37
EyobNiguse pushed a commit to EyobNiguse/Zero that referenced this pull request Jun 30, 2026
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