connection.select_value only returns strings in postgres with pg gem(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.
这篇关于connection.select_value 只返回带有 pg gem 的 postgres 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:connection.select_value 只返回带有 pg gem 的 postgres 中的字符串


基础教程推荐
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01