Skip to main content
Mais Hábito API uses PostgreSQL 16 as its database and Knex.js as the query builder and migration runner.

Prerequisites

  • PostgreSQL 16 installed and running
  • A superuser or role with CREATEDB privileges

Initial setup

1

Start PostgreSQL

Ensure the PostgreSQL server is running on your machine or is reachable from the host where the API will run.
2

Create the database

Connect with psql and create the database:
If you want a dedicated role:
3

Configure environment variables

Update your .env file with the credentials for the database you just created. See Environment Variables for the full variable list.
4

Run migrations

Apply all migrations to create the schema:

Knex configuration

The Knex configuration lives in src/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_URL is absent, Knex uses the DB_* variables from src/config/env.ts.
src/database/knexfile.ts
The database connection singleton exported from src/database/connection.ts is imported throughout the application:
src/database/connection.ts

Migration commands

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 run migrate:latest.

Schema overview