2

Does anyone know what could be causing this error? I'm trying to convert a MySQL site to Postgres so I can host on Heroku. I'm new to database syntax, and this problem has been bugging me for days.

PG::Error: ERROR:  syntax error at or near "ON"
LINE 1: ...tores ("key", "value") VALUES ('traffic:hits', 0) ON DUPLICA...
                                                             ^

Here's the github page for the site I'm trying to convert. https://github.com/jcs/lobsters

This is the query. I added the backslash double quotes in replace of `.

if Rails.env == "test"
  Keystore.connection.execute("INSERT OR IGNORE INTO " <<
    "#{Keystore.table_name} (\"key\", \"value\") VALUES " <<
    "(#{q(key)}, 0)")
  Keystore.connection.execute("UPDATE #{Keystore.table_name} " <<
    "SET \"value\" = \"value\" + #{q(amount)} WHERE \"key\" = #{q(key)}")
else
  Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
    "\"key\", \"value\") VALUES (#{q(key)}, #{q(amount)}) ON DUPLICATE KEY " +
    "UPDATE \"value\" = \"value\" + #{q(amount)}")
end
4

2 回答 2

2

Postgres'INSERT不支持 MySQL 的 variant INSERT ... ON DUPLICATE KEY UPDATE

有关替代方案,请参阅此问题的答案。

于 2012-09-14T15:56:58.973 回答
0

昨晚我正在研究这个确切的代码,这是我如何修复它的初步看法,遵循这个答案

def self.put(key, value)
key_column = Keystore.connection.quote_column_name("key")
value_column = Keystore.connection.quote_column_name("value")

if Keystore.connection.adapter_name == "SQLite"
  Keystore.connection.execute("INSERT OR REPLACE INTO " <<
    "#{Keystore.table_name} (#{key_column}, #{value_column}) VALUES " <<
    "(#{q(key)}, #{q(value)})")

elsif Keystore.connection.adapter_name == "PostgreSQL"
  Keystore.connection.execute("UPDATE #{Keystore.table_name} " +
    "SET #{value_column} =#{q(value)} WHERE #{key_column} =#{q(key)}")
  Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (#{key_column}, #{value_column}) " +
    "SELECT #{q(key)}, #{q(value)} " +
    "WHERE NOT EXISTS (SELECT 1 FROM #{Keystore.table_name} WHERE #{key_column} = #{q(key)}) "
    )

elsif Keystore.connection.adapter_name == "MySQL" || Keystore.connection.adapter_name == "Mysql2"
  Keystore.connection.execute("INSERT INTO #{Keystore.table_name} (" +
    "#{key_column}, #{value_column}) VALUES (#{q(key)}, #{q(value)}) ON DUPLICATE KEY " +
    "UPDATE #{value_column} = #{q(value)}")

else
  raise "Error: keystore requires db-specific put method."

end

true
end

除了为了 postgres 兼容性之外,在 lobsters 代码库中还有很多东西需要修复——在其他控制器文件中找到了 mysql 特定的东西。我目前正在https://github.com/seltzered/journaltalk我自己的龙虾叉上处理它们- postgres 修复应该在未来一两天内提交。

于 2013-10-27T21:53:50.580 回答