Skip to content

Minor fix to better support `Insert()` on `kmysql` and `ksqlite` adapters

Compare
Choose a tag to compare
@VinGarcia VinGarcia released this 04 Nov 02:51
· 6 commits to master since this release

The Insert() adapter has a feature that allows IDs created by the database to be returned and saved back to the original struct.

An example of an ID that is generated by the database is a serial or auto-increment integer ID, or an ID that is a string and defaults to a "UUID()" function.

On Postgres the newly created ID is returned using the "RETURNING" key-word on the SQL query, on SQLServer this is done using the "OUTPUT" key-word on the SQL query. But for sqlite and mysql there is no equivalent key-word supported for returning a newly created value during an insert.

This means that we can't really return any ID value directly from the database during an Insert query for neither mysql nor sqlite.

The recommended alternative (which is what KSQL does) is to use LastInsertID(). This function is implemented on all databases and works specifically for integer IDs with an "auto-increment" behavior.

For the case of retrieving the ID using the LastInsertID() function we have a separate function called insertWithLastInsertID(). This function has to use reflection to copy the int64 value returned by the LastInsertID() function to the struct attribute that should contain this ID. This function used to work fine if the ID was an integer and it correctly ignored IDs if the type was a string as there is no way of returning this IDs efficiently and returned no errors.

However if the user decided to use a *int or an *string as the ID type on the struct the Insert operation would fail with a misleading error message.

v1.12.2 (and v1.12.1) fixes this error and now will cause *string IDs to be correctly ignored and will correctly work for *int IDs.