Class: LazyRecords::SqlVirtualRecords

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_virtual_records.rb

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ SqlVirtualRecords

Returns a new instance of SqlVirtualRecords.



5
6
7
8
# File 'lib/sql_virtual_records.rb', line 5

def initialize(connection)
  @c = connection
  @predicate_to_sql = PredicateToSql.new
end

Instance Method Details

#add(table_name, records) ⇒ Object



10
11
12
13
14
15
# File 'lib/sql_virtual_records.rb', line 10

def add(table_name, records)
  records.each do |r|
    sql = 'insert into ' + table_name.to_s + " (#{r.get_hash.keys.to_a.join(',')}) values (#{r.get_hash.values.map(&:inspect).to_a.join(',')})"
    @c.query(sql)
  end
end

#get(table_name, selection = nil) ⇒ Object



17
18
19
20
21
# File 'lib/sql_virtual_records.rb', line 17

def get(table_name, selection=nil)
  sql = option(selection).is_some? ? 'select * from ' + table_name.to_s + ' where ' + @predicate_to_sql.convert(selection) :
        'select * from ' + table_name.to_s
  sequence(@c.query(sql).map { |r| Record.new(r) })
end

#remove(table_name, selection = nil) ⇒ Object



29
30
31
32
# File 'lib/sql_virtual_records.rb', line 29

def remove(table_name, selection=nil)
  sql = option(selection).is_some? ? 'delete from ' + table_name.to_s + ' where ' + @predicate_to_sql.convert(selection) : 'delete from ' + table_name.to_s
  sequence(@c.query(sql))
end

#set(table_name, selection, *updates) ⇒ Object



23
24
25
26
27
# File 'lib/sql_virtual_records.rb', line 23

def set(table_name, selection, *updates)
  pending_fields = Maps.merge(sequence(updates).in_pairs.map { |e| {e.key => e.value} })
  sql = 'update ' + table_name.to_s + ' set ' + pending_fields.map { |k, v| "#{k}='#{v}'" }.join(',') + ' where ' + @predicate_to_sql.convert(selection)
  sequence(@c.query(sql))
end

#sql_query(sql) ⇒ Object



34
35
36
# File 'lib/sql_virtual_records.rb', line 34

def sql_query(sql)
  sequence(@c.query(sql).map { |r| Record.new(r) })
end