Move persistence to plugin shared.

This commit is contained in:
2023-02-07 12:49:47 -05:00
parent 5f9f6e5fa7
commit 3f67e737c4
8 changed files with 20 additions and 18 deletions

View File

@ -4,4 +4,7 @@ plugins {
dependencies {
api(project(":common-all"))
api("org.jetbrains.xodus:xodus-openAPI:2.0.1")
api("org.jetbrains.xodus:xodus-entity-store:2.0.1")
}

View File

@ -3,5 +3,6 @@ package gay.pizza.foundation.shared
import java.nio.file.Path
interface IFoundationCore {
val persistence: PluginPersistence
val pluginDataPath: Path
}

View File

@ -0,0 +1,36 @@
package gay.pizza.foundation.shared
import jetbrains.exodus.entitystore.Entity
import jetbrains.exodus.entitystore.EntityIterable
import jetbrains.exodus.entitystore.PersistentEntityStores
import jetbrains.exodus.entitystore.StoreTransaction
class PersistentStore(core: IFoundationCore, fileStoreName: String) : AutoCloseable {
private val fileStorePath = core.pluginDataPath.resolve("persistence/${fileStoreName}")
private val entityStore = PersistentEntityStores.newInstance(fileStorePath.toFile())
fun <R> transact(block: StoreTransaction.() -> R): R {
var result: R? = null
entityStore.executeInTransaction { tx ->
result = block(tx)
}
return result!!
}
fun create(entityTypeName: String, populate: Entity.() -> Unit) = transact {
populate(newEntity(entityTypeName))
}
fun <R> getAll(entityTypeName: String, block: (EntityIterable) -> R): R =
transact { block(getAll(entityTypeName)) }
fun <T, R> find(entityTypeName: String, propertyName: String, value: Comparable<T>, block: (EntityIterable) -> R): R =
transact { block(find(entityTypeName, propertyName, value)) }
fun deleteAllEntities(entityTypeName: String) =
transact { entityStore.deleteEntityType(entityTypeName) }
override fun close() {
entityStore.close()
}
}

View File

@ -0,0 +1,18 @@
package gay.pizza.foundation.shared
import java.util.concurrent.ConcurrentHashMap
class PluginPersistence(val core: IFoundationCore) {
val stores = ConcurrentHashMap<String, PersistentStore>()
/**
* Fetch a persistent store by name. Make sure the name is path-safe, descriptive and consistent across server runs.
*/
fun store(name: String): PersistentStore =
stores.getOrPut(name) { PersistentStore(core, name) }
fun unload() {
stores.values.forEach { store -> store.close() }
stores.clear()
}
}