ultra-smart-kit 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,459 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Redis
4
+ module Commands
5
+ module Keys
6
+ # Scan the keyspace
7
+ #
8
+ # @example Retrieve the first batch of keys
9
+ # redis.scan(0)
10
+ # # => ["4", ["key:21", "key:47", "key:42"]]
11
+ # @example Retrieve a batch of keys matching a pattern
12
+ # redis.scan(4, :match => "key:1?")
13
+ # # => ["92", ["key:13", "key:18"]]
14
+ # @example Retrieve a batch of keys of a certain type
15
+ # redis.scan(92, :type => "zset")
16
+ # # => ["173", ["sortedset:14", "sortedset:78"]]
17
+ #
18
+ # @param [String, Integer] cursor the cursor of the iteration
19
+ # @param [Hash] options
20
+ # - `:match => String`: only return keys matching the pattern
21
+ # - `:count => Integer`: return count keys at most per iteration
22
+ # - `:type => String`: return keys only of the given type
23
+ #
24
+ # @return [String, Array<String>] the next cursor and all found keys
25
+ #
26
+ # See the [Redis Server SCAN documentation](https://redis.io/docs/latest/commands/scan/) for further details
27
+ def scan(cursor, **options)
28
+ _scan(:scan, cursor, [], **options)
29
+ end
30
+
31
+ # Scan the keyspace
32
+ #
33
+ # @example Retrieve all of the keys (with possible duplicates)
34
+ # redis.scan_each.to_a
35
+ # # => ["key:21", "key:47", "key:42"]
36
+ # @example Execute block for each key matching a pattern
37
+ # redis.scan_each(:match => "key:1?") {|key| puts key}
38
+ # # => key:13
39
+ # # => key:18
40
+ # @example Execute block for each key of a type
41
+ # redis.scan_each(:type => "hash") {|key| puts redis.type(key)}
42
+ # # => "hash"
43
+ # # => "hash"
44
+ #
45
+ # @param [Hash] options
46
+ # - `:match => String`: only return keys matching the pattern
47
+ # - `:count => Integer`: return count keys at most per iteration
48
+ # - `:type => String`: return keys only of the given type
49
+ #
50
+ # @return [Enumerator] an enumerator for all found keys
51
+ #
52
+ # See the [Redis Server SCAN documentation](https://redis.io/docs/latest/commands/scan/) for further details
53
+ def scan_each(**options, &block)
54
+ return to_enum(:scan_each, **options) unless block_given?
55
+
56
+ cursor = 0
57
+ loop do
58
+ cursor, keys = scan(cursor, **options)
59
+ keys.each(&block)
60
+ break if cursor == "0"
61
+ end
62
+ end
63
+
64
+ # Remove the expiration from a key.
65
+ #
66
+ # @param [String] key
67
+ # @return [Boolean] whether the timeout was removed or not
68
+ def persist(key)
69
+ send_command([:persist, key], &Boolify)
70
+ end
71
+
72
+ # Set a key's time to live in seconds.
73
+ #
74
+ # @param [String] key
75
+ # @param [Integer] seconds time to live
76
+ # @param [Hash] options
77
+ # - `:nx => true`: Set expiry only when the key has no expiry.
78
+ # - `:xx => true`: Set expiry only when the key has an existing expiry.
79
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
80
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
81
+ # @return [Boolean] whether the timeout was set or not
82
+ def expire(key, seconds, nx: nil, xx: nil, gt: nil, lt: nil)
83
+ args = [:expire, key, Integer(seconds)]
84
+ args << "NX" if nx
85
+ args << "XX" if xx
86
+ args << "GT" if gt
87
+ args << "LT" if lt
88
+
89
+ send_command(args, &Boolify)
90
+ end
91
+
92
+ # Set the expiration for a key as a UNIX timestamp.
93
+ #
94
+ # @param [String] key
95
+ # @param [Integer] unix_time expiry time specified as a UNIX timestamp
96
+ # @param [Hash] options
97
+ # - `:nx => true`: Set expiry only when the key has no expiry.
98
+ # - `:xx => true`: Set expiry only when the key has an existing expiry.
99
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
100
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
101
+ # @return [Boolean] whether the timeout was set or not
102
+ def expireat(key, unix_time, nx: nil, xx: nil, gt: nil, lt: nil)
103
+ args = [:expireat, key, Integer(unix_time)]
104
+ args << "NX" if nx
105
+ args << "XX" if xx
106
+ args << "GT" if gt
107
+ args << "LT" if lt
108
+
109
+ send_command(args, &Boolify)
110
+ end
111
+
112
+ # Get a key's expiry time specified as number of seconds from UNIX Epoch
113
+ #
114
+ # @param [String] key
115
+ # @return [Integer] expiry time specified as number of seconds from UNIX Epoch
116
+ def expiretime(key)
117
+ send_command([:expiretime, key])
118
+ end
119
+
120
+ # Get the time to live (in seconds) for a key.
121
+ #
122
+ # @param [String] key
123
+ # @return [Integer] remaining time to live in seconds.
124
+ #
125
+ # In Redis 2.6 or older the command returns -1 if the key does not exist or if
126
+ # the key exist but has no associated expire.
127
+ #
128
+ # Starting with Redis 2.8 the return value in case of error changed:
129
+ #
130
+ # - The command returns -2 if the key does not exist.
131
+ # - The command returns -1 if the key exists but has no associated expire.
132
+ def ttl(key)
133
+ send_command([:ttl, key])
134
+ end
135
+
136
+ # Set a key's time to live in milliseconds.
137
+ #
138
+ # @param [String] key
139
+ # @param [Integer] milliseconds time to live
140
+ # @param [Hash] options
141
+ # - `:nx => true`: Set expiry only when the key has no expiry.
142
+ # - `:xx => true`: Set expiry only when the key has an existing expiry.
143
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
144
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
145
+ # @return [Boolean] whether the timeout was set or not
146
+ def pexpire(key, milliseconds, nx: nil, xx: nil, gt: nil, lt: nil)
147
+ args = [:pexpire, key, Integer(milliseconds)]
148
+ args << "NX" if nx
149
+ args << "XX" if xx
150
+ args << "GT" if gt
151
+ args << "LT" if lt
152
+
153
+ send_command(args, &Boolify)
154
+ end
155
+
156
+ # Set the expiration for a key as number of milliseconds from UNIX Epoch.
157
+ #
158
+ # @param [String] key
159
+ # @param [Integer] ms_unix_time expiry time specified as number of milliseconds from UNIX Epoch.
160
+ # @param [Hash] options
161
+ # - `:nx => true`: Set expiry only when the key has no expiry.
162
+ # - `:xx => true`: Set expiry only when the key has an existing expiry.
163
+ # - `:gt => true`: Set expiry only when the new expiry is greater than current one.
164
+ # - `:lt => true`: Set expiry only when the new expiry is less than current one.
165
+ # @return [Boolean] whether the timeout was set or not
166
+ def pexpireat(key, ms_unix_time, nx: nil, xx: nil, gt: nil, lt: nil)
167
+ args = [:pexpireat, key, Integer(ms_unix_time)]
168
+ args << "NX" if nx
169
+ args << "XX" if xx
170
+ args << "GT" if gt
171
+ args << "LT" if lt
172
+
173
+ send_command(args, &Boolify)
174
+ end
175
+
176
+ # Get a key's expiry time specified as number of milliseconds from UNIX Epoch
177
+ #
178
+ # @param [String] key
179
+ # @return [Integer] expiry time specified as number of milliseconds from UNIX Epoch
180
+ def pexpiretime(key)
181
+ send_command([:pexpiretime, key])
182
+ end
183
+
184
+ # Get the time to live (in milliseconds) for a key.
185
+ #
186
+ # @param [String] key
187
+ # @return [Integer] remaining time to live in milliseconds
188
+ # In Redis 2.6 or older the command returns -1 if the key does not exist or if
189
+ # the key exist but has no associated expire.
190
+ #
191
+ # Starting with Redis 2.8 the return value in case of error changed:
192
+ #
193
+ # - The command returns -2 if the key does not exist.
194
+ # - The command returns -1 if the key exists but has no associated expire.
195
+ def pttl(key)
196
+ send_command([:pttl, key])
197
+ end
198
+
199
+ # Return a serialized version of the value stored at a key.
200
+ #
201
+ # @param [String] key
202
+ # @return [String] serialized_value
203
+ def dump(key)
204
+ send_command([:dump, key])
205
+ end
206
+
207
+ # Create a key using the serialized value, previously obtained using DUMP.
208
+ #
209
+ # @param [String] key
210
+ # @param [String] ttl
211
+ # @param [String] serialized_value
212
+ # @param [Hash] options
213
+ # - `:replace => Boolean`: if false, raises an error if key already exists
214
+ # @raise [Redis::CommandError]
215
+ # @return [String] `"OK"`
216
+ def restore(key, ttl, serialized_value, replace: nil)
217
+ args = [:restore, key, ttl, serialized_value]
218
+ args << 'REPLACE' if replace
219
+
220
+ send_command(args)
221
+ end
222
+
223
+ # Transfer a key from the connected instance to another instance.
224
+ #
225
+ # @param [String, Array<String>] key
226
+ # @param [Hash] options
227
+ # - `:host => String`: host of instance to migrate to
228
+ # - `:port => Integer`: port of instance to migrate to
229
+ # - `:db => Integer`: database to migrate to (default: same as source)
230
+ # - `:timeout => Integer`: timeout (default: same as connection timeout)
231
+ # - `:copy => Boolean`: Do not remove the key from the local instance.
232
+ # - `:replace => Boolean`: Replace existing key on the remote instance.
233
+ # @return [String] `"OK"`
234
+ def migrate(key, options)
235
+ args = [:migrate]
236
+ args << (options[:host] || raise(':host not specified'))
237
+ args << (options[:port] || raise(':port not specified'))
238
+ args << (key.is_a?(String) ? key : '')
239
+ args << (options[:db] || @client.db).to_i
240
+ args << (options[:timeout] || @client.timeout).to_i
241
+ args << 'COPY' if options[:copy]
242
+ args << 'REPLACE' if options[:replace]
243
+ args += ['KEYS', *key] if key.is_a?(Array)
244
+
245
+ send_command(args)
246
+ end
247
+
248
+ # Delete one or more keys.
249
+ #
250
+ # @param [String, Array<String>] keys
251
+ # @return [Integer] number of keys that were deleted
252
+ def del(*keys)
253
+ keys.flatten!(1)
254
+ return 0 if keys.empty?
255
+
256
+ send_command([:del] + keys)
257
+ end
258
+
259
+ # Unlink one or more keys.
260
+ #
261
+ # @param [String, Array<String>] keys
262
+ # @return [Integer] number of keys that were unlinked
263
+ def unlink(*keys)
264
+ send_command([:unlink] + keys)
265
+ end
266
+
267
+ # Determine how many of the keys exists.
268
+ #
269
+ # @param [String, Array<String>] keys
270
+ # @return [Integer]
271
+ def exists(*keys)
272
+ send_command([:exists, *keys])
273
+ end
274
+
275
+ # Determine if any of the keys exists.
276
+ #
277
+ # @param [String, Array<String>] keys
278
+ # @return [Boolean]
279
+ def exists?(*keys)
280
+ send_command([:exists, *keys]) do |value|
281
+ value > 0
282
+ end
283
+ end
284
+
285
+ # Find all keys matching the given pattern.
286
+ #
287
+ # @param [String] pattern
288
+ # @return [Array<String>]
289
+ #
290
+ # See the [Redis Server KEYS documentation](https://redis.io/docs/latest/commands/keys/) for further details
291
+ def keys(pattern = "*")
292
+ send_command([:keys, pattern]) do |reply|
293
+ if reply.is_a?(String)
294
+ reply.split(" ")
295
+ else
296
+ reply
297
+ end
298
+ end
299
+ end
300
+
301
+ # Move a key to another database.
302
+ #
303
+ # @example Move a key to another database
304
+ # redis.set "foo", "bar"
305
+ # # => "OK"
306
+ # redis.move "foo", 2
307
+ # # => true
308
+ # redis.exists "foo"
309
+ # # => false
310
+ # redis.select 2
311
+ # # => "OK"
312
+ # redis.exists "foo"
313
+ # # => true
314
+ # redis.get "foo"
315
+ # # => "bar"
316
+ #
317
+ # @param [String] key
318
+ # @param [Integer] db
319
+ # @return [Boolean] whether the key was moved or not
320
+ def move(key, db)
321
+ send_command([:move, key, db], &Boolify)
322
+ end
323
+
324
+ # Copy a value from one key to another.
325
+ #
326
+ # @example Copy a value to another key
327
+ # redis.set "foo", "value"
328
+ # # => "OK"
329
+ # redis.copy "foo", "bar"
330
+ # # => true
331
+ # redis.get "bar"
332
+ # # => "value"
333
+ #
334
+ # @example Copy a value to a key in another database
335
+ # redis.set "foo", "value"
336
+ # # => "OK"
337
+ # redis.copy "foo", "bar", db: 2
338
+ # # => true
339
+ # redis.select 2
340
+ # # => "OK"
341
+ # redis.get "bar"
342
+ # # => "value"
343
+ #
344
+ # @param [String] source
345
+ # @param [String] destination
346
+ # @param [Integer] db
347
+ # @param [Boolean] replace removes the `destination` key before copying value to it
348
+ # @return [Boolean] whether the key was copied or not
349
+ def copy(source, destination, db: nil, replace: false)
350
+ command = [:copy, source, destination]
351
+ command << "DB" << db if db
352
+ command << "REPLACE" if replace
353
+
354
+ send_command(command, &Boolify)
355
+ end
356
+
357
+ def object(*args)
358
+ send_command([:object] + args)
359
+ end
360
+
361
+ # Return a random key from the keyspace.
362
+ #
363
+ # @return [String]
364
+ def randomkey
365
+ send_command([:randomkey])
366
+ end
367
+
368
+ # Rename a key. If the new key already exists it is overwritten.
369
+ #
370
+ # @param [String] old_name
371
+ # @param [String] new_name
372
+ # @return [String] `OK`
373
+ def rename(old_name, new_name)
374
+ send_command([:rename, old_name, new_name])
375
+ end
376
+
377
+ # Rename a key, only if the new key does not exist.
378
+ #
379
+ # @param [String] old_name
380
+ # @param [String] new_name
381
+ # @return [Boolean] whether the key was renamed or not
382
+ def renamenx(old_name, new_name)
383
+ send_command([:renamenx, old_name, new_name], &Boolify)
384
+ end
385
+
386
+ # Sort the elements in a list, set or sorted set.
387
+ #
388
+ # @example Retrieve the first 2 elements from an alphabetically sorted "list"
389
+ # redis.sort("list", :order => "alpha", :limit => [0, 2])
390
+ # # => ["a", "b"]
391
+ # @example Store an alphabetically descending list in "target"
392
+ # redis.sort("list", :order => "desc alpha", :store => "target")
393
+ # # => 26
394
+ #
395
+ # @param [String] key
396
+ # @param [Hash] options
397
+ # - `:by => String`: use external key to sort elements by
398
+ # - `:limit => [offset, count]`: skip `offset` elements, return a maximum
399
+ # of `count` elements
400
+ # - `:get => [String, Array<String>]`: single key or array of keys to
401
+ # retrieve per element in the result
402
+ # - `:order => String`: combination of `ASC`, `DESC` and optionally `ALPHA`
403
+ # - `:store => String`: key to store the result at
404
+ #
405
+ # @return [Array<String>, Array<Array<String>>, Integer]
406
+ # - when `:get` is not specified, or holds a single element, an array of elements
407
+ # - when `:get` is specified, and holds more than one element, an array of
408
+ # elements where every element is an array with the result for every
409
+ # element specified in `:get`
410
+ # - when `:store` is specified, the number of elements in the stored result
411
+ def sort(key, by: nil, limit: nil, get: nil, order: nil, store: nil)
412
+ args = [:sort, key]
413
+ args << "BY" << by if by
414
+
415
+ if limit
416
+ args << "LIMIT"
417
+ args.concat(limit)
418
+ end
419
+
420
+ get = Array(get)
421
+ get.each do |item|
422
+ args << "GET" << item
423
+ end
424
+
425
+ args.concat(order.split(" ")) if order
426
+ args << "STORE" << store if store
427
+
428
+ send_command(args) do |reply|
429
+ if get.size > 1 && !store
430
+ reply.each_slice(get.size).to_a if reply
431
+ else
432
+ reply
433
+ end
434
+ end
435
+ end
436
+
437
+ # Determine the type stored at key.
438
+ #
439
+ # @param [String] key
440
+ # @return [String] `string`, `list`, `set`, `zset`, `hash` or `none`
441
+ def type(key)
442
+ send_command([:type, key])
443
+ end
444
+
445
+ private
446
+
447
+ def _scan(command, cursor, args, match: nil, count: nil, type: nil, &block)
448
+ # SSCAN/ZSCAN/HSCAN already prepend the key to +args+.
449
+
450
+ args << cursor
451
+ args << "MATCH" << match if match
452
+ args << "COUNT" << Integer(count) if count
453
+ args << "TYPE" << type if type
454
+
455
+ send_command([command] + args, &block)
456
+ end
457
+ end
458
+ end
459
+ end