Overview
The Go backend utilizes GORM’sAutoMigrate feature grouped within a dedicated Migrator service. Migrations are decoupled from the main server startup to allow for safer deployment strategies.
Migration Structure
Migrations are defined ininternal/shared/infrastructure/database/postgresql/migrations/.
migrator.go: contains the list of models and the logic to run migrations and seeding.models_test.go: ensures all migration models are correctly defined.
Running Migrations
The migration tool is located atcmd/migrate/main.go.
Basic Usage
- Enable required PostgreSQL extensions (like
pgvector). - Synchronize the schema for all registered models.
- Seed default system data (e.g., subscription plans).
Seeding Sample Data
For development and testing environments, you can seed the database with demo organizations, users, and products:Adding a New Table
- Define your GORM model in a relevant module or directly in
migrator.goif it’s a shared core model. - Register the model in the
RunMigrations()method ininternal/shared/infrastructure/database/postgresql/migrations/migrator.go. - Re-run the migration tool.
Troubleshooting
Constraint Errors
If you receive a “column contains null values” error when adding aNOT NULL column to a table with existing data:
- Make the column nullable in the model temporarily.
- Run migration.
- Populate the column with data.
- Set
not nullback in the model and run migration again.
Type Cast Errors
If changing a column type (e.g.,bytea → jsonb):
GORM might fail to auto-cast. You may need to run a manual ALTER TABLE query: