Skip to main content
This guide provides practical examples of database queries using Drizzle ORM for common use cases in ShipFree.

Setup

All queries use the database client from src/database/index.ts:

User Queries

Find User by Email

Find User by ID with Relations

Create New User

Update User Profile

Session Queries

Find Active Session by Token

Get All User Sessions

Delete Expired Sessions

Subscription Queries

Get User’s Active Subscription

Get Subscription with Customer Details

Find Subscriptions by Provider

Update Subscription Status

Find Subscriptions Ending Soon

Payment Queries

Get User’s Payment History

Get Successful Payments

Calculate Total Revenue by Plan

Create Payment Record

Customer Queries

Find or Create Customer

Get Customer with All Relations

Complex Queries

Get User’s Complete Billing Data

Get Dashboard Analytics

Find Users by Subscription Plan

Transaction Examples

Create User with Customer

Cancel Subscription with Refund

Query Builder Patterns

Dynamic Filters

Pagination

Best Practices

When creating or updating multiple related records, wrap operations in a transaction to ensure data consistency.
The schema includes indexes on commonly queried fields like userId, providerCustomerId, and status. Always filter by indexed columns when possible.
Use Drizzle’s with clause to fetch related data in a single query instead of making multiple queries.
Many fields are nullable. Always check for null before using values.

Next Steps

Database Schema

View complete schema reference

Drizzle ORM Docs

Official Drizzle documentation