postgresql - 如何使用 PostgreSQL 数据库上公开的 kotlin 在外键上创建索引
问题描述
我正在使用 Kotlin Exposed 来定义一个像这样的表
object Headers : Table("headers") {
val id = uuid("id").primaryKey()
// tons more columns
}
我有另一个这样定义的表
object Transactions : Table("transactions") {
val headerId = (uuid("header_id").references(Headers.id)).index("custom_header_index")
// tons more columns
}
现在你可以看到我正在尝试在这个引用/外键上创建一个索引,因为如果我尝试查询这个关系,我会得到以下结果
EXPLAIN SELECT * FROM transactions WHERE header_id = 'bdbfc5d6-9cf1-430a-a361-a5f96cc7d799'
Gather (cost=1000.00..13771.31 rows=8 width=171)"
Workers Planned: 2"
-> Parallel Seq Scan on transactions (cost=0.00..12770.51 rows=3 width=171)"
Filter: (header_id = 'bdbfc5d6-9cf1-430a-a361-a5f96cc7d799'::uuid)"
它正在执行顺序扫描。而且由于该表将包含数十万条记录,因此速度非常慢。
我已经尝试了几件事以使其正常工作,但没有任何语法更改似乎会导致任何架构更改
例子:
// no infix
val headerId = (uuid("header_id").references(Headers.id)).index("custom_header_index")
// infix
val headerId = (uuid("header_id") references Headers.id).index("custom_header_index")
// index before reference
val headerId = (uuid("header_id").index("custom_header_index") references Headers.id)
我已经尝试了所有这些有和没有自定义索引名称的方法。
我还应该注意我正在使用
SchemaUtils.createMissingTablesAndColumns(Headers, Transactions)
它在所有其他类型的列上检测到索引更改,但在外部关系上检测不到。
我做错了什么,如何让 kotlin-exposed 来创建这些索引?
编辑:澄清
抱歉,我的问题没有明确说明我的问题是 Kotlin Exposed 没有创建这些索引。当我手动创建它们时,一切都按预期工作。
同时我也找到了这个问题的可能原因
for (table in tables) {
val existingTableIndices = currentDialect.existingIndices(table)[table].orEmpty().filterFKeys()
val mappedIndices = table.indices.filterFKeys() // Here foreign keys are filtered
existingTableIndices.forEach { index ->
mappedIndices.firstOrNull { it.onlyNameDiffer(index) }?.let {
exposedLogger.trace("Index on table '${table.tableName}' differs only in name: in db ${index.indexName} -> in mapping ${it.indexName}")
nameDiffers.add(index)
nameDiffers.add(it)
}
}
notMappedIndices.getOrPut(table.nameInDatabaseCase(), {hashSetOf()}).addAll(existingTableIndices.subtract(mappedIndices))
missingIndices.addAll(mappedIndices.subtract(existingTableIndices))
}
上面的代码来自 Exposed 库,它过滤它必须创建的所有索引,如果列上有外键则将其删除,从而无法在这些列上创建常规索引。
我可能会在他们的 github 存储库中提出一个问题,如果它得到修复,我会更新这个问题。
解决方案
推荐阅读
- heroku - Heroku 中的信用卡被拒绝
- php - 为什么 CodeIgniter url 会突然显示 403 错误页面
- excel - 从同一行电源查询中获取列
- cuda - 在 CUDA __fsqrt 圆形内在函数中,什么术语被四舍五入?
- android - 当我运行颤振项目时,它正在发生
- arrays - 我试图从颤动的错误中创建一个列表数组,但每次运行代码时都会遇到错误
- linux - 我运行了一个我创建的 sh 脚本,但它失败了,因为它发现了不在脚本本身中的无效字符
- excel - 从单元格到 DTPicker 并再次返回到单元格 - VBA - Userform
- typescript - 有没有办法强制 TypeScript 返回某种类型?
- javascript - 使skypack成功构建带有JSX的npm包需要什么?