Prerequisites
- PostgreSQL 16 installed and running
- A superuser or role with
CREATEDBprivileges
Initial setup
Start PostgreSQL
Ensure the PostgreSQL server is running on your machine or is reachable
from the host where the API will run.
Configure environment variables
Update your
.env file with the credentials for the database you just
created. See Environment Variables for the
full variable list.Knex configuration
The Knex configuration lives insrc/database/knexfile.ts. It supports two
connection modes:
DATABASE_URL— when this environment variable is set, Knex connects via connection string (standard for managed platforms such as Railway or Heroku).- Individual credentials — when
DATABASE_URLis absent, Knex uses theDB_*variables fromsrc/config/env.ts.
src/database/knexfile.ts
src/database/connection.ts is
imported throughout the application:
src/database/connection.ts
Migration commands
| Command | Description |
|---|---|
npm run migrate:dev | Runs migrations using ts-node directly against the TypeScript source files. Loads .env automatically. |
npm run migrate | Runs migrations from the compiled dist/ directory. Environment variables must be set externally. |
Migrations execute in timestamp order based on their filename prefix (e.g.
20260127234005_). Never rename a migration file after it has been applied
to any environment — doing so causes Knex to treat it as a new, unapplied
migration.Migration files
The following migrations are applied in order when you runmigrate:latest.
| File | What it does |
|---|---|
20260127234005_create_users_table | Creates the users table |
20260203000059_create_user_auth_providers_table | Creates the user_auth_providers table with indexes |
20260203000758_add_foreign_key_user_auth_providers | Adds the user_id → users.id foreign key with ON DELETE CASCADE |
20260314000100_create_challenge_templates | Creates the challenge_templates table |
20260314000110_create_user_challenges | Creates the user_challenges table |
20260314000120_create_tasks | Creates the tasks table |
20260314000130_create_task_completions | Creates the task_completions table |
20260314001000_seed_challenge_templates | Seeds 7 built-in challenge templates |
20260315203000_add_notes_to_user_challenges | Adds the nullable notes column to user_challenges |
Schema overview
| Table | Primary key | Key columns |
|---|---|---|
users | id (UUID) | name, points, current_streak, max_streak |
user_auth_providers | id (UUID) | user_id, provider (local/google/facebook), email, password, provider_id |
challenge_templates | id (serial) | title, description, duration_days |
user_challenges | id (serial) | user_id, template_id, status (ACTIVE/COMPLETED/ABANDONED), start_date, completed_at, notes |
tasks | id (serial) | user_id, challenge_template_id, title, points, is_daily_routine |
task_completions | id (serial) | user_id, task_id, completed_at |