ormx icon indicating copy to clipboard operation
ormx copied to clipboard

Support for `GENERATED ALWAYS AS IDENTITY` columns

Open mattfbacon opened this issue 3 years ago • 3 comments

As far as I know, it is generally considered best practice to enforce that the ID column will always be generated. The GENERATED ALWAYS modifier allows this. Additionally, the AS IDENTITY modifier creates the numeric sequence.

The documentation for deriving Table states that:

ormx will generate a helper struct for inserting rows into the database when using #[ormx(insertable)]. This struct will contain all fields of the struct, except

  • the ID
  • fields annotated with #[ormx(default)]

since the value of these fields will be generated by the database.

However, the implementation of the derive macro for the Insertable trait does not follow this:

https://github.com/NyxCode/ormx/blob/bc65c51f12c8b2c5c8d884599a7dd02851ad9c69/ormx-macros/src/backend/postgres/insert.rs#L38

https://github.com/NyxCode/ormx/blob/bc65c51f12c8b2c5c8d884599a7dd02851ad9c69/ormx-macros/src/table/mod.rs#L48-L50

I believe insertable_fields should also exclude the ID, or maybe the ID should be marked as having a default value by setting the default field to true.

mattfbacon avatar Apr 15 '22 19:04 mattfbacon

For the moment I have worked around this by manually adding #[ormx(default)] to the field for the ID column.

mattfbacon avatar Apr 15 '22 19:04 mattfbacon

@mattfbacon thanks for opening this issue.
It seems like the documentation is out-of-date. Nowadays, the ID column is not handled specially - if it's database-generated, it has to be #[ormx(default)].

NyxCode avatar Apr 29 '22 19:04 NyxCode

OK. This is still semi-relevant though because a GENERATED ALWAYS column can't be updated either, which is still allowed for fields annotated with #[ormx(default)]. In my fork, I added a #[ormx(default = "always")] option to accomplish this.

mattfbacon avatar Apr 29 '22 20:04 mattfbacon