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 中的字符串
基础教程推荐
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
