Class: Tina4::DocStore::Cursor

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/tina4/docstore.rb

Overview

Lazy result cursor. Builds and runs SQL only when iterated.

Instance Method Summary collapse

Constructor Details

#initialize(collection, where, params, projection = nil) ⇒ Cursor

Returns a new instance of Cursor.



395
396
397
398
399
400
401
402
403
# File 'lib/tina4/docstore.rb', line 395

def initialize(collection, where, params, projection = nil)
  @collection = collection
  @where = where
  @params = params
  @projection = projection
  @sort = []
  @limit = nil
  @skip = 0
end

Instance Method Details

#build_sqlObject



424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/tina4/docstore.rb', line 424

def build_sql
  sql = "SELECT doc FROM #{@collection.quoted_name} WHERE #{@where}"
  unless @sort.empty?
    order = @sort.map { |k, d| "#{DocStore.extract(k)} #{d.to_i.negative? ? 'DESC' : 'ASC'}" }.join(", ")
    sql += " ORDER BY #{order}"
  end
  if @limit
    sql += " LIMIT #{@limit.to_i}"
    sql += " OFFSET #{@skip.to_i}" if @skip.positive?
  elsif @skip.positive?
    sql += " LIMIT -1 OFFSET #{@skip.to_i}"
  end
  sql
end

#eachObject



439
440
441
442
443
444
445
446
# File 'lib/tina4/docstore.rb', line 439

def each
  return enum_for(:each) unless block_given?

  @collection.connection.execute(build_sql, @params).each do |row|
    doc_text = row.is_a?(Hash) ? (row["doc"] || row[:doc] || row.values.first) : row.first
    yield @collection.load_doc(doc_text, @projection)
  end
end

#limit(num) ⇒ Object



414
415
416
417
# File 'lib/tina4/docstore.rb', line 414

def limit(num)
  @limit = num.to_i
  self
end

#skip(num) ⇒ Object



419
420
421
422
# File 'lib/tina4/docstore.rb', line 419

def skip(num)
  @skip = num.to_i
  self
end

#sort(key_or_list, direction = 1) ⇒ Object



405
406
407
408
409
410
411
412
# File 'lib/tina4/docstore.rb', line 405

def sort(key_or_list, direction = 1)
  if key_or_list.is_a?(String) || key_or_list.is_a?(Symbol)
    @sort << [key_or_list.to_s, direction]
  else
    key_or_list.each { |k, d| @sort << [k.to_s, d] }
  end
  self
end

#to_aObject Also known as: to_list



448
449
450
451
452
# File 'lib/tina4/docstore.rb', line 448

def to_a
  out = []
  each { |doc| out << doc }
  out
end