Overview
The Cat Data API uses Knex.js as a SQL query builder and migration tool. Migrations allow you to version control your database schema and make changes in a consistent, repeatable way.Knex Configuration
The database configuration is defined inknexfile.js at the project root:
knexfile.js
The configuration uses environment variables from your
.env file to connect to PostgreSQL.Running Migrations
Run all pending migrations
Apply all migrations that haven’t been run yet:This executes all migration files in the
migrations/ directory in chronological order.Existing Migrations
The Cat Data API includes four migrations that define the database schema:1. Create Images Table
File:20250717082325_create_images_table.js
images table for storing uploaded cat image metadata.
2. Create Tags Table
File:20250717082710_create_tags_table.js
tags table for categorizing cat data with labels.
3. Create Items Table
File:20250717082805_create_items_table.js
items table for cat data entries with foreign key reference to images.
4. Create Items-to-Tags Junction Table
File:20250717083056_create_items_to_tags_table.js
Creating New Migrations
Generate a migration file
Create a new migration with a descriptive name:This creates a timestamped file in the
migrations/ directory:Write the migration
Edit the generated file to define the schema changes:
exports.up- Applies the migration (adds the column)exports.down- Reverts the migration (removes the column)
Migration Best Practices
Always include both
up and down functions - This allows migrations to be rolled back if needed.- Use descriptive names - Migration names should clearly describe what they do
- One change per migration - Keep migrations focused on a single logical change
- Never modify existing migrations - Once a migration has been run in production, create a new migration instead
- Test rollbacks - Verify that your
downfunction properly reverses theupfunction - Use transactions - Knex wraps migrations in transactions by default to ensure atomicity
Database Schema Overview
After running all migrations, the database contains:| Table | Purpose | Key Columns |
|---|---|---|
| images | Stores uploaded image metadata | id, name, created_at, updated_at |
| tags | Categorization labels | id, name |
| items | Cat data entries | id, name, description, image_id |
| items_to_tags | Many-to-many relationships | id, item_id, tag_id |
All foreign keys use
CASCADE deletion, so deleting a parent record automatically removes related child records.Troubleshooting
Migration fails with “relation already exists”
The table may already exist from a previous migration. Check the status:Connection errors
Verify your database credentials in.env match your PostgreSQL configuration. See Environment Variables.