Guest User

Untitled

a guest
May 27th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. # I run a Rails site that needs to work across databases. My code is littered
  2. # with conditionals to switch between PostgreSQL and SQLite. This is quite
  3. # annoying. I was working on a query today that needs to extract year-month ->
  4. # total price from the database. I had a nice SQL query that works in
  5. # PostgreSQL but doesn't work in SQLite. Probably doesn't work in MySQL or MS
  6. # SQL Server because, you know, the SQL standard is a completely fucking
  7. # useless standard as it doesn't actually enable one to write a portable
  8. # query.
  9.  
  10. # Here is the Ruby:
  11.  
  12. Job.find_all_by_supplier_id(supplier.id).
  13. group_by {|i| i.date_printed.to_s[0..6] }.
  14. map {|k, v| { :date => k,
  15. :price => v.inject(0) {|result, i| result + i.price }.to_f
  16. } unless k.nil? || k == "" }.
  17. compact.to_a.sort_by {|i| i[0] }
  18.  
  19. # Now, here's the SQL I am replacing:
  20.  
  21. %q{
  22. SELECT to_char(date_trunc('month', date_printed), 'YYYY-mm')
  23. as date, SUM(price) as price
  24. FROM jobs
  25. WHERE supplier_id = 4
  26. GROUP BY date
  27. ORDER BY date;
  28. }
  29.  
  30. # The great thing about Ruby is how much more *readable* it is, amirite?
  31. # And, gee, it's not like my database might optimize the SUM() call or the
  32. # grouping or whatever and create indexes. Like a fucking RDBMS ought to.
  33.  
  34. # Sigh. It really would be lovely if SQL were to magically become a useful,
  35. # portable *real* standard.
  36.  
  37. # Cue the .NET crowd with all their fancy LINQ. I'm jealous.
  38.  
  39. # Sigh again.
Add Comment
Please, Sign In to add comment