简体   繁体   中英

How can I specify column name casing in TypeORM migrations

I'm using typeORM and I want to use migrations instead of syncing because I'm working in a team and it's actually a lot of tedious work to get the db to a state in which the app actually functions.

The problem is that every column name I specify in the migration gets converted to lowercase which I've worked around by making all entity props snake_case (which is horrible btw). But foreign keys get converted to camelCase by (I think) postgres by default so I can't relate anything to each other by foreign key in my migration. (because it needs to be camelCase but the query gets converted to lowercase)

Have i made clear what my problem is?

Is there a way to solve this, or is there a workaround?

An alternative to allow TypeOrm to support conversion from camelCase to snake_case can be achieved by adjusting your ormconfig.js to support the Typeorm Naming Strategies package. This will allow you to have coding convention within the code and database naming convention within the database.

It can be set up by:

npm i --save typeorm-naming-strategies

Then within your ormconfig.js, add the following lines:

const SnakeNamingStrategy = require('typeorm-naming-strategies')
  .SnakeNamingStrategy;

module.exports = {
    name: 'development',
    type: 'postgres',
    host: 'localhost',
    port: 5432,
   ...
   namingStrategy: new SnakeNamingStrategy(),
}

TypeOrm will now follow the snake_case convention when naming columns within postgres

In postgresql, column and table names are automatically converted to lowercase unless you include them in double quotes:

columnName becomes columnname
"columnName" remains as columnName

See https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html -- "Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case."

So you should write migrations as, for example,

ALTER TABLE "tableName" ADD COLUMN "columnName" character varying ...

and queries similarly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM