3 ms·
"I just write raw SQL that serves JSON directly back." I'm surprised and intrigued by this. How do you get your query to return JSON? What percentage of your c
by ajmurmann 9y ago
"I just write raw SQL that serves JSON directly back."
I'm surprised and intrigued by this. How do you get your query to return JSON? What percentage of your code actually works like that? How business logic heavy is your SQL? This is super interesting!
- weberc2 9y agoPostgres and probably others support JSON these days.
- semiquaver 9y agoI'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.