postgresql 取消嵌套行列表以便在更新时选择

yzxexxkh  于 2023-01-17  发布在  PostgreSQL
关注(0)|答案(1)|浏览(125)

假设我想对一个记录的单链表中的一些元素进行重新排序...
想到的方法是构建一个(previous, current) id元组数组,然后在UPDATE语句的FROM子句中取消嵌套。
也就是说,大概是这样的:

private fun updateCompositionElementOrdering(elementIdsInExpectedOrder: List<Int>) {
    val PREVIOUS_ELEMENT = DSL.field("previous_element_id", Int::class.javaObjectType)
    val CURRENT_ELEMENT = DSL.field("current_element_id", Int::class.javaObjectType)

    val previousAndCurrent = elementIdsInExpectedOrder.mapIndexed { i, currentElement ->
        val previousElementId = if (i == 0) null else elementIdsInExpectedOrder[i - 1]
        DSL.row(previousElementId, currentElement)
    }

    ctx
        .update(COMPOSITION_ELEMENT)
        .set(COMPOSITION_ELEMENT.PREVIOUS_COMPOSITION_ELEMENT_ID, PREVIOUS_ELEMENT)
        .from(
            DSL.unnest(previousAndCurrent).`as`(DSL.name("p"), PREVIOUS_ELEMENT.unqualifiedName, CURRENT_ELEMENT.unqualifiedName)
        )
        .where(COMPOSITION_ELEMENT.ID.eq(CURRENT_ELEMENT))
        .execute()
}

当然是private val ctx: DSLContext
但这会导致:

jOOQ; bad SQL grammar [
    update "public"."composition_element"
    set
        "previous_composition_element_id" = previous_element_id,
        "modified_by_id" = ? 
    from
        unnest(cast(? as any[])) as "values" (previous_element_id, current_element_id)
    where "public"."composition_element"."id" = current_element_id
];

nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at or near "any"

(this与jOOQ 3.17.4Postgres 13.5一起使用)

j2qf4p5b

j2qf4p5b1#

jOOQ目前不支持取消嵌套行数组。它可能应该:https://github.com/jOOQ/jOOQ/issues/14505
...但这也是一个棘手的事情在PostgreSQL。例如:

select *
from unnest(array[row(1, 2), row(3, 4)]) as t (a, b)

产生:
SQL错误[42601]:错误:返回"record"的函数需要列定义列表
您需要指定列类型:

select *
from unnest(array[row(1, 2), row(3, 4)]) as t (a integer, b integer)

有一个功能请求,但它不是太受欢迎,因为这个功能是多么的深奥:https://github.com/jOOQ/jOOQ/issues/5926
也许,最好使用DSL.values()

DSL.values(previousAndCurrent)
   .`as`(DSL.name("p"), 
         PREVIOUS_ELEMENT.unqualifiedName, 
         CURRENT_ELEMENT.unqualifiedName)

相关问题