Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created April 12, 2011 17:08
Show Gist options
  • Save tenderlove/915934 to your computer and use it in GitHub Desktop.
Save tenderlove/915934 to your computer and use it in GitHub Desktop.
An example using lolquery
###
# lolquery is an fresh new take on SQL DSLs. NEVER WRITE SQL AGAIN! Using
# amazing lolquery technology, you too will never have to write another SQL
# statement again!
#
# Check out this simple example of using lolquery. Bask in it's simplicity,
# it's expressiveness, but most importantly, it's lack of writing SQL!
#
# <3 <3 <3 <3 <3
require 'lolquery'
x = SELECT * FROM("users") .WHERE(:id => 10)
puts x # => SELECT * FROM "users" WHERE "users"."id" = 10
require 'rubygems'
require 'arel'
require 'the_fake_record' # stub out AR (stolen from arel tests)
class Select < Struct.new(:columns)
def self.* other
other.select = new(Arel.sql('*'))
other
end
end
class From < Struct.new(:table, :conditions)
def WHERE conditions
self.conditions = conditions
Where.new(self)
end
end
class Where < Struct.new(:from, :select)
def to_s
Arel::Table.engine = Arel::Sql::Engine.new(FakeRecord::Base.new)
table = Arel::Table.new from.table
table.project(select.columns).where(
from.conditions.map { |k,v| table[k].eq v }).to_sql
end
end
SELECT = Select
def FROM table
From.new table
end
module FakeRecord
class Column < Struct.new(:name, :type)
end
class Connection
attr_reader :tables
def initialize
@tables = %w{ users photos developers }
@columns = {
'users' => [
Column.new('id', :integer),
Column.new('name', :string),
Column.new('bool', :boolean),
Column.new('created_at', :date),
]
}
@primary_keys = {
'users' => 'id'
}
end
def primary_key name
@primary_keys[name.to_s]
end
def table_exists? name
@tables.include? name.to_s
end
def columns name, message = nil
@columns[name.to_s]
end
def quote_table_name name
"\"#{name.to_s}\""
end
def quote_column_name name
"\"#{name.to_s}\""
end
def quote thing, column = nil
if column && column.type == :integer
return 'NULL' if thing.nil?
return thing.to_i
end
case thing
when true
"'t'"
when false
"'f'"
when nil
'NULL'
when Numeric
thing
else
"'#{thing}'"
end
end
end
class ConnectionPool
class Spec < Struct.new(:config)
end
attr_reader :spec, :connection
def initialize
@spec = Spec.new(:adapter => 'america')
@connection = Connection.new
end
def with_connection
yield connection
end
end
class Base
attr_accessor :connection_pool
def initialize
@connection_pool = ConnectionPool.new
end
def connection
connection_pool.connection
end
end
end
@provideal
Copy link

Is there support for MongoDB, I mean... not writing NoSQL would be even better!

@tenderlove
Copy link
Author

@provideal Yes, use this gist and you can avoid writing SQL for your NoSQL database. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment