valkey-glide 1.3.5__pp39-pypy39_pp73-macosx_10_7_x86_64.whl

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.

Potentially problematic release.


This version of valkey-glide might be problematic. Click here for more details.

Files changed (37) hide show
  1. glide/__init__.py +330 -0
  2. glide/async_commands/__init__.py +5 -0
  3. glide/async_commands/bitmap.py +311 -0
  4. glide/async_commands/cluster_commands.py +1294 -0
  5. glide/async_commands/command_args.py +102 -0
  6. glide/async_commands/core.py +7040 -0
  7. glide/async_commands/server_modules/ft.py +395 -0
  8. glide/async_commands/server_modules/ft_options/ft_aggregate_options.py +293 -0
  9. glide/async_commands/server_modules/ft_options/ft_constants.py +84 -0
  10. glide/async_commands/server_modules/ft_options/ft_create_options.py +409 -0
  11. glide/async_commands/server_modules/ft_options/ft_profile_options.py +108 -0
  12. glide/async_commands/server_modules/ft_options/ft_search_options.py +131 -0
  13. glide/async_commands/server_modules/glide_json.py +1255 -0
  14. glide/async_commands/server_modules/json_batch.py +790 -0
  15. glide/async_commands/sorted_set.py +402 -0
  16. glide/async_commands/standalone_commands.py +935 -0
  17. glide/async_commands/stream.py +442 -0
  18. glide/async_commands/transaction.py +5175 -0
  19. glide/config.py +590 -0
  20. glide/constants.py +120 -0
  21. glide/exceptions.py +62 -0
  22. glide/glide.pyi +36 -0
  23. glide/glide.pypy39-pp73-darwin.so +0 -0
  24. glide/glide_client.py +604 -0
  25. glide/logger.py +85 -0
  26. glide/protobuf/command_request_pb2.py +54 -0
  27. glide/protobuf/command_request_pb2.pyi +1164 -0
  28. glide/protobuf/connection_request_pb2.py +52 -0
  29. glide/protobuf/connection_request_pb2.pyi +292 -0
  30. glide/protobuf/response_pb2.py +32 -0
  31. glide/protobuf/response_pb2.pyi +101 -0
  32. glide/protobuf_codec.py +109 -0
  33. glide/py.typed +0 -0
  34. glide/routes.py +114 -0
  35. valkey_glide-1.3.5.dist-info/METADATA +125 -0
  36. valkey_glide-1.3.5.dist-info/RECORD +37 -0
  37. valkey_glide-1.3.5.dist-info/WHEEL +4 -0
@@ -0,0 +1,935 @@
1
+ # Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, List, Mapping, Optional, Union, cast
6
+
7
+ from glide.async_commands.command_args import ObjectType
8
+ from glide.async_commands.core import (
9
+ CoreCommands,
10
+ FlushMode,
11
+ FunctionRestorePolicy,
12
+ InfoSection,
13
+ )
14
+ from glide.async_commands.transaction import Transaction
15
+ from glide.constants import (
16
+ TOK,
17
+ TEncodable,
18
+ TFunctionListResponse,
19
+ TFunctionStatsFullResponse,
20
+ TResult,
21
+ )
22
+ from glide.protobuf.command_request_pb2 import RequestType
23
+
24
+ from ..glide import Script
25
+
26
+
27
+ class StandaloneCommands(CoreCommands):
28
+ async def custom_command(self, command_args: List[TEncodable]) -> TResult:
29
+ """
30
+ Executes a single command, without checking inputs.
31
+ See the [Valkey GLIDE Wiki](https://github.com/valkey-io/valkey-glide/wiki/General-Concepts#custom-command)
32
+ for details on the restrictions and limitations of the custom command API.
33
+
34
+ @example - Return a list of all pub/sub clients:
35
+
36
+ connection.customCommand(["CLIENT", "LIST","TYPE", "PUBSUB"])
37
+ Args:
38
+ command_args (List[TEncodable]): List of the command's arguments, where each argument is either a string or bytes.
39
+ Every part of the command, including the command name and subcommands, should be added as a separate value in args.
40
+
41
+ Returns:
42
+ TResult: The returning value depends on the executed command.
43
+ """
44
+ return await self._execute_command(RequestType.CustomCommand, command_args)
45
+
46
+ async def info(
47
+ self,
48
+ sections: Optional[List[InfoSection]] = None,
49
+ ) -> bytes:
50
+ """
51
+ Get information and statistics about the server.
52
+ See https://valkey.io/commands/info/ for details.
53
+
54
+ Args:
55
+ sections (Optional[List[InfoSection]]): A list of InfoSection values specifying which sections of
56
+ information to retrieve. When no parameter is provided, the default option is assumed.
57
+
58
+
59
+ Returns:
60
+ bytes: Returns bytes containing the information for the sections requested.
61
+ """
62
+ args: List[TEncodable] = (
63
+ [section.value for section in sections] if sections else []
64
+ )
65
+ return cast(bytes, await self._execute_command(RequestType.Info, args))
66
+
67
+ async def exec(
68
+ self,
69
+ transaction: Transaction,
70
+ ) -> Optional[List[TResult]]:
71
+ """
72
+ Execute a transaction by processing the queued commands.
73
+ See https://valkey.io/docs/topics/transactions/ for details on Transactions.
74
+
75
+ Args:
76
+ transaction (Transaction): A `Transaction` object containing a list of commands to be executed.
77
+
78
+ Returns:
79
+ Optional[List[TResult]]: A list of results corresponding to the execution of each command
80
+ in the transaction. If a command returns a value, it will be included in the list. If a command
81
+ doesn't return a value, the list entry will be `None`.
82
+ If the transaction failed due to a WATCH command, `exec` will return `None`.
83
+ """
84
+ commands = transaction.commands[:]
85
+ return await self._execute_transaction(commands)
86
+
87
+ async def select(self, index: int) -> TOK:
88
+ """
89
+ Change the currently selected database.
90
+ See https://valkey.io/commands/select/ for details.
91
+
92
+ Args:
93
+ index (int): The index of the database to select.
94
+
95
+ Returns:
96
+ A simple OK response.
97
+ """
98
+ return cast(TOK, await self._execute_command(RequestType.Select, [str(index)]))
99
+
100
+ async def config_resetstat(self) -> TOK:
101
+ """
102
+ Resets the statistics reported by the server using the INFO and LATENCY HISTOGRAM commands.
103
+ See https://valkey.io/commands/config-resetstat/ for details.
104
+
105
+ Returns:
106
+ OK: Returns "OK" to confirm that the statistics were successfully reset.
107
+ """
108
+ return cast(TOK, await self._execute_command(RequestType.ConfigResetStat, []))
109
+
110
+ async def config_rewrite(self) -> TOK:
111
+ """
112
+ Rewrite the configuration file with the current configuration.
113
+ See https://valkey.io/commands/config-rewrite/ for details.
114
+
115
+ Returns:
116
+ OK: OK is returned when the configuration was rewritten properly. Otherwise, an error is raised.
117
+ """
118
+ return cast(TOK, await self._execute_command(RequestType.ConfigRewrite, []))
119
+
120
+ async def client_id(
121
+ self,
122
+ ) -> int:
123
+ """
124
+ Returns the current connection id.
125
+ See https://valkey.io/commands/client-id/ for more information.
126
+
127
+ Returns:
128
+ int: the id of the client.
129
+ """
130
+ return cast(int, await self._execute_command(RequestType.ClientId, []))
131
+
132
+ async def ping(self, message: Optional[TEncodable] = None) -> bytes:
133
+ """
134
+ Ping the server.
135
+ See https://valkey.io/commands/ping/ for more details.
136
+
137
+ Args:
138
+ message (Optional[TEncodable]): An optional message to include in the PING command. If not provided,
139
+ the server will respond with b"PONG". If provided, the server will respond with a copy of the message.
140
+
141
+ Returns:
142
+ bytes: b"PONG" if `message` is not provided, otherwise return a copy of `message`.
143
+
144
+ Examples:
145
+ >>> await client.ping()
146
+ b"PONG"
147
+ >>> await client.ping("Hello")
148
+ b"Hello"
149
+ """
150
+ argument = [] if message is None else [message]
151
+ return cast(bytes, await self._execute_command(RequestType.Ping, argument))
152
+
153
+ async def config_get(self, parameters: List[TEncodable]) -> Dict[bytes, bytes]:
154
+ """
155
+ Get the values of configuration parameters.
156
+ Starting from server version 7, command supports multiple parameters.
157
+ See https://valkey.io/commands/config-get/ for details.
158
+
159
+ Args:
160
+ parameters (List[TEncodable]): A list of configuration parameter names to retrieve values for.
161
+
162
+ Returns:
163
+ Dict[bytes, bytes]: A dictionary of values corresponding to the configuration parameters.
164
+
165
+ Examples:
166
+ >>> await client.config_get(["timeout"] , RandomNode())
167
+ {b'timeout': b'1000'}
168
+ >>> await client.config_get([b"timeout" , "maxmemory"])
169
+ {b'timeout': b'1000', b'maxmemory': b'1GB'}
170
+ """
171
+ return cast(
172
+ Dict[bytes, bytes],
173
+ await self._execute_command(RequestType.ConfigGet, parameters),
174
+ )
175
+
176
+ async def config_set(self, parameters_map: Mapping[TEncodable, TEncodable]) -> TOK:
177
+ """
178
+ Set configuration parameters to the specified values.
179
+ Starting from server version 7, command supports multiple parameters.
180
+ See https://valkey.io/commands/config-set/ for details.
181
+
182
+ Args:
183
+ parameters_map (Mapping[TEncodable, TEncodable]): A map consisting of configuration
184
+ parameters and their respective values to set.
185
+
186
+ Returns:
187
+ OK: Returns OK if all configurations have been successfully set. Otherwise, raises an error.
188
+
189
+ Examples:
190
+ >>> config_set({"timeout": "1000", "maxmemory": "1GB"})
191
+ OK
192
+ """
193
+ parameters: List[TEncodable] = []
194
+ for pair in parameters_map.items():
195
+ parameters.extend(pair)
196
+ return cast(TOK, await self._execute_command(RequestType.ConfigSet, parameters))
197
+
198
+ async def client_getname(self) -> Optional[bytes]:
199
+ """
200
+ Get the name of the primary's connection.
201
+ See https://valkey.io/commands/client-getname/ for more details.
202
+
203
+ Returns:
204
+ Optional[bytes]: Returns the name of the client connection as a byte string if a name is set,
205
+ or None if no name is assigned.
206
+
207
+ Examples:
208
+ >>> await client.client_getname()
209
+ b'Connection Name'
210
+ """
211
+ return cast(
212
+ Optional[bytes], await self._execute_command(RequestType.ClientGetName, [])
213
+ )
214
+
215
+ async def dbsize(self) -> int:
216
+ """
217
+ Returns the number of keys in the currently selected database.
218
+ See https://valkey.io/commands/dbsize for more details.
219
+
220
+ Returns:
221
+ int: The number of keys in the currently selected database.
222
+
223
+ Examples:
224
+ >>> await client.dbsize()
225
+ 10 # Indicates there are 10 keys in the current database.
226
+ """
227
+ return cast(int, await self._execute_command(RequestType.DBSize, []))
228
+
229
+ async def echo(self, message: TEncodable) -> bytes:
230
+ """
231
+ Echoes the provided `message` back.
232
+
233
+ See https://valkey.io/commands/echo for more details.
234
+
235
+ Args:
236
+ message (TEncodable): The message to be echoed back.
237
+
238
+ Returns:
239
+ bytes: The provided `message`.
240
+
241
+ Examples:
242
+ >>> await client.echo("Valkey GLIDE")
243
+ b'Valkey GLIDE'
244
+ """
245
+ return cast(bytes, await self._execute_command(RequestType.Echo, [message]))
246
+
247
+ async def function_load(
248
+ self, library_code: TEncodable, replace: bool = False
249
+ ) -> bytes:
250
+ """
251
+ Loads a library to Valkey.
252
+
253
+ See https://valkey.io/commands/function-load/ for more details.
254
+
255
+ Args:
256
+ library_code (TEncodable): The source code that implements the library.
257
+ replace (bool): Whether the given library should overwrite a library with the same name if
258
+ it already exists.
259
+
260
+ Returns:
261
+ bytes: The library name that was loaded.
262
+
263
+ Examples:
264
+ >>> code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return args[1] end)"
265
+ >>> await client.function_load(code, True)
266
+ b"mylib"
267
+
268
+ Since: Valkey 7.0.0.
269
+ """
270
+ return cast(
271
+ bytes,
272
+ await self._execute_command(
273
+ RequestType.FunctionLoad,
274
+ ["REPLACE", library_code] if replace else [library_code],
275
+ ),
276
+ )
277
+
278
+ async def function_list(
279
+ self, library_name_pattern: Optional[TEncodable] = None, with_code: bool = False
280
+ ) -> TFunctionListResponse:
281
+ """
282
+ Returns information about the functions and libraries.
283
+
284
+ See https://valkey.io/commands/function-list/ for more details.
285
+
286
+ Args:
287
+ library_name_pattern (Optional[TEncodable]): A wildcard pattern for matching library names.
288
+ with_code (bool): Specifies whether to request the library code from the server or not.
289
+
290
+ Returns:
291
+ TFunctionListResponse: Info about all or
292
+ selected libraries and their functions.
293
+
294
+ Examples:
295
+ >>> response = await client.function_list("myLib?_backup", True)
296
+ [{
297
+ b"library_name": b"myLib5_backup",
298
+ b"engine": b"LUA",
299
+ b"functions": [{
300
+ b"name": b"myfunc",
301
+ b"description": None,
302
+ b"flags": {b"no-writes"},
303
+ }],
304
+ b"library_code": b"#!lua name=mylib \n sever.register_function('myfunc', function(keys, args) return args[1] end)"
305
+ }]
306
+
307
+ Since: Valkey 7.0.0.
308
+ """
309
+ args = []
310
+ if library_name_pattern is not None:
311
+ args.extend(["LIBRARYNAME", library_name_pattern])
312
+ if with_code:
313
+ args.append("WITHCODE")
314
+ return cast(
315
+ TFunctionListResponse,
316
+ await self._execute_command(
317
+ RequestType.FunctionList,
318
+ args,
319
+ ),
320
+ )
321
+
322
+ async def function_flush(self, mode: Optional[FlushMode] = None) -> TOK:
323
+ """
324
+ Deletes all function libraries.
325
+
326
+ See https://valkey.io/commands/function-flush/ for more details.
327
+
328
+ Args:
329
+ mode (Optional[FlushMode]): The flushing mode, could be either `SYNC` or `ASYNC`.
330
+
331
+ Returns:
332
+ TOK: A simple `OK`.
333
+
334
+ Examples:
335
+ >>> await client.function_flush(FlushMode.SYNC)
336
+ "OK"
337
+
338
+ Since: Valkey 7.0.0.
339
+ """
340
+ return cast(
341
+ TOK,
342
+ await self._execute_command(
343
+ RequestType.FunctionFlush,
344
+ [mode.value] if mode else [],
345
+ ),
346
+ )
347
+
348
+ async def function_delete(self, library_name: TEncodable) -> TOK:
349
+ """
350
+ Deletes a library and all its functions.
351
+
352
+ See https://valkey.io/commands/function-delete/ for more details.
353
+
354
+ Args:
355
+ library_code (TEncodable): The library name to delete
356
+
357
+ Returns:
358
+ TOK: A simple `OK`.
359
+
360
+ Examples:
361
+ >>> await client.function_delete("my_lib")
362
+ "OK"
363
+
364
+ Since: Valkey 7.0.0.
365
+ """
366
+ return cast(
367
+ TOK,
368
+ await self._execute_command(
369
+ RequestType.FunctionDelete,
370
+ [library_name],
371
+ ),
372
+ )
373
+
374
+ async def function_kill(self) -> TOK:
375
+ """
376
+ Kills a function that is currently executing.
377
+ This command only terminates read-only functions.
378
+
379
+ FUNCTION KILL runs on all nodes of the server, including primary and replicas.
380
+
381
+ See https://valkey.io/commands/function-kill/ for more details.
382
+
383
+ Returns:
384
+ TOK: A simple `OK`.
385
+
386
+ Examples:
387
+ >>> await client.function_kill()
388
+ "OK"
389
+
390
+ Since: Valkey 7.0.0.
391
+ """
392
+ return cast(
393
+ TOK,
394
+ await self._execute_command(RequestType.FunctionKill, []),
395
+ )
396
+
397
+ async def function_stats(self) -> TFunctionStatsFullResponse:
398
+ """
399
+ Returns information about the function that's currently running and information about the
400
+ available execution engines.
401
+
402
+ FUNCTION STATS runs on all nodes of the server, including primary and replicas.
403
+ The response includes a mapping from node address to the command response for that node.
404
+
405
+ See https://valkey.io/commands/function-stats/ for more details
406
+
407
+ Returns:
408
+ TFunctionStatsFullResponse: A Map where the key is the node address and the value is a Map of two keys:
409
+ - `running_script` with information about the running script.
410
+ - `engines` with information about available engines and their stats.
411
+ See example for more details.
412
+
413
+ Examples:
414
+ >>> await client.function_stats()
415
+ {b"addr": { # Response from the master node
416
+ b'running_script': {
417
+ b'name': b'foo',
418
+ b'command': [b'FCALL', b'foo', b'0', b'hello'],
419
+ b'duration_ms': 7758
420
+ },
421
+ b'engines': {
422
+ b'LUA': {
423
+ b'libraries_count': 1,
424
+ b'functions_count': 1,
425
+ }
426
+ }
427
+ },
428
+ b"addr2": { # Response from a replica
429
+ b'running_script': None,
430
+ b"engines": {
431
+ b'LUA': {
432
+ b'libraries_count': 1,
433
+ b'functions_count': 1,
434
+ }
435
+ }
436
+ }}
437
+
438
+ Since: Valkey version 7.0.0.
439
+ """
440
+ return cast(
441
+ TFunctionStatsFullResponse,
442
+ await self._execute_command(RequestType.FunctionStats, []),
443
+ )
444
+
445
+ async def function_dump(self) -> bytes:
446
+ """
447
+ Returns the serialized payload of all loaded libraries.
448
+
449
+ See https://valkey.io/docs/latest/commands/function-dump/ for more details.
450
+
451
+ Returns:
452
+ bytes: The serialized payload of all loaded libraries.
453
+
454
+ Examples:
455
+ >>> payload = await client.function_dump()
456
+ # The serialized payload of all loaded libraries. This response can
457
+ # be used to restore loaded functions on any Valkey instance.
458
+ >>> await client.function_restore(payload)
459
+ "OK" # The serialized dump response was used to restore the libraries.
460
+
461
+ Since: Valkey 7.0.0.
462
+ """
463
+ return cast(bytes, await self._execute_command(RequestType.FunctionDump, []))
464
+
465
+ async def function_restore(
466
+ self, payload: TEncodable, policy: Optional[FunctionRestorePolicy] = None
467
+ ) -> TOK:
468
+ """
469
+ Restores libraries from the serialized payload returned by the `function_dump` command.
470
+
471
+ See https://valkey.io/docs/latest/commands/function-restore/ for more details.
472
+
473
+ Args:
474
+ payload (TEncodable): The serialized data from the `function_dump` command.
475
+ policy (Optional[FunctionRestorePolicy]): A policy for handling existing libraries.
476
+
477
+ Returns:
478
+ TOK: OK.
479
+
480
+ Examples:
481
+ >>> payload = await client.function_dump()
482
+ # The serialized payload of all loaded libraries. This response can
483
+ # be used to restore loaded functions on any Valkey instance.
484
+ >>> await client.function_restore(payload)
485
+ "OK" # The serialized dump response was used to restore the libraries.
486
+ >>> await client.function_restore(payload, FunctionRestorePolicy.FLUSH)
487
+ "OK" # The serialized dump response was used to restore the libraries with the specified policy.
488
+
489
+ Since: Valkey 7.0.0.
490
+ """
491
+ args: List[TEncodable] = [payload]
492
+ if policy is not None:
493
+ args.append(policy.value)
494
+
495
+ return cast(TOK, await self._execute_command(RequestType.FunctionRestore, args))
496
+
497
+ async def time(self) -> List[bytes]:
498
+ """
499
+ Returns the server time.
500
+
501
+ See https://valkey.io/commands/time/ for more details.
502
+
503
+ Returns:
504
+ List[bytes]: The current server time as a two items `array`:
505
+ A Unix timestamp and the amount of microseconds already elapsed in the current second.
506
+ The returned `array` is in a [Unix timestamp, Microseconds already elapsed] format.
507
+
508
+ Examples:
509
+ >>> await client.time()
510
+ [b'1710925775', b'913580']
511
+ """
512
+ return cast(
513
+ List[bytes],
514
+ await self._execute_command(RequestType.Time, []),
515
+ )
516
+
517
+ async def lastsave(self) -> int:
518
+ """
519
+ Returns the Unix time of the last DB save timestamp or startup timestamp if no save was made since then.
520
+
521
+ See https://valkey.io/commands/lastsave for more details.
522
+
523
+ Returns:
524
+ int: The Unix time of the last successful DB save.
525
+
526
+ Examples:
527
+ >>> await client.lastsave()
528
+ 1710925775 # Unix time of the last DB save
529
+ """
530
+ return cast(
531
+ int,
532
+ await self._execute_command(RequestType.LastSave, []),
533
+ )
534
+
535
+ async def move(self, key: TEncodable, db_index: int) -> bool:
536
+ """
537
+ Move `key` from the currently selected database to the database specified by `db_index`.
538
+
539
+ See https://valkey.io/commands/move/ for more details.
540
+
541
+ Args:
542
+ key (TEncodable): The key to move.
543
+ db_index (int): The index of the database to move `key` to.
544
+
545
+ Returns:
546
+ bool: True if `key` was moved, or False if the `key` already exists in the destination database
547
+ or does not exist in the source database.
548
+
549
+ Example:
550
+ >>> await client.move("some_key", 1)
551
+ True
552
+ """
553
+ return cast(
554
+ bool,
555
+ await self._execute_command(RequestType.Move, [key, str(db_index)]),
556
+ )
557
+
558
+ async def publish(self, message: TEncodable, channel: TEncodable) -> int:
559
+ """
560
+ Publish a message on pubsub channel.
561
+ See https://valkey.io/commands/publish for more details.
562
+
563
+ Args:
564
+ message (TEncodable): Message to publish
565
+ channel (TEncodable): Channel to publish the message on.
566
+
567
+ Returns:
568
+ int: Number of subscriptions in primary node that received the message.
569
+ Note that this value does not include subscriptions that configured on replicas.
570
+
571
+ Examples:
572
+ >>> await client.publish("Hi all!", "global-channel")
573
+ 1 # This message was posted to 1 subscription which is configured on primary node
574
+ """
575
+ return cast(
576
+ int, await self._execute_command(RequestType.Publish, [channel, message])
577
+ )
578
+
579
+ async def flushall(self, flush_mode: Optional[FlushMode] = None) -> TOK:
580
+ """
581
+ Deletes all the keys of all the existing databases. This command never fails.
582
+
583
+ See https://valkey.io/commands/flushall for more details.
584
+
585
+ Args:
586
+ flush_mode (Optional[FlushMode]): The flushing mode, could be either `SYNC` or `ASYNC`.
587
+
588
+ Returns:
589
+ TOK: A simple OK response.
590
+
591
+ Examples:
592
+ >>> await client.flushall(FlushMode.ASYNC)
593
+ OK # This command never fails.
594
+ """
595
+ args: List[TEncodable] = []
596
+ if flush_mode is not None:
597
+ args.append(flush_mode.value)
598
+
599
+ return cast(
600
+ TOK,
601
+ await self._execute_command(RequestType.FlushAll, args),
602
+ )
603
+
604
+ async def flushdb(self, flush_mode: Optional[FlushMode] = None) -> TOK:
605
+ """
606
+ Deletes all the keys of the currently selected database. This command never fails.
607
+
608
+ See https://valkey.io/commands/flushdb for more details.
609
+
610
+ Args:
611
+ flush_mode (Optional[FlushMode]): The flushing mode, could be either `SYNC` or `ASYNC`.
612
+
613
+ Returns:
614
+ TOK: A simple OK response.
615
+
616
+ Examples:
617
+ >>> await client.flushdb()
618
+ OK # The keys of the currently selected database were deleted.
619
+ >>> await client.flushdb(FlushMode.ASYNC)
620
+ OK # The keys of the currently selected database were deleted asynchronously.
621
+ """
622
+ args: List[TEncodable] = []
623
+ if flush_mode is not None:
624
+ args.append(flush_mode.value)
625
+
626
+ return cast(
627
+ TOK,
628
+ await self._execute_command(RequestType.FlushDB, args),
629
+ )
630
+
631
+ async def copy(
632
+ self,
633
+ source: TEncodable,
634
+ destination: TEncodable,
635
+ destinationDB: Optional[int] = None,
636
+ replace: Optional[bool] = None,
637
+ ) -> bool:
638
+ """
639
+ Copies the value stored at the `source` to the `destination` key. If `destinationDB`
640
+ is specified, the value will be copied to the database specified by `destinationDB`,
641
+ otherwise the current database will be used. When `replace` is True, removes the
642
+ `destination` key first if it already exists, otherwise performs no action.
643
+
644
+ See https://valkey.io/commands/copy for more details.
645
+
646
+ Args:
647
+ source (TEncodable): The key to the source value.
648
+ destination (TEncodable): The key where the value should be copied to.
649
+ destinationDB (Optional[int]): The alternative logical database index for the destination key.
650
+ replace (Optional[bool]): If the destination key should be removed before copying the value to it.
651
+
652
+ Returns:
653
+ bool: True if the source was copied. Otherwise, return False.
654
+
655
+ Examples:
656
+ >>> await client.set("source", "sheep")
657
+ >>> await client.copy(b"source", b"destination", 1, False)
658
+ True # Source was copied
659
+ >>> await client.select(1)
660
+ >>> await client.get("destination")
661
+ b"sheep"
662
+
663
+ Since: Valkey version 6.2.0.
664
+ """
665
+ args: List[TEncodable] = [source, destination]
666
+ if destinationDB is not None:
667
+ args.extend(["DB", str(destinationDB)])
668
+ if replace is True:
669
+ args.append("REPLACE")
670
+ return cast(
671
+ bool,
672
+ await self._execute_command(RequestType.Copy, args),
673
+ )
674
+
675
+ async def lolwut(
676
+ self,
677
+ version: Optional[int] = None,
678
+ parameters: Optional[List[int]] = None,
679
+ ) -> bytes:
680
+ """
681
+ Displays a piece of generative computer art and the Valkey version.
682
+
683
+ See https://valkey.io/commands/lolwut for more details.
684
+
685
+ Args:
686
+ version (Optional[int]): Version of computer art to generate.
687
+ parameters (Optional[List[int]]): Additional set of arguments in order to change the output:
688
+ For version `5`, those are length of the line, number of squares per row, and number of squares per column.
689
+ For version `6`, those are number of columns and number of lines.
690
+
691
+ Returns:
692
+ bytes: A piece of generative computer art along with the current Valkey version.
693
+
694
+ Examples:
695
+ >>> await client.lolwut(6, [40, 20]);
696
+ b"Redis ver. 7.2.3" # Indicates the current Valkey version
697
+ >>> await client.lolwut(5, [30, 5, 5]);
698
+ b"Redis ver. 7.2.3" # Indicates the current Valkey version
699
+ """
700
+ args: List[TEncodable] = []
701
+ if version is not None:
702
+ args.extend(["VERSION", str(version)])
703
+ if parameters:
704
+ for var in parameters:
705
+ args.extend(str(var))
706
+ return cast(
707
+ bytes,
708
+ await self._execute_command(RequestType.Lolwut, args),
709
+ )
710
+
711
+ async def random_key(self) -> Optional[bytes]:
712
+ """
713
+ Returns a random existing key name from the currently selected database.
714
+
715
+ See https://valkey.io/commands/randomkey for more details.
716
+
717
+ Returns:
718
+ Optional[bytes]: A random existing key name from the currently selected database.
719
+
720
+ Examples:
721
+ >>> await client.random_key()
722
+ b"random_key_name" # "random_key_name" is a random existing key name from the currently selected database.
723
+ """
724
+ return cast(
725
+ Optional[bytes],
726
+ await self._execute_command(RequestType.RandomKey, []),
727
+ )
728
+
729
+ async def wait(
730
+ self,
731
+ numreplicas: int,
732
+ timeout: int,
733
+ ) -> int:
734
+ """
735
+ Blocks the current client until all the previous write commands are successfully transferred
736
+ and acknowledged by at least `numreplicas` of replicas. If `timeout` is
737
+ reached, the command returns even if the specified number of replicas were not yet reached.
738
+
739
+ See https://valkey.io/commands/wait for more details.
740
+
741
+ Args:
742
+ numreplicas (int): The number of replicas to reach.
743
+ timeout (int): The timeout value specified in milliseconds. A value of 0 will block indefinitely.
744
+
745
+ Returns:
746
+ int: The number of replicas reached by all the writes performed in the context of the current connection.
747
+
748
+ Examples:
749
+ >>> await client.set("key", "value");
750
+ >>> await client.wait(1, 1000);
751
+ // return 1 when a replica is reached or 0 if 1000ms is reached.
752
+ """
753
+ args: List[TEncodable] = [str(numreplicas), str(timeout)]
754
+ return cast(
755
+ int,
756
+ await self._execute_command(RequestType.Wait, args),
757
+ )
758
+
759
+ async def unwatch(self) -> TOK:
760
+ """
761
+ Flushes all the previously watched keys for a transaction. Executing a transaction will
762
+ automatically flush all previously watched keys.
763
+
764
+ See https://valkey.io/commands/unwatch for more details.
765
+
766
+ Returns:
767
+ TOK: A simple "OK" response.
768
+
769
+ Examples:
770
+ >>> await client.watch("sampleKey")
771
+ 'OK'
772
+ >>> await client.unwatch()
773
+ 'OK'
774
+ """
775
+ return cast(
776
+ TOK,
777
+ await self._execute_command(RequestType.UnWatch, []),
778
+ )
779
+
780
+ async def scan(
781
+ self,
782
+ cursor: TEncodable,
783
+ match: Optional[TEncodable] = None,
784
+ count: Optional[int] = None,
785
+ type: Optional[ObjectType] = None,
786
+ ) -> List[Union[bytes, List[bytes]]]:
787
+ """
788
+ Incrementally iterate over a collection of keys.
789
+ SCAN is a cursor based iterator. This means that at every call of the command,
790
+ the server returns an updated cursor that the user needs to use as the cursor argument in the next call.
791
+ An iteration starts when the cursor is set to "0", and terminates when the cursor returned by the server is "0".
792
+
793
+ A full iteration always retrieves all the elements that were present
794
+ in the collection from the start to the end of a full iteration.
795
+ Elements that were not constantly present in the collection during a full iteration, may be returned or not.
796
+
797
+ See https://valkey.io/commands/scan for more details.
798
+
799
+ Args:
800
+ cursor (TResult): The cursor used for iteration. For the first iteration, the cursor should be set to "0".
801
+ Using a non-zero cursor in the first iteration,
802
+ or an invalid cursor at any iteration, will lead to undefined results.
803
+ Using the same cursor in multiple iterations will, in case nothing changed between the iterations,
804
+ return the same elements multiple times.
805
+ If the the db has changed, it may result an undefined behavior.
806
+ match (Optional[TResult]): A pattern to match keys against.
807
+ count (Optional[int]): The number of keys to return per iteration.
808
+ The number of keys returned per iteration is not guaranteed to be the same as the count argument.
809
+ the argument is used as a hint for the server to know how many "steps" it can use to retrieve the keys.
810
+ The default value is 10.
811
+ type (ObjectType): The type of object to scan for.
812
+
813
+ Returns:
814
+ List[Union[bytes, List[bytes]]]: A List containing the next cursor value and a list of keys,
815
+ formatted as [cursor, [key1, key2, ...]]
816
+
817
+ Examples:
818
+ >>> result = await client.scan(b'0')
819
+ print(result) #[b'17', [b'key1', b'key2', b'key3', b'key4', b'key5', b'set1', b'set2', b'set3']]
820
+ first_cursor_result = result[0]
821
+ result = await client.scan(first_cursor_result)
822
+ print(result) #[b'349', [b'key4', b'key5', b'set1', b'hash1', b'zset1', b'list1', b'list2',
823
+ b'list3', b'zset2', b'zset3', b'zset4', b'zset5', b'zset6']]
824
+ result = await client.scan(result[0])
825
+ print(result) #[b'0', [b'key6', b'key7']]
826
+
827
+ >>> result = await client.scan(first_cursor_result, match=b'key*', count=2)
828
+ print(result) #[b'6', [b'key4', b'key5']]
829
+
830
+ >>> result = await client.scan("0", type=ObjectType.Set)
831
+ print(result) #[b'362', [b'set1', b'set2', b'set3']]
832
+ """
833
+ args = [cursor]
834
+ if match:
835
+ args.extend(["MATCH", match])
836
+ if count:
837
+ args.extend(["COUNT", str(count)])
838
+ if type:
839
+ args.extend(["TYPE", type.value])
840
+ return cast(
841
+ List[Union[bytes, List[bytes]]],
842
+ await self._execute_command(RequestType.Scan, args),
843
+ )
844
+
845
+ async def script_exists(self, sha1s: List[TEncodable]) -> List[bool]:
846
+ """
847
+ Check existence of scripts in the script cache by their SHA1 digest.
848
+
849
+ See https://valkey.io/commands/script-exists for more details.
850
+
851
+ Args:
852
+ sha1s (List[TEncodable]): List of SHA1 digests of the scripts to check.
853
+
854
+ Returns:
855
+ List[bool]: A list of boolean values indicating the existence of each script.
856
+
857
+ Examples:
858
+ >>> await client.script_exists(["sha1_digest1", "sha1_digest2"])
859
+ [True, False]
860
+ """
861
+ return cast(
862
+ List[bool], await self._execute_command(RequestType.ScriptExists, sha1s)
863
+ )
864
+
865
+ async def script_flush(self, mode: Optional[FlushMode] = None) -> TOK:
866
+ """
867
+ Flush the Lua scripts cache.
868
+
869
+ See https://valkey.io/commands/script-flush for more details.
870
+
871
+ Args:
872
+ mode (Optional[FlushMode]): The flushing mode, could be either `SYNC` or `ASYNC`.
873
+
874
+ Returns:
875
+ TOK: A simple `OK` response.
876
+
877
+ Examples:
878
+ >>> await client.script_flush()
879
+ "OK"
880
+
881
+ >>> await client.script_flush(FlushMode.ASYNC)
882
+ "OK"
883
+ """
884
+
885
+ return cast(
886
+ TOK,
887
+ await self._execute_command(
888
+ RequestType.ScriptFlush, [mode.value] if mode else []
889
+ ),
890
+ )
891
+
892
+ async def script_kill(self) -> TOK:
893
+ """
894
+ Kill the currently executing Lua script, assuming no write operation was yet performed by the script.
895
+
896
+ See https://valkey.io/commands/script-kill for more details.
897
+
898
+ Returns:
899
+ TOK: A simple `OK` response.
900
+
901
+ Examples:
902
+ >>> await client.script_kill()
903
+ "OK"
904
+ """
905
+ return cast(TOK, await self._execute_command(RequestType.ScriptKill, []))
906
+
907
+ async def invoke_script(
908
+ self,
909
+ script: Script,
910
+ keys: Optional[List[TEncodable]] = None,
911
+ args: Optional[List[TEncodable]] = None,
912
+ ) -> TResult:
913
+ """
914
+ Invokes a Lua script with its keys and arguments.
915
+ This method simplifies the process of invoking scripts on a the server by using an object that represents a Lua script.
916
+ The script loading, argument preparation, and execution will all be handled internally.
917
+ If the script has not already been loaded, it will be loaded automatically using the `SCRIPT LOAD` command.
918
+ After that, it will be invoked using the `EVALSHA` command.
919
+
920
+ See https://valkey.io/commands/script-load/ and https://valkey.io/commands/evalsha/ for more details.
921
+
922
+ Args:
923
+ script (Script): The Lua script to execute.
924
+ keys (Optional[List[TEncodable]]): The keys that are used in the script.
925
+ args (Optional[List[TEncodable]]): The arguments for the script.
926
+
927
+ Returns:
928
+ TResult: a value that depends on the script that was executed.
929
+
930
+ Examples:
931
+ >>> lua_script = Script("return { KEYS[1], ARGV[1] }")
932
+ >>> await client.invoke_script(lua_script, keys=["foo"], args=["bar"] );
933
+ [b"foo", b"bar"]
934
+ """
935
+ return await self._execute_script(script.get_hash(), keys, args)