Skip to content

Commit

Permalink
Modify checking for entity creation #925 (#926)
Browse files Browse the repository at this point in the history
  • Loading branch information
socar-brad authored Jun 7, 2020
1 parent b983784 commit 43d6ab1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ open class Entity<ID:Comparable<ID>>(val id: EntityID<ID>) {
_readValues!!
}

internal fun isNewEntity(): Boolean {
val cache = TransactionManager.current().entityCache
return cache.inserts[klass.table]?.contains(this) ?: false
}

/**
* Updates entity fields from database.
* Override function to refresh some additional state if any.
Expand All @@ -35,7 +40,7 @@ open class Entity<ID:Comparable<ID>>(val id: EntityID<ID>) {
*/
open fun refresh(flush: Boolean = false) {
val cache = TransactionManager.current().entityCache
val isNewEntity = id._value == null
val isNewEntity = isNewEntity()
when {
isNewEntity && flush -> cache.flushInserts(klass.table)
flush -> flush()
Expand Down Expand Up @@ -139,7 +144,7 @@ open class Entity<ID:Comparable<ID>>(val id: EntityID<ID>) {
}

open fun flush(batch: EntityBatchUpdate? = null): Boolean {
if (id._value == null) {
if (isNewEntity()) {
TransactionManager.current().entityCache.flushInserts(this.klass.table)
return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ abstract class EntityClass<ID : Comparable<ID>, out T: Entity<ID>>(val table: Id
*/
fun reload(entity: Entity<ID>, flush: Boolean = false): T? {
if (flush) {
if (entity.id._value == null)
if (entity.isNewEntity())
TransactionManager.current().entityCache.flushInserts(table)
else
entity.flush()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,21 @@ class EntityTests: DatabaseTestsBase() {
}
}

@Test fun testNewWithIdAndRefresh() {
val objectsToVerify = arrayListOf<Pair<Human, TestDB>>()
withTables(Humans) { testDb ->
val x = Human.new(2) {
h = "foo"
}
x.refresh(flush = true)
objectsToVerify.add(x to testDb)
}
objectsToVerify.forEach { (human, testDb) ->
assertEquals("foo", human.h, "Failed on ${testDb.name}" )
assertEquals(2, human.id.value, "Failed on ${testDb.name}" )
}
}

internal object OneAutoFieldTable : IntIdTable("single")
internal class SingleFieldEntity(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<SingleFieldEntity>(OneAutoFieldTable)
Expand Down

0 comments on commit 43d6ab1

Please sign in to comment.