Hacker News new | comments | show | ask | jobs | submit login

"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!






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.

Postgres and probably others support JSON these days.



Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: