简体   繁体   English

如何在 TypeORM 迁移中指定列名大小写

[英]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.我正在使用 typeORM 并且我想使用迁移而不是同步,因为我在一个团队中工作,实际上要让数据库进入应用程序实际运行的状态需要很多繁琐的工作。

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.但是默认情况下,外键会通过(我认为)postgres 转换为驼峰式大小写,因此我无法在迁移中通过外键将任何内容相互关联。 (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.通过调整 ormconfig.js 以支持Typeorm Naming Strategies包,可以实现允许 TypeOrm 支持从 camelCase 转换为 snake_case 的替代方法。 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:然后在你的 ormconfig.js 中,添加以下几行:

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在 postgres 中命名列时,TypeOrm 现在将遵循 snake_case 约定

In postgresql, column and table names are automatically converted to lowercase unless you include them in double quotes:在 postgresql 中,列名和表名会自动转换为小写,除非您将它们包含在双引号中:

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."请参阅https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html --“引用标识符也使其区分大小写,而未引用的名称始终折叠为小写。”

So you should write migrations as, for example,因此,您应该将迁移编写为,例如,

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

and queries similarly.和查询类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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