Skip to content

Commit

Permalink
During schema generation, ignore duplicate column references.
Browse files Browse the repository at this point in the history
When creating @manytoone relationships, the column is typically located  Currently, during schema generation, a check is put in place to avoid attempting to create
duplicate columns. For example:

```
@entity class Pet {
  @id string name;
  @manytoone @joincolumn("person_fk") Person owner; // OK
  // @manytoone @joincolumn("person_fk") Person owner2; // ERROR - Duplicate column
}

@entity class Person {
  @id string name;
}
```

The code above represents the tables, which allow many pets to reference the same person.
```
CREATE TABLE pet (name varchar, person_fk varchar);
CREATE TABLE person (name varchar);
```

However, there are new ways to have a @manytomany relationship when using an @EmbeddedId.
Consider RoboPets, which have a name, and also a manufacturer. Many RoboPets can share the
same manufacturer, there's a many-to-one relationship.

```
@embeddable class PetPk {
  string name;
  string manufacturerId;
}

@entity class RoboPet {
  @EmbeddedId PetPk pk;
  // This works on existing schemas, but fails while generating schemas with the error:
  // "duplicate column name robot_pet.manufacturer_id in schema"
  @manytoone @joincolumn("manufacturer_id") Manufacturer manufacturerId;
}

@entity class Manufacturer {
  @id string manufacturerId;
}
```

The code above represents the tables:
```
CREATE TABLE robo_pet(name varchar, manufacturer_id varchar);
CREATE TABLE manufacturer(manufacturer_id);
```

The many-to-one relationship is established because many RoboPets share the same "manufacturer_id" column.
This relationship is currently flagged as an error, because the column mentioned in @joincolumn on
RoboPet.manufacturerId is already defined, however, it is a valid relationship and functions on
schemas that have already been created.
  • Loading branch information
vnayar authored and SingingBush committed May 14, 2024
1 parent 9a28569 commit 6fc1767
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion source/hibernated/metadata.d
Original file line number Diff line number Diff line change
Expand Up @@ -3807,7 +3807,9 @@ class TableInfo {
indexes ~= index;
}
void addColumn(ColumnInfo column) {
enforceHelper!HibernatedException((column.columnName in columnNameMap) is null, "duplicate column name " ~ tableName ~ "." ~ column.columnName ~ " in schema");
// Perform no logic if the column already exists, e.g. a @ManyToOne relationship using a key which is part of an @EmbeddedId.
if (column.columnName in columnNameMap) return;

columns ~= column;
columnNameMap[column.columnName] = column;
if (column.property !is null && (column.property.manyToOne || column.property.oneToOne)) {
Expand Down

0 comments on commit 6fc1767

Please sign in to comment.