Class: Zermelo::Backends::Redis

Inherits:
Object
  • Object
show all
Includes:
Zermelo::Backend
Defined in:
lib/zermelo/backends/redis.rb

Instance Method Summary collapse

Methods included from Zermelo::Backend

#add, #clear, #delete, #escape_key_name, #get, #index_keys, #lock, #move, #purge, #safe_value, #set, #unescape_key_name

Constructor Details

#initializeRedis



15
16
17
18
# File 'lib/zermelo/backends/redis.rb', line 15

def initialize
  @transaction_redis = nil
  @changes = nil
end

Instance Method Details

#abort_transactionObject



134
135
136
137
138
139
140
# File 'lib/zermelo/backends/redis.rb', line 134

def abort_transaction
  return false if @transaction_redis.nil?
  @transaction_redis.discard
  @transaction_redis = nil
  @changes = []
  true
end

#begin_transactionObject



117
118
119
120
121
122
123
# File 'lib/zermelo/backends/redis.rb', line 117

def begin_transaction
  return false unless @transaction_redis.nil?
  @transaction_redis = Zermelo.redis
  @transaction_redis.multi
  @changes = []
  true
end

#commit_transactionObject



125
126
127
128
129
130
131
132
# File 'lib/zermelo/backends/redis.rb', line 125

def commit_transaction
  return false if @transaction_redis.nil?
  apply_changes(@changes)
  @transaction_redis.exec
  @transaction_redis = nil
  @changes = []
  true
end

#filter(ids_key, associated_class, callback_target_class = nil, callback_target_id = nil, callbacks = nil, sort_order = nil) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/zermelo/backends/redis.rb', line 39

def filter(ids_key, associated_class, callback_target_class = nil,
  callback_target_id = nil, callbacks = nil, sort_order = nil)

  Zermelo::Filters::Redis.new(self, ids_key, associated_class,
                              callback_target_class, callback_target_id,
                              callbacks, sort_order)
end

#get_multiple(*attr_keys) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/zermelo/backends/redis.rb', line 47

def get_multiple(*attr_keys)
  attr_keys.inject({}) do |memo, attr_key|
    redis_attr_key = key_to_backend_key(attr_key)

    class_key = attr_key.klass.send(:class_key)

    memo[class_key] ||= {}
    memo[class_key][attr_key.id] ||= {}
    memo[class_key][attr_key.id][attr_key.name.to_s] = if Zermelo::COLLECTION_TYPES.has_key?(attr_key.type)

      case attr_key.type
      when :list
        if attr_key.accessor.nil?
          Zermelo.redis.lrange(redis_attr_key, 0, -1)
        else
          # TODO
        end
      when :set
        if attr_key.accessor.nil?
          Set.new( Zermelo.redis.smembers(redis_attr_key) )
        else
          # TODO
        end
      when :hash
        if attr_key.accessor.nil?
          Zermelo.redis.hgetall(redis_attr_key)
        else
          # TODO
        end
      when :sorted_set
        if attr_key.accessor.nil?
          Zermelo::OrderedSet.new(Zermelo.redis.zrange(redis_attr_key, 0, -1))
        else
          # TODO
        end
      end

    else
      value = Zermelo.redis.hget(redis_attr_key, attr_key.name.to_s)

      if value.nil?
        nil
      else
        case attr_key.type
        when :string
          value.to_s
        when :integer
          value.to_i
        when :float
          value.to_f
        when :timestamp
          Time.at(value.to_f)
        when :boolean
          case value
          when TrueClass
            true
          when FalseClass
            false
          when String
            'true'.eql?(value.downcase)
          else
            nil
          end
        end
      end
    end
    memo
  end
end

#index_lookup(att, associated_class, type, idx_class, value, attr_type, temp_keys) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/zermelo/backends/redis.rb', line 157

def index_lookup(att, associated_class, type, idx_class, value,
  attr_type, temp_keys)

  if (idx_class == Zermelo::Associations::RangeIndex) && !value.is_a?(Zermelo::Filters::IndexRange)
    raise "Range index must be passed a range"
  end

  case value
  when Regexp
    raise "Can't query non-string values via regexp" unless :string.eql?(attr_type)

    idx_key = associated_class.send(:temp_key, type)
    temp_keys << idx_key
    idx_result = key_to_backend_key(idx_key)

    starts_with_string_re = /^string:/
    case idx_class.name
    when 'Zermelo::Associations::UniqueIndex'
      index_key = key_to_backend_key(Zermelo::Records::Key.new(
        :klass  => associated_class,
        :name   => "by_#{att}",
        :type   => :hash,
        :object => :index
      ))
      candidates = Zermelo.redis.hgetall(index_key)
      matching_ids = candidates.values_at(*candidates.keys.select {|k|
        (starts_with_string_re === k) &&
          (value === unescape_key_name(k.sub(starts_with_string_re, '')))
      })

      unless matching_ids.empty?
        case type
        when :set
          Zermelo.redis.sadd(idx_result, matching_ids)
        when :sorted_set
          Zermelo.redis.zadd(idx_result, matching_ids.map {|m| [1, m]})
        end
      end
    when 'Zermelo::Associations::Index'
      key_root = key_to_backend_key(Zermelo::Records::Key.new(
        :klass  => associated_class,
        :name   => "by_#{att}:string",
        :type   => :set,
        :object => :index
      ))

      key_pat = "#{key_root}:?*"

      matching_sets = if (Zermelo.redis_version.split('.') <=> ['2', '8', '0']) == 1
        # lock will be subsumed by outer lock if present -- required to
        # know that scan is getting consistent results
        associated_class.lock do
          Zermelo.redis.scan_each(:match => key_pat).to_a
        end
      else
        # SCAN is only supported in Redis >= 2.8.0
        Zermelo.redis.keys(key_pat)
      end

      matching_sets.select! do |k|
        k =~ /^#{key_root}:(.+)$/
        value === $1
      end

      unless matching_sets.empty?
        case type
        when :set
          Zermelo.redis.sunionstore(idx_result, matching_sets)
        when :sorted_set
          Zermelo.redis.zunionstore(idx_result, matching_sets)
        end
      end
    end
    idx_key
  else
    index = associated_class.send("#{att}_index")

    case index
    when Zermelo::Associations::RangeIndex
      range_lookup(index.key, value, type, attr_type, associated_class, temp_keys)
    when Zermelo::Associations::UniqueIndex
      idx_key = associated_class.send(:temp_key, type)
      temp_keys << idx_key

      val = Zermelo.redis.hget(key_to_backend_key(index.key),
                         index_keys(attr_type, value).join(':'))

      case type
      when :set
        Zermelo.redis.sadd(key_to_backend_key(idx_key), val)
      when :sorted_set
        Zermelo.redis.zadd(key_to_backend_key(idx_key), [1, val])
      end
      idx_key
    when Zermelo::Associations::Index
      index.key(value)
    end
  end
end

#key_to_backend_key(key) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/zermelo/backends/redis.rb', line 20

def key_to_backend_key(key)
  class_key = key.klass.send(:class_key)

  obj = case key.object
  when :attribute
    'attrs'
  when :association
    'assocs'
  when :index
    'indices'
  when :temporary
    'tmp'
  end

  name = Zermelo::COLLECTION_TYPES.has_key?(key.type) ? ":#{key.name}" : ''

  "#{class_key}:#{key.id.nil? ? '' : key.id}:#{obj}#{name}"
end

#range_lookup(key, range, type, attr_type, associated_class, temp_keys) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/zermelo/backends/redis.rb', line 257

def range_lookup(key, range, type, attr_type, associated_class, temp_keys)
  r_key = key_to_backend_key(key)
  opts = case type
  when :set
    {}
  when :sorted_set
    {:with_scores => true}
  end
  result = if range.by_score
    range_start  = range.start.nil?  ? '-inf' : safe_value(attr_type, range.start)
    range_finish = range.finish.nil? ? '+inf' : safe_value(attr_type, range.finish)
    Zermelo.redis.zrangebyscore(r_key, range_start, range_finish, opts)
  else
    range_start  = range.start  ||  0
    range_finish = range.finish || -1
    Zermelo.redis.zrange(r_key, range_start, range_finish, opts)
  end

  # TODO another way for index_lookup to indicate 'empty result', rather
  # than creating & returning an empty key
  ret_key = associated_class.send(:temp_key, key.type)
  temp_keys << ret_key
  unless result.empty?
    r_key = key_to_backend_key(ret_key)
    case type
    when :set
      Zermelo.redis.sadd(r_key, result)
    when :sorted_set
      Zermelo.redis.zadd(r_key, result.map {|r| [r.last, r.first]})
    end
  end
  ret_key
end

#temp_key_wrapObject



142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/zermelo/backends/redis.rb', line 142

def temp_key_wrap
  return unless block_given?
  temp_keys = []
  begin
    yield(temp_keys)
  rescue
    raise
  ensure
    unless temp_keys.empty?
      Zermelo.redis.del(*temp_keys.collect {|tk| key_to_backend_key(tk)})
      temp_keys.clear
    end
  end
end