Class: LazyRecords::SqlRecords

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

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ SqlRecords

Returns a new instance of SqlRecords.



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

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

Instance Method Details

#add(definition, records) ⇒ Object

Raises:

  • (UnsupportedTypeException.new)


10
11
12
13
14
15
16
17
18
# File 'lib/sql_records.rb', line 10

def add(definition, records)
  raise(UnsupportedTypeException.new, "records must be of type: #{Sequence}<#{Record}> but was: #{records.class}") unless records.is_a?(Sequences::Sequence)
  excludes = definition.add_exclusions.get_or_else(empty).map(&:name)
  records.each do |r|
    data = r.get_hash.reject { |k, v| excludes.contains?(k) }
    sql = 'insert into ' + definition.name.to_s + " (#{data.keys.join(',')}) values (#{data.values.map(&:inspect).join(',')})"
    @c.query(sql)
  end
end

#get(definition, selection = nil) ⇒ Object



20
21
22
23
24
# File 'lib/sql_records.rb', line 20

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

#inner_join(def1, def2, keyword_map) ⇒ Object



37
38
39
40
# File 'lib/sql_records.rb', line 37

def inner_join(def1, def2, keyword_map)
  sql = 'select ' + process_columns(def1, def2) + ' from ' + def1.name.to_s + ' inner join ' + def2.name.to_s + ' on ' + process_keywords(keyword_map, def1, def2)
  sql_query(sql)
end

#remove(definition, selection = nil) ⇒ Object



32
33
34
35
# File 'lib/sql_records.rb', line 32

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

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



26
27
28
29
30
# File 'lib/sql_records.rb', line 26

def set(definition, selection, *updates)
  pending_fields = Maps.merge(sequence(updates).in_pairs.map { |e| {e.key.name.to_sym => e.value} })
  sql = 'update ' + definition.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



42
43
44
# File 'lib/sql_records.rb', line 42

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