Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify checking for entity creation #925 #926

Merged
merged 1 commit into from
Jun 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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