Database Developer Guide

This guide covers working with Drizzle ORM, database migrations, and Row-Level Security (RLS) in the Refresh App Web.

Overview

Database: Neon Postgres (serverless) ORM: Drizzle ORM 0.44 Migration Tool: Drizzle Kit Connection: HTTP-based (no persistent connections)

Database Configuration

Location: drizzle.config.ts

import { defineConfig } from 'drizzle-kit';

export default defineConfig({
	schema: './src/lib/server/db/schema',
	dbCredentials: { url: process.env.WRITE_DATABASE_URL },
	dialect: 'postgresql',
	entities: {
		roles: {
			provider: 'neon',
			include: ['refresh_ai_db_admin']
		}
	}
});

Schema Organization

Schemas are organized by domain in src/lib/server/db/schema/. Each file represents a logical grouping of related tables. For the complete list of tables and their relationships, see Architecture: Database Architecture - Core Tables.

Creating a Table

Example schema file:

Database Client

Two client types based on read/write needs:

Querying

Basic Queries

Relational Queries

Complex Filters

Mutations

Insert

Update

Delete

Row-Level Security (RLS)

Enabling RLS

Using RLS in Code

Migrations

Creating Migrations

  1. Edit schema file (e.g., add new column)

  2. Generate migration:

  1. Review generated SQL in drizzle/migrations/

  2. Apply migration:

Custom Migrations

For complex changes, create custom migration:

Edit the generated file:

Best Practices

  1. Always use RLS for tenant data - Prevents data leaks

  2. Use read client in load functions - Enforces RLS

  3. Use write client sparingly - Only for system operations

  4. Index foreign keys - Improves query performance

  5. Add timestamps - Track created_at and updated_at

Troubleshooting

RLS Denying Access

Problem: Queries return no results

Solution:

  1. Verify JWT contains correct tenant_id

  2. Check RLS policy is enabled

  3. Ensure user has granted permissions

Migration Conflicts

Problem: Migration fails due to conflicts

Solution:

  1. Review migration SQL

  2. Manually fix conflicts

  3. Re-run migration


Last updated: October 2025

Last updated