Skip to content

Commit

Permalink
cheat: add ambition
Browse files Browse the repository at this point in the history
  • Loading branch information
defunkt committed Aug 28, 2007
1 parent cb008e5 commit ce2edc4
Show file tree
Hide file tree
Showing 23 changed files with 1,107 additions and 12 deletions.
18 changes: 18 additions & 0 deletions lib/ambition/LICENSE
@@ -0,0 +1,18 @@
Copyright (c) 2007 Chris Wanstrath

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
143 changes: 143 additions & 0 deletions lib/ambition/README
@@ -0,0 +1,143 @@
== Ambitious SQL

A simple experiment and even simpler ActiveRecord library.

I could tell you all about how awesome the internals are, or
how fun it was to write, or how it'll make you rich and famous,
but instead I'm just going to show you some examples.

== Examples

Basically, you write your SQL in Ruby. No, not in Ruby. As Ruby.

User.select { |u| u.city == 'San Francisco' }.each do |user|
puts user.name
end

And that's it.

The key is the +each+ method. You build up a +Query+ using +select+, +detect+,
+limit+, and +sort_by+, then call +each+ on it. This'll run the query and enumerate
through the results.

Our +Query+ object has two useful methods: +to_sql+ and +to_hash+. With these, we can
check out what exactly we're building.

See, +to_sql+:
>> User.select { |m| m.name == 'jon' }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon'"

See, +to_hash+:
>> User.select { |m| m.name == 'jon' }.to_hash
=> {:conditions=>"users.`name` = 'jon'"}

== Limitations

You can use variables, but any more complex Ruby (right now) won't work
inside your blocks. Just do it outside the block and assign it to a variable, okay?

Instead of:
User.select { |m| m.date == 2.days.ago }

Just do:
date = 2.days.ago
User.select { |m| m.date == date }

Instance variables and globals work, too.

== Equality -- select { |u| u.field == 'bob' }

>> User.select { |m| m.name == 'jon' }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon'"

>> User.select { |m| m.name != 'jon' }.to_sql
=> "SELECT * FROM users WHERE users.`name` <> 'jon'"

>> User.select { |m| m.name == 'jon' && m.age == 21 }.to_sql
=> "SELECT * FROM users WHERE (users.`name` = 'jon' AND users.`age` = 21)"

>> User.select { |m| m.name == 'jon' || m.age == 21 }.to_sql
=> "SELECT * FROM users WHERE (users.`name` = 'jon' OR users.`age` = 21)"

>> User.select { |m| m.name == 'jon' || m.age == 21 && m.password == 'pass' }.to_sql
=> "SELECT * FROM users WHERE (users.`name` = 'jon' OR (users.`age` = 21 AND users.`password` = 'pass'))"

>> User.select { |m| (m.name == 'jon' || m.name == 'rick') && m.age == 21 }.to_sql
=> "SELECT * FROM users WHERE ((users.`name` = 'jon' OR users.`name` = 'rick') AND users.`age` = 21)"

== Comparisons -- select { |u| u.age > 21 }

>> User.select { |m| m.age > 21 }.to_sql
=> "SELECT * FROM users WHERE users.`age` > 21"

>> User.select { |m| m.age < 21 }.to_sql
=> "SELECT * FROM users WHERE users.`age` < 21"

>> sql = User.select { |m| [1, 2, 3, 4].include? m.id }.to_sql
=> "SELECT * FROM users WHERE users.`id` IN (1, 2, 3, 4)"

== LIKE and REGEXP (RLIKE) -- select { |m| m.name =~ 'chris' }

>> User.select { |m| m.name =~ 'chris' }.to_sql
=> "SELECT * FROM users WHERE users.`name` LIKE 'chris'"

>> User.select { |m| m.name =~ 'chri%' }.to_sql
=> "SELECT * FROM users WHERE users.`name` LIKE 'chri%'"

>> User.select { |m| m.name !~ 'chris' }.to_sql
=> "SELECT * FROM users WHERE users.`name` NOT LIKE 'chris'"

>> User.select { |m| !(m.name =~ 'chris') }.to_sql
=> "SELECT * FROM users WHERE users.`name` NOT LIKE 'chris'"

>> User.select { |m| m.name =~ /chris/ }.to_sql
=> "SELECT * FROM users WHERE users.`name` REGEXP 'chris'"

== #detect

>> User.detect { |m| m.name == 'chris' }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'chris' LIMIT 1"

== LIMITs -- first, first(x), [offset, limit]

>> User.select { |m| m.name == 'jon' }.first.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' LIMIT 1"

>> User.select { |m| m.name == 'jon' }.first(5).to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' LIMIT 5"

>> User.select { |m| m.name == 'jon' }[10, 20].to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' LIMIT 10, 20"

== ORDER -- sort_by { |u| u.field }

>> User.select { |m| m.name == 'jon' }.sort_by { |m| m.name }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY name"

>> User.select { |m| m.name == 'jon' }.sort_by { |m| [ m.name, m.age ] }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY name, age"

>> User.select { |m| m.name == 'jon' }.sort_by { |m| [ m.name, -m.age ] }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY name, age DESC"

>> User.select { |m| m.name == 'jon' }.sort_by { |m| [ -m.name, -m.age ] }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY name DESC, age DESC"

>> User.select { |m| m.name == 'jon' }.sort_by { |m| -m.age }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY age DESC"

>> User.select { |m| m.name == 'jon' }.sort_by { rand }.to_sql
=> "SELECT * FROM users WHERE users.`name` = 'jon' ORDER BY RAND()"

