Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

mysql - connection.select_value only returns strings in postgres with pg gem

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

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

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"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...