Class: SQLite::Query

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db) ⇒ Query

Returns a new instance of Query.



19
20
21
# File 'lib/sqlite.rb', line 19

def initialize(db)
  @db = db
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



17
18
19
# File 'lib/sqlite.rb', line 17

def db
  @db
end

Instance Method Details

#exec(sql) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sqlite.rb', line 23

def exec(sql)
  stmt = @db.prepare(sql)
  
  return nil if stmt == nil

  recordset = Recordset.new()
  recordset.rows = 0

  # Iterate over result set
  while true
    row     = []
    ordinal = 0

    stmt.each do |name, value|        
      if recordset.rows == 0
        recordset.columns << name
        recordset.headers[name] = ordinal
        recordset.header_names[ordinal] = name
        recordset.header_indexes[name]  = ordinal
        recordset.types << stmt.columnType(ordinal)
        ordinal += 1
      else
        row << value
      end
    end

    recordset.data << row if recordset.rows > 0

    recordset.rows += 1

    if stmt.step() != SQLITE_ROW
      break
    end
  end

  # Subtract 1 for header
  recordset.rows -= 1

  return recordset
end