PHP MySQL JavaScript

Dashboard Stability: Handling Missing Commits Table

Introduction

The application's dashboard was experiencing crashes for tenants that had not yet run the commits migration. This post details the solution implemented to gracefully handle the absence of the commits table in the tenant schema, preventing dashboard failures.

The Problem

When the dashboard attempted to query the commits table to display user activity and calculate API limits, it would throw an exception if the table didn't exist for a particular tenant. This typically happened when a new tenant was created but the commits migration hadn't been executed yet, leading to a broken dashboard experience.

The Solution

To address this, a try-catch block was implemented around the database queries that access the commits table. This allows the application to gracefully handle the QueryException that occurs when the table is missing.

use Illuminate\Database\QueryException;

// ...

try {
    /** @var string|null $lastCommitDate */
    $lastCommitDate = Commit::query()
        ->where('user_id', $user->id)
        ->max('github_created_at');

    if ($lastCommitDate) {
        return Carbon::parse($lastCommitDate)->addDay()->startOfDay();
    }
} catch (QueryException) {
    // commits table may not exist yet for this tenant
}

This pattern was applied to all queries targeting the commits table within the dashboard logic.

Key Changes

  1. Try-Catch Blocks: Enclose Commit queries within try-catch blocks to intercept QueryException.
  2. Graceful Fallback: In the catch block, the application now falls back to default values, preventing the dashboard from crashing.
  3. Consistent Handling: The same approach was applied across all relevant queries related to commit activity, ensuring consistent behavior.

Results

  • The dashboard no longer crashes for tenants without the commits table.
  • The GitHub sync action can gracefully proceed even if the commits migration hasn't been run.
  • Improved user experience by preventing unexpected errors.

Lessons Learned

When working with multi-tenant applications, it's crucial to anticipate scenarios where migrations might not be run in a consistent order across all tenants. Implementing robust error handling and fallback mechanisms can prevent application failures and ensure a smooth user experience. Always consider database schema differences when querying tenant-specific data.

Gerardo Ruiz

Gerardo Ruiz

Author

Share: