diff --git a/CHANGES.md b/CHANGES.md index 8217c6b..ed34eed 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,11 @@ # Changes +## unreleased + +### Feature + +- added `insertAndRefreshRecord` function + ## 2024-01-18 / 0.1.0 ### Feature diff --git a/src/main/kotlin/ls/jooq/execute/RecordMutators.kt b/src/main/kotlin/ls/jooq/execute/RecordMutators.kt index be139da..77e25a7 100644 --- a/src/main/kotlin/ls/jooq/execute/RecordMutators.kt +++ b/src/main/kotlin/ls/jooq/execute/RecordMutators.kt @@ -1,5 +1,6 @@ package ls.jooq.execute +import kotlinx.coroutines.reactive.awaitFirst import kotlinx.coroutines.reactive.awaitSingle import ls.jooq.prepare.insert import ls.jooq.prepare.update @@ -45,3 +46,16 @@ suspend fun > DSLContext.updateIfChangedAndExecute(record // SQL [update "table" set [ no fields are updated ] where "table"."pk" = $1]; syntax error at or near "[" this.updateAndExecute(record) } else null + +/** + * Inserts a [record] and sets the values of [record] from the returned values of the insert + * + * @param R the type of record + * @param record - the record to insert + * @return the inserted record, note that also the param record will have updated values + */ +suspend fun > DSLContext.insertAndRefreshRecord(record: UpdatableRecord): UpdatableRecord { + val inserted = insert(record).returning().awaitFirst() + record.from(inserted) + return record +} diff --git a/src/test/kotlin/ls/jooq/execute/RecordMutatorsTest.kt b/src/test/kotlin/ls/jooq/execute/RecordMutatorsTest.kt index 4b3247e..2c240f8 100644 --- a/src/test/kotlin/ls/jooq/execute/RecordMutatorsTest.kt +++ b/src/test/kotlin/ls/jooq/execute/RecordMutatorsTest.kt @@ -3,6 +3,7 @@ package ls.jooq.execute import DBExtension import DBTest import io.kotest.core.spec.style.FreeSpec +import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import kotlinx.coroutines.reactive.awaitSingle @@ -14,6 +15,31 @@ class RecordMutatorsTest : FreeSpec({ val ctx = DBExtension.dslContext + "DSLContext.insertAndRefreshRecord" - { + + "should insert the record" { + val record = AuthorRecord() + record.firstName = "max" + record.lastName = "irrelevant" + ctx.insertAndRefreshRecord(record) + + val insertedContent = ctx.selectFrom(Tables.AUTHOR).awaitAll().shouldHaveSize(1).first() + insertedContent.firstName shouldBe "max" + insertedContent.lastName shouldBe "irrelevant" + insertedContent.id.shouldNotBeNull() + } + + "after the call the record should have values set from database defaults" { + val record = AuthorRecord() + record.firstName = "max" + record.lastName = "irrelevant" + ctx.insertAndRefreshRecord(record) + + record.id.shouldNotBeNull() + record.created.shouldNotBeNull() + } + } + "DSLContext.create()" - { "should create a record of the given type and insert it into the DB" {