乐闻世界logo
搜索文章和话题

How can I specify column name casing in TypeORM migrations

1个答案

1

In TypeORM, when creating migration files to create or modify tables and columns, you may encounter issues related to database case sensitivity. Different databases handle case sensitivity in varying ways. For instance, in PostgreSQL, column names are typically lowercase by default, while in MySQL, case sensitivity is determined by server configuration (usually case-insensitive). To specify column name case sensitivity in TypeORM migrations, use quotes when defining entities to preserve the case. This applies when creating entities and writing migration scripts. See the following example:

typescript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; @Entity() export class UserProfile { @PrimaryGeneratedColumn() id: number; @Column({ name: ""FirstName"" }) firstName: string; @Column({ name: ""LastName"" }) lastName: string; }

In this example, we specify "FirstName" and "LastName" as the column names in the database, with the enclosing double quotes ensuring that the case is preserved during creation.

Similarly, when manually writing TypeORM migrations to create or modify tables and columns, use quotes to maintain case accuracy. For instance:

typescript
import { MigrationInterface, QueryRunner } from 'typeorm'; export class CreateUserProfilesTable1589983924164 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query( `CREATE TABLE "user_profiles" ( "id" SERIAL NOT NULL, "FirstName" character varying NOT NULL, "LastName" character varying NOT NULL, CONSTRAINT "PK_a24972a9f12a2b146b1a6e54560" PRIMARY KEY ("id") )` ); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "user_profiles"`); } }

In this migration script, we create a new table user_profiles and ensure that the FirstName and LastName columns retain their case.

Always consider database case sensitivity when writing TypeORM migrations and decide whether to use quotes based on specific database requirements. This helps avoid issues when migrating across different environments or databases.

2024年6月29日 12:07 回复

你的答案