dorm-plg 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.
dorm/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ __version__ = "0.1.0"
2
+
3
+
4
+ def get_url_prefix() -> str:
5
+ """Return the URL prefix for DORM, read from settings.DORM_URL (default: '__dorm__')."""
6
+ from django.conf import settings
7
+ return getattr(settings, "DORM_URL_NAME", "__dorm__")
dorm/apps.py ADDED
@@ -0,0 +1,16 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DormConfig(AppConfig):
5
+ name = "dorm"
6
+ default_auto_field = "django.db.models.BigAutoField"
7
+
8
+ def ready(self):
9
+ import logging
10
+ from django.conf import settings
11
+
12
+ if not settings.DEBUG:
13
+ logging.getLogger("dorm").warning(
14
+ "DORM is installed but DEBUG=False — all requests will return 404. "
15
+ "Consider removing 'dorm' from INSTALLED_APPS in production."
16
+ )
dorm/exceptions.py ADDED
@@ -0,0 +1,6 @@
1
+ class DormNotDebugError(Exception):
2
+ pass
3
+
4
+
5
+ class DormExecutionError(Exception):
6
+ pass
dorm/executor.py ADDED
@@ -0,0 +1,63 @@
1
+ import ast
2
+ import traceback as tb
3
+
4
+
5
+ def _build_namespace() -> dict:
6
+ from django.apps import apps
7
+ from django.db.models import Avg, Count, F, Max, Min, OuterRef, Q, Subquery, Sum, Value
8
+
9
+ namespace: dict = {
10
+ "Q": Q, "F": F,
11
+ "Count": Count, "Sum": Sum, "Avg": Avg, "Max": Max, "Min": Min,
12
+ "Value": Value, "OuterRef": OuterRef, "Subquery": Subquery,
13
+ }
14
+ for model in apps.get_models():
15
+ namespace[model.__name__] = model
16
+ return namespace
17
+
18
+
19
+ def execute(code: str, extra_locals: dict | None = None) -> dict:
20
+ """
21
+ Execute a multi-line ORM code string.
22
+
23
+ The last expression in the code block is captured as the result,
24
+ mimicking REPL behaviour. Returns:
25
+ {"success": True, "result": <any>}
26
+ {"success": False, "error_type": str, "error": str, "traceback": str}
27
+ """
28
+ namespace = _build_namespace()
29
+ if extra_locals:
30
+ namespace.update(extra_locals)
31
+
32
+ try:
33
+ tree = ast.parse(code)
34
+ except SyntaxError as e:
35
+ return {
36
+ "success": False,
37
+ "error_type": "SyntaxError",
38
+ "error": str(e),
39
+ "traceback": "",
40
+ }
41
+
42
+ try:
43
+ result = None
44
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
45
+ # Split: exec all statements, eval the last expression
46
+ exec_tree = ast.Module(body=tree.body[:-1], type_ignores=[])
47
+ eval_tree = ast.Expression(body=tree.body[-1].value)
48
+ ast.fix_missing_locations(exec_tree)
49
+ ast.fix_missing_locations(eval_tree)
50
+ exec(compile(exec_tree, "<dorm>", "exec"), namespace)
51
+ result = eval(compile(eval_tree, "<dorm>", "eval"), namespace)
52
+ else:
53
+ exec(compile(tree, "<dorm>", "exec"), namespace)
54
+
55
+ return {"success": True, "result": result}
56
+
57
+ except Exception as e:
58
+ return {
59
+ "success": False,
60
+ "error_type": type(e).__name__,
61
+ "error": str(e),
62
+ "traceback": tb.format_exc(),
63
+ }
@@ -0,0 +1,383 @@
1
+ /* DORM — Django ORM Playground */
2
+
3
+ :root {
4
+ --bg: #e0e0e0;
5
+ --surface: #ffffff;
6
+ --border: #cccccc;
7
+ --header-bg: #111111;
8
+ --header-text: #ffffff;
9
+ --pane-bar-bg: #f4f4f4;
10
+ --pane-bar-border: #e0e0e0;
11
+ --text: #000000;
12
+ --text-muted: #666666;
13
+ --divider: #c0c0c0;
14
+ --divider-hover: #555555;
15
+ --btn-bg: #000000;
16
+ --btn-text: #ffffff;
17
+ --btn-hover: #333333;
18
+ --th-bg: #1a1a1a;
19
+ --th-text: #ffffff;
20
+ --td-border: #eeeeee;
21
+ --row-hover: #fafafa;
22
+ --value-bg: #f8f8f8;
23
+ --error-bg: #fff8f8;
24
+ --error-border: #e0b0b0;
25
+ --error-text: #cc0000;
26
+ --kbd-bg: rgba(255,255,255,0.18);
27
+ }
28
+
29
+ *, *::before, *::after {
30
+ box-sizing: border-box;
31
+ margin: 0;
32
+ padding: 0;
33
+ }
34
+
35
+ html, body {
36
+ height: 100%;
37
+ overflow: hidden;
38
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
39
+ background: var(--bg);
40
+ color: var(--text);
41
+ }
42
+
43
+ /* ── Root shell ──────────────────────────────────────────── */
44
+
45
+ .dorm-root {
46
+ display: flex;
47
+ flex-direction: column;
48
+ height: 100vh;
49
+ overflow: hidden;
50
+ }
51
+
52
+ /* ── Header ──────────────────────────────────────────────── */
53
+
54
+ .dorm-header {
55
+ flex: 0 0 auto;
56
+ display: flex;
57
+ align-items: center;
58
+ justify-content: space-between;
59
+ padding: 0 1rem;
60
+ height: 44px;
61
+ background: var(--header-bg);
62
+ color: var(--header-text);
63
+ }
64
+
65
+ .dorm-logo {
66
+ font-size: 0.95rem;
67
+ font-weight: 700;
68
+ letter-spacing: 0.18em;
69
+ color: var(--header-text);
70
+ }
71
+
72
+ /* ── Layout toggle buttons ───────────────────────────────── */
73
+
74
+ .dorm-layout-toggle {
75
+ display: flex;
76
+ gap: 2px;
77
+ background: rgba(255,255,255,0.08);
78
+ border-radius: 5px;
79
+ padding: 3px;
80
+ }
81
+
82
+ .dorm-layout-opt {
83
+ display: flex;
84
+ align-items: center;
85
+ justify-content: center;
86
+ width: 30px;
87
+ height: 26px;
88
+ background: transparent;
89
+ border: none;
90
+ border-radius: 3px;
91
+ color: #888;
92
+ cursor: pointer;
93
+ transition: background 0.1s, color 0.1s;
94
+ }
95
+
96
+ .dorm-layout-opt:hover {
97
+ color: #ccc;
98
+ }
99
+
100
+ .dorm-layout-opt.active {
101
+ background: #ffffff;
102
+ color: #000000;
103
+ }
104
+
105
+ /* ── Split layout container ──────────────────────────────── */
106
+
107
+ .dorm-layout {
108
+ flex: 1;
109
+ display: flex;
110
+ min-height: 0;
111
+ gap: 0;
112
+ }
113
+
114
+ .dorm-layout[data-dir="row"] { flex-direction: row; }
115
+ .dorm-layout[data-dir="col"] { flex-direction: column; }
116
+
117
+ /* ── Panes ───────────────────────────────────────────────── */
118
+
119
+ .dorm-pane {
120
+ display: flex;
121
+ flex-direction: column;
122
+ overflow: hidden;
123
+ min-width: 0;
124
+ min-height: 0;
125
+ background: var(--surface);
126
+ }
127
+
128
+ #dorm-pane-a { flex: 0 0 50%; }
129
+ #dorm-pane-b { flex: 1 1 0; }
130
+
131
+ /* ── Pane top bar ────────────────────────────────────────── */
132
+
133
+ .dorm-pane-bar {
134
+ flex: 0 0 auto;
135
+ display: flex;
136
+ align-items: center;
137
+ justify-content: space-between;
138
+ padding: 0 0.875rem;
139
+ height: 36px;
140
+ background: var(--pane-bar-bg);
141
+ border-bottom: 1px solid var(--pane-bar-border);
142
+ }
143
+
144
+ .dorm-pane-label {
145
+ font-size: 0.72rem;
146
+ font-weight: 600;
147
+ letter-spacing: 0.1em;
148
+ text-transform: uppercase;
149
+ color: var(--text-muted);
150
+ }
151
+
152
+ /* ── Editor (input pane) ─────────────────────────────────── */
153
+
154
+ #dorm-form {
155
+ flex: 1;
156
+ display: flex;
157
+ flex-direction: column;
158
+ min-height: 0;
159
+ }
160
+
161
+ .dorm-editor {
162
+ flex: 1;
163
+ width: 100%;
164
+ padding: 0.875rem 1rem;
165
+ background: var(--surface);
166
+ color: var(--text);
167
+ font-family: "JetBrains Mono", "Fira Code", Consolas, "Courier New", monospace;
168
+ font-size: 0.875rem;
169
+ line-height: 1.65;
170
+ border: none;
171
+ outline: none;
172
+ resize: none;
173
+ }
174
+
175
+ /* ── Verbose names checkbox ──────────────────────────────── */
176
+
177
+ .dorm-verbose-label {
178
+ display: flex;
179
+ align-items: center;
180
+ gap: 0.35rem;
181
+ font-size: 0.72rem;
182
+ font-weight: 500;
183
+ color: var(--text-muted);
184
+ cursor: pointer;
185
+ user-select: none;
186
+ }
187
+
188
+ .dorm-verbose-label input[type="checkbox"] {
189
+ accent-color: var(--btn-bg);
190
+ cursor: pointer;
191
+ width: 13px;
192
+ height: 13px;
193
+ }
194
+
195
+ /* ── Run button ──────────────────────────────────────────── */
196
+
197
+ .dorm-run-btn {
198
+ display: inline-flex;
199
+ align-items: center;
200
+ gap: 0.45rem;
201
+ padding: 0.3rem 0.9rem;
202
+ background: var(--btn-bg);
203
+ color: var(--btn-text);
204
+ border: none;
205
+ border-radius: 4px;
206
+ font-size: 0.8rem;
207
+ font-weight: 600;
208
+ cursor: pointer;
209
+ transition: background 0.12s;
210
+ }
211
+
212
+ .dorm-run-btn:hover { background: var(--btn-hover); }
213
+ .dorm-run-btn:active { background: #555; }
214
+
215
+ kbd {
216
+ font-size: 0.7rem;
217
+ padding: 0.1em 0.35em;
218
+ background: var(--kbd-bg);
219
+ border-radius: 3px;
220
+ font-family: inherit;
221
+ }
222
+
223
+ /* ── Divider ─────────────────────────────────────────────── */
224
+
225
+ .dorm-divider {
226
+ flex: 0 0 5px;
227
+ background: var(--divider);
228
+ transition: background 0.12s;
229
+ position: relative;
230
+ }
231
+
232
+ .dorm-layout[data-dir="row"] .dorm-divider { cursor: col-resize; }
233
+ .dorm-layout[data-dir="col"] .dorm-divider { cursor: row-resize; }
234
+
235
+ .dorm-divider:hover { background: var(--divider-hover); }
236
+
237
+ /* Expand hit area by 4px on each side */
238
+ .dorm-layout[data-dir="row"] .dorm-divider::after {
239
+ content: "";
240
+ position: absolute;
241
+ inset: 0 -4px;
242
+ }
243
+ .dorm-layout[data-dir="col"] .dorm-divider::after {
244
+ content: "";
245
+ position: absolute;
246
+ inset: -4px 0;
247
+ }
248
+
249
+ /* ── Result body ─────────────────────────────────────────── */
250
+
251
+ .dorm-result-body {
252
+ flex: 1;
253
+ overflow: auto;
254
+ padding: 0.875rem 1rem;
255
+ }
256
+
257
+ /* ── Result bar (meta + export buttons) ─────────────────── */
258
+
259
+ .dorm-result-bar {
260
+ display: flex;
261
+ align-items: center;
262
+ justify-content: space-between;
263
+ margin-bottom: 0.5rem;
264
+ }
265
+
266
+ .dorm-result-meta {
267
+ font-size: 0.75rem;
268
+ color: var(--text-muted);
269
+ margin-bottom: 0.5rem;
270
+ }
271
+
272
+ .dorm-export-btns {
273
+ display: flex;
274
+ gap: 4px;
275
+ }
276
+
277
+ .dorm-export-btn {
278
+ padding: 0.2rem 0.6rem;
279
+ background: transparent;
280
+ color: var(--text-muted);
281
+ border: 1px solid var(--border);
282
+ border-radius: 3px;
283
+ font-size: 0.72rem;
284
+ font-weight: 600;
285
+ cursor: pointer;
286
+ transition: background 0.1s, color 0.1s, border-color 0.1s;
287
+ }
288
+
289
+ .dorm-export-btn:hover {
290
+ background: var(--btn-bg);
291
+ color: var(--btn-text);
292
+ border-color: var(--btn-bg);
293
+ }
294
+
295
+ .dorm-table-wrapper {
296
+ overflow-x: auto;
297
+ border: 1px solid var(--border);
298
+ border-radius: 4px;
299
+ }
300
+
301
+ .dorm-table {
302
+ width: 100%;
303
+ border-collapse: collapse;
304
+ font-size: 0.8rem;
305
+ }
306
+
307
+ .dorm-table th {
308
+ padding: 0.5rem 0.875rem;
309
+ background: var(--th-bg);
310
+ color: var(--th-text);
311
+ text-align: left;
312
+ font-weight: 600;
313
+ white-space: nowrap;
314
+ border-bottom: none;
315
+ }
316
+
317
+ .dorm-table td {
318
+ padding: 0.4rem 0.875rem;
319
+ border-bottom: 1px solid var(--td-border);
320
+ color: var(--text);
321
+ font-family: "JetBrains Mono", Consolas, monospace;
322
+ white-space: nowrap;
323
+ }
324
+
325
+ .dorm-table tr:last-child td { border-bottom: none; }
326
+ .dorm-table tr:hover td { background: var(--row-hover); }
327
+
328
+ /* ── Value output ────────────────────────────────────────── */
329
+
330
+ .dorm-value {
331
+ padding: 0.875rem 1rem;
332
+ background: var(--value-bg);
333
+ border: 1px solid var(--border);
334
+ border-radius: 4px;
335
+ color: var(--text);
336
+ font-family: "JetBrains Mono", Consolas, monospace;
337
+ font-size: 0.8rem;
338
+ white-space: pre-wrap;
339
+ word-break: break-word;
340
+ }
341
+
342
+ /* ── Error output ────────────────────────────────────────── */
343
+
344
+ .dorm-error {
345
+ padding: 0.875rem 1rem;
346
+ background: var(--error-bg);
347
+ border: 1px solid var(--error-border);
348
+ border-radius: 4px;
349
+ }
350
+
351
+ .dorm-error-title {
352
+ font-family: "JetBrains Mono", Consolas, monospace;
353
+ font-size: 0.8rem;
354
+ font-weight: 700;
355
+ color: var(--error-text);
356
+ margin-bottom: 0.5rem;
357
+ }
358
+
359
+ .dorm-error-traceback {
360
+ font-family: "JetBrains Mono", Consolas, monospace;
361
+ font-size: 0.75rem;
362
+ color: var(--error-text);
363
+ white-space: pre-wrap;
364
+ word-break: break-word;
365
+ opacity: 0.75;
366
+ }
367
+
368
+ /* ── Drag state ──────────────────────────────────────────── */
369
+
370
+ body.is-resizing-row {
371
+ cursor: col-resize !important;
372
+ user-select: none;
373
+ }
374
+ body.is-resizing-col {
375
+ cursor: row-resize !important;
376
+ user-select: none;
377
+ }
378
+
379
+ /* Prevent pane content from stealing the cursor during drag */
380
+ body.is-resizing-row .dorm-pane,
381
+ body.is-resizing-col .dorm-pane {
382
+ pointer-events: none;
383
+ }
@@ -0,0 +1,123 @@
1
+ (function () {
2
+ "use strict";
3
+
4
+ const layout = document.getElementById("dorm-layout");
5
+ const paneA = document.getElementById("dorm-pane-a");
6
+ const divider = document.getElementById("dorm-divider");
7
+ const verboseCb = document.getElementById("dorm-verbose-cb");
8
+
9
+ let isResizing = false;
10
+ let startPos = 0;
11
+ let startSize = 0;
12
+
13
+ // ── Layout toggle ─────────────────────────────────────────
14
+
15
+ window.dormSetLayout = function (dir) {
16
+ layout.dataset.dir = dir;
17
+ paneA.style.flex = "0 0 50%";
18
+ document.querySelectorAll(".dorm-layout-opt").forEach(function (btn) {
19
+ btn.classList.toggle("active", btn.dataset.dir === dir);
20
+ });
21
+ };
22
+
23
+ // ── Verbose names toggle ──────────────────────────────────
24
+
25
+ function applyVerbose() {
26
+ var useVerbose = verboseCb ? verboseCb.checked : true;
27
+ document.querySelectorAll(".dorm-table th").forEach(function (th) {
28
+ th.textContent = useVerbose ? th.dataset.verbose : th.dataset.field;
29
+ });
30
+ }
31
+
32
+ if (verboseCb) {
33
+ verboseCb.addEventListener("change", applyVerbose);
34
+ }
35
+
36
+ // Re-apply after each htmx result swap
37
+ document.body.addEventListener("htmx:afterSwap", applyVerbose);
38
+
39
+ // ── CSV / JSON export ─────────────────────────────────────
40
+
41
+ window.dormExport = function (format) {
42
+ var table = document.querySelector(".dorm-table");
43
+ if (!table) return;
44
+
45
+ var headers = Array.from(table.querySelectorAll("thead th"))
46
+ .map(function (th) { return th.textContent.trim(); });
47
+
48
+ var rows = Array.from(table.querySelectorAll("tbody tr"))
49
+ .map(function (tr) {
50
+ return Array.from(tr.querySelectorAll("td"))
51
+ .map(function (td) { return td.textContent.trim(); });
52
+ });
53
+
54
+ var model = (table.dataset.model || "dorm") + "_records";
55
+ var content, filename, mime;
56
+
57
+ if (format === "csv") {
58
+ var esc = function (v) { return '"' + v.replace(/;/g, '').replace(/"/g, '""') + '"'; };
59
+ content = [headers.map(esc).join(";")]
60
+ .concat(rows.map(function (r) { return r.map(esc).join(";"); }))
61
+ .join("\n");
62
+ filename = model + ".csv";
63
+ mime = "text/csv;charset=utf-8;";
64
+ } else {
65
+ var data = rows.map(function (row) {
66
+ var obj = {};
67
+ headers.forEach(function (h, i) { obj[h] = row[i]; });
68
+ return obj;
69
+ });
70
+ content = JSON.stringify(data, null, 2);
71
+ filename = model + ".json";
72
+ mime = "application/json";
73
+ }
74
+
75
+ var blob = new Blob([content], { type: mime });
76
+ var url = URL.createObjectURL(blob);
77
+ var a = document.createElement("a");
78
+ a.href = url;
79
+ a.download = filename;
80
+ a.click();
81
+ URL.revokeObjectURL(url);
82
+ };
83
+
84
+ // ── Resize drag ───────────────────────────────────────────
85
+
86
+ divider.addEventListener("mousedown", function (e) {
87
+ isResizing = true;
88
+ var isRow = layout.dataset.dir === "row";
89
+ startPos = isRow ? e.clientX : e.clientY;
90
+ startSize = isRow ? paneA.offsetWidth : paneA.offsetHeight;
91
+ document.body.classList.add(isRow ? "is-resizing-row" : "is-resizing-col");
92
+ e.preventDefault();
93
+ });
94
+
95
+ document.addEventListener("mousemove", function (e) {
96
+ if (!isResizing) return;
97
+ var isRow = layout.dataset.dir === "row";
98
+ var pos = isRow ? e.clientX : e.clientY;
99
+ var delta = pos - startPos;
100
+ var container = isRow ? layout.offsetWidth : layout.offsetHeight;
101
+ var newSize = Math.max(80, Math.min(startSize + delta, container - 85));
102
+ paneA.style.flex = "0 0 " + newSize + "px";
103
+ });
104
+
105
+ document.addEventListener("mouseup", function () {
106
+ if (!isResizing) return;
107
+ isResizing = false;
108
+ document.body.classList.remove("is-resizing-row", "is-resizing-col");
109
+ });
110
+
111
+ // ── Ctrl+Enter submit ─────────────────────────────────────
112
+
113
+ document.addEventListener("keydown", function (e) {
114
+ if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
115
+ var form = document.getElementById("dorm-form");
116
+ if (form) {
117
+ e.preventDefault();
118
+ htmx.trigger(form, "submit");
119
+ }
120
+ }
121
+ });
122
+
123
+ }());
@@ -0,0 +1,15 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>DORM — Django ORM Playground</title>
7
+ {% load static %}
8
+ <link rel="stylesheet" href="{% static 'dorm/css/dorm.css' %}">
9
+ <script src="https://unpkg.com/htmx.org@1.9.12" defer></script>
10
+ <script src="{% static 'dorm/js/dorm.js' %}" defer></script>
11
+ </head>
12
+ <body>
13
+ {% block content %}{% endblock %}
14
+ </body>
15
+ </html>
@@ -0,0 +1,4 @@
1
+ <div class="dorm-error">
2
+ <p class="dorm-error-title">{{ error_type }}: {{ error_message }}</p>
3
+ <pre class="dorm-error-traceback">{{ traceback }}</pre>
4
+ </div>
@@ -0,0 +1,31 @@
1
+ {% if result_type == "table" %}
2
+ <div class="dorm-result-bar">
3
+ <span class="dorm-result-meta">
4
+ {% if truncated %}Showing first {{ row_count }} rows (truncated)
5
+ {% else %}{{ row_count }} row{{ row_count|pluralize }}{% endif %}
6
+ </span>
7
+ <div class="dorm-export-btns">
8
+ <button class="dorm-export-btn" onclick="dormExport('csv')">↓ CSV</button>
9
+ <button class="dorm-export-btn" onclick="dormExport('json')">↓ JSON</button>
10
+ </div>
11
+ </div>
12
+ <div class="dorm-table-wrapper">
13
+ <table class="dorm-table" data-model="{{ model_name }}">
14
+ <thead>
15
+ <tr>{% for label, field in columns_meta %}<th data-verbose="{{ label }}" data-field="{{ field }}">{{ label }}</th>{% endfor %}</tr>
16
+ </thead>
17
+ <tbody>
18
+ {% for row in rows %}
19
+ <tr>{% for cell in row %}<td>{{ cell }}</td>{% endfor %}</tr>
20
+ {% endfor %}
21
+ </tbody>
22
+ </table>
23
+ </div>
24
+
25
+ {% elif result_type == "empty" %}
26
+ <p class="dorm-result-meta">0 rows returned</p>
27
+
28
+ {% elif result_type == "value" %}
29
+ <pre class="dorm-value">{{ value }}</pre>
30
+
31
+ {% endif %}
@@ -0,0 +1,61 @@
1
+ {% extends "dorm/base.html" %}
2
+
3
+ {% block content %}
4
+ <div class="dorm-root">
5
+
6
+ <header class="dorm-header">
7
+ <span class="dorm-logo">DORM</span>
8
+ <div class="dorm-layout-toggle">
9
+ <button class="dorm-layout-opt active" data-dir="row"
10
+ onclick="dormSetLayout('row')" title="Side by side">
11
+ <svg width="18" height="14" viewBox="0 0 18 14" fill="none">
12
+ <rect x="0" y="0" width="7" height="14" rx="1.5" fill="currentColor"/>
13
+ <rect x="11" y="0" width="7" height="14" rx="1.5" fill="currentColor"/>
14
+ </svg>
15
+ </button>
16
+ <button class="dorm-layout-opt" data-dir="col"
17
+ onclick="dormSetLayout('col')" title="Stacked">
18
+ <svg width="14" height="18" viewBox="0 0 14 18" fill="none">
19
+ <rect x="0" y="0" width="14" height="7" rx="1.5" fill="currentColor"/>
20
+ <rect x="0" y="11" width="14" height="7" rx="1.5" fill="currentColor"/>
21
+ </svg>
22
+ </button>
23
+ </div>
24
+ </header>
25
+
26
+ <div class="dorm-layout" id="dorm-layout" data-dir="row">
27
+
28
+ <div class="dorm-pane" id="dorm-pane-a">
29
+ <div class="dorm-pane-bar">
30
+ <span class="dorm-pane-label">Query</span>
31
+ <button class="dorm-run-btn" type="submit" form="dorm-form">
32
+ Run <kbd>Ctrl+Enter</kbd>
33
+ </button>
34
+ </div>
35
+ <form id="dorm-form"
36
+ hx-post="{% url 'dorm:run' %}"
37
+ hx-target="#dorm-result"
38
+ hx-swap="innerHTML">
39
+ {% csrf_token %}
40
+ <textarea id="dorm-editor" name="code" class="dorm-editor"
41
+ placeholder="# All models are auto-imported — no imports needed&#10;Author.objects.all()"
42
+ spellcheck="false"
43
+ autofocus></textarea>
44
+ </form>
45
+ </div>
46
+
47
+ <div class="dorm-divider" id="dorm-divider"></div>
48
+
49
+ <div class="dorm-pane" id="dorm-pane-b">
50
+ <div class="dorm-pane-bar">
51
+ <span class="dorm-pane-label">Result</span>
52
+ <label class="dorm-verbose-label">
53
+ <input type="checkbox" id="dorm-verbose-cb" checked> Verbose names
54
+ </label>
55
+ </div>
56
+ <div id="dorm-result" class="dorm-result-body"></div>
57
+ </div>
58
+
59
+ </div>
60
+ </div>
61
+ {% endblock %}
dorm/urls.py ADDED
@@ -0,0 +1,10 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ app_name = "dorm"
6
+
7
+ urlpatterns = [
8
+ path("", views.playground, name="playground"),
9
+ path("run/", views.run_query, name="run"),
10
+ ]
dorm/views.py ADDED
@@ -0,0 +1,158 @@
1
+ from django.conf import settings
2
+ from django.db.models import QuerySet
3
+ from django.http import Http404
4
+ from django.shortcuts import render
5
+
6
+ from . import executor
7
+
8
+ _MAX_ROWS = 200
9
+
10
+
11
+ def _is_accessible(request) -> bool:
12
+ """
13
+ Returns True when the request should be allowed into the playground.
14
+
15
+ Rules:
16
+ - DEBUG=False → always denied (404)
17
+ - DORM_AUTH_ACCESS=True → DEBUG=True AND user must be authenticated
18
+ - default → DEBUG=True is sufficient (no auth required)
19
+ """
20
+ if not settings.DEBUG:
21
+ return False
22
+ if getattr(settings, "DORM_AUTH_ACCESS", False):
23
+ return request.user.is_authenticated
24
+ return True
25
+
26
+
27
+ def playground(request):
28
+ if not _is_accessible(request):
29
+ raise Http404
30
+ return render(request, "dorm/playground.html")
31
+
32
+
33
+ def run_query(request):
34
+ if not _is_accessible(request):
35
+ raise Http404
36
+
37
+ code = request.POST.get("code", "").strip()
38
+ if not code:
39
+ return render(request, "dorm/partials/result.html", {"result_type": "none"})
40
+
41
+ outcome = executor.execute(code)
42
+
43
+ if not outcome["success"]:
44
+ return render(request, "dorm/partials/error.html", {
45
+ "error_type": outcome["error_type"],
46
+ "error_message": outcome["error"],
47
+ "traceback": outcome["traceback"],
48
+ })
49
+
50
+ ctx = _serialize_result(outcome["result"])
51
+ return render(request, "dorm/partials/result.html", ctx)
52
+
53
+
54
+ # --- result serialisation ---
55
+
56
+ def _fmt(value) -> str:
57
+ return "NULL" if value is None else str(value)
58
+
59
+
60
+ def _field_label(model, key: str) -> str:
61
+ """Return verbose_name for a model field key, falling back to the key itself."""
62
+ try:
63
+ vn = str(model._meta.get_field(key).verbose_name)
64
+ return vn if vn else key
65
+ except Exception:
66
+ return key
67
+
68
+
69
+ def _meta_columns(meta_fields) -> tuple[list, list]:
70
+ """Return (verbose_labels, field_names) for a list of concrete meta fields."""
71
+ labels = [str(f.verbose_name) or f.name for f in meta_fields]
72
+ names = [f.name for f in meta_fields]
73
+ return labels, names
74
+
75
+
76
+ def _serialize_result(result) -> dict:
77
+ if result is None:
78
+ return {"result_type": "none"}
79
+
80
+ if isinstance(result, QuerySet):
81
+ return _serialize_queryset(result)
82
+
83
+ # Single model instance
84
+ if hasattr(result, "_meta"):
85
+ labels, field_names = _meta_columns(result._meta.concrete_fields)
86
+ return {
87
+ "result_type": "table",
88
+ "model_name": result.__class__.__name__.lower(),
89
+ "columns_meta": list(zip(labels, field_names)),
90
+ "rows": [[_fmt(getattr(result, fn)) for fn in field_names]],
91
+ "row_count": 1,
92
+ "truncated": False,
93
+ }
94
+
95
+ # List / tuple of model instances
96
+ if isinstance(result, (list, tuple)) and result and hasattr(result[0], "_meta"):
97
+ labels, field_names = _meta_columns(result[0]._meta.concrete_fields)
98
+ rows = [[_fmt(getattr(row, fn)) for fn in field_names] for row in result[:_MAX_ROWS]]
99
+ return {
100
+ "result_type": "table",
101
+ "model_name": result[0].__class__.__name__.lower(),
102
+ "columns_meta": list(zip(labels, field_names)),
103
+ "rows": rows,
104
+ "row_count": len(rows),
105
+ "truncated": len(result) > _MAX_ROWS,
106
+ }
107
+
108
+ return {"result_type": "value", "value": repr(result)}
109
+
110
+
111
+ def _serialize_queryset(qs: QuerySet) -> dict:
112
+ iterable = qs._iterable_class.__name__
113
+
114
+ if iterable == "ValuesIterable":
115
+ sample = list(qs[: _MAX_ROWS + 1])
116
+ truncated = len(sample) > _MAX_ROWS
117
+ sample = sample[:_MAX_ROWS]
118
+ if not sample:
119
+ return {"result_type": "empty"}
120
+ raw_names = list(sample[0].keys())
121
+ labels = [_field_label(qs.model, k) for k in raw_names]
122
+ rows = [[_fmt(row[k]) for k in raw_names] for row in sample]
123
+
124
+ elif iterable in ("ValuesListIterable", "FlatValuesListIterable", "NamedValuesListIterable"):
125
+ sample = list(qs[: _MAX_ROWS + 1])
126
+ truncated = len(sample) > _MAX_ROWS
127
+ sample = sample[:_MAX_ROWS]
128
+ if not sample:
129
+ return {"result_type": "empty"}
130
+ flat = not isinstance(sample[0], (list, tuple))
131
+ qs_fields = list(qs._fields) if qs._fields else None
132
+ if flat:
133
+ raw_names = qs_fields or ["value"]
134
+ labels = [_field_label(qs.model, qs_fields[0])] if qs_fields else ["value"]
135
+ rows = [[_fmt(v)] for v in sample]
136
+ else:
137
+ raw_names = qs_fields or [f"col_{i}" for i in range(len(sample[0]))]
138
+ labels = [_field_label(qs.model, fn) for fn in qs_fields] if qs_fields else list(raw_names)
139
+ rows = [[_fmt(v) for v in row] for row in sample]
140
+
141
+ else:
142
+ # ModelIterable (default queryset)
143
+ sample = list(qs[: _MAX_ROWS + 1])
144
+ truncated = len(sample) > _MAX_ROWS
145
+ sample = sample[:_MAX_ROWS]
146
+ if not sample:
147
+ return {"result_type": "empty"}
148
+ labels, raw_names = _meta_columns(qs.model._meta.concrete_fields)
149
+ rows = [[_fmt(getattr(row, fn)) for fn in raw_names] for row in sample]
150
+
151
+ return {
152
+ "result_type": "table",
153
+ "model_name": qs.model.__name__.lower(),
154
+ "columns_meta": list(zip(labels, raw_names)),
155
+ "rows": rows,
156
+ "row_count": len(rows),
157
+ "truncated": truncated,
158
+ }
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: dorm-plg
3
+ Version: 0.1.0
4
+ Summary: Django ORM playground — dev-only web UI for ORM queries
5
+ Author-email: almamydev <almamydev10@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/almamydev/dorm
8
+ Project-URL: Repository, https://github.com/almamydev/dorm
9
+ Project-URL: Bug Tracker, https://github.com/almamydev/dorm/issues
10
+ Keywords: django,orm,playground,developer-tools,debugging
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4.2
15
+ Classifier: Framework :: Django :: 5.0
16
+ Classifier: Framework :: Django :: 5.1
17
+ Classifier: Framework :: Django :: 5.2
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Classifier: Topic :: Software Development :: Debuggers
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: Django>=4.2
31
+ Requires-Dist: django-htmx>=1.17
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest; extra == "dev"
34
+ Requires-Dist: pytest-django; extra == "dev"
35
+ Requires-Dist: build; extra == "dev"
36
+ Requires-Dist: twine; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # DORM
40
+
41
+ A Django ORM playground — a dev-only web UI to run ORM queries against your connected database.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install dorm-plg
47
+ ```
48
+
49
+ ## Setup
50
+
51
+ ```python
52
+ # settings.py
53
+ INSTALLED_APPS = [..., "django_htmx", "dorm"]
54
+ MIDDLEWARE = [..., "django_htmx.middleware.HtmxMiddleware"]
55
+ ```
56
+
57
+ ```python
58
+ # urls.py
59
+ from django.urls import path, include
60
+
61
+ urlpatterns = [
62
+ ...
63
+ path("__dorm__/", include("dorm.urls", namespace="dorm")),
64
+ ]
65
+ ```
66
+
67
+ Open `/__dorm__/` in your browser and start writing ORM queries.
68
+
69
+ > **Warning**: DORM executes arbitrary Python code in your Django process. It is gated behind `DEBUG=True` and must never be used in production.
70
+
71
+ ## Usage
72
+
73
+ In the playground editor, write any Django ORM expression. All models from your `INSTALLED_APPS` are available without importing them:
74
+
75
+ ```python
76
+ # Get all users
77
+ User.objects.all()
78
+
79
+ # Filter with related fields
80
+ Book.objects.filter(author__name="Tolkien").select_related("author")
81
+
82
+ # Aggregations
83
+ from django.db.models import Count
84
+ Author.objects.annotate(book_count=Count("books")).order_by("-book_count")
85
+ ```
86
+
87
+ Press **Ctrl+Enter** or click **Run** to execute. Results are rendered as a table.
88
+
89
+ ## Development
90
+
91
+ ```bash
92
+ git clone https://github.com/yourname/dorm
93
+ cd dorm
94
+ python3.10 -m venv .venv
95
+ source .venv/bin/activate
96
+ pip install -e ".[dev]"
97
+ cd sandbox && python manage.py migrate && python manage.py runserver
98
+ # Open: http://127.0.0.1:8000/__dorm__/
99
+ ```
@@ -0,0 +1,17 @@
1
+ dorm/__init__.py,sha256=A_z4fYdCRyX7MANWgWoXpS9s_VNhv_z_QqVqicP2VfE,241
2
+ dorm/apps.py,sha256=zub_AbPrGUI3D6vR4TI2qAYkJdcGbVlRMgIeAxrF7b4,484
3
+ dorm/exceptions.py,sha256=AqdUW7IDl3OnGCgDpSfbbh6JHqA-WQ-3odiFpeB2oSk,93
4
+ dorm/executor.py,sha256=Y1kOxh0M3FGgaiw7OGEuzJwYDtpPnbdYmGO5bu0Gno8,2026
5
+ dorm/urls.py,sha256=xKpyAKnWhtKDc3gLSXjnnPFhi0plQUahLGP400C6y7s,186
6
+ dorm/views.py,sha256=OYbR9QJhWt3IVmYd3KyuWuxMRFLLp_YkVHG-omfnZBg,5436
7
+ dorm/static/dorm/css/dorm.css,sha256=jrWlq0p8kFy5dmMm9P3oMH0HJpQMht-qlfgU5JvUCgw,9709
8
+ dorm/static/dorm/js/dorm.js,sha256=Td6PHnTogdhWOVtFMF_7X77bXMJmYS16motRyHw-f5E,4943
9
+ dorm/templates/dorm/base.html,sha256=XTjCCxBUroOgc7r6AhdzvBEac_TuoAOvZG4_nvFsQKc,484
10
+ dorm/templates/dorm/playground.html,sha256=XjWSQy4wZK8i6aNS_P009TVwoAXSqX8bP0y7U8i-h-0,2505
11
+ dorm/templates/dorm/partials/error.html,sha256=9RhYAhnJrbGnT6v9VukBpWa3WM-YhORilftYdVU6pwE,166
12
+ dorm/templates/dorm/partials/result.html,sha256=5mnoyO4Fgbo7ktlqdplqPMDyCzweWMqGc-WgNSbopdU,1112
13
+ dorm_plg-0.1.0.dist-info/licenses/LICENSE,sha256=6LvMYgzedjf2cJBq3jkcw18hl9SIYoWWLaduhrhyxxY,1074
14
+ dorm_plg-0.1.0.dist-info/METADATA,sha256=l4eW-mI3EroaMBVgHuBsu8DI_6SxIXzDCR6B2UNQdu4,2946
15
+ dorm_plg-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
16
+ dorm_plg-0.1.0.dist-info/top_level.txt,sha256=MO6l5LFiWC8-BWEh9oxsN48Et24eU9_WGs1UvHG4LHw,5
17
+ dorm_plg-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DORM Contributors
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.
@@ -0,0 +1 @@
1
+ dorm