views:

69

answers:

2

When we use ActiveRecord, we can use:

User.find(:first, :conditions=>["name=?", name])

It looks like ActiveRecord are using 'prepared statement', but after looking into the code, I found ActiveRecord just use String.dup and connection.quote() to adjust the content to build a sql, not like Java.

So, there is no real prepared statment in raiils? And why rails doesn't provide it?

+3  A: 

If by prepared statement you mean a piece of SQL that is held in a compiled form for more efficient execution, then you're correct: it's not something implemented in Rails. There are several reasons for this:

  1. Rails is the web framework - it doesn't know or care about databases. By default, Rails uses
    • ActiveRecord for object-relational mapping. You can change this if you want to - it doesn't have to be a RDBMS even.
    • ActiveRecord doesn't know about specific database platforms. For that it relies on "adapters", which translate AR's requirements into platform-specific SQL.
    • Some RDBMSs that have AR adapters support prepared statements (or equivalent) but others don't.
Mike Woodhouse
Interesting. Where would I find out which adapters support prepared statements?
FrustratedWithFormsDesigner
I suggest going to the source; there are only 3 AR adapters (mysql, postgresql and sqlite): http://github.com/rails/rails/tree/1c11437a32a973fa9b521c32caa7256f9772acd7/activerecord/lib/active_record/connection_adapters
egarcia
@egarcia - Not at all! I use Oracle in production and have used SQL Server in the past. Both have AR adapters, they just weren't written within the Rails core setup, which is kinda the point. Every mainstream RDBMS is supported by someone (even Sybase) and there are heaps of NoSQL options too. Google "Activerecord adapter" to get a taste of the range available - it's huge.
Mike Woodhouse
@FrustratedWithFormsDesigner - I fear I may have been unclear: AR doesn't explicitly support prepared statements at all. Where a DB platform implements them, you may be able to access the functionality via ActiveRecord::Base#execute or similar. Of course, you could always fork the adapter and add support yourself...
Mike Woodhouse
@Mike Woodhouse: I meant there were 3 on the link I put there. Sorry if that wasn't clear.
egarcia
+2  A: 

In many (most?) ways, a DB View is a prepared statement. And it is easy to use views with ActiveRecord. Just declare the view in your DB (I use rake tasks) and then access it via ActiveRecord.

Works great for read-only access to complicated SQL. Saves the DB from many of the steps required to parse/compute SQL.

Larry K
@Larry, thanks. I get it now.
Freewind