Bugs: Browse | Submit New | Admin

[#9448] change in AR's SQL breaks cached_model

Date:
2007-03-22 00:33
Priority:
3
Submitted By:
Jason LaPier (jlapier)
Assigned To:
Eric Hodel (drbrain)
Category:
cached_model
State:
Open
Summary:
change in AR's SQL breaks cached_model

Detailed description
looks like in active_record 1.15.3 they've changed the SELECT statement slightly again, so now it uses those backquote-things
around the primary key.

Instead of SELECT * FROM things WHERE (things.id = 4) it now looks like:
SELECT * FROM things WHERE (things.`id` = 4). 

Using's topfunky's fix for taking out the LIMIT, this change to line 49 in lib/cached_model.rb worked for me:
return super unless args.first =~ /^SELECT \* FROM #{table_name} WHERE \(#{table_name}\.(`)?#{primary_key}(`)? = '?(\d+)'?\)(
+LIMIT 1)?/

(I tried to make it backwards compatible by putting the ` in as (`)?  )

- Jason L.

Add A Comment: Notepad

Please login


Followup

Message
Date: 2007-11-14 10:10
Sender: Maarten de Jong

We have the same problem here when using sql server as it uses
square brackets.

This should work for everyone I guess: 

return super unless args.first =~ 
/^SELECT \* FROM #{table_name} WHERE
\(#{table_name}\.`?[?#{primary_key}`?]? = ’?'?(\d+)'?’?\)(+LIMIT
1)?/

One thing that I don't understand: is the find_by_sql method
really the best place to check for this? CachedModel waits for
the sql to be generated and then it uses the cache instead of
the DB to get the data. Seems to me like a bit of a hacky way
to detect if a record is retrieved by the ID.
Date: 2007-09-14 15:44
Sender: David Welton

Thinking about this approach some more... it's kind of gross
trying to get the id like that, but this makes it a little bit
nicer:

    return super unless args.first =~ /^SELECT.*FROM
#{table_name}.*#{connection.quote_column_name(primary_key)} =
'?(\d+)'?\)/

I think all you really need is the bit about the primary key
being equal to a number, and the proper quoting method.
Date: 2007-09-14 14:37
Sender: David Welton

This approach is also problematic because it breaks for Postgres,
as well:

Book Load (0.000931)  SELECT id, title FROM books WHERE
(books."id" = 1)
Date: 2007-04-06 04:03
Sender: Jason LaPier

I just realized the parenths around the backticks (`) screw
up the match count, so you also have to change 1 to a 3 in
the next line:

id = $3.to_i

Attached Files:

Name Description Download
No Files Currently Attached

Changes:

No Changes Have Been Made to This Item