canonical / sqlair

Friendly type mapping for SQL databases
Apache License 2.0
16 stars 8 forks source link

Allow omitempty flag to be used with INSERT statements #142

Closed Aflynn50 closed 3 months ago

Aflynn50 commented 3 months ago

When inserting a into a table with unique primary keys the user needs to specify the primary key in their object every time. If it is left to its default zero value it will most likely break the unique constraint. In some tables, the primary key can is auto when a new row is inserted. In this case the user may want to insert a full struct using the asterisk notation but omitting the primary key.

To automatically omit a primary key, the user can set a flag in the db tag after the column name for the field e.g.

type Person struct {
    ID        int    `db:"id, omitempty"`
    Name      string `db:"name"`
    PostCode  int    `db:"address_id"`
}

This will indicate to SQLair that if this value is zero when the parameter is passed for execution, it should not be inserted into the database.

As specified in the INSERT statement support specification, the omit empty flag should only work for struct fields being inserted via an asterisk. If the field is inserted explicitly, e.g. INSERT INTO t (id) VALUES ($Person.id) then we should throw an error. Similarly, if a tag with omitempty set is used in an input expression elsewhere, an error should also be thrown e.g. SELECT &Person.* FROM person WHERE id = $Person.id.