Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 475
Stefan Wullems Avatar asked Oct 22 '18 14:10

Stefan Wullems


2 Answers

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.

like image 26
yoz Avatar answered Nov 15 '22 09:11

yoz


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

like image 179
Dan Barclay Avatar answered Nov 15 '22 09:11

Dan Barclay