Class: Factbase::Query

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

Overview

Query.

This is an internal class, it is not supposed to be instantiated directly. It is created by the query() method of the Factbase class.

It is NOT thread-safe!

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(maps, mutex, query) ⇒ Query

Constructor.

Parameters:

  • maps (Array<Fact>)

    Array of facts to start with

  • mutex (Mutex)

    Mutex to sync all modifications to the maps

  • query (String)

    The query as a string



44
45
46
47
48
# File 'lib/factbase/query.rb', line 44

def initialize(maps, mutex, query)
  @maps = maps
  @mutex = mutex
  @query = query
end

Instance Method Details

#delete!Integer

Delete all facts that match the query.

Returns:

  • (Integer)

    Total number of facts deleted



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/factbase/query.rb', line 90

def delete!
  term = Factbase::Syntax.new(@query).to_term
  deleted = 0
  @mutex.synchronize do
    @maps.delete_if do |m|
      f = Factbase::Fact.new(@mutex, m)
      if term.evaluate(f, @maps)
        deleted += 1
        true
      else
        false
      end
    end
  end
  deleted
end

#each(params = {}) {|Fact| ... } ⇒ Integer

Iterate facts one by one.

Parameters:

  • params (Hash) (defaults to: {})

    Optional params accessible in the query via the “$” symbol

Yields:

  • (Fact)

    Facts one-by-one

Returns:

  • (Integer)

    Total number of facts yielded



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/factbase/query.rb', line 54

def each(params = {})
  return to_enum(__method__, params) unless block_given?
  term = Factbase::Syntax.new(@query).to_term
  yielded = 0
  @maps.each do |m|
    extras = {}
    f = Factbase::Fact.new(@mutex, m)
    params = params.transform_keys(&:to_s) if params.is_a?(Hash)
    f = Factbase::Tee.new(f, params)
    a = Factbase::Accum.new(f, extras, false)
    r = term.evaluate(a, @maps)
    unless r.is_a?(TrueClass) || r.is_a?(FalseClass)
      raise "Unexpected evaluation result (#{r.class}), must be Boolean at #{@query}"
    end
    next unless r
    yield Factbase::Accum.new(f, extras, true)
    yielded += 1
  end
  yielded
end

#one(params = {}) ⇒ Object

Read a single value.

Parameters:

  • params (Hash) (defaults to: {})

    Optional params accessible in the query via the “$” symbol

Returns:

  • The value evaluated



78
79
80
81
82
83
84
85
86
# File 'lib/factbase/query.rb', line 78

def one(params = {})
  term = Factbase::Syntax.new(@query).to_term
  params = params.transform_keys(&:to_s) if params.is_a?(Hash)
  r = term.evaluate(Factbase::Tee.new(nil, params), @maps)
  unless %w[String Integer Float Time Array NilClass].include?(r.class.to_s)
    raise "Incorrect type #{r.class} returned by #{@query}"
  end
  r
end