Allow explicitly named primary keys, foreign keys, and indices
a constraintName option on @Index, @PrimaryGeneratedColumn, and @JoinColumn would be nice.
example:
@Entity()
class Post {
@PrimaryGeneratedColumn({
constraintName: 'pk_post_id'
})
id: number
@ManyToOne(author => Author, author => author.posts)
@JoinColumn({
constraintName: 'fk_post_author_id'
})
author: Author
}
So, is there no way to specify a foreign key constraint_name directly? I could not find anything in the documentation. My use case is to find which foreign key constraint fails by checking mysqlErr.sqlMessage and send specific error messages.
2020, is this still not an option?
If having unique names is a must, then what about something similar to what you have for migrations: where there is a unique id generated in the front, then a custom name can be given after? Best of both worlds
I Saw it on documentation.
@ManyToOne(type => Category) @JoinColumn({ name: "cat_id" }) category: Category;
@hugo-dutra this is for the field name, not the name of the foreign key itself
@hugo-dutra this is for the field name, not the name of the foreign key itself
Strange, I had the impression of seeing a foreign key with the same name created in the database. And a field with that name created in the table with the name of the foreign key. But, thanks for the comment. Thank you.
https://github.com/typeorm/typeorm/blob/master/docs/relations.md#joincolumn-options
Well, it seems I need this feature as well...
I need as well. I already can see my DBA complaining...
I need this as well when I see the error message
QueryFailedError: constraint "PK_0669fe20e252eb692bf4d344975" of relation "settings" does not exist
Who knows what's the meaning of PK_0669fe20e252eb692bf4d344975 ?
I can't believe I don't have this option. Almost 3 years have passed! Any response?! :-/
Can't use auto-migrations for my use-case, which means the FK constraints expected by TypeORM won't match up with what I called them, which means no lazy loading :(
For those struggling with this, it is possible to explicitly set the name of FK constraints by building a naming strategy. If you look at the DefaultNamingStrategy interface it also allows you to set others such as primaryKeyName.
CustomNamingStrategy
The following naming convention is used below: <table1>_<table2>_<columns> then i hash this because it could get long and mysql will throw an identifier too long error.
This method makes the foreign keys deterministic so that i can use the same migrations for both test and production db.
import { DefaultNamingStrategy, Table, NamingStrategyInterface } from "typeorm";
import crypto from "crypto";
export class CustomNamingStrategy extends DefaultNamingStrategy implements NamingStrategyInterface {
foreignKeyName(tableOrName: Table | string, columnNames: string[], referencedTablePath?: string, referencedColumnNames?: string[]): string {
tableOrName =
typeof tableOrName === "string" ? tableOrName : tableOrName.name;
const name = columnNames.reduce(
(name, column) => `${name}_${column}`,
`${tableOrName}_${referencedTablePath}`,
);
return`fk_${crypto.createHash('md5').update(name).digest("hex")}`
}
}
ormconfig.ts
Then import the custom naming strategy in your config.
module.exports = {
"type": "mysql",
"host": process.env.DB_HOST,
...
namingStrategy: new CustomNamingStrategy()
}
references:
https://github.com/typeorm/typeorm/tree/master/sample/sample12-custom-naming-strategy https://github.com/typeorm/typeorm/issues/5286 https://github.com/typeorm/typeorm/pull/4274/files
Guys. I think this issue is very close to being Crucial.
When you get insert or update on table "..." violates foreign key constraint "FK_13d991343c840a2afe2774e0f01 - it is such a bad message that I have a question: who thought it is a good idea to keep it like this?
And it is in that way for 4(!) years...
@EPecherkin why is that so bad? You can just look up what look up FK_... in your DB and check what it is. Or even better check the error logs of your database.
For people being J in their MBTI profile, i guess being able to name the constraints is the MUST.
And according to me, we should be able to name the constraints the way we want, and easily.
I need this feature as well.
Any progress on this issue? I ran into this problem while migrating to TypeORM from other framework.
I encountered a problem, where one column should be used for two foreign key references on different tables. TypeORM seems to name them the same which gives me a duplicate foreign key name error. #5289
Wouldn't a lot of this issue be resolved by a better implementation of the DefaultNamingStrategy.foreignKeyName function so it is more human readable?
eg:
current implementation produces: FK_0669fe20e252eb692bf4d344975
https://github.com/typeorm/typeorm/blob/master/src/naming-strategy/DefaultNamingStrategy.ts#L105-L118
foreignKeyName(
tableOrName: Table | string,
columnNames: string[],
_referencedTablePath?: string,
_referencedColumnNames?: string[],
): string {
// sort incoming column names to avoid issue when ["id", "name"] and ["name", "id"] arrays
const clonedColumnNames = [...columnNames]
clonedColumnNames.sort()
const tableName = this.getTableName(tableOrName)
const replacedTableName = tableName.replace(".", "_")
const key = `${replacedTableName}_${clonedColumnNames.join("_")}`
return "FK_" + RandomGenerator.sha1(key).substr(0, 27)
}
If we changed it to this, it would produce something like: FK_post_author_id_0669fe20e252eb692bf4d344975
foreignKeyName(
tableOrName: Table | string,
columnNames: string[],
_referencedTablePath?: string,
_referencedColumnNames?: string[],
): string {
// sort incoming column names to avoid issue when ["id", "name"] and ["name", "id"] arrays
const clonedColumnNames = [...columnNames]
clonedColumnNames.sort()
const tableName = this.getTableName(tableOrName)
const replacedTableName = tableName.replace(".", "_")
const key = [replacedTableName, ...clonedColumnNames].join("_");
const sha = RandomGenerator.sha1(key).substring(0, 27);
return "FK_" + key + '_' + sha;
}
The advantage being:
- The developer can instantly see what foreign key it is without having to go lookup the sha hash in the database
- most of the time there won't be a need for the developer to create a custom naming function
- the uniqueness should be identical, since the original sha hash is still included in the name. Although it might even be possible to omit it. Not sure about this.
Disadvantages:
- the foreign key names will be a lot longer. Especially if a lot of columns are used. Is there a max length in certain databases?
- The names will not be the same as before this change. Which might mess up migrations for existing databases?
I love that idea!
Your disadvantages are both true and a real challenge. This would be incompatible AF :(