4

I am migrating a database from mysql to postgres. The migration itself was ok, following the postgres documentation.

Right now, I'm fixing our specific mysql queries.

In some point, we have now something like this:

select(%(
  SUM(CASE WHEN income THEN value ELSE 0 END) AS rents,
  SUM(CASE WHEN not income THEN value ELSE 0 END) AS expenses
))

In mysql, it was a sum(if(incomes, value, 0)) etc, and it was working as expected.

With PG, it returns a string instead of a numeric.

I already checked the database and the data type is correct.

What can I do, besides cast to_d or to_f?


EDIT: the complete query:

SELECT 
 SUM(CASE WHEN income THEN value ELSE 0 END) AS rents,
 SUM(CASE WHEN not income THEN value ELSE 0 END) AS expenses
 FROM "transactions"
 WHERE "transactions"."type" IN ('Transaction')
 AND "transactions"."user_id" = 1
 AND "transactions"."paid" = 't'
 AND (transactions.date between '2013-09-01' and '2013-09-30')
 LIMIT 1
caarlos0
  • 20,020
  • 27
  • 85
  • 160

1 Answers1

3

As far as I know, using .to_f, .to_i or whatever is the answer - the Rails PostGres adapter seems adamant that everything is a String unless it's an ActiveRecord model.

See: connection.select_value only returns strings in postgres with pg gem

I don't particularly approve of this, but it is, as the saying goes, 'working as intended'.

Community
  • 1
  • 1
MrTheWalrus
  • 9,670
  • 2
  • 42
  • 66