db33studio 1.0.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.
Files changed (49) hide show
  1. db33studio/__init__.py +3 -0
  2. db33studio/__main__.py +6 -0
  3. db33studio/db.py +307 -0
  4. db33studio/engines/__init__.py +0 -0
  5. db33studio/engines/base.py +477 -0
  6. db33studio/engines/mysql.py +802 -0
  7. db33studio/engines/postgres.py +687 -0
  8. db33studio/engines/redis.py +627 -0
  9. db33studio/engines/redis_commands.py +130 -0
  10. db33studio/engines/registry.py +125 -0
  11. db33studio/engines/sqlite.py +576 -0
  12. db33studio/errors.py +9 -0
  13. db33studio/handlers/__init__.py +10 -0
  14. db33studio/handlers/connections.py +94 -0
  15. db33studio/handlers/deps.py +51 -0
  16. db33studio/handlers/index.py +88 -0
  17. db33studio/handlers/query.py +52 -0
  18. db33studio/handlers/redis.py +209 -0
  19. db33studio/handlers/tables.py +76 -0
  20. db33studio/handlers/tabs.py +42 -0
  21. db33studio/jobs/__init__.py +0 -0
  22. db33studio/jobs/projects.py +3 -0
  23. db33studio/lib/__init__.py +0 -0
  24. db33studio/lib/http_errors.py +18 -0
  25. db33studio/lib/migrations.py +159 -0
  26. db33studio/lib/response.py +87 -0
  27. db33studio/logs.py +3 -0
  28. db33studio/main.py +62 -0
  29. db33studio/migrations/0002_connections.down.sql +1 -0
  30. db33studio/migrations/0002_connections.up.sql +15 -0
  31. db33studio/migrations/0003_workspace_tabs.down.sql +2 -0
  32. db33studio/migrations/0003_workspace_tabs.up.sql +26 -0
  33. db33studio/model/__init__.py +0 -0
  34. db33studio/model/connections/__init__.py +0 -0
  35. db33studio/model/connections/dto.py +71 -0
  36. db33studio/model/connections/service.py +225 -0
  37. db33studio/model/tabs/__init__.py +0 -0
  38. db33studio/model/tabs/dto.py +64 -0
  39. db33studio/model/tabs/service.py +63 -0
  40. db33studio/server.py +20 -0
  41. db33studio/webui/assets/index-BcHKGlt4.js +52 -0
  42. db33studio/webui/assets/index-jCXeM1xx.css +2 -0
  43. db33studio/webui/index.html +39 -0
  44. db33studio-1.0.0.dist-info/METADATA +405 -0
  45. db33studio-1.0.0.dist-info/RECORD +49 -0
  46. db33studio-1.0.0.dist-info/WHEEL +5 -0
  47. db33studio-1.0.0.dist-info/entry_points.txt +2 -0
  48. db33studio-1.0.0.dist-info/licenses/LICENSE +202 -0
  49. db33studio-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,477 @@
1
+ """Shared engine contract, value helpers and dialect helpers.
2
+
3
+ An engine wraps exactly one open connection to one target database. Engines are
4
+ created by ``engines.registry.open_engine`` and closed by that same context
5
+ manager; nothing else may hold one open across requests.
6
+
7
+ Every engine module (``sqlite.py``, ``postgres.py``, ``mysql.py``, ``redis.py``)
8
+ lives next to this file and exposes one entry point::
9
+
10
+ async def open(record: Mapping[str, Any], *, timeout: float | None = None) -> Engine
11
+
12
+ ``record`` is a saved connection row: ``engine``, ``host``, ``port``,
13
+ ``username``, ``password``, ``database_name``, ``file_path`` and ``params``
14
+ (JSON text or a dict). ``timeout`` is a connect budget in seconds, or ``None``
15
+ for the driver default.
16
+
17
+ Rules that keep the four engines interchangeable:
18
+
19
+ - Every driver exception becomes ``EngineError`` with code ``QueryFailed``
20
+ (statement failures) or ``ConnectionFailed`` (cannot connect). Messages are
21
+ shown to the user: never put the password or a DSN that contains it in one.
22
+ - Identifiers coming from the UI are validated with ``safe_ident`` and rendered
23
+ with ``quote_ident`` / ``qualified``. Values are always placeholders.
24
+ - Values leaving an engine go through ``jsonify_value`` so the response is
25
+ JSON-safe.
26
+ - This module must stay framework-free: no FastAPI or HTTP imports.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import math
33
+ import re
34
+ from abc import ABC, abstractmethod
35
+ from collections.abc import Mapping, Sequence
36
+ from dataclasses import dataclass, field
37
+ from datetime import date, datetime, time, timedelta
38
+ from decimal import Decimal
39
+ from typing import Any, ClassVar, Literal
40
+ from uuid import UUID
41
+
42
+ #: Largest page ``/table`` accepts.
43
+ MAX_PAGE_SIZE = 1000
44
+
45
+ #: Largest number of rows ``/query`` ever hands back.
46
+ MAX_QUERY_ROWS = 500
47
+
48
+ #: Bytes previewed from a binary value before truncating.
49
+ MAX_BYTES_PREVIEW = 4096
50
+
51
+ #: Driver messages are echoed to the client, but never longer than this.
52
+ MAX_ERROR_LENGTH = 800
53
+
54
+ ENGINE_NAMES = ("postgres", "mysql", "sqlite", "redis")
55
+
56
+ IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*\Z")
57
+
58
+ _DOLLAR_TAG_RE = re.compile(r"\$[A-Za-z_][A-Za-z0-9_]*\$|\$\$")
59
+
60
+ _COMMAND_RE = re.compile(
61
+ r"^\s*(?:--[^\n]*(?:\n|$)|/\*.*?\*/|\s)*([A-Za-z]+)", re.DOTALL
62
+ )
63
+
64
+
65
+ class EngineError(Exception):
66
+ """A target-database failure, already safe to show to the user.
67
+
68
+ ``code`` is the errcode the API returns: ``QueryFailed`` for statements,
69
+ ``ConnectionFailed`` when the connection cannot be opened, ``BadRequest``
70
+ for rejected input and ``NotFound`` for a missing target object.
71
+ """
72
+
73
+ def __init__(self, message: str, code: str = "QueryFailed"):
74
+ super().__init__(message)
75
+ self.message = truncate_message(str(message))
76
+ self.code = code
77
+
78
+ def __str__(self) -> str:
79
+ return self.message
80
+
81
+
82
+ def truncate_message(message: str, limit: int = MAX_ERROR_LENGTH) -> str:
83
+ """Trim a driver message so it fits the error envelope."""
84
+ text = " ".join(str(message).split())
85
+ if len(text) <= limit:
86
+ return text
87
+ return text[: limit - 1] + "\u2026"
88
+
89
+
90
+ # -- identifiers -----------------------------------------------------------
91
+
92
+
93
+ def safe_ident(name: str, field: str = "identifier") -> str:
94
+ """Validate an identifier from the UI and return it unchanged."""
95
+ if not isinstance(name, str) or IDENTIFIER_RE.match(name) is None:
96
+ raise EngineError(f"invalid {field}: {name!r}", code="BadRequest")
97
+ return name
98
+
99
+
100
+ def quote_ident(name: str, engine: str = "sqlite") -> str:
101
+ """Quote an identifier for the dialect (backticks for MySQL)."""
102
+ if engine == "mysql":
103
+ return "`" + name.replace("`", "``") + "`"
104
+ return '"' + name.replace('"', '""') + '"'
105
+
106
+
107
+ def qualified(schema: str | None, table: str, engine: str = "sqlite") -> str:
108
+ """Render ``schema.table`` with both parts quoted."""
109
+ if schema:
110
+ return f"{quote_ident(schema, engine)}.{quote_ident(table, engine)}"
111
+ return quote_ident(table, engine)
112
+
113
+
114
+ # -- sql statements --------------------------------------------------------
115
+
116
+
117
+ def _skip_quoted(sql: str, index: int, quote: str) -> int:
118
+ """Return the index just past the closing quote."""
119
+ length = len(sql)
120
+ position = index + 1
121
+ while position < length:
122
+ char = sql[position]
123
+ if char == "\\" and quote != "`":
124
+ position += 2
125
+ continue
126
+ if char == quote:
127
+ if position + 1 < length and sql[position + 1] == quote:
128
+ position += 2
129
+ continue
130
+ return position + 1
131
+ position += 1
132
+ return length
133
+
134
+
135
+ def split_statements(sql: str) -> list[str]:
136
+ """Split a script on top-level semicolons.
137
+
138
+ Handles single/double/backtick quotes (with backslash escapes and doubled
139
+ quotes), ``--`` and ``/* */`` comments, and PostgreSQL dollar quoting.
140
+ Empty statements are dropped.
141
+ """
142
+ statements: list[str] = []
143
+ length = len(sql)
144
+ index = 0
145
+ start = 0
146
+
147
+ while index < length:
148
+ char = sql[index]
149
+
150
+ if sql.startswith("--", index):
151
+ newline = sql.find("\n", index + 2)
152
+ index = length if newline == -1 else newline + 1
153
+ continue
154
+
155
+ if sql.startswith("/*", index):
156
+ end = sql.find("*/", index + 2)
157
+ index = length if end == -1 else end + 2
158
+ continue
159
+
160
+ if char in ("'", '"', "`"):
161
+ index = _skip_quoted(sql, index, char)
162
+ continue
163
+
164
+ if char == "$":
165
+ tag_match = _DOLLAR_TAG_RE.match(sql, index)
166
+ if tag_match is not None:
167
+ tag = tag_match.group(0)
168
+ end = sql.find(tag, tag_match.end())
169
+ index = length if end == -1 else end + len(tag)
170
+ continue
171
+
172
+ if char == ";":
173
+ statements.append(sql[start:index])
174
+ start = index + 1
175
+
176
+ index += 1
177
+
178
+ statements.append(sql[start:])
179
+ return [statement.strip() for statement in statements if statement.strip()]
180
+
181
+
182
+ def statement_command(statement: str) -> str | None:
183
+ """First keyword of a statement, upper-cased, skipping leading comments."""
184
+ match = _COMMAND_RE.match(statement)
185
+ return None if match is None else match.group(1).upper()
186
+
187
+
188
+ # -- values ----------------------------------------------------------------
189
+
190
+
191
+ def jsonify_value(value: Any) -> Any:
192
+ """Convert a driver value into something ``json.dumps`` accepts."""
193
+ if value is None or isinstance(value, (bool, int, str)):
194
+ return value
195
+ if isinstance(value, float):
196
+ return value if math.isfinite(value) else str(value)
197
+ if isinstance(value, (datetime, date, time)):
198
+ return value.isoformat()
199
+ if isinstance(value, timedelta):
200
+ return str(value)
201
+ if isinstance(value, Decimal):
202
+ return str(value)
203
+ if isinstance(value, UUID):
204
+ return str(value)
205
+ if isinstance(value, (bytes, bytearray, memoryview)):
206
+ raw = bytes(value)
207
+ text = "0x" + raw[:MAX_BYTES_PREVIEW].hex()
208
+ return text + "\u2026" if len(raw) > MAX_BYTES_PREVIEW else text
209
+ if isinstance(value, (dict, list, tuple, set)):
210
+ payload = list(value) if isinstance(value, set) else value
211
+ return json.dumps(payload, default=str)
212
+ return str(value)
213
+
214
+
215
+ def clamp_int(
216
+ value: Any,
217
+ low: int,
218
+ high: int,
219
+ default: int | None = None,
220
+ ) -> int:
221
+ """Coerce ``value`` to an int inside ``[low, high]``."""
222
+ fallback = low if default is None else default
223
+ if value is None or isinstance(value, bool):
224
+ number = fallback
225
+ else:
226
+ try:
227
+ number = int(value)
228
+ except (TypeError, ValueError):
229
+ number = fallback
230
+ return max(low, min(high, number))
231
+
232
+
233
+ def parse_params(raw: Any) -> dict[str, Any]:
234
+ """Read the stored ``params`` JSON column (or an already-parsed dict)."""
235
+ if isinstance(raw, Mapping):
236
+ return dict(raw)
237
+ if isinstance(raw, (str, bytes, bytearray)) and raw:
238
+ try:
239
+ data = json.loads(raw)
240
+ except (ValueError, UnicodeDecodeError):
241
+ return {}
242
+ return dict(data) if isinstance(data, dict) else {}
243
+ return {}
244
+
245
+
246
+ def description_columns(
247
+ description: Sequence[Sequence[Any]] | None,
248
+ ) -> list[dict[str, str]]:
249
+ """Turn a DB-API ``cursor.description`` into ``[{name, data_type}]``.
250
+
251
+ SQLite reports no type code, so those columns fall back to ``text``.
252
+ """
253
+ columns: list[dict[str, str]] = []
254
+ for item in description or ():
255
+ name = str(item[0])
256
+ type_code = item[1] if len(item) > 1 else None
257
+ data_type = type_code if isinstance(type_code, str) and type_code else "text"
258
+ columns.append({"name": name, "data_type": data_type})
259
+ return columns
260
+
261
+
262
+ def rows_from_cursor(
263
+ rows: Sequence[Sequence[Any]],
264
+ description: Sequence[Sequence[Any]] | None,
265
+ ) -> list[dict[str, Any]]:
266
+ """Map cursor rows onto ``{column_name: jsonified value}`` dicts."""
267
+ names = [str(item[0]) for item in description or ()]
268
+ result: list[dict[str, Any]] = []
269
+ for row in rows:
270
+ values = tuple(row)
271
+ result.append(
272
+ {
273
+ name: jsonify_value(values[position]) if position < len(values) else None
274
+ for position, name in enumerate(names)
275
+ }
276
+ )
277
+ return result
278
+
279
+
280
+ # -- result shapes ---------------------------------------------------------
281
+
282
+
283
+ @dataclass
284
+ class ColumnInfo:
285
+ """One column, covering both the data and the structure response shapes."""
286
+
287
+ name: str
288
+ data_type: str
289
+ nullable: bool = True
290
+ default: str | None = None
291
+ is_primary_key: bool = False
292
+ is_foreign_key: bool = False
293
+ references: str | None = None
294
+ is_indexed: bool = False
295
+ check: str | None = None
296
+ comment: str | None = None
297
+
298
+ def as_table_column(self) -> dict[str, Any]:
299
+ return {
300
+ "name": self.name,
301
+ "data_type": self.data_type,
302
+ "nullable": self.nullable,
303
+ "default": self.default,
304
+ "is_primary_key": self.is_primary_key,
305
+ "is_foreign_key": self.is_foreign_key,
306
+ "references": self.references,
307
+ }
308
+
309
+ def as_structure_column(self) -> dict[str, Any]:
310
+ return {
311
+ "name": self.name,
312
+ "data_type": self.data_type,
313
+ "nullable": self.nullable,
314
+ "default": self.default,
315
+ "is_primary_key": self.is_primary_key,
316
+ "is_foreign_key": self.is_foreign_key,
317
+ "is_indexed": self.is_indexed,
318
+ "check": self.check,
319
+ "comment": self.comment,
320
+ }
321
+
322
+
323
+ @dataclass
324
+ class TableSummary:
325
+ name: str
326
+ kind: Literal["table", "view"] = "table"
327
+ row_estimate: int | None = None
328
+
329
+ def to_dict(self) -> dict[str, Any]:
330
+ return {
331
+ "name": self.name,
332
+ "kind": self.kind,
333
+ "row_estimate": self.row_estimate,
334
+ }
335
+
336
+
337
+ @dataclass
338
+ class EnumType:
339
+ name: str
340
+ values: list[str] = field(default_factory=list)
341
+
342
+ def to_dict(self) -> dict[str, Any]:
343
+ return {"name": self.name, "values": list(self.values)}
344
+
345
+
346
+ @dataclass
347
+ class SchemaInfo:
348
+ name: str
349
+ tables: list[TableSummary] = field(default_factory=list)
350
+ enums: list[EnumType] = field(default_factory=list)
351
+
352
+ def to_dict(self) -> dict[str, Any]:
353
+ return {
354
+ "name": self.name,
355
+ "tables": [table.to_dict() for table in self.tables],
356
+ "enums": [enum.to_dict() for enum in self.enums],
357
+ }
358
+
359
+
360
+ @dataclass
361
+ class TreeResult:
362
+ engine: str
363
+ database: str | None
364
+ server_version: str
365
+ schemas: list[SchemaInfo] = field(default_factory=list)
366
+ stats: dict[str, Any] = field(
367
+ default_factory=lambda: {"tables": 0, "views": 0, "enums": 0, "size_bytes": None}
368
+ )
369
+
370
+ def to_dict(self) -> dict[str, Any]:
371
+ return {
372
+ "engine": self.engine,
373
+ "database": self.database,
374
+ "server_version": self.server_version,
375
+ "schemas": [schema.to_dict() for schema in self.schemas],
376
+ "stats": dict(self.stats),
377
+ }
378
+
379
+
380
+ @dataclass
381
+ class TableData:
382
+ columns: list[ColumnInfo]
383
+ rows: list[dict[str, Any]]
384
+ total_rows: int
385
+ limit: int
386
+ offset: int
387
+ duration_ms: float = 0.0
388
+
389
+ def to_dict(self) -> dict[str, Any]:
390
+ return {
391
+ "columns": [column.as_table_column() for column in self.columns],
392
+ "rows": self.rows,
393
+ "total_rows": self.total_rows,
394
+ "returned_rows": len(self.rows),
395
+ "limit": self.limit,
396
+ "offset": self.offset,
397
+ "duration_ms": self.duration_ms,
398
+ }
399
+
400
+
401
+ @dataclass
402
+ class StatementResult:
403
+ columns: list[dict[str, str]] = field(default_factory=list)
404
+ rows: list[dict[str, Any]] = field(default_factory=list)
405
+ row_count: int = 0
406
+ duration_ms: float = 0.0
407
+ command: str | None = None
408
+ truncated: bool = False
409
+
410
+ def to_dict(self) -> dict[str, Any]:
411
+ return {
412
+ "columns": list(self.columns),
413
+ "rows": self.rows,
414
+ "row_count": self.row_count,
415
+ "duration_ms": self.duration_ms,
416
+ "command": self.command,
417
+ "truncated": self.truncated,
418
+ }
419
+
420
+
421
+ # -- the engine ------------------------------------------------------------
422
+
423
+
424
+ class Engine(ABC):
425
+ """One open connection to a target database.
426
+
427
+ ``server_version`` is the display string used by the schema tree;
428
+ ``version()`` returns the same string, kept async because networked drivers
429
+ query it. Implementations should set ``self._server_version`` before their
430
+ module-level ``open()`` returns.
431
+ """
432
+
433
+ name: ClassVar[str] = ""
434
+
435
+ def __init__(self, *, database: str | None = None, server_version: str = "") -> None:
436
+ self.database = database
437
+ self._server_version = server_version
438
+
439
+ @property
440
+ def engine(self) -> str:
441
+ return self.name
442
+
443
+ @property
444
+ def server_version(self) -> str:
445
+ return self._server_version
446
+
447
+ async def version(self) -> str:
448
+ return self._server_version
449
+
450
+ @abstractmethod
451
+ async def close(self) -> None:
452
+ """Release the connection. Must be safe to call twice."""
453
+
454
+ @abstractmethod
455
+ async def tree(self) -> TreeResult:
456
+ """Schemas, tables, views and enum types visible to the user."""
457
+
458
+ @abstractmethod
459
+ async def table_data(
460
+ self,
461
+ schema: str | None,
462
+ table: str,
463
+ *,
464
+ where: str | None = None,
465
+ order_by: str | None = None,
466
+ limit: int = 100,
467
+ offset: int = 0,
468
+ ) -> TableData:
469
+ """A page of rows, the column header and the count for the same filter."""
470
+
471
+ @abstractmethod
472
+ async def table_structure(self, schema: str | None, table: str) -> dict[str, Any]:
473
+ """DDL, columns, constraints, indexes and foreign keys as plain dicts."""
474
+
475
+ @abstractmethod
476
+ async def run_sql(self, sql: str, limit: int = 1000) -> list[StatementResult]:
477
+ """Run a script; one result per statement, rows capped at ``limit``."""