Skip to content

Commit

Permalink
FIXME in MiniSQL#tables
Browse files Browse the repository at this point in the history
  • Loading branch information
tianyicui committed Oct 25, 2010
1 parent 33b4933 commit d7eea88
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/minisql.rb
Expand Up @@ -37,12 +37,20 @@ def drop_index name

# Idea:
#
# select('*').from(:table).where do
# column[:co1] = ...
# rows = select['*'].from(:table)
#
# or
#
# rows = select['*'].from(:table).where do
# column[:co1] == ...
# column[:co2] < ...
# column[:co3] > ...
# column[:co3] >= ...
# end
def select columns
#
# rows.each ... # no sql are executed until here
def select
require 'selector'
Selector.new self
end

def insert_into
Expand All @@ -56,9 +64,8 @@ def execute command, &block
end

def tables
# FIXME: use self#select
result = []
execute 'select name from sqlite_master' do |row|
select[:name].from(:sqlite_master) do |row|
result << row[0].to_sym
end
result
Expand Down
119 changes: 119 additions & 0 deletions lib/selector.rb
@@ -0,0 +1,119 @@
class Selector

def initialize db
@db = db
@columns = []
@from = nil
@where = nil
@result_set = nil
end

def [] *columns
raise 'already defined columns' unless @columns.empty?
@columns = columns
self
end

def from table, &block
raise 'more than one from clause' unless @from.nil?
@from = table
block_given? ? self.each(&block) : self
end

def where &block
raise 'more than one where clause' unless @where.nil?
@where = Where.new
@where.instance_eval(block)
self
end

def dump
sql = 'SELECT ' + @columns.join(', ') + " FROM #{@from}"
sql += ' ' + @where.dump unless @where.nil?
sql += ' ;'
sql
end

def each &block
@result_set = @db.execute dump if @result_set.nil?
@result_set.each &block
end

include Enumerable

class Where

def initialize
@columns = []
end

def column
col = Column.new
@columns << col
col
end

def dump
raise 'empty where clause' if @columns.empty?
'WHERE ' + @columns.map{|c| c.dump }.join(' and ')
end

class Column

def initialize
@name = nil
@op = nil # can be '=', '<>' '<', '>', '<=', '>='
@rval = nil
@result_set = nil
end

def [] name
raise 'named again' unless @name.nil?
@name=name
self
end

def == rval
cmp '=', rval
end

def != rval
cmp '<>', rval
end

def < rval
cmp '<', rval
end

def > rval
cmp '>', rval
end

def <= rval
cmp '<=', rval
end

def >= rval
cmp '>=', rval
end

def dump
raise 'column has no name' if @name.nil?
raise "column #{@name} has no comparison operator" if @op.nil?
"#{@name} #{@op} #{@rval}"
end

protected

def cmp op, rval
raise "more than one comparison operator detected, already have #{@op}" unless @op.nil?
@op=op
@rval=rval
self
end

end

end

end

0 comments on commit d7eea88

Please sign in to comment.