Skip to content

Commit d393664

Browse files
committed
💥(coreLib/db) DBApi更新
1 parent e6bda40 commit d393664

5 files changed

Lines changed: 107 additions & 72 deletions

File tree

scripts/coreLibrary/DBConnector.kts

Lines changed: 0 additions & 41 deletions
This file was deleted.

scripts/coreLibrary/db/h2db.kts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
@file:Import("com.h2database:h2:2.0.206", mavenDepends = true)
2+
3+
import cf.wayzer.scriptAgent.util.Services
4+
import org.jetbrains.exposed.sql.Database
5+
import org.jetbrains.exposed.sql.DatabaseConfig
6+
import org.jetbrains.exposed.sql.ExperimentalKeywordApi
7+
import java.sql.DriverManager
8+
9+
val enable by config.key(true, "开启H2DB")
10+
val preserveKeywordCasing by config.key(true, "是否保留关键字大小写, 老用户请设置为false")
11+
val preserveKeywordCasing0 get() = preserveKeywordCasing
12+
13+
onEnable {
14+
if (!enable) {
15+
ScriptManager.disableScript(this, "配置关闭")
16+
return@onEnable
17+
}
18+
Class.forName("org.h2.Driver")
19+
20+
val path = Config.dataDir.resolve("h2DB.db").absolutePath
21+
val db = Database.connect({
22+
DriverManager.getConnection("jdbc:h2:$path")
23+
}, DatabaseConfig {
24+
@OptIn(ExperimentalKeywordApi::class)
25+
preserveKeywordCasing = preserveKeywordCasing0
26+
})
27+
@OptIn(SAExperimentalApi::class)
28+
Services.provide(db)
29+
}
Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
@file:Import("org.jetbrains.exposed:exposed-core:0.59.0", mavenDepends = true)
2-
@file:Import("org.jetbrains.exposed:exposed-dao:0.59.0", mavenDepends = true)
3-
@file:Import("org.jetbrains.exposed:exposed-java-time:0.59.0", mavenDepends = true)
4-
@file:Import("org.jetbrains.exposed:exposed-jdbc:0.59.0", mavenDepends = true)
5-
6-
package coreLibrary
7-
1+
package coreLib.db
2+
3+
import cf.wayzer.scriptAgent.ScriptRegistry
4+
import cf.wayzer.scriptAgent.define.SAExperimentalApi
5+
import cf.wayzer.scriptAgent.define.Script
6+
import cf.wayzer.scriptAgent.util.DSLBuilder
7+
import cf.wayzer.scriptAgent.util.Services
8+
import coreLibrary.lib.getOrNull
89
import org.jetbrains.exposed.dao.id.EntityID
910
import org.jetbrains.exposed.dao.id.IdTable
1011
import org.jetbrains.exposed.sql.*
@@ -13,14 +14,17 @@ import org.jetbrains.exposed.sql.javatime.timestamp
1314
import org.jetbrains.exposed.sql.transactions.TransactionManager
1415
import org.jetbrains.exposed.sql.transactions.transaction
1516
import java.time.Instant
16-
import java.util.logging.Level
1717
import kotlin.system.measureTimeMillis
1818

19+
@OptIn(SAExperimentalApi::class)
20+
object DBApi {
21+
val db = Services.get<Database>()
22+
23+
private var Script.registeredTable: List<Table>? by DSLBuilder.dataKey()
1924

20-
@Suppress("unused", "MemberVisibilityCanBePrivate")
21-
object DB : ServiceRegistry<Database>() {
2225
object TableVersion : IdTable<String>("TableVersion") {
2326
// can't use `text` as h2db don't support for primaryKey
27+
2428
override val id: Column<EntityID<String>> = varchar("table", 64).entityId()
2529
override val primaryKey: PrimaryKey = PrimaryKey(id) // h2database#2191
2630

@@ -65,9 +69,6 @@ object DB : ServiceRegistry<Database>() {
6569
}
6670
}
6771

68-
private val key = DataKeyWithDefault("DB_registeredTable") { mutableSetOf<Table>() }
69-
private val Script.registeredTable by key
70-
7172
interface WithUpgrade {
7273
val version: Int
7374

@@ -80,24 +81,24 @@ object DB : ServiceRegistry<Database>() {
8081
/**
8182
* 为模块注册表格
8283
* 注册时不一定立刻运行
83-
* 会等[DB]初始化后统一注册
84+
* 会等[db]初始化后统一注册
8485
* 如果DB有版本变化,请实现[WithUpgrade],未实现默认版本号1
8586
*/
86-
@Synchronized
87-
@ScriptDsl
88-
fun Script.registerTable(vararg t: Table) {
89-
registeredTable.addAll(t)
90-
if (provided)
91-
transaction {
87+
context(script: Script)
88+
fun registerTable(vararg t: Table) {
89+
script.registeredTable = script.registeredTable.orEmpty() + t
90+
db.getOrNull()?.let {
91+
transaction(it) {
9292
withDataBaseLock { initTable(t.asIterable()) }
9393
}
94+
}
9495
}
9596

9697
@Synchronized
97-
internal fun initDB(db: Database) {
98+
fun initDB(db: Database) {
9899
TransactionManager.defaultDatabase = db
99-
val allTable = ScriptRegistry.allScripts { it.inst?.dslExists(key) == true }
100-
.flatMapTo(mutableSetOf()) { it.inst!!.registeredTable }
100+
val allTable = ScriptRegistry.allScripts { it.inst != null }
101+
.flatMapTo(mutableSetOf()) { it.inst?.registeredTable.orEmpty() }
101102

102103
transaction {
103104
withDataBaseLock {
@@ -114,12 +115,4 @@ object DB : ServiceRegistry<Database>() {
114115
}
115116
exposedLogger.info("Finish check upgrade for ${tables.size} tables, costs $time ms")
116117
}
117-
}
118-
119-
DB.subscribe(this) {
120-
try {
121-
DB.initDB(it)
122-
} catch (e: Exception) {
123-
logger.log(Level.SEVERE, "Error when initDB", e)
124-
}
125118
}

scripts/coreLibrary/db/module.kts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
@file:Depends("coreLibrary")
2+
@file:Import("org.jetbrains.exposed:exposed-core:0.59.0", mavenDepends = true)
3+
@file:Import("org.jetbrains.exposed:exposed-dao:0.59.0", mavenDepends = true)
4+
@file:Import("org.jetbrains.exposed:exposed-java-time:0.59.0", mavenDepends = true)
5+
@file:Import("org.jetbrains.exposed:exposed-jdbc:0.59.0", mavenDepends = true)
6+
7+
import coreLib.db.DBApi
8+
import java.util.logging.Level
9+
10+
onEnable {
11+
launch {
12+
@OptIn(SAExperimentalApi::class)
13+
DBApi.db.observe().collect {
14+
if (it.size > 1) {
15+
logger.warning("More than one database registered: $it")
16+
}
17+
val db = it.firstOrNull() ?: return@collect
18+
try {
19+
DBApi.initDB(db)
20+
} catch (e: Exception) {
21+
logger.log(Level.SEVERE, "Error when initDB", e)
22+
}
23+
}
24+
}
25+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
@file:Import("org.postgresql:postgresql:42.7.5", mavenDepends = true)
2+
3+
import cf.wayzer.scriptAgent.util.Services
4+
import org.jetbrains.exposed.sql.Database
5+
import org.jetbrains.exposed.sql.DatabaseConfig
6+
import org.jetbrains.exposed.sql.ExperimentalKeywordApi
7+
8+
val url by config.key("postgresql://db:5432/postgres", "数据库连接uri")
9+
val user by config.key("", "用户名")
10+
val password by config.key("", "密码")
11+
val preserveKeywordCasing by config.key(true, "是否保留关键字大小写, 老用户请设置为false")
12+
val preserveKeywordCasing0 get() = preserveKeywordCasing
13+
14+
onEnable {
15+
if (user.isEmpty() || password.isEmpty()) {
16+
ScriptManager.disableScript(this, "配置无效,请先通过sa config设置user/password.")
17+
return@onEnable
18+
}
19+
20+
Class.forName("org.postgresql.Driver")
21+
val db = Database.connect({
22+
java.sql.DriverManager.getConnection("jdbc:$url", user, password)
23+
}, DatabaseConfig {
24+
@OptIn(ExperimentalKeywordApi::class)
25+
preserveKeywordCasing = preserveKeywordCasing0
26+
})
27+
@OptIn(SAExperimentalApi::class)
28+
Services.provide(db)
29+
}

0 commit comments

Comments
 (0)