upsert postgresql返回id

时间:2015-08-23 17:49:12

标签: sql postgresql go upsert

最初我认为这是一个heroku问题,因为一些奇怪的原因,这个代码在本地运行良好,但在进一步调查后,我意识到id一直在返回0。基本上我正在尝试编写一个返回id的upsert。我正在使用sql库。

-- ----------------------------
--  Table structure for books
-- ----------------------------
DROP TABLE IF EXISTS "public"."books" CASCADE;
CREATE TABLE "public"."books" (
    "id" serial primary key,
    "title" varchar(255) NOT NULL COLLATE "default",
    "first" varchar(40) NOT NULL COLLATE "default",
    "last" varchar(40) NOT NULL COLLATE "default",
    "class" varchar(40) NOT NULL COLLATE "default"
)
WITH (OIDS=FALSE);
-- ----------------------------
--  Table structure for bookitems
-- ----------------------------
DROP TABLE IF EXISTS "public"."bookitem";
CREATE TABLE "public"."bookitem" (

    "id" serial primary key,
    "price" int NOT NULL,
    "condition" int NOT NULL,
    "views" int NOT NULL,
    "seller" bigint NOT NULL,
    "book" int REFERENCES books(id),
    "saletype" int NOT NULL,
    "date" bigint NOT NULL,
    "description" varchar(255) NOT NULL COLLATE "default",
    "bucket" int NOT NULL,
    "status" int NOT NULL --This is for showing what the staus of the item is (bought sold etc.)
    --FOREIGN KEY (book) REFERENCES books(id)
)
WITH (OIDS=FALSE);

以下是触发错误的代码:

rows, err := db.Query(`with vals as (
      select $1::VARCHAR as title, $2::VARCHAR as first, $3::VARCHAR as last, $4::VARCHAR as class
    )
    insert into books (title, first, last, class)
    select v.title, v.first, v.last, v.class
    from vals as v
    where not exists (select * from books as t where t.title = v.title and t.last = v.last and t.first = v.first and t.class = v.class)
    RETURNING id`, r.FormValue("title"),
            r.FormValue("first"),
            r.FormValue("last"),
            r.FormValue("class"))
        //defer rows.Close()
        rows.Scan(&id)

        PanicIf(err)

        _, err = db.Query("INSERT INTO bookitem (price, condition, views, seller, book, saletype,   date, description, bucket, status) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
            r.FormValue("price"),
            r.FormValue("condition"),
            0,
            0,
            id,
            r.FormValue("saletype"),
            0,
            r.FormValue("description"),
            0,
            0)

        PanicIf(err)

我运行部署到heroku时遇到的错误是:

pq: insert or update on table "bookitem" violates foreign key constraint"bookitem_book_fkey"

此时任何建议都会受到赞赏,因为我已经尝试了两次来解决这个问题无济于事。

P.S。感谢所有帮助我意识到这个问题是我的代码而不是heroku的人!

1 个答案:

答案 0 :(得分:0)

因此将其更改为QueryRow解决了我的问题。我认为它必须与并发问题有关。希望这对未来的人有用。