Fix multi-threading, add Query interface, java test

This commit is contained in:
2024-05-04 17:13:34 +02:00
parent 34b620dfa5
commit cc3ac67be6
11 changed files with 488 additions and 80 deletions

View File

@@ -0,0 +1,129 @@
package nl.astraeus.persistence
import nl.astraeus.nl.astraeus.persistence.Persistable
import nl.astraeus.nl.astraeus.persistence.Persistent
import nl.astraeus.nl.astraeus.persistence.Reference
import nl.astraeus.nl.astraeus.persistence.count
import nl.astraeus.nl.astraeus.persistence.index
import nl.astraeus.nl.astraeus.persistence.searchIndex
import java.io.File
import kotlin.random.Random
import kotlin.test.Test
class TestThreaded {
class Company(
override var id: Long = 0,
override var version: Long = 0,
val name: String,
val adres: String = "Blaat"
) : Persistable, Cloneable {
//var persons: MutableList<Person> by ListReference<Person, Company>(Person::class.java)
companion object {
private const val serialVersionUID: Long = 1L
}
}
class Person(
override var id: Long = 0,
override var version: Long = 0,
val name: String,
val age: Int,
) : Persistable, Cloneable {
var company: Company by Reference<Company, Person>(Company::class.java)
companion object {
private const val serialVersionUID: Long = 1L
}
}
@Test
fun testThreaded() {
println("Test threaded")
val pst = Persistent(
directory = File("data", "test-threaded"),
arrayOf(
index<Person>("name") { p -> (p as? Person)?.name ?: "" },
index<Person>("age") { p -> (p as? Person)?.age ?: -1 },
index<Person>("ageGt20") { p -> ((p as? Person)?.age ?: 0) > 20 },
index<Person>("ageGt23") { p -> ((p as? Person)?.age ?: 0) > 23 },
index<Person>("ageOnlyGt20") { p ->
if (((p as? Person)?.age ?: 0) > 20) {
true
} else {
null
}
},
index<Person>("nameAndAge") { p ->
val person = p as? Person
if (person == null) {
null
} else {
person.name to person.age
}
},
index<Company>("name") { p -> (p as? Company)?.name ?: "" },
)
)
val companyNames = arrayOf("Company A", "Company B", "Company C", "Company D", "Company E")
val names = arrayOf("John Doe", "Jane Doe", "John Smith", "Jane Smith", "John Johnson", "Jane Johnson")
val random = Random(System.currentTimeMillis())
val empty = pst.query {
count<Person>() == 0
}
if (empty) {
val runnable = {
repeat(10) {
pst.transaction {
val company = Company(
id = 0L,
name = companyNames[random.nextInt(companyNames.size)]
)
repeat(10) {
val person = Person(
id = 0L,
name = names[random.nextInt(names.size)],
age = random.nextInt(0, 100),
)
person.company = company
store(person)
}
}
}
}
val threads = Array(25) {
Thread(runnable)
}
for (thread in threads) {
thread.start()
}
for (thread in threads) {
thread.join()
}
}
pst.query {
searchIndex<Person>("nameAndAge") { nameAndAge ->
val (name, age) = nameAndAge as Pair<String, Int>
name.contains("mit") && age > 80
}.forEach { p ->
println("Found person by name and age: ${p.id}: ${p.name} - ${p.age}")
}
}
pst.snapshot()
pst.datastore.printStatus()
pst.removeOldFiles()
}
}