News for hackers. Stuff that matters.
Re:Frameworks Don't Make Much Sense by pmontra on Friday March 11, 2016 @04:21AM (#11265583)
Yes, ORMs let newbies code queries safely.

However you can deal with SQL safely bypassing the ORM if you compose the queries correctly. An example with Ruby and the pg driver for PostgreSQL:

    db.prepare("select_title", "select title from posts where author = $1::text")
    ...
    db.exec_prepared("select_title", [ author ]) do |result|
      ...
    end
I concede that it's more prone to unsafe coding than Post.where(author: author).pluck(:title) Everybody in the team must resist the temptation to ever write a db.exec("select title from posts where author = #{author}")

What I do is using the ORM all the times, except for complex queries that would be a nightmare to code with ActiveRecord/Arel and to understand when written in Ruby. In those case I use ActiveRecord's find_by_sql. It can be protected by SQL injections easily. I quote the documentation:

    Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
Again, it has the same problem of having to enforce the discipline of passing the arguments in the right way but there are countless ways of making a project unsafe and the team must be trained to prevent unsafe coding practices. SQL is only one of them.

There are no comments on this comment yet.