Postgres weird PG::UndefinedColumn: ERROR: on value

Postgres weird PG::UndefinedColumn: ERROR: on value

执行一个简单的 select - 使用 activerecord 执行的操作,

ActiveRecord::Base.connection.execute('select * from spree_variants where sku = "1SB-E4196-00";')

我收到这个错误:

from /Users/abc/.rvm/gems/ruby-2.7.2@cboparts/gems/activerecord-6.0.3.5/lib/active_record/connection_adapters/postgresql/database_statements.rb:92:in `exec'
Caused by PG::UndefinedColumn: ERROR:  column "1SB-E4196-00" does not exist
LINE 1: select * from spree_variants where sku = "1SB-E4196-00";

为什么将 "1SB-E4196-00" 视为一个列而不是 SKU?该错误似乎具有误导性。

因为 PostgreSQL 期望在 single quotes. While double quotes 中限定的字符串具有不同的含义:

There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word.

这意味着如果以下查询应该有效:

ActiveRecord::Base.connection.execute(
  "select * from spree_variants where sku = '1SB-E4196-00';"
)

顺便说一句,如果您正在使用 Rails 并拥有 SpreeVariant 模型,那么您可以在控制台中看到 Rails 如何格式化和转义查询,如下所示:

puts SpreeVariant.where(sku: '1SB-E4196-00').to_sql