ayb 0.1.12

ayb makes it easy to create, host, and share embedded databases like SQLite and DuckDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
{% extends "base_content.html" %}

{% block title %}Explore {{ entity }}/{{ database }}{% endblock %}

{% block page_content %}
<div class="max-w-screen-xl mx-auto px-6">
    <div class="max-w-screen-xl mx-auto">
        <div class="breadcrumbs mb-4">
            <a href="/{{ entity }}" class="hover:underline">{{ entity }}</a> /
            <span class="font-semibold">{{ database }}</span> ({{ database_type }})
        </div>
        <ul data-uk-tab class="mb-6" id="database-tabs">
            <li><a class="px-4 pb-3 pt-2" href="#query">Query</a></li>
            {% if can_manage_database %}
                <li><a class="px-4 pb-3 pt-2" href="#sharing">Sharing</a></li>
                <li><a class="px-4 pb-3 pt-2" href="#snapshots">Snapshots</a></li>
            {% endif %}
        </ul>
        <ul class="uk-switcher mt-4">
            <li>
                {% if highest_query_access_level %}
                    <div class="query-interface">
                        <h3 class="text-lg font-medium mb-2">Database querying</h3>
                        <p class="text-muted-foreground mb-4">Select, add, and update data.</p>
                        <form
                          id="query-form"
                          class="mb-4"
                          action="/{{ entity }}/{{ database }}/query"
                          method="post"
                          hx-post="/{{ entity }}/{{ database }}/query"
                          hx-target="#query-results"
                          hx-target-400="#query-results"
                          hx-swap="innerHTML">
                            <div class="mb-2">
                                <textarea id="query" name="query" rows="5"
                                    class="p-4 w-full border rounded focus:border-blue-500"
                                    placeholder="Enter a SQL query, like 'SELECT * FROM your_table LIMIT 10'"></textarea>
                            </div>
                            <div>
                                <button type="submit" class="uk-btn uk-btn-primary" disabled id="run-query-btn">
                                    Run query
                                </button>
                                <script>
                                    // Form is submittable once a query exists.
                                    // Track query changes to show stale overlay.
                                    let lastExecutedQuery = '';

                                    function showStaleOverlay() {
                                        const overlays = document.querySelectorAll('#query-results .stale-overlay');
                                        overlays.forEach(overlay => {
                                            overlay.classList.remove('hidden');
                                        });
                                    }

                                    function hideStaleOverlay() {
                                        const overlays = document.querySelectorAll('#query-results .stale-overlay');
                                        overlays.forEach(overlay => {
                                            overlay.classList.add('hidden');
                                        });
                                    }

                                    function hasQueryResults() {
                                        return document.querySelector('#query-results .query-results-wrapper, #query-results .query-error-wrapper') !== null;
                                    }

                                    document.addEventListener('DOMContentLoaded', function() {
                                        const queryTextarea = document.getElementById('query');
                                        const runButton = document.getElementById('run-query-btn');
                                        const queryForm = document.getElementById('query-form');

                                        runButton.disabled = queryTextarea.value.trim() === '';

                                        queryTextarea.addEventListener('input', function() {
                                            const currentQuery = this.value;
                                            runButton.disabled = currentQuery.trim() === '';

                                            // Show stale overlay if query changed after execution
                                            if (hasQueryResults() && currentQuery !== lastExecutedQuery && lastExecutedQuery !== '') {
                                                showStaleOverlay();
                                            }
                                        });

                                        document.body.addEventListener('htmx:beforeRequest', function(event) {
                                            // Hide overlay when submitting query form
                                            if (event.target === queryForm) {
                                                hideStaleOverlay();
                                            }
                                        });

                                        document.body.addEventListener('htmx:afterRequest', function(event) {
                                            // Update last executed query after any query submission
                                            if (event.target === queryForm) {
                                                lastExecutedQuery = queryTextarea.value;
                                            }
                                        });
                                    });
                                </script>
                            </div>
                        </form>
                        <div id="query-results">
                        </div>
                    </div>
                {% else %}
                    <div class="uk-alert" data-uk-alert="">
                        <div class="uk-alert-title">You don't have query access to this database.</div>
                        {% if logged_in_entity %}
                        <p>You can request access from the database owner or fork a copy.</p>
                        {% else %}
                        <p>
                            <a href="/log_in?next=/{{ entity }}/{{ database }}" class="underline">Login</a>
                            is required for query access.
                        </p>
                        {% endif %}
                    </div>
                {% endif %}
            </li>
            <li>
                <div class="sharing-interface">
                    <h3 class="text-lg font-medium mb-2">Database sharing</h3>
                    <p class="text-muted-foreground mb-4">Manage who can access this database and what permissions they have.</p>

                    <!-- Public sharing level form -->
                    <div class="uk-card uk-card-default mb-4">
                        <div class="uk-card-header">
                            <h4 class="uk-card-title">Public sharing level</h4>
                        </div>
                        <div class="uk-card-body">
                            <form id="public-sharing-form" class="space-y-4">
                                <div class="uk-btn-group" data-uk-button-radio>
                                    <button
                                        type="button"
                                        class="uk-btn uk-btn-default{% if public_sharing_level == 'no-access' %} uk-active{% endif %}"
                                        data-value="no-access"
                                        onclick="setPublicSharingLevel(this, 'no-access')">
                                        Private
                                    </button>
                                    <button
                                        type="button"
                                        class="uk-btn uk-btn-default{% if public_sharing_level == 'fork' %} uk-active{% endif %}"
                                        data-value="fork"
                                        onclick="setPublicSharingLevel(this, 'fork')">
                                        Forkable
                                    </button>
                                    <button
                                        type="button"
                                        class="uk-btn uk-btn-default{% if public_sharing_level == 'read-only' %} uk-active{% endif %}"
                                        data-value="read-only"
                                        onclick="setPublicSharingLevel(this, 'read-only')">
                                        Read-only
                                    </button>
                                </div>
                                <input type="hidden" id="public-sharing-level-value" name="public_sharing_level" value="">
                                <div>
                                    <button type="button" id="update-public-sharing-btn" class="uk-btn uk-btn-primary" disabled
                                            hx-post="/{{ entity }}/{{ database }}/update_public_sharing"
                                            hx-target="#public-sharing-results"
                                            hx-target-400="#public-sharing-results"
                                            hx-swap="innerHTML"
                                            hx-include="#public-sharing-level-value">
                                        Update sharing level
                                    </button>
                                </div>
                            </form>
                            <div id="public-sharing-results" class="mt-2"></div>
                        </div>
                    </div>

                    <!-- Share with specific entity form -->
                    <div class="uk-card uk-card-default">
                        <div class="uk-card-header">
                            <h4 class="uk-card-title">Share with specific user</h4>
                        </div>
                        <div class="uk-card-body">
                            <form id="entity-sharing-form" class="space-y-4"
                                  hx-post="/{{ entity }}/{{ database }}/share"
                                  hx-target="#sharing-results"
                                  hx-target-400="#sharing-results"
                                  hx-swap="innerHTML">
                                <div class="flex flex-col md:flex-row md:gap-4">
                                    <div class="flex-none md:w-1/3">
                                        <label for="share-entity" class="block text-sm font-medium mb-1">Username</label>
                                        <input
                                            type="text"
                                            id="share-entity"
                                            name="entity"
                                            class="p-2 border rounded focus:border-blue-500 w-full"
                                            placeholder="Enter username"
                                            onInput="checkEntitySharingForm()"
                                            required>
                                    </div>
                                    <div class="flex-grow mt-2 md:mt-0">
                                        <label class="block text-sm font-medium mb-1">Access level</label>
                                        <div class="uk-btn-group" data-uk-button-radio>
                                            <button
                                                type="button"
                                                class="uk-btn uk-btn-default"
                                                data-value="read-only"
                                                onclick="setEntitySharingLevel(this, 'read-only')">
                                                Read-only
                                            </button>
                                            <button
                                                type="button"
                                                class="uk-btn uk-btn-default"
                                                data-value="read-write"
                                                onclick="setEntitySharingLevel(this, 'read-write')">
                                                Read-write
                                            </button>
                                            <button
                                                type="button"
                                                class="uk-btn uk-btn-default"
                                                data-value="manager"
                                                onclick="setEntitySharingLevel(this, 'manager')">
                                                Manager
                                            </button>
                                        </div>
                                        <input type="hidden" id="entity-sharing-level-value" name="sharing_level" value="">
                                    </div>
                                </div>
                                <div>
                                    <button type="submit" id="share-entity-btn" class="uk-btn uk-btn-primary" disabled>
                                        Update access
                                    </button>
                                </div>
                            </form>
                            <div id="sharing-results" class="mt-2"></div>

                            <div id="share-list-container">
                                <div class="mt-4 text-center">
                                    <div uk-spinner></div>
                                    <p class="text-sm text-muted-foreground mt-2">Loading permissions...</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Remove access confirmation modal -->
                    <div id="remove-share-modal" class="uk-flex-top" data-uk-modal>
                        <div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical">
                            <h2 class="uk-modal-title">Remove access</h2>
                            <p class="mt-1">Are you sure you want to remove access for <strong id="remove-username"></strong>?</p>
                            <p class="uk-text-right mt-4">
                                <button class="uk-btn uk-btn-default uk-modal-close" type="button">Cancel</button>
                                <button
                                    class="uk-btn uk-btn-destructive"
                                    id="confirm-remove-btn"
                                    type="button"
                                    onclick="removePermission()">
                                    Remove access
                                </button>
                            </p>
                            <form id="remove-share-form" style="display: none;"
                                  hx-post="/{{ entity }}/{{ database }}/share"
                                  hx-target="#sharing-results"
                                  hx-target-400="#sharing-results"
                                  hx-swap="innerHTML">
                                <input type="hidden" name="entity" id="remove-entity-input">
                                <input type="hidden" name="sharing_level" value="no-access">
                            </form>
                        </div>
                    </div>

                    <script>
                        let originalPublicSharingLevel = '';
                        let selectedPublicSharingLevel = '';
                        let selectedEntitySharingLevel = '';
                        let removeEntityName = '';
                        let restoreSnapshotId = '';

                        function setPublicSharingLevel(button, value) {
                            selectedPublicSharingLevel = value;
                            document.getElementById('public-sharing-level-value').value = value;

                            // Update button states
                            const buttons = button.parentElement.querySelectorAll('button');
                            buttons.forEach(btn => {
                                btn.classList.remove('uk-active');
                            });
                            button.classList.add('uk-active');

                            // Enable/disable update button based on whether value changed
                            const updateBtn = document.getElementById('update-public-sharing-btn');
                            updateBtn.disabled = (value === originalPublicSharingLevel);
                        }

                        function setEntitySharingLevel(button, value) {
                            selectedEntitySharingLevel = value;
                            document.getElementById('entity-sharing-level-value').value = value;

                            // Update button states
                            const buttons = button.parentElement.querySelectorAll('button');
                            buttons.forEach(btn => {
                                btn.classList.remove('uk-active');
                            });
                            button.classList.add('uk-active');

                            checkEntitySharingForm();
                        }

                        function checkEntitySharingForm() {
                            const entityInput = document.getElementById('share-entity');
                            const submitBtn = document.getElementById('share-entity-btn');
                            const hasEntity = entityInput.value.trim() !== '';
                            const hasLevel = selectedEntitySharingLevel !== '';
                            submitBtn.disabled = !(hasEntity && hasLevel);
                        }

                        function editPermission(entityName, currentLevel) {
                            // Prefill the form with the entity name and current sharing level
                            document.getElementById('share-entity').value = entityName;

                            // Set the sharing level button - find the button within the entity sharing form
                            const entitySharingForm = document.getElementById('entity-sharing-form');
                            const levelButton = entitySharingForm.querySelector(`[data-value="${currentLevel}"]`);
                            if (levelButton) {
                                setEntitySharingLevel(levelButton, currentLevel);
                            }

                            // Scroll to the form
                            document.getElementById('entity-sharing-form').scrollIntoView({ behavior: 'smooth' });
                        }

                        function confirmRemovePermission(entityName) {
                            removeEntityName = entityName;
                            document.getElementById('remove-username').textContent = entityName;
                            document.getElementById('remove-entity-input').value = entityName;
                            // Clear any previous messages
                            document.getElementById('sharing-results').innerHTML = '';
                            UIkit.modal('#remove-share-modal').show();
                        }

                        function removePermission() {
                            // Submit the hidden form to remove access
                            htmx.trigger('#remove-share-form', 'submit');
                            UIkit.modal('#remove-share-modal').hide();
                        }

                        function loadPermissions() {
                            fetch('/{{ entity }}/{{ database }}/permissions')
                                .then(response => response.text())
                                .then(html => {
                                    document.getElementById('share-list-container').innerHTML = html;
                                })
                                .catch(error => {
                                    console.error('Error loading share list:', error);
                                    document.getElementById('share-list-container').innerHTML =
                                        '<div class="mt-4"><p class="text-sm text-red-600">Error loading permissions.</p></div>';
                                });
                        }

                        function loadSnapshots() {
                            fetch('/{{ entity }}/{{ database }}/snapshots')
                                .then(response => response.text())
                                .then(html => {
                                    document.getElementById('snapshots-list-container').innerHTML = html;
                                })
                                .catch(error => {
                                    console.error('Error loading snapshots:', error);
                                    document.getElementById('snapshots-list-container').innerHTML =
                                        '<div class="mt-4"><p class="text-sm text-red-600">Error loading snapshots.</p></div>';
                                });
                        }

                        function confirmRestoreSnapshot(snapshotId, snapshotDate) {
                            restoreSnapshotId = snapshotId;
                            const truncatedId = snapshotId.substring(0, 10) + '...';
                            document.getElementById('restore-snapshot-id').textContent = truncatedId;
                            document.getElementById('restore-snapshot-date').textContent = snapshotDate;
                            document.getElementById('restore-snapshot-input').value = snapshotId;
                            // Clear any previous messages
                            document.getElementById('restore-snapshot-results').innerHTML = '';
                            UIkit.modal('#restore-snapshot-modal').show();
                        }

                        function restoreSnapshot() {
                            // Submit the hidden form to restore the snapshot
                            htmx.trigger('#restore-snapshot-form', 'submit');
                            UIkit.modal('#restore-snapshot-modal').hide();
                        }

                        // Handle URL hash navigation for tabs
                        function setActiveTabFromHash() {
                            const hash = window.location.hash;
                            const tabs = document.querySelectorAll('#database-tabs li');
                            const tabContents = document.querySelectorAll('.uk-switcher li');

                            // Map hash to tab index
                            let activeIndex = 0; // Default to query tab
                            if (hash === '#sharing' && tabs.length > 1) {
                                activeIndex = 1;
                                // Load share list when switching to sharing tab
                                loadPermissions();
                            } else if (hash === '#snapshots' && tabs.length > 2) {
                                activeIndex = 2;
                                // Load snapshots when switching to snapshots tab
                                loadSnapshots();
                            }

                            // Remove active class from all tabs and contents
                            tabs.forEach(tab => tab.classList.remove('uk-active'));
                            tabContents.forEach(content => content.style.display = 'none');

                            // Set active tab and content
                            if (tabs[activeIndex]) {
                                tabs[activeIndex].classList.add('uk-active');
                            }
                            if (tabContents[activeIndex]) {
                                tabContents[activeIndex].style.display = 'block';
                            }
                        }

                        // Listen for hash changes
                        window.addEventListener('hashchange', setActiveTabFromHash);

                        // Add click handlers to tab links to update URL hash
                        function addTabClickHandlers() {
                            const tabLinks = document.querySelectorAll('#database-tabs a');
                            tabLinks.forEach(link => {
                                link.addEventListener('click', function(e) {
                                    e.preventDefault();
                                    const hash = this.getAttribute('href');
                                    window.location.hash = hash;
                                });
                            });
                        }

                        // Initialize form state when page loads
                        document.addEventListener('DOMContentLoaded', function() {
                            // Add tab click handlers
                            addTabClickHandlers();

                            // Set active tab based on URL hash
                            setActiveTabFromHash();
                            // Set initial public sharing level from the backend
                            originalPublicSharingLevel = '{{ public_sharing_level }}';
                            const currentButton = document.querySelector('[data-value="{{ public_sharing_level }}"]');
                            if (currentButton) {
                                setPublicSharingLevel(currentButton, '{{ public_sharing_level }}');
                            }

                            // Listen for HTMX requests to clear messages and handle responses
                            document.body.addEventListener('htmx:beforeRequest', function(event) {
                                // Clear messages before making requests
                                if (event.target.id === 'update-public-sharing-btn') {
                                    document.getElementById('public-sharing-results').innerHTML = '';
                                } else if (event.target.closest('#entity-sharing-form')) {
                                    document.getElementById('sharing-results').innerHTML = '';
                                }
                            });

                            document.body.addEventListener('htmx:afterRequest', function(event) {
                                if (event.detail.xhr.status === 200 && event.target.id === 'update-public-sharing-btn') {
                                    // Update the original value to the newly selected value
                                    originalPublicSharingLevel = selectedPublicSharingLevel;
                                    // Disable the button since it now matches the original value
                                    event.target.disabled = true;
                                } else if (event.detail.xhr.status === 200 &&
                                          (event.target.closest('#entity-sharing-form') || event.target.closest('#remove-share-form'))) {
                                    // Refresh the shares list after any successful sharing operation
                                    loadPermissions();
                                    // Clear the form after adding/updating permissions
                                    if (event.target.closest('#entity-sharing-form')) {
                                        document.getElementById('share-entity').value = '';
                                        selectedEntitySharingLevel = '';
                                        document.getElementById('entity-sharing-level-value').value = '';
                                        // Remove active class from all sharing level buttons
                                        document.querySelectorAll('#entity-sharing-form .uk-btn-group button').forEach(btn => {
                                            btn.classList.remove('uk-active');
                                        });
                                        checkEntitySharingForm();
                                    }
                                    // Close modal after successful remove operation
                                    if (event.target.closest('#remove-share-form')) {
                                        UIkit.modal('#remove-share-modal').hide();
                                    }
                                } else if (event.detail.xhr.status === 200 && event.target.closest('#restore-snapshot-form')) {
                                    // Refresh the snapshots list after successful restore
                                    loadSnapshots();
                                    // Close modal after successful restore
                                    UIkit.modal('#restore-snapshot-modal').hide();
                                }
                            });
                        });
                    </script>
                </div>
            </li>
            <li>
                <div class="snapshots-interface">
                    <h3 class="text-lg font-medium mb-2">Database snapshots</h3>
                    <p class="text-muted-foreground mb-4">View and restore database snapshots.</p>

                    <div id="restore-snapshot-results" class="mb-4"></div>
                    <div id="snapshots-list-container">
                        <div class="mt-4 text-center">
                            <div uk-spinner></div>
                            <p class="text-sm text-muted-foreground mt-2">Loading snapshots...</p>
                        </div>
                    </div>

                    <!-- Restore snapshot confirmation modal -->
                    <div id="restore-snapshot-modal" class="uk-flex-top" data-uk-modal>
                        <div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical">
                            <h2 class="uk-modal-title">Restore snapshot</h2>
                            <p class="mt-1">Are you sure you want to restore the database from snapshot <code id="restore-snapshot-id"></code> (Created: <span id="restore-snapshot-date"></span>)?</p>
                            <p class="uk-text-muted text-sm mt-2">This will replace the current database content with the snapshot data.</p>
                            <p class="uk-text-right mt-4">
                                <button class="uk-btn uk-btn-default uk-modal-close" type="button">Cancel</button>
                                <button
                                    class="uk-btn uk-btn-primary"
                                    id="confirm-restore-btn"
                                    type="button"
                                    onclick="restoreSnapshot()">
                                    Restore database
                                </button>
                            </p>
                            <form id="restore-snapshot-form" style="display: none;"
                                  hx-post="/{{ entity }}/{{ database }}/restore_snapshot"
                                  hx-target="#restore-snapshot-results"
                                  hx-target-400="#restore-snapshot-results"
                                  hx-swap="innerHTML">
                                <input type="hidden" name="snapshot_id" id="restore-snapshot-input">
                            </form>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
    </div>
</div>
{% endblock %}