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
db33studio/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """DB33 Studio: a FastAPI backend for browsing SQL and Redis databases."""
2
+
3
+ __version__ = "1.0.0"
db33studio/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Support `python -m db33studio` as an equivalent of the `db33studio` script."""
2
+
3
+ from .main import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
db33studio/db.py ADDED
@@ -0,0 +1,307 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import sys
5
+ from collections.abc import AsyncGenerator, Iterable, Mapping, Sequence
6
+ from contextlib import asynccontextmanager
7
+ from datetime import date, datetime
8
+ from pathlib import Path
9
+ from typing import Any, TypeAlias
10
+
11
+ import aiosqlite
12
+
13
+
14
+ def _default_data_dir() -> Path:
15
+ """Per-user data directory for the app metadata database."""
16
+ if os.name == "nt":
17
+ base = os.getenv("LOCALAPPDATA")
18
+ root = Path(base) if base else Path.home() / "AppData" / "Local"
19
+ elif sys.platform == "darwin":
20
+ root = Path.home() / "Library" / "Application Support"
21
+ else:
22
+ base = os.getenv("XDG_DATA_HOME")
23
+ root = Path(base) if base else Path.home() / ".local" / "share"
24
+ return root / "db33studio"
25
+
26
+
27
+ DB_PATH = os.getenv("DATABASE_PATH") or str(_default_data_dir() / "app.db")
28
+
29
+ _PRAGMAS = (
30
+ "PRAGMA journal_mode = WAL",
31
+ "PRAGMA foreign_keys = ON",
32
+ "PRAGMA busy_timeout = 5000",
33
+ )
34
+
35
+ _IDENTIFIER_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
36
+
37
+ Row: TypeAlias = dict[str, Any]
38
+
39
+
40
+ async def _open(path: str) -> aiosqlite.Connection:
41
+ parent = Path(path).parent
42
+ if str(parent) not in ("", "."):
43
+ parent.mkdir(parents=True, exist_ok=True)
44
+
45
+ conn = await aiosqlite.connect(path)
46
+ conn.row_factory = aiosqlite.Row
47
+ for pragma in _PRAGMAS:
48
+ await conn.execute(pragma)
49
+ return conn
50
+
51
+
52
+ @asynccontextmanager
53
+ async def db_context(path: str | None = None) -> AsyncGenerator[aiosqlite.Connection]:
54
+ conn = await _open(path or DB_PATH)
55
+ try:
56
+ yield conn
57
+ await conn.commit()
58
+ except BaseException:
59
+ await conn.rollback()
60
+ raise
61
+ finally:
62
+ await conn.close()
63
+
64
+
65
+ async def get_db() -> AsyncGenerator[aiosqlite.Connection]:
66
+ """FastAPI dependency that yields a connection for a single request."""
67
+ async with db_context() as conn:
68
+ yield conn
69
+
70
+
71
+ async def run_migrations(
72
+ migrations_dir: str | Path | None = None,
73
+ state_path: str | Path | None = None,
74
+ ) -> list[str]:
75
+ from .lib import migrations
76
+
77
+ return await migrations.run_migrations(migrations_dir, state_path)
78
+
79
+
80
+ def _adapt(value: Any) -> Any:
81
+ """Convert python values sqlite cannot bind into something it can."""
82
+ if isinstance(value, bool):
83
+ return int(value)
84
+ if isinstance(value, (datetime, date)):
85
+ return value.isoformat()
86
+ if isinstance(value, (dict, list, tuple)):
87
+ return json.dumps(value, default=str)
88
+ return value
89
+
90
+
91
+ def _quote_identifier(name: str) -> str:
92
+ if not _IDENTIFIER_RE.match(name):
93
+ raise ValueError(f"invalid sql identifier: {name!r}")
94
+ return f'"{name}"'
95
+
96
+
97
+ def _build_insert(table: str, columns: Sequence[str]) -> str:
98
+ quoted = ", ".join(_quote_identifier(column) for column in columns)
99
+ placeholders = ", ".join("?" for _ in columns)
100
+ return f"INSERT INTO {_quote_identifier(table)} ({quoted}) VALUES ({placeholders})"
101
+
102
+
103
+ class DB:
104
+ """Async wrapper around one aiosqlite connection.
105
+
106
+ Every statement is committed right away unless it runs inside
107
+ ``DB.transaction()``. Query helpers return plain dicts.
108
+ """
109
+
110
+ connection: aiosqlite.Connection
111
+
112
+ def __init__(self, connection: aiosqlite.Connection):
113
+ self.connection = connection
114
+ self._autocommit = True
115
+
116
+ # -- raw statements ----------------------------------------------------
117
+
118
+ async def execute(self, sql: str, *parameters: Any) -> aiosqlite.Cursor:
119
+ cursor = await self.connection.execute(sql, self._params(parameters))
120
+ await self._maybe_commit()
121
+ return cursor
122
+
123
+ async def executemany(
124
+ self, sql: str, parameters: Iterable[Sequence[Any]]
125
+ ) -> aiosqlite.Cursor:
126
+ rows = [tuple(_adapt(value) for value in row) for row in parameters]
127
+ cursor = await self.connection.executemany(sql, rows)
128
+ await self._maybe_commit()
129
+ return cursor
130
+
131
+
132
+ async def executescript(self, sql: str) -> None:
133
+ await self.connection.executescript(sql)
134
+ await self._maybe_commit()
135
+
136
+ # -- reads -------------------------------------------------------------
137
+
138
+ async def fetchOne(self, sql: str, *parameters: Any) -> Row | None:
139
+ cursor = await self.connection.execute(sql, self._params(parameters))
140
+ try:
141
+ row = await cursor.fetchone()
142
+ finally:
143
+ await cursor.close()
144
+ return None if row is None else dict(row)
145
+
146
+ async def fetchAll(self, sql: str, *parameters: Any) -> list[Row]:
147
+ cursor = await self.connection.execute(sql, self._params(parameters))
148
+ try:
149
+ rows = await cursor.fetchall()
150
+ finally:
151
+ await cursor.close()
152
+ return [dict(row) for row in rows]
153
+
154
+ async def fetchMany(self, sql: str, size: int, *parameters: Any) -> list[Row]:
155
+ if size <= 0:
156
+ raise ValueError("size must be a positive integer")
157
+
158
+ cursor = await self.connection.execute(sql, self._params(parameters))
159
+ try:
160
+ rows = await cursor.fetchmany(size)
161
+ finally:
162
+ await cursor.close()
163
+ return [dict(row) for row in rows]
164
+
165
+ async def iterate(self, sql: str, *parameters: Any, size: int = 256) -> AsyncGenerator[Row]:
166
+ """Stream rows in chunks instead of materialising the whole result."""
167
+ if size <= 0:
168
+ raise ValueError("size must be a positive integer")
169
+
170
+ cursor = await self.connection.execute(sql, self._params(parameters))
171
+ try:
172
+ while True:
173
+ rows = await cursor.fetchmany(size)
174
+ if not rows:
175
+ break
176
+ for row in rows:
177
+ yield dict(row)
178
+ finally:
179
+ await cursor.close()
180
+
181
+ async def scalar(self, sql: str, *parameters: Any) -> Any:
182
+ """First column of the first row, or None when nothing matches."""
183
+ cursor = await self.connection.execute(sql, self._params(parameters))
184
+ try:
185
+ row = await cursor.fetchone()
186
+ finally:
187
+ await cursor.close()
188
+ return None if row is None else row[0]
189
+
190
+ async def pluck(self, sql: str, *parameters: Any) -> list[Any]:
191
+ """First column of every row."""
192
+ cursor = await self.connection.execute(sql, self._params(parameters))
193
+ try:
194
+ rows = await cursor.fetchall()
195
+ finally:
196
+ await cursor.close()
197
+ return [row[0] for row in rows]
198
+
199
+ async def exists(self, sql: str, *parameters: Any) -> bool:
200
+ return await self.scalar(sql, *parameters) is not None
201
+
202
+ # -- writes ------------------------------------------------------------
203
+
204
+ async def insert(self, table: str, values: Mapping[str, Any]) -> int:
205
+ """Insert one row, return its rowid (the ``id`` column for INTEGER PRIMARY KEY tables)."""
206
+ if not values:
207
+ raise ValueError("nothing to insert")
208
+
209
+ sql = _build_insert(table, list(values))
210
+ cursor = await self.execute(sql, *values.values())
211
+ try:
212
+ return cursor.lastrowid
213
+ finally:
214
+ await cursor.close()
215
+
216
+
217
+ async def insertMany(self, table: str, rows: Sequence[Mapping[str, Any]]) -> int:
218
+ """Insert several rows with the same columns, return the number of rows."""
219
+ if not rows:
220
+ return 0
221
+
222
+ columns = list(rows[0])
223
+ try:
224
+ parameters = [tuple(row[column] for column in columns) for row in rows]
225
+ except KeyError as missing:
226
+ raise ValueError(f"row is missing column {missing.args[0]!r}") from None
227
+
228
+ cursor = await self.executemany(_build_insert(table, columns), parameters)
229
+ try:
230
+ return cursor.rowcount
231
+ finally:
232
+ await cursor.close()
233
+
234
+ # -- sqlite introspection ---------------------------------------------
235
+
236
+ async def tables(self) -> list[str]:
237
+ return await self.pluck(
238
+ "SELECT name FROM sqlite_master "
239
+ "WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
240
+ )
241
+
242
+ async def columns(self, table: str) -> list[Row]:
243
+ cursor = await self.connection.execute(f"PRAGMA table_info({_quote_identifier(table)})")
244
+ try:
245
+ rows = await cursor.fetchall()
246
+ finally:
247
+ await cursor.close()
248
+ return [dict(row) for row in rows]
249
+
250
+ async def pragma(self, name: str, value: str | int | None = None) -> list[Row]:
251
+ """Read a pragma, or set it when a value is given."""
252
+ if not _IDENTIFIER_RE.match(name):
253
+ raise ValueError(f"invalid pragma name: {name!r}")
254
+
255
+ statement = f"PRAGMA {name}"
256
+ if value is not None:
257
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
258
+ raise ValueError(f"unsupported pragma value: {value!r}")
259
+ if isinstance(value, str) and not _IDENTIFIER_RE.match(value):
260
+ raise ValueError(f"invalid pragma value: {value!r}")
261
+ statement = f"{statement} = {value}"
262
+
263
+ cursor = await self.connection.execute(statement)
264
+ try:
265
+ rows = await cursor.fetchall()
266
+ finally:
267
+ await cursor.close()
268
+ return [dict(row) for row in rows]
269
+
270
+ # -- transactions ------------------------------------------------------
271
+
272
+ @property
273
+ def in_transaction(self) -> bool:
274
+ return self.connection.in_transaction
275
+
276
+ @asynccontextmanager
277
+ async def transaction(self) -> AsyncGenerator["DB"]:
278
+ """Group writes into one transaction: commit on success, rollback on error."""
279
+ previous = self._autocommit
280
+ self._autocommit = False
281
+ try:
282
+ yield self
283
+ await self.connection.commit()
284
+ except BaseException:
285
+ await self.connection.rollback()
286
+ raise
287
+ finally:
288
+ self._autocommit = previous
289
+
290
+ async def commit(self) -> None:
291
+ await self.connection.commit()
292
+
293
+ async def rollback(self) -> None:
294
+ await self.connection.rollback()
295
+
296
+ async def close(self) -> None:
297
+ await self.connection.close()
298
+
299
+ # -- internals ---------------------------------------------------------
300
+
301
+ async def _maybe_commit(self) -> None:
302
+ if self._autocommit:
303
+ await self.connection.commit()
304
+
305
+ @staticmethod
306
+ def _params(parameters: Sequence[Any]) -> tuple[Any, ...]:
307
+ return tuple(_adapt(value) for value in parameters)
File without changes