2 ms·
I've also managed to obtain extremely good performance from this approach. It's good in areas where for one reason or another you need to dump several MB of JS
by semiquaver 9y ago
I've also managed to obtain extremely good performance from this approach. It's good in areas where for one reason or another you need to dump several MB of JSON, which languanges like ruby simply can't do performantly but postgres definitely can. Here's an extremely quick and dirty example:
def serialize_in_postgres(relation, columns)
ActiveRecord::Base.connection.select_rows(
<<-SQL
select array_to_json(array_agg(row_to_json(result))) from
( #{relation.select(columns).to_sql} ) result
SQL
)
end
puts serialize_in_postgres(SomeArModel.limit(2), ['id', '"created_at"::date'])
# => [{"id":12345,"created_at":"2017-06-11"},{"id":23456,"created_at":"2017-06-11"}]
Unlike the parent, I would not recommend doing this everywhere, or even most places, but it is a very useful tool to have.