== COUNT -- select { |u| u.name == 'jon' }.size

>> User.select { |m| m.name == 'jon' }.size
=> 21

== SELECT * FROM bugs

Found a bug? Sweet. Add it at the Lighthouse: http://err.lighthouseapp.com/projects/466-plugins/tickets/new

Feature requests are welcome. Ideas for cross-table stuff and joins, especially.

* Chris Wanstrath [ chris@ozmm.org ]
23 changes: 23 additions & 0 deletions lib/ambition/Rakefile
@@ -0,0 +1,23 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'

desc 'Default: run unit tests.'
task :default => :test

desc 'Test it!'
Rake::TestTask.new(:test) do |t|
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end

desc 'Generate RDoc documentation'
Rake::RDocTask.new(:rdoc) do |rdoc|
files = ['README', 'LICENSE', 'lib/**/*.rb']
rdoc.rdoc_files.add(files)
rdoc.main = "README" # page to start on
rdoc.title = "ambition"
rdoc.template = File.exists?(t="/Users/chris/ruby/projects/err/rock/template.rb") ? t : "/var/www/rock/template.rb"
rdoc.rdoc_dir = 'doc' # rdoc output folder
rdoc.options << '--inline-source'
end
1 change: 1 addition & 0 deletions lib/ambition/init.rb
@@ -0,0 +1 @@
require 'ambition'
21 changes: 21 additions & 0 deletions lib/ambition/lib/ambition.rb
@@ -0,0 +1,21 @@
require 'rubygems'
require 'proc_to_ruby'
require 'ambition/processor'
require 'ambition/query'
require 'ambition/where'
require 'ambition/order'
require 'ambition/limit'
require 'ambition/count'
require 'ambition/enumerable'

module Ambition
include Where, Order, Limit, Enumerable, Count

attr_accessor :query_context

def query_context
@query_context || Query.new(self)
end
end

ActiveRecord::Base.extend Ambition
8 changes: 8 additions & 0 deletions lib/ambition/lib/ambition/count.rb
@@ -0,0 +1,8 @@
module Ambition
module Count
def size
count(query_context.to_hash)
end
alias_method :length, :size
end
end
9 changes: 9 additions & 0 deletions lib/ambition/lib/ambition/enumerable.rb
@@ -0,0 +1,9 @@
module Ambition
module Enumerable
include ::Enumerable

def each(&block)
find(:all, query_context.to_hash).each(&block)
end
end
end
38 changes: 38 additions & 0 deletions lib/ambition/lib/ambition/limit.rb
@@ -0,0 +1,38 @@
module Ambition
module Limit
def first(limit = 1, offset = nil)
query_context.add LimitProcessor.new(limit, offset)
find(limit == 1 ? :first : :all, query_context.to_hash)
end

def [](offset, limit)
first(offset, limit)
end
end

class LimitProcessor
def initialize(*args)
@args = args
end

def prefix
'LIMIT '
end

def key
:limit
end

def join_string
', '
end

def to_sql
"LIMIT #{to_s}"
end

def to_s
@args.compact * ', '
end
end
end
54 changes: 54 additions & 0 deletions lib/ambition/lib/ambition/order.rb
@@ -0,0 +1,54 @@
module Ambition
module Order
def sort_by(&block)
query_context.add OrderProcessor.new(table_name, block)
end
end

class OrderProcessor < Processor
def initialize(table_name, block)
super()
@prefix = 'ORDER BY '
@join_string = ', '
@receiver = nil
@table_name = table_name
@block = block
@key = :order
end

##
# Sexp Processing Methods
def process_call(exp)
receiver, method, other = *exp
exp.clear

translation(receiver, method, other)
end

def process_vcall(exp)
if (method = exp.shift) == :rand
'RAND()'
else
raise "Not implemented: :vcall for #{method}"
end
end

def process_masgn(exp)
exp.clear
''
end

##
# Helpers!
def translation(receiver, method, other)
case method
when :-@
"#{process(receiver)} DESC"
when :__send__
"#{@table_name}.#{eval('to_s', @block)}"
else
"#{@table_name}.#{method}"
end
end
end
end
58 changes: 58 additions & 0 deletions lib/ambition/lib/ambition/processor.rb
@@ -0,0 +1,58 @@
require 'active_record/connection_adapters/abstract/quoting'

module Ambition
class Processor < SexpProcessor
include ActiveRecord::ConnectionAdapters::Quoting

attr_reader :key, :join_string, :prefix

def initialize
super()
@strict = false
@expected = String
@auto_shift_type = true
@warn_on_default = false
@default_method = :process_error
end

##
# Processing methods
def process_error(exp)
raise "Missing process method for sexp: #{exp.inspect}"
end

def process_proc(exp)
receiver, body = process(exp.shift), exp.shift
return process(body)
end

def process_dasgn_curr(exp)
@receiver = exp.shift
return @receiver.to_s
end

def process_array(exp)
arrayed = exp.map { |m| process(m) }
exp.clear
return arrayed.join(', ')
end

##
# Helper methods
def to_sql
@prefix.to_s + to_s
end

def to_s
process(@block.to_sexp).squeeze(' ')
end

def sanitize(value)
case value.to_s
when 'true' then '1'
when 'false' then '0'
else ActiveRecord::Base.connection.quote(value) rescue quote(value)
end
end
end
end

0 comments on commit ce2edc4

Please sign in to comment.