Postgres Ruby中的Upsert

时间:2013-07-24 08:40:02

标签: ruby pg

我已经看到了解决这个问题的其他问题,我知道PostgreSQL没有内置的upsert,必须使用2种方法完成。这是我在Ruby中使用pg gem的代码。

@db.exec_params("UPDATE crawled SET url = $1, timestamp = $2 WHERE url = $1",[url,DateTime.now])

@db.exec_params("INSERT INTO crawled (url, timestamp) VALUES ($1, $2) WHERE NOT EXISTS 
              (SELECT 1 FROM crawled WHERE url = $1)",[url,DateTime.now])

然而,当我运行此操作时,我收到语法错误

exec_params': ERROR:  syntax error at or near "WHERE" (PG::Error)
LINE 1: ...ERT INTO crawled (url, timestamp) VALUES ($1, $2) WHERE NOT ...

我的错误在哪里?

2 个答案:

答案 0 :(得分:0)

从看你的例子我有两个问题。

  1. 哪条线路导致错误?

  2. table应该用表名替换,不是吗? http://www.postgresql.org/docs/8.2/static/sql-insert.html

答案 1 :(得分:0)

伪码:

# transaction
query('BEGIN');

# find out if row already exists, and lock it if it does
result = query('SELECT * FROM crawled WHERE url = $1 FOR UPDATE', [url])

# row exists, so update it
if (result.rows > 0) {
    query('UPDATE crawled SET timestamp = $2 WHERE url = $1', [url, DateTime.now])
}

# row doesn't exist, insert
else {
    query('INSERT INTO crawled (url, timestamp) VALUES ($1, $2)', [url, DateTime.now])
}

# commit transaction
query('COMMIT');