Skip to main content

Database Operations

All database interactions in HostMetrics are encapsulated in modules under src/lib/db/. Components and pages never call Supabase directly — they use hooks (from src/hooks/) which in turn call these database modules.

Module Structure

The Client Pattern

Every database module imports from _client.ts, which provides two key functions:
  • getClient() — Returns the Supabase client instance (browser or server depending on context)
  • getCurrentUserId() — Returns the authenticated user’s ID. Throws if not authenticated.
Every query must filter by user_id to enforce data isolation between users.

Standard CRUD Pattern

Each database module follows a consistent structure. Here is a typical example:

Pagination for Large Tables

Supabase limits query results to 1,000 rows by default. For tables that may exceed this limit (like trips and toll_transactions), use range-based pagination:

Error Handling

All database operations check for errors and throw with context:
Hooks catch these errors and expose them via an error state property for components to render.

Schema Types

TypeScript types for all database tables are defined in src/lib/db/schema/ across 7 files with over 2,750 lines of type definitions. Each table typically has three type variants:
For queries that need data from related tables, use Supabase’s select syntax:

Soft Deletes

Some entities (like vehicles) use soft deletes. Instead of removing the row, the status is updated:
Queries for active records should filter out deleted rows: