【问题标题】:UPDATE in PostgreSQL 9.1 seems to misuse placeholder typesPostgreSQL 9.1 中的 UPDATE 似乎滥用占位符类型
【发布时间】:2013-11-13 20:35:31
【问题描述】:

给定以下架构(作为示例)

CREATE TABLE "test" (
  "id" int, 
  "title" varchar
);

在 NodeJS 中,我尝试使用以下内容进行更新

client.query(
            'WITH new_vals ("id","title") AS (VALUES($1,$2)) ' +
            'UPDATE "test" "t" SET "id"=nv.id, "title"=nv.title ' +
            'FROM new_vals nv ' +
            'WHERE "t"."id"=nv.id;',
        [1,'test'],
        function(err, res){ ... }
);

它给了我以下错误:'error: operator does not exist: integer = text'

好的,让我们尝试停止使用"t"."id"=nv.id,只重用一个可用参数:

client.query(
            'WITH new_vals ("id","title") AS (VALUES($1,$2)) ' +
            'UPDATE "test" "t" SET "id"=nv.id, "title"=nv.title ' +
            'FROM new_vals nv ' +
            'WHERE "t"."id"=$1;',
        [1,'test'],
        function(err, res){ ... }
);

仍然'错误:运算符不存在:整数=文本'

好的,现在让我们添加另一个$3 占位符:

client.query(
            'WITH new_vals ("id","title") AS (VALUES($1,$2)) ' +
            'UPDATE "test" "t" SET "id"=nv.id, "title"=nv.title ' +
            'FROM new_vals nv ' +
            'WHERE "t"."id"=$3;',
        [1,'test',1],
        function(err, res){ ... }
);

另一个错误:'error: column "id" is of type integer but expression is of type text'

我完全迷路了。为什么不在 WHERE 中使用 int 运算符类?这里有什么问题?

奇怪的是,没有WITH 子句的标准UPDATE 形式可以正常工作...

如果您需要使用代码:https://gist.github.com/kolypto/7455957

【问题讨论】:

    标签: node.js postgresql sql-update operators postgresql-9.1


    【解决方案1】:

    在这种情况下:

    WITH new_vals ("id","title") AS (VALUES($1,$2))
    

    PostgreSQL 不知道 $1$2 将是什么类型,因此它们最终将被视为文本值。 fine manual notes this

    INSERT 中使用VALUES 时,所有值都会自动强制转换为相应目标列的数据类型。在其他上下文中使用时,可能需要指定正确的数据类型。

    values($1, $2) 中,无法推断类型,因此您必须明确:

    WITH new_vals ("id", "title") AS (VALUES($1::integer, $2::text))
    

    $2 的演员表不是必需的,但我喜欢保持一致。

    【讨论】:

    • 听起来很合理。但是它如何解释最后一个带有 $3 占位符的示例,该占位符仅在 WHERE 子句中使用?
    • AFAIK 这是事情何时发生的问题。当占位符被替换时,CTE 已经被视为values(unknown, unknown),因此假定它是两个text 值。在WHERE 中,稍后在知道$3 的值时检查类型。
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多