sqlit-provider-redis 0.1.0__py3-none-any.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.
- sqlit_provider_redis/__init__.py +0 -0
- sqlit_provider_redis/adapter.py +224 -0
- sqlit_provider_redis/autoload.py +21 -0
- sqlit_provider_redis/bootstrap.py +85 -0
- sqlit_provider_redis/provider.py +69 -0
- sqlit_provider_redis/tui.py +127 -0
- sqlit_provider_redis-0.1.0.dist-info/METADATA +81 -0
- sqlit_provider_redis-0.1.0.dist-info/RECORD +11 -0
- sqlit_provider_redis-0.1.0.dist-info/WHEEL +4 -0
- sqlit_provider_redis-0.1.0.dist-info/licenses/LICENSE +21 -0
- sqlit_provider_redis.pth +1 -0
|
File without changes
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""One command-console adapter for Redis and Valkey."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shlex
|
|
7
|
+
import ssl
|
|
8
|
+
from typing import Any
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
|
|
11
|
+
from sqlit.domains.connections.domain.config import ConnectionConfig
|
|
12
|
+
from sqlit.domains.connections.providers.adapters.base import DatabaseAdapter
|
|
13
|
+
from sqlit.domains.connections.providers.tls import get_tls_files, get_tls_mode
|
|
14
|
+
|
|
15
|
+
_READ_COMMANDS = frozenset(
|
|
16
|
+
"PING ECHO GET MGET GETRANGE STRLEN HGET HMGET HGETALL HLEN HEXISTS HSCAN "
|
|
17
|
+
"LRANGE LINDEX LLEN SMEMBERS SISMEMBER SCARD SSCAN ZRANGE ZCARD ZSCORE ZRANK ZSCAN "
|
|
18
|
+
"XRANGE XLEN TYPE TTL PTTL EXISTS SCAN INFO DBSIZE TIME COMMAND".split()
|
|
19
|
+
)
|
|
20
|
+
_UNSUPPORTED_COMMANDS = frozenset(
|
|
21
|
+
"SELECT AUTH HELLO RESET QUIT CLIENT MULTI EXEC DISCARD WATCH UNWATCH "
|
|
22
|
+
"SUBSCRIBE PSUBSCRIBE SSUBSCRIBE MONITOR BLPOP BRPOP BRPOPLPUSH BLMOVE BLMPOP "
|
|
23
|
+
"BZPOPMIN BZPOPMAX BZMPOP WAIT WAITAOF".split()
|
|
24
|
+
)
|
|
25
|
+
# URL query options arrive as strings; anything else would reach redis-py unchecked.
|
|
26
|
+
_OPTIONS = {
|
|
27
|
+
"protocol": int,
|
|
28
|
+
"socket_timeout": float,
|
|
29
|
+
"socket_connect_timeout": float,
|
|
30
|
+
"client_name": str,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _tokens(query: str) -> list[str]:
|
|
35
|
+
query = query.strip()
|
|
36
|
+
if "\n" in query or "\r" in query:
|
|
37
|
+
raise ValueError("Execute one single-line command at a time.")
|
|
38
|
+
tokens = shlex.split(query)
|
|
39
|
+
if tokens:
|
|
40
|
+
tokens[0] = tokens[0].upper()
|
|
41
|
+
return tokens
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _plain(value: Any) -> Any:
|
|
45
|
+
if isinstance(value, bytes):
|
|
46
|
+
try:
|
|
47
|
+
return value.decode("utf-8")
|
|
48
|
+
except UnicodeDecodeError:
|
|
49
|
+
return "0x" + value.hex()
|
|
50
|
+
if isinstance(value, dict):
|
|
51
|
+
return {str(_plain(k)): _plain(v) for k, v in value.items()}
|
|
52
|
+
if isinstance(value, (list, tuple, set)):
|
|
53
|
+
return [_plain(v) for v in value]
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _cell(value: Any) -> Any:
|
|
58
|
+
return json.dumps(value, ensure_ascii=False) if isinstance(value, (dict, list)) else value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RedisAdapter(DatabaseAdapter):
|
|
62
|
+
supports_multiple_databases = False
|
|
63
|
+
supports_cross_database_queries = False
|
|
64
|
+
supports_stored_procedures = False
|
|
65
|
+
supports_indexes = False
|
|
66
|
+
supports_triggers = False
|
|
67
|
+
supports_process_worker = False
|
|
68
|
+
|
|
69
|
+
def __init__(self, name: str = "Redis") -> None:
|
|
70
|
+
self._name = name
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def name(self) -> str:
|
|
74
|
+
return self._name
|
|
75
|
+
|
|
76
|
+
def normalize_config(self, config: ConnectionConfig) -> ConnectionConfig:
|
|
77
|
+
for name in list(config.extra_options):
|
|
78
|
+
if name.startswith("tls_"):
|
|
79
|
+
config.set_option(name, config.extra_options.pop(name))
|
|
80
|
+
endpoint = config.tcp_endpoint
|
|
81
|
+
if endpoint and not endpoint.database:
|
|
82
|
+
config = config.with_endpoint(database="0")
|
|
83
|
+
# Credentials in URLs must not accidentally select unauthenticated mode.
|
|
84
|
+
if endpoint and config.get_option("auth_type") in (None, "none"):
|
|
85
|
+
config.set_option(
|
|
86
|
+
"auth_type",
|
|
87
|
+
"acl" if endpoint.username else "password" if endpoint.password else "none",
|
|
88
|
+
)
|
|
89
|
+
return config
|
|
90
|
+
|
|
91
|
+
def validate_config(self, config: ConnectionConfig) -> None:
|
|
92
|
+
endpoint = config.tcp_endpoint
|
|
93
|
+
if endpoint is None or int(endpoint.database or "0") < 0:
|
|
94
|
+
raise ValueError("Database must be a non-negative index.")
|
|
95
|
+
|
|
96
|
+
def apply_database_override(self, config: ConnectionConfig, database: str) -> ConnectionConfig:
|
|
97
|
+
return config.with_endpoint(database=database)
|
|
98
|
+
|
|
99
|
+
def connect(self, config: ConnectionConfig) -> Any:
|
|
100
|
+
# Imported here so sqlit startup does not pay for redis-py.
|
|
101
|
+
import redis
|
|
102
|
+
from redis.backoff import NoBackoff
|
|
103
|
+
from redis.retry import Retry
|
|
104
|
+
|
|
105
|
+
endpoint = config.tcp_endpoint
|
|
106
|
+
if endpoint is None:
|
|
107
|
+
raise ValueError("Redis/Valkey requires a TCP endpoint.")
|
|
108
|
+
mode = get_tls_mode(config)
|
|
109
|
+
use_tls = mode not in {"default", "disable"} or urlparse(
|
|
110
|
+
config.connection_url or ""
|
|
111
|
+
).scheme in {"rediss", "valkeys"}
|
|
112
|
+
kwargs: dict[str, Any] = dict(
|
|
113
|
+
host=endpoint.host,
|
|
114
|
+
port=int(endpoint.port or "6379"),
|
|
115
|
+
db=int(endpoint.database or "0"),
|
|
116
|
+
username=endpoint.username or None,
|
|
117
|
+
password=endpoint.password or None,
|
|
118
|
+
decode_responses=False,
|
|
119
|
+
protocol=2,
|
|
120
|
+
socket_connect_timeout=3,
|
|
121
|
+
socket_timeout=3,
|
|
122
|
+
# A retried write could run twice after the server loses its reply.
|
|
123
|
+
retry=Retry(NoBackoff(), 0),
|
|
124
|
+
)
|
|
125
|
+
if use_tls:
|
|
126
|
+
ca, cert, key, key_password = get_tls_files(config)
|
|
127
|
+
kwargs.update(
|
|
128
|
+
ssl=True,
|
|
129
|
+
ssl_cert_reqs=ssl.CERT_NONE if mode == "require" else ssl.CERT_REQUIRED,
|
|
130
|
+
ssl_check_hostname=mode != "verify-ca",
|
|
131
|
+
)
|
|
132
|
+
for name, value in (
|
|
133
|
+
("ssl_ca_certs", ca),
|
|
134
|
+
("ssl_certfile", cert),
|
|
135
|
+
("ssl_keyfile", key),
|
|
136
|
+
("ssl_password", key_password),
|
|
137
|
+
):
|
|
138
|
+
if value:
|
|
139
|
+
kwargs[name] = value
|
|
140
|
+
for name, value in config.extra_options.items():
|
|
141
|
+
if name.startswith("tls_"):
|
|
142
|
+
continue
|
|
143
|
+
if name not in _OPTIONS:
|
|
144
|
+
raise ValueError(
|
|
145
|
+
f"Unsupported connection option '{name}'; use {', '.join(sorted(_OPTIONS))}."
|
|
146
|
+
)
|
|
147
|
+
kwargs[name] = _OPTIONS[name](value)
|
|
148
|
+
client = redis.Redis(**kwargs)
|
|
149
|
+
try:
|
|
150
|
+
client.ping()
|
|
151
|
+
except Exception:
|
|
152
|
+
client.close()
|
|
153
|
+
raise
|
|
154
|
+
return client
|
|
155
|
+
|
|
156
|
+
def execute_test_query(self, conn: Any) -> None:
|
|
157
|
+
conn.ping()
|
|
158
|
+
|
|
159
|
+
def classify_query(self, query: str) -> bool:
|
|
160
|
+
# Every ordinary command has a response, including SET and DEL.
|
|
161
|
+
return True
|
|
162
|
+
|
|
163
|
+
def classify_query_alert(self, query: str) -> Any:
|
|
164
|
+
from sqlit.domains.query.app.alerts import AlertSeverity
|
|
165
|
+
|
|
166
|
+
tokens = _tokens(query)
|
|
167
|
+
command = tokens[0] if tokens else ""
|
|
168
|
+
if command in {"DEL", "UNLINK", "FLUSHDB", "FLUSHALL"}:
|
|
169
|
+
return AlertSeverity.DELETE
|
|
170
|
+
if not command or command in _READ_COMMANDS:
|
|
171
|
+
return AlertSeverity.NONE
|
|
172
|
+
return AlertSeverity.WRITE
|
|
173
|
+
|
|
174
|
+
def execute_query(
|
|
175
|
+
self, conn: Any, query: str, max_rows: int | None = None
|
|
176
|
+
) -> tuple[list[str], list[tuple], bool]:
|
|
177
|
+
tokens = _tokens(query)
|
|
178
|
+
if not tokens:
|
|
179
|
+
return [], [], False
|
|
180
|
+
if tokens[0] in _UNSUPPORTED_COMMANDS:
|
|
181
|
+
raise ValueError("Stateful, subscription and blocking commands are unsupported.")
|
|
182
|
+
upper_tokens = [token.upper() for token in tokens]
|
|
183
|
+
if tokens[0] in {"XREAD", "XREADGROUP"}:
|
|
184
|
+
options_end = (
|
|
185
|
+
upper_tokens.index("STREAMS") if "STREAMS" in upper_tokens else len(tokens)
|
|
186
|
+
)
|
|
187
|
+
if "BLOCK" in upper_tokens[1:options_end]:
|
|
188
|
+
raise ValueError("Blocking stream commands are unsupported.")
|
|
189
|
+
# redis-py picks the reply parser by command name, e.g. "COMMAND COUNT".
|
|
190
|
+
pair = " ".join(upper_tokens[:2])
|
|
191
|
+
if pair in conn.response_callbacks or tokens[0] == "COMMAND":
|
|
192
|
+
tokens[:2] = [pair]
|
|
193
|
+
data = _plain(conn.execute_command(*tokens))
|
|
194
|
+
if isinstance(data, dict):
|
|
195
|
+
columns, rows = ["key", "value"], [(k, _cell(v)) for k, v in data.items()]
|
|
196
|
+
elif isinstance(data, list):
|
|
197
|
+
columns, rows = ["index", "value"], [(i, _cell(v)) for i, v in enumerate(data)]
|
|
198
|
+
else:
|
|
199
|
+
columns, rows = ["result"], [(data,)]
|
|
200
|
+
truncated = max_rows is not None and len(rows) > max_rows
|
|
201
|
+
return columns, rows[:max_rows] if truncated else rows, truncated
|
|
202
|
+
|
|
203
|
+
def execute_non_query(self, conn: Any, query: str) -> int:
|
|
204
|
+
raise ValueError(
|
|
205
|
+
"Redis/Valkey commands return responses; SQL transactions are unsupported."
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def get_databases(self, conn: Any) -> list[str]:
|
|
209
|
+
return [str(conn.connection_pool.connection_kwargs.get("db", 0))]
|
|
210
|
+
|
|
211
|
+
def _nothing(self, conn: Any, *args: Any, **kwargs: Any) -> list:
|
|
212
|
+
return []
|
|
213
|
+
|
|
214
|
+
# sqlit's abstract adapter interface requires these metadata methods.
|
|
215
|
+
get_tables = get_views = get_columns = get_procedures = _nothing
|
|
216
|
+
get_indexes = get_triggers = get_sequences = _nothing
|
|
217
|
+
|
|
218
|
+
def quote_identifier(self, name: str) -> str:
|
|
219
|
+
return shlex.quote(name)
|
|
220
|
+
|
|
221
|
+
def build_select_query(
|
|
222
|
+
self, table: str, limit: int, database: str | None = None, schema: str | None = None
|
|
223
|
+
) -> str:
|
|
224
|
+
raise ValueError("The command console does not map keys to SQL tables.")
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Activate only for the stock sqlit console scripts."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
if Path(sys.argv[0]).name in {"sqlit", "sqlit-tui", ".sqlit-wrapped", "sqlit.exe", "sqlit-tui.exe"}:
|
|
7
|
+
import sqlit
|
|
8
|
+
|
|
9
|
+
from .bootstrap import install, is_tested
|
|
10
|
+
|
|
11
|
+
if not is_tested(sqlit.__version__):
|
|
12
|
+
print(
|
|
13
|
+
f"sqlit-provider-redis is untested with sqlit {sqlit.__version__}; "
|
|
14
|
+
"Redis/Valkey may misbehave.",
|
|
15
|
+
file=sys.stderr,
|
|
16
|
+
)
|
|
17
|
+
try:
|
|
18
|
+
install()
|
|
19
|
+
except Exception as error:
|
|
20
|
+
# A host this shim cannot patch keeps working without Redis/Valkey.
|
|
21
|
+
print(f"Redis/Valkey providers disabled: {error}", file=sys.stderr)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Startup compatibility shim; never changes installed sqlit files."""
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
import sys
|
|
5
|
+
from enum import Enum
|
|
6
|
+
|
|
7
|
+
_installed = False
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def is_tested(version: str) -> bool:
|
|
11
|
+
# shortcut: internal registration and TUI APIs; test this shim before upgrading sqlit.
|
|
12
|
+
try:
|
|
13
|
+
parts = tuple(int(part) for part in version.split(".")[:3])
|
|
14
|
+
except ValueError:
|
|
15
|
+
return False
|
|
16
|
+
return (1, 6, 4) <= parts < (1, 8)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def install() -> None:
|
|
20
|
+
global _installed
|
|
21
|
+
if _installed:
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
from sqlit.domains.connections.domain import config
|
|
25
|
+
from sqlit.domains.connections.providers.catalog import get_supported_db_types
|
|
26
|
+
|
|
27
|
+
# Import everything that can fail on an untested host before changing sqlit's state.
|
|
28
|
+
from .provider import register_providers
|
|
29
|
+
|
|
30
|
+
original_type, original_order = config.DatabaseType, config.DATABASE_TYPE_DISPLAY_ORDER
|
|
31
|
+
members = {item.name: item.value for item in original_type}
|
|
32
|
+
members.update(REDIS="redis", VALKEY="valkey")
|
|
33
|
+
extended = Enum("DatabaseType", members, type=str, module=config.__name__)
|
|
34
|
+
order = [extended(item.value) for item in original_order]
|
|
35
|
+
order += [extended.REDIS, extended.VALKEY]
|
|
36
|
+
|
|
37
|
+
# Another provider may already have imported UI modules with enum aliases.
|
|
38
|
+
for name, module in list(sys.modules.items()):
|
|
39
|
+
if name.startswith("sqlit.") and module is not None:
|
|
40
|
+
if getattr(module, "DatabaseType", None) is original_type:
|
|
41
|
+
module.DatabaseType = extended
|
|
42
|
+
if getattr(module, "DATABASE_TYPE_DISPLAY_ORDER", None) is original_order:
|
|
43
|
+
module.DATABASE_TYPE_DISPLAY_ORDER = order
|
|
44
|
+
|
|
45
|
+
get_supported_db_types()
|
|
46
|
+
register_providers()
|
|
47
|
+
|
|
48
|
+
# Order matters: sqlit's prompt and connection modules bind this function by name
|
|
49
|
+
# when they are imported, so it has to be replaced before any of them load.
|
|
50
|
+
from sqlit.domains.connections.domain import passwords
|
|
51
|
+
|
|
52
|
+
original_uses_db_password = passwords.uses_db_password
|
|
53
|
+
|
|
54
|
+
def uses_db_password(connection):
|
|
55
|
+
if (
|
|
56
|
+
connection.db_type in {"redis", "valkey"}
|
|
57
|
+
and connection.get_option("auth_type", "none") == "none"
|
|
58
|
+
):
|
|
59
|
+
return False
|
|
60
|
+
return original_uses_db_password(connection)
|
|
61
|
+
|
|
62
|
+
passwords.uses_db_password = uses_db_password
|
|
63
|
+
|
|
64
|
+
sys.meta_path.insert(0, _TuiHook())
|
|
65
|
+
_installed = True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _TuiHook:
|
|
69
|
+
"""Swap in the TUI subclass when sqlit imports its TUI, keeping CLI startup fast."""
|
|
70
|
+
|
|
71
|
+
def find_spec(self, name, path=None, target=None):
|
|
72
|
+
if name != "sqlit.domains.shell.app.main":
|
|
73
|
+
return None
|
|
74
|
+
sys.meta_path.remove(self)
|
|
75
|
+
spec = importlib.util.find_spec(name)
|
|
76
|
+
run = spec.loader.exec_module
|
|
77
|
+
|
|
78
|
+
def exec_module(module):
|
|
79
|
+
run(module)
|
|
80
|
+
from .tui import RedisValkeyTUI
|
|
81
|
+
|
|
82
|
+
module.SSMSTUI = RedisValkeyTUI
|
|
83
|
+
|
|
84
|
+
spec.loader.exec_module = exec_module
|
|
85
|
+
return spec
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Register Redis and Valkey using sqlit's existing provider model."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
|
|
5
|
+
from sqlit.domains.connections.providers.adapter_provider import build_adapter_provider
|
|
6
|
+
from sqlit.domains.connections.providers.catalog import get_provider_schema, register_provider
|
|
7
|
+
from sqlit.domains.connections.providers.model import ProviderSpec
|
|
8
|
+
from sqlit.domains.connections.providers.schema_helpers import (
|
|
9
|
+
SSH_FIELDS,
|
|
10
|
+
TLS_FIELDS,
|
|
11
|
+
ConnectionSchema,
|
|
12
|
+
FieldType,
|
|
13
|
+
SchemaField,
|
|
14
|
+
SelectOption,
|
|
15
|
+
_database_field,
|
|
16
|
+
_password_field,
|
|
17
|
+
_port_field,
|
|
18
|
+
_server_field,
|
|
19
|
+
_username_field,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .adapter import RedisAdapter
|
|
23
|
+
|
|
24
|
+
REDIS_SCHEMA = ConnectionSchema(
|
|
25
|
+
db_type="redis",
|
|
26
|
+
display_name="Redis",
|
|
27
|
+
fields=(
|
|
28
|
+
_server_field(),
|
|
29
|
+
_port_field("6379"),
|
|
30
|
+
_database_field("0"),
|
|
31
|
+
SchemaField(
|
|
32
|
+
"auth_type",
|
|
33
|
+
"Authentication",
|
|
34
|
+
field_type=FieldType.SELECT,
|
|
35
|
+
options=(
|
|
36
|
+
SelectOption("none", "None"),
|
|
37
|
+
SelectOption("password", "Password"),
|
|
38
|
+
SelectOption("acl", "ACL username/password"),
|
|
39
|
+
),
|
|
40
|
+
default="none",
|
|
41
|
+
),
|
|
42
|
+
_username_field(required=False),
|
|
43
|
+
_password_field(),
|
|
44
|
+
)
|
|
45
|
+
+ SSH_FIELDS
|
|
46
|
+
+ TLS_FIELDS,
|
|
47
|
+
default_port="6379",
|
|
48
|
+
)
|
|
49
|
+
VALKEY_SCHEMA = replace(REDIS_SCHEMA, db_type="valkey", display_name="Valkey")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _provider_factory(spec):
|
|
53
|
+
return build_adapter_provider(
|
|
54
|
+
spec, get_provider_schema(spec.db_type), RedisAdapter(spec.display_name)
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def register_providers():
|
|
59
|
+
for schema in (REDIS_SCHEMA, VALKEY_SCHEMA):
|
|
60
|
+
register_provider(
|
|
61
|
+
ProviderSpec(
|
|
62
|
+
db_type=schema.db_type,
|
|
63
|
+
display_name=schema.display_name,
|
|
64
|
+
schema_path=(__name__, f"{schema.db_type.upper()}_SCHEMA"),
|
|
65
|
+
default_port="6379",
|
|
66
|
+
url_schemes=(schema.db_type, schema.db_type + "s"),
|
|
67
|
+
provider_factory=_provider_factory,
|
|
68
|
+
)
|
|
69
|
+
)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Keep SQL handling upstream; override the native command path in a subclass."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import inspect
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from sqlit.domains.connections.app.session import ConnectionSession
|
|
9
|
+
from sqlit.domains.query.app.alerts import (
|
|
10
|
+
CONNECTION_ALERT_OPTION,
|
|
11
|
+
DATABASE_ALERT_SETTING,
|
|
12
|
+
lookup_database_override,
|
|
13
|
+
resolve_alert_mode,
|
|
14
|
+
should_confirm,
|
|
15
|
+
)
|
|
16
|
+
from sqlit.domains.shell.app.main import SSMSTUI
|
|
17
|
+
from sqlit.shared.ui.screens.confirm import ConfirmScreen
|
|
18
|
+
from textual.css.query import NoMatches
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RedisValkeyTUI(SSMSTUI):
|
|
22
|
+
CSS_PATH = Path(inspect.getfile(SSMSTUI)).with_name("main.css")
|
|
23
|
+
|
|
24
|
+
def _native(self) -> bool:
|
|
25
|
+
return self.current_provider is not None and self.current_provider.metadata.db_type in {
|
|
26
|
+
"redis",
|
|
27
|
+
"valkey",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
def watch_current_provider(self, old_value, new_value) -> None:
|
|
31
|
+
super().watch_current_provider(old_value, new_value)
|
|
32
|
+
if not getattr(self, "_screen_stack", None):
|
|
33
|
+
return
|
|
34
|
+
try:
|
|
35
|
+
self.query_input.language = None if self._native() else "sql"
|
|
36
|
+
except NoMatches:
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
def _get_autocomplete_suggestions(self, text, cursor_pos):
|
|
40
|
+
return [] if self._native() else super()._get_autocomplete_suggestions(text, cursor_pos)
|
|
41
|
+
|
|
42
|
+
def _sql_action(self, name):
|
|
43
|
+
if self._native():
|
|
44
|
+
self.notify("SQL action is unavailable for Redis/Valkey", severity="warning")
|
|
45
|
+
return
|
|
46
|
+
getattr(super(), name)()
|
|
47
|
+
|
|
48
|
+
def action_format_query(self):
|
|
49
|
+
self._sql_action("action_format_query")
|
|
50
|
+
|
|
51
|
+
def action_delete_row(self):
|
|
52
|
+
self._sql_action("action_delete_row")
|
|
53
|
+
|
|
54
|
+
def action_edit_cell(self):
|
|
55
|
+
self._sql_action("action_edit_cell")
|
|
56
|
+
|
|
57
|
+
def action_execute_query_atomic(self):
|
|
58
|
+
self._sql_action("action_execute_query_atomic")
|
|
59
|
+
|
|
60
|
+
def action_execute_single_statement(self):
|
|
61
|
+
if self._native():
|
|
62
|
+
self._execute_query_common(keep_insert_mode=False)
|
|
63
|
+
else:
|
|
64
|
+
super().action_execute_single_statement()
|
|
65
|
+
|
|
66
|
+
def _maybe_confirm_query(self, query, proceed):
|
|
67
|
+
if not self._native():
|
|
68
|
+
return super()._maybe_confirm_query(query, proceed)
|
|
69
|
+
config = self.current_config
|
|
70
|
+
database = self._get_effective_database()
|
|
71
|
+
overrides = self.services.settings_store.get(DATABASE_ALERT_SETTING) or {}
|
|
72
|
+
database_override = lookup_database_override(overrides, config.name, database)
|
|
73
|
+
mode, _ = resolve_alert_mode(
|
|
74
|
+
global_mode=self.services.runtime.query_alert_mode or 0,
|
|
75
|
+
connection_option=config.get_option(CONNECTION_ALERT_OPTION),
|
|
76
|
+
database_override=database_override,
|
|
77
|
+
)
|
|
78
|
+
try:
|
|
79
|
+
severity = self.current_provider.dialect.classify_query_alert(query)
|
|
80
|
+
except ValueError as error:
|
|
81
|
+
self.notify(str(error), severity="error")
|
|
82
|
+
return
|
|
83
|
+
if should_confirm(mode, severity):
|
|
84
|
+
self.push_screen(
|
|
85
|
+
ConfirmScreen("Confirm command", query, yes_label="Yes", no_label="No"),
|
|
86
|
+
lambda confirmed: proceed() if confirmed else None,
|
|
87
|
+
)
|
|
88
|
+
else:
|
|
89
|
+
proceed()
|
|
90
|
+
|
|
91
|
+
async def _run_query_async(self, query, keep_insert_mode):
|
|
92
|
+
if not self._native():
|
|
93
|
+
return await super()._run_query_async(query, keep_insert_mode)
|
|
94
|
+
|
|
95
|
+
provider = self.current_provider
|
|
96
|
+
config = self.current_config
|
|
97
|
+
target = self._query_target_database or self._get_effective_database()
|
|
98
|
+
self._query_target_database = None
|
|
99
|
+
if target:
|
|
100
|
+
config = provider.apply_database_override(config, target)
|
|
101
|
+
|
|
102
|
+
def execute():
|
|
103
|
+
with ConnectionSession.create(
|
|
104
|
+
config, provider_factory=self.services.provider_factory
|
|
105
|
+
) as session:
|
|
106
|
+
return session.provider.query_executor.execute_query(
|
|
107
|
+
session.connection,
|
|
108
|
+
query,
|
|
109
|
+
self.services.runtime.max_rows or 10000,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
start = time.perf_counter()
|
|
114
|
+
columns, rows, truncated = await asyncio.to_thread(execute)
|
|
115
|
+
elapsed_ms = (time.perf_counter() - start) * 1000
|
|
116
|
+
try:
|
|
117
|
+
await asyncio.to_thread(self._save_query_history, config, query)
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
self._pending_result_table_info = None
|
|
121
|
+
await self._display_query_results(columns, rows, len(rows), truncated, elapsed_ms)
|
|
122
|
+
if keep_insert_mode:
|
|
123
|
+
self._restore_insert_mode()
|
|
124
|
+
except Exception as error:
|
|
125
|
+
self._display_query_error(str(error))
|
|
126
|
+
finally:
|
|
127
|
+
self._stop_query_spinner()
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sqlit-provider-redis
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Redis and Valkey command console provider for sqlit
|
|
5
|
+
Project-URL: Repository, https://github.com/sudosubin/sqlit-provider-redis
|
|
6
|
+
Project-URL: Issues, https://github.com/sudosubin/sqlit-provider-redis/issues
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Database
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: redis<9,>=5
|
|
20
|
+
Provides-Extra: host
|
|
21
|
+
Requires-Dist: sqlit-tui<1.8,>=1.6.4; extra == 'host'
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
|
|
24
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
25
|
+
Requires-Dist: ruff<0.18,>=0.17; extra == 'test'
|
|
26
|
+
Requires-Dist: trustme; extra == 'test'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# sqlit-provider-redis
|
|
30
|
+
|
|
31
|
+
Redis and Valkey command console for [sqlit](https://github.com/Maxteabag/sqlit).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
Install next to sqlit (1.6.4–1.7.x):
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install sqlit-provider-redis
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
sqlit connections add redis --name cache --server redis.example.com \
|
|
45
|
+
--auth-type password --password-stdin
|
|
46
|
+
sqlit query -c cache -q 'GET example'
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`--auth-type` is `none`, `password` or `acl` (with `--username`). Use `valkey`
|
|
50
|
+
instead of `redis` for Valkey.
|
|
51
|
+
|
|
52
|
+
## Stored configuration
|
|
53
|
+
|
|
54
|
+
`~/.config/sqlit/connections.json`:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"name": "cache",
|
|
59
|
+
"db_type": "redis",
|
|
60
|
+
"options": { "auth_type": "password", "tls_mode": "default" },
|
|
61
|
+
"endpoint": {
|
|
62
|
+
"kind": "tcp",
|
|
63
|
+
"host": "redis.example.com",
|
|
64
|
+
"port": "6379",
|
|
65
|
+
"database": "0",
|
|
66
|
+
"username": "",
|
|
67
|
+
"password": null
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The password is stored in the system keyring as `<name>:db`, never in this file.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
pip install -e ".[host,test]"
|
|
78
|
+
pytest
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Tests also need `redis-server` and `valkey-server` on `PATH`.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
sqlit_provider_redis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
sqlit_provider_redis/adapter.py,sha256=Jf0HF5UaGi1Ez75hsenPsxDG8N87MCrpLgHkElhUoE8,8685
|
|
3
|
+
sqlit_provider_redis/autoload.py,sha256=hbkAEwOkSYRfmO4idh4ULlkdsr35up69m1T9qUJ96Fo,690
|
|
4
|
+
sqlit_provider_redis/bootstrap.py,sha256=QI2ZkNyWojC45JANCmKc0-5-TEOn0XmXURc4JcIPt0c,2935
|
|
5
|
+
sqlit_provider_redis/provider.py,sha256=W93ciPs48mtf0Njx60lCLxEeQD2gQIrZz2bUNzv0Fgc,2038
|
|
6
|
+
sqlit_provider_redis/tui.py,sha256=9CLAlJ3ThT8SzBNjGimFLNLqPaGcYBnJDlX1W32aths,4741
|
|
7
|
+
sqlit_provider_redis.pth,sha256=T8UojLh4hMcPWNNpK8w2CVv0GG47JYDGUMkHW3I7c5s,37
|
|
8
|
+
sqlit_provider_redis-0.1.0.dist-info/METADATA,sha256=X0mMVP7xaAdivJiJivHaoWael1d5-fApjHTZrwHzMsU,2137
|
|
9
|
+
sqlit_provider_redis-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
sqlit_provider_redis-0.1.0.dist-info/licenses/LICENSE,sha256=ARNB0P5QvdAUUfrbOC5Rr8KIvTyDveL--GWtlmus3L4,1066
|
|
11
|
+
sqlit_provider_redis-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Subin Kim
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
sqlit_provider_redis.pth
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import sqlit_provider_redis.autoload
|