Class: Knj::Db::Query_buffer

Inherits:
Object
  • Object
show all
Defined in:
lib/knj/knjdb/query_buffer.rb

Overview

This class buffers a lot of queries and flushes them out via transactions.

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Query_buffer

Constructor. Takes arguments to be used and a block.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/knj/knjdb/query_buffer.rb', line 4

def initialize(args)
  @args = args
  @queries = []
  @inserts = {}
  @queries_count = 0
  @debug = @args[:debug]
  @lock = Mutex.new
  
  STDOUT.puts "Query buffer started." if @debug
  
  begin
    yield(self)
  ensure
    self.flush
  end
end

Instance Method Details

#delete(table, where) ⇒ Object

Delete as on a normal Knj::Db.

Examples

db.q_buffer do |buffer|

buffer.delete(:users, {:id => 5})

end



38
39
40
41
42
# File 'lib/knj/knjdb/query_buffer.rb', line 38

def delete(table, where)
  STDOUT.puts "Delete called on table #{table} with arguments: '#{where}'." if @debug
  self.query(@args[:db].delete(table, where, :return_sql => true))
  return nil
end

#flushObject

Flushes all queries out in a transaction. This will automatically be called for every 1000 queries.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/knj/knjdb/query_buffer.rb', line 61

def flush
  return nil if @queries_count <= 0
  
  @lock.synchronize do
    @args[:db].transaction do
      @queries.shift(1000).each do |str|
        STDOUT.print "Executing via buffer: #{str}\n" if @debug
        @args[:db].q(str)
      end
      
      @inserts.each do |table, datas_arr|
        while !datas_arr.empty?
          datas_chunk_arr = datas_arr.shift(1000)
          @args[:db].insert_multi(table, datas_chunk_arr)
        end
      end
    end
    
    @inserts.clear
    @queries_count = 0
  end
  
  return nil
end

#insert(table, data) ⇒ Object

Plans to inset a hash into a table. It will only be inserted when flush is called.

Examples

db.q_buffer do |buffer|

buffer.insert(:users, {:name => "John Doe"})

end



49
50
51
52
53
54
55
56
57
58
# File 'lib/knj/knjdb/query_buffer.rb', line 49

def insert(table, data)
  @lock.synchronize do
    @inserts[table] = [] if !@inserts.key?(table)
    @inserts[table] << data
    @queries_count += 1
  end
  
  self.flush if @queries_count >= 1000
  return nil
end

#query(str) ⇒ Object

Adds a query to the buffer.



22
23
24
25
26
27
28
29
30
31
# File 'lib/knj/knjdb/query_buffer.rb', line 22

def query(str)
  @lock.synchronize do
    STDOUT.print "Adding to buffer: #{str}\n" if @debug
    @queries << str
    @queries_count += 1
  end
  
  self.flush if @queries_count >= 1000
  return nil
end