connection.select_value 只返回带有 pg gem 的 postgres 中的字符串

我正在将 Rails 应用程序从使用 mysql (mysql2 gem) 转换为 postgres (pg gem).

I'm converting a rails app from using mysql (mysql2 gem) to postgres (pg gem).

在mysql中,ActiveRecord::Base.connection.select_value根据数据调用返回值,例如:

With mysql, ActiveRecord::Base.connection.select_value calls return values typed according to the data, for example:

> ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM errors")
=> 86
> ActiveRecord::Base.connection.select_value("SELECT exception FROM errors where id=565")
=> "TechTalk.Genome.SqlExecutionException"
> ActiveRecord::Base.connection.select_value("SELECT id FROM errors where id=565")
=> 565

然而,对于 postgres,connection.select_value 总是返回一个字符串:

However, with postgres, connection.select_value always returns a string:

> ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM errors")
=> "1"
> ActiveRecord::Base.connection.select_value("SELECT id FROM errors")
=> "1"
> ActiveRecord::Base.connection.select_value("SELECT source FROM errors limit 1")
=> "webapp"

这破坏了一些单元测试,虽然这些是可以修复的,但我确信我们还有其他代码依赖于这些返回值.有没有办法在使用 postgres 时从 connection.select_value 获取正确类型的返回值?

This broke a few unit tests, and while those are fixable, I'm certain we have other code relying on these return values. Is there a way to get properly-typed return values from connection.select_value when using postgres?

推荐答案

简短的回答是否定的.pg"驱动程序有意在本机libpq"驱动程序之上提供尽可能薄的层.它不进行类型转换,因为这是更高级别的库的责任,这些库对将使用结果的域有一些了解.这个决定的理由记录在在PostgreSQL Wiki上,我很乐意在邮件列表中在邮件列表上与您进一步讨论.

The short answer is no. The 'pg' driver intentionally provides as thin a layer as possible on top of the native 'libpq' driver. It doesn't do typecasting, as that's the responsibility of higher-level libraries that have some insight into the domain in which the results will be used. The rationale for this decision is documented on the PostgreSQL Wiki, and I'd be happy to discuss it with you further on the mailing list.

相关文章