Migration generate drops/creates all constraints
Problem
Issue type: [ ] question [x ] bug report [ ] feature request [ ] documentation issue Database system/driver: [ ] `cordova` [ ] `mongodb` [ ] `mssql` [ ] `mysql` / `mariadb` [ ] `oracle` [x] `postgres` [ ] `sqlite` [ ] `sqljs` [ ] `websql` TypeORM version: [ ] `latest` [x] `@next` [ ] `0.x.x` (or put your version here) On an existing database in PostgreSQL 9.6.2 migration generation wants to drop all unique constraints and create them again. I ran this migration however it wants to do it on the next generate as well. The only thing I can tell(without digging into the code) is that the order in [code block] is backwards on the columns in the SQL statement..
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix Migration Generation for Unique Constraints in PostgreSQL
The migration generation process in TypeORM for PostgreSQL is incorrectly identifying the order of columns in unique constraints, leading to unnecessary drops and recreations of these constraints. This behavior is likely due to a mismatch between the expected column order in the database schema and how TypeORM interprets it during migration generation.
Awaiting Verification
Be the first to verify this fix
- 1
Review Existing Unique Constraints
Examine the current unique constraints in your PostgreSQL database to verify their column order. This can be done by querying the information schema.
sqlSELECT * FROM information_schema.table_constraints WHERE constraint_type = 'UNIQUE'; - 2
Update Entity Definitions
Ensure that the entity definitions in your TypeORM models match the column order of the unique constraints in the database. Adjust the order in your entity classes accordingly.
typescriptexport class YourEntity { @PrimaryGeneratedColumn() id: number; @Column() columnA: string; @Column() columnB: string; @Unique(['columnA', 'columnB']) @Column() columnC: string; } - 3
Regenerate Migrations
After updating the entity definitions, regenerate the migrations to ensure TypeORM correctly identifies the constraints without dropping them unnecessarily.
bashtypeorm migration:generate -n UpdateUniqueConstraints - 4
Apply Migrations
Run the newly generated migrations to apply the changes to your database. This will ensure that the unique constraints are correctly set without unnecessary drops.
bashtypeorm migration:run - 5
Test Migration Generation
After applying the migrations, run the migration generation command again to confirm that TypeORM no longer attempts to drop and recreate the unique constraints.
bashtypeorm migration:generate -n TestMigrationGeneration
Validation
To confirm the fix worked, check the output of the migration generation command. It should not list any unique constraints as needing to be dropped or recreated. Additionally, verify the unique constraints in the database to ensure they are intact.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep