NyxCode / ormx

bringing orm-like features to sqlx
MIT License
287 stars 32 forks source link

Support for `GENERATED ALWAYS AS IDENTITY` columns #30

Closed mattfbacon closed 5 days ago

mattfbacon commented 2 years ago

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 commented 2 years ago

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

NyxCode commented 2 years ago

@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)].

mattfbacon commented 2 years ago

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.