orangy / squash

SQL access DSL for Kotlin
265 stars 16 forks source link

question: How I can get return data from insert statement. #31

Closed gintsgints closed 5 years ago

gintsgints commented 5 years ago

Should insert statement return inserted data after issuing execute() ?

codesplode commented 5 years ago

Hi @gintsgints,

To get data back from an insert, all you have to do is add fetch() before your execute call. This is an example from the unit tests:

        val spbId = insertInto(Cities).values {
            it[name] = "St. Petersburg"
        }.fetch(Cities.id).execute()

Find it in the code here : Cities Test Data Insert

gintsgints commented 5 years ago

Somehow not work for me. Returns only ID.

https://github.com/gintsgints/hello-ktor-api/tree/squashORM

Blog service example https://github.com/gintsgints/hello-ktor-api/blob/squashORM/src/entity/blog/BlogService.kt

codesplode commented 5 years ago

The fetch method as written is intended to get the generated column, though the name doesn't necessarily imply that, and it only supports one generated column currently. I just reviewed the implementation and see it is actually receiving its data from the generated column using the jdbc api, so there is no extra query getting the id, but you are limited to getting only one generated column.

Source Reference (generatedColumn is the property set by the fetch(column) method): https://github.com/orangy/squash/blob/dc025481b7104a5e234d6df370d715b6b37c81eb/squash-jdbc/src/org/jetbrains/squash/drivers/JDBCTransaction.kt#L60-L62

For your example, if you are trying to refresh all columns data after database defaults and such, I would recommend having creating a second query for the time being. In my applications, I typically have a read(key) that makes it easy to do this or refresh(bean) that I can use in insert methods. I hope that helps.

If you do need multiple generated keys, this should be a pretty easy modification and I may need this in the future as well. I would be happy to help or potentially do the change if the time becomes available, but I simply share a lot of pull requests with the project and am not an admin of it.

gintsgints commented 5 years ago

Thanks. I think it answers my question well.