-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_editor.html
More file actions
2146 lines (1849 loc) · 72.4 KB
/
sqlite_editor.html
File metadata and controls
2146 lines (1849 loc) · 72.4 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQLite web editor 100% Javascript client-side</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.18.0/clusterize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.18.0/clusterize.min.js"></script>
<style>
.list-group-item { padding: .1rem 1.25rem; }
#overlay {
position: fixed;
top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
#overlay-content {
background: white;
padding: 20px;
border-radius: 8px;
max-width: 860px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.clusterize-viewport { max-height: 55vh; }
.table-container {
overflow-x: auto;
border: 1px solid #dee2e6;
border-radius: 0.25rem;
max-height: 70vh;
}
.cont_lst-tablas{
max-height: 85vh;
overflow: auto;
border: 1px solid #dee2e6;
}
.field-row { margin-bottom: 6px; padding: 10px; background: #f9f9f9; border-radius: 5px; }
#tableList li.list-group-item { cursor: pointer; }
#tableList li.list-group-item.selected {
background-color: #007bff;
color: white;
}
</style>
</head>
<body class="p-3">
<div class="container-fluid">
<!-- Fila 1: col-12 con inputs -->
<div class="row mb-3">
<div class="col-12 bg-light border p-3">
<h4 class="mb-3">SQLite WEB Editor</h4>
<div class="form-row">
<!-- Input File -->
<div class="col-md-4 mb-2">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputFileSQLite" onchange="loadDatabaseFromFile();">
<label class="custom-file-label" for="inputFileSQLite">Select Database SQLite</label>
</div>
</div>
</div>
<!-- Botón Crear Database -->
<div class="col-md-4 mb-2">
<button type="button" class="btn btn-primary btn-block" onclick="openCreateDatabaseOverlayWithTemplates();">
Create SQLite Database
</button>
</div>
<!-- Botón Descargar Database -->
<div class="col-md-4 mb-2">
<button type="button" class="btn btn-success btn-block" onclick="downloadDatabase()">
Download Database
</button>
</div>
</div>
</div>
</div>
<!-- Fila 2: col-md-4 (lateral) y col-md-8 (principal) -->
<div class="row mb-3">
<!-- Columna izquierda (col-md-4) -->
<div class="col-md-4 col-12 bg-light border p-3">
<!-- Encabezado con botón flotante -->
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 class="mb-0">List of Tables</h5>
<button type="button" class="btn btn-sm btn-primary" onclick="openCreateTableOverlay()">
Create Table
</button>
</div>
<!-- Lista de tablas -->
<div class="cont_lst-tablas">
<ul id="tableList" class="list-group">
<div class="alert alert-info mb-0">The database tables are shown here.</div>
</ul>
</div>
</div>
<!-- Columna principal (col-md-8) -->
<div class="col-md-8 col-12 bg-light border p-3">
<!-- Título de tabla -->
<h5 class="mb-3">Table: <span id="tableName" class="text-muted"></span></h5>
<!-- Tabs de navegación -->
<ul class="nav nav-tabs mb-3" id="tablaTabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="datos-tab" data-toggle="tab" href="#datos" role="tab">
View Table
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="estructura-tab" data-toggle="tab" href="#estructura" role="tab">
Structure
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="consulta-tab" data-toggle="tab" href="#consulta" role="tab">
SQL Query
</a>
</li>
<li class="nav-item">
<a class="nav-link" id="triggers-tab" data-toggle="tab" href="#triggers" role="tab">
Triggers
</a>
</li>
</ul>
<!-- Contenido de los tabs -->
<div class="tab-content" id="tablaTabsContent">
<!-- Tab 1: Datos -->
<div class="tab-pane fade show active" id="datos" role="tabpanel">
<!-- Encabezado con botón flotante -->
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 id="tableSelTitle" class="mb-0">Selected Table</h5>
<button type="button" class="btn btn-sm btn-primary" onclick="openEditOverlay(null)">
Add Record
</button>
</div>
<!-- Tabla de datos -->
<div class="table-container">
<table id="dataTable" class="table table-sm table-bordered mb-0">
<thead id="dataHeader"></thead>
<tbody id="dataTableBody"></tbody>
</table>
<div id="dataRows" class="clusterize-scroll">
<!-- Clusterize inyectará las filas aquí -->
</div>
</div>
</div>
<!-- Tab 2: Estructura -->
<div class="tab-pane fade" id="estructura" role="tabpanel">
<!-- Encabezado con botón flotante -->
<div class="d-flex justify-content-between align-items-center mb-3">
<h5 id="tableSelTitleStruct" class="mb-0">Selected Table Structure</h5>
<button type="button" class="btn btn-sm btn-primary" onclick="openEditTableOverlay()">
Edit Structure
</button>
</div>
<div id="schemaTable">
<div class="alert alert-info mb-0">The structure of the selected table is shown here.</div>
</div>
</div>
<!-- Tab 3: Consulta SQL -->
<div class="tab-pane fade" id="consulta" role="tabpanel">
<!-- Resultados -->
<div id="queryResults" class="table-container mb-2">
<div class="alert alert-info mb-0">The results will appear here.</div>
</div>
<!-- Textarea para consulta -->
<div class="mb-3">
<label for="sqlQuery" class="sr-only">SQL Query</label>
<textarea class="form-control" id="sqlQuery" rows="4" placeholder="Write your SQL query here..."></textarea>
</div>
<!-- Botones -->
<div class="mb-3">
<button type="button" class="btn btn-primary mr-2" onclick="executeSQLQuery()">
Run Query
</button>
<button type="button" class="btn btn-outline-secondary" onclick="$('#sqlQuery').val('');">
Clear
</button>
</div>
</div>
<!-- Tab 2: Triggers -->
<div class="tab-pane fade" id="triggers" role="tabpanel">
<button type="button" class="btn btn-warning btn-sm mb-2" id="addTriggerBtn" onclick="openCreateTriggerOverlay();">
<i class="fas fa-edit"></i> Add Trigger
</button>
<div id="triggerList">
<div class="alert alert-info mb-0">The triggers of the selected table are shown here.</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Overlay genérico -->
<div id="overlay">
<div id="overlay-content">
<h5 id="overlay-title">Form</h5>
<form id="recordForm"></form>
<div class="mt-3 d-flex justify-content-end">
<button type="button" class="btn btn-secondary mr-2" id="overlayCancel" onclick="hideOverlay()">Cancel</button>
<button type="button" class="btn btn-primary" id="overlaySave" onclick="handleOverlaySave()">Save</button>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
<script>
var DBNAME;
var DB = null;
var CURRENT_TABLE = null;
var currentRowId = null;
var clusterize = null;
var overlayMode = null;
let SQLready = false;
initSqlJs({
locateFile: filename => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${filename}`
}).then(function(SQL) {
window.SQL = SQL;
SQLready = true;
});
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function handleOverlaySave() {
switch(overlayMode) {
case 'create-table':
saveCreateTable();
break;
case 'add-column':
saveAddColumn();
break;
case 'edit-record':
saveEditRecord();
break;
case 'edit-table':
saveEditTable();
break;
case 'create-trigger':
saveTrigger();
break;
case 'create-database':
saveCreateDatabaseWithTemplate();
break;
default:
alert('Overlay mode not recognized.');
}
}
function loadDatabaseFromFile() {
if (!SQLready) {
alert('Please wait, SQLite is still loading.');
return;
}
const file = document.querySelector("#inputFileSQLite").files[0];
if (!file) return;
DBNAME = file.name;
const reader = new FileReader();
reader.onload = function() {
try {
DB = new SQL.Database(new Uint8Array(reader.result));
loadTables();
} catch (err) {
alert('Error loading database: ' + err.message);
}
};
reader.readAsArrayBuffer(file);
}
function createNewDatabase(name) {
if (!SQLready) {
alert('Please wait, SQLite is still loading.');
return;
}
DB = new SQL.Database();
alert(`Database "${name}" created in memory.`);
loadTables();
}
function loadTables() {
const result = DB.exec("SELECT name FROM sqlite_master WHERE type='table';");
const tableNames = result.length ? result[0].values.map(row => row[0]) : [];
const $list = $('#tableList');
$list.empty();
tableNames.forEach(name => {
const $li = $(`
<li class="list-group-item d-flex justify-content-between align-items-center" onclick="selectTable('${name}')">
<span class="table-name">${escapeHtml(name)}</span>
<div class="table-item-actions">
<button class="btn btn-xs btn-danger delete-table fas fa-times" onclick="event.stopPropagation(); deleteTable('${name}')"></button>
</div>
</li>
`);
$list.append($li);
});
}
function selectTable(tableName) {
CURRENT_TABLE = tableName;
$('#tableName').text(tableName);
$('#tableSelTitle').text(`Selected Table: ${tableName}`);
$('#tableSelTitleStruct').text(`Selected Table Structure: ${tableName}`);
renderData();
renderSchema();
loadTriggers();
}
function getPrimaryKeyInfo(tableName) {
try {
// Obtener información de las columnas de la tabla
const result = DB.exec(`PRAGMA table_info("${tableName}")`);
if (!result || !result[0] || !result[0].values) {
return null;
}
// Buscar columnas que sean Primary Key
// En SQLite, pk = 0 significa no es PK, pk > 0 significa es PK
const pkColumns = result[0].values
.filter(row => row[5] > 0) // Columna 5 es 'pk'
.map(row => row[1]); // Columna 1 es 'name'
if (pkColumns.length === 0) {
return null; // No hay Primary Key
}
return {
columns: pkColumns,
isComposite: pkColumns.length > 1,
field: pkColumns[0] // Primera columna PK (para PK simple)
};
} catch (err) {
console.error('Error obtaining Primary Key:', err);
return null;
}
}
function renderData() {
if (!CURRENT_TABLE || !DB) return;
// Limpiar contenido anterior
$('#dataHeader').html('');
$('#dataTableBody').html('');
$('#dataRows').html('');
// Obtener información de la Primary Key
const pkInfo = getPrimaryKeyInfo(CURRENT_TABLE);
const hasPrimaryKey = pkInfo !== null;
let res;
try {
res = DB.exec(`SELECT * FROM "${CURRENT_TABLE}"`);
} catch (e) {
console.error('Error loading data:', e);
$('#dataHeader').html('<tr><th colspan="100" class="text-center text-danger">Error loading data</th></tr>');
return;
}
if (!res.length || !res[0].columns || !res[0].values) {
$('#dataHeader').html('<tr><th colspan="100" class="text-center text-muted">Empty table</th></tr>');
return;
}
const columns = res[0].columns;
const rows = res[0].values;
// Crear encabezados
let headerHtml = '<tr>';
columns.forEach(col => {
headerHtml += `<th>${escapeHtml(col)}</th>`;
});
headerHtml += '<th>Actions</th></tr>';
$('#dataHeader').html(headerHtml);
// Crear filas
const items = rows.map(row => {
// Celdas de datos
const cells = row.map(cell =>
cell === null ? '<td><em class="text-muted">NULL</em></td>' : `<td>${escapeHtml(String(cell))}</td>`
);
// Botones de acciones
let actionButtons = '<td>';
// Botón Editar
const rowJson = encodeURIComponent(JSON.stringify(row));
// Botónes
if (!hasPrimaryKey) {
actionButtons += `<button class="btn btn-sm btn-success fas fa-edit mr-1" title="Without Primary Key"></button>`;
actionButtons += `<button class="btn btn-sm btn-secondary fas fa-times" title="Without Primary Key" disabled></button>`;
} else if (pkInfo.isComposite) {
// PK compuesta
const pkObject = {};
pkInfo.columns.forEach(col => {
const idx = columns.indexOf(col);
pkObject[col] = row[idx];
});
const pkJson = escapeHtml(JSON.stringify(pkObject));
actionButtons += `<button class="btn btn-sm btn-success edit-record-btn fas fa-edit mr-1" title="Edit" data-table="${CURRENT_TABLE}" data-pk='${pkJson}'></button>`;
actionButtons += `<button class="btn btn-sm btn-danger del-record-btn fas fa-times" title="Delete" data-table="${CURRENT_TABLE}" data-pk='${pkJson}'></button>`;
} else {
// PK simple
const pkObject = {
[pkInfo.field]: row[columns.indexOf(pkInfo.field)]
};
const pkJson = escapeHtml(JSON.stringify(pkObject));
actionButtons += `<button class="btn btn-sm btn-success edit-record-btn fas fa-edit mr-1" title="Edit" data-table="${CURRENT_TABLE}" data-pk='${pkJson}'></button>`;
actionButtons += `<button class="btn btn-sm btn-danger del-record-btn fas fa-times" title="Delete" data-table="${CURRENT_TABLE}" data-pk='${pkJson}'></button>`;
}
actionButtons += '</td>';
cells.push(actionButtons);
return '<tr>' + cells.join('') + '</tr>';
});
// Limpiar Clusterize anterior
if (window.clusterize) {
window.clusterize.destroy();
window.clusterize = null;
}
// Inicializar Clusterize
window.clusterize = new Clusterize({
rows: items,
scrollId: 'dataRows',
contentId: 'dataTableBody',
tag: 'tbody'
});
// Eventos delegados
$('#dataTableBody')
.off('click.crud')
.on('click.crud', '.edit-record-btn', function (e) {
e.stopPropagation();
openEditOverlay(CURRENT_TABLE, $(this));
})
.on('click.crud', '.del-record-btn', function (e) {
e.stopPropagation();
deleteRecord(CURRENT_TABLE, $(this));
});
}
function renderSchema() {
if (!CURRENT_TABLE) return;
const res = DB.exec(`PRAGMA table_info("${CURRENT_TABLE}");`);
if (!res.length || !res[0].values.length) {
$('#schemaTable').html('<p>There is no schematic information.</p>');
return;
}
const cols = ['cid', 'name', 'type', 'notnull', 'dflt_value', 'pk'];
let html = `<table class="table table-sm"><thead><tr>`;
cols.forEach(c => html += `<th>${c}</th>`);
html += '<th>Actions</th></tr></thead><tbody>';
res[0].values.forEach(row => {
html += '<tr>';
row.forEach(cell => {
html += `<td>${cell === null ? '<em>null</em>' : escapeHtml(String(cell))}</td>`;
});
const colName = row[1];
html += `<td><button class="btn btn-xs btn-danger delete-column fas fa-times" data-col="${colName}"></button></td>`;
html += '</tr>';
});
html += '</tbody></table>';
$('#schemaTable').html(html);
$('#schemaTable .delete-column').on('click', function() {
const colName = $(this).data('col');
if (confirm(`Delete the column "${colName}" from the table "${CURRENT_TABLE}"?\nThis action cannot be undone!`)) {
deleteColumn(CURRENT_TABLE, colName);
}
});
}
function deleteTable(tableName) {
try {
DB.run(`DROP TABLE "${tableName}";`);
if (CURRENT_TABLE === tableName) {
CURRENT_TABLE = null;
$('#currentTableTitle').text('Tabla: -');
$('#dataHeader, #dataRows, #schemaTable').empty();
$('#dataTable thead, #dataTable tbody').html('');
}
loadTables();
} catch (err) {
alert('Error while deleting table: ' + err.message);
}
}
function deleteRecord(tableName, $btn) {
if (!DB) {
alert('No database is loaded.');
return;
}
if (!tableName) {
alert('Error: Table name is required.');
return;
}
// Obtener PK desde el botón (JSON unificado)
const pk = $btn.data('pk');
if (!pk || typeof pk !== 'object' || Object.keys(pk).length === 0) {
alert('No primary key could be identified for the record.');
return;
}
// Construir WHERE dinámico
const whereClause = Object.keys(pk)
.map(k => `"${k}" = ?`)
.join(' AND ');
const wherePreview = Object.entries(pk)
.map(([k, v]) => `"${k}" = ${v === null ? 'NULL' : v}`)
.join(' AND ');
// Confirmación
const confirmMessage =
`Delete record from table "${tableName}"?\n\n` +
`${wherePreview}\n\n` +
`⚠️ This action cannot be undone.`;
if (!confirm(confirmMessage)) return;
try {
const deleteQuery = `
DELETE FROM "${tableName}"
WHERE ${whereClause};
`;
// Ejecutar DELETE con parámetros
DB.run(deleteQuery, Object.values(pk));
// Verificar cambios
const result = DB.exec(`SELECT changes()`);
const deletedCount = result[0].values[0][0];
if (deletedCount === 0) {
alert('No record was found with those values.');
return;
}
// Eliminar fila del DOM
$btn.closest('tr').remove();
// Refrescar Clusterize
if (window.clusterize) {
window.clusterize.refresh();
}
alert('✅ Record deleted successfully.');
} catch (err) {
console.error('Error while deleting record:', err);
alert(`❌ Error while deleting: ${err.message}`);
}
}
// === EDITAR/INSERTAR REGISTRO ===
function openEditOverlay(tableName, btn) {
console.log('openEditOverlay llamado');
overlayMode = 'edit-record';
const $btn = $(btn);
const pkData = $btn.data('pk'); // objeto o undefined
const hasPK = pkData && typeof pkData === 'object';
const $form = $('#recordForm');
const $title = $('#overlay-title');
if (!DB || !CURRENT_TABLE) {
document.getElementById("dataRows").innerHTML =
'<div class="alert alert-danger mb-0">First you must load a database and select a table.</div>';
return;
}
// Guardar PK actuales para el UPDATE
window.currentPK = hasPK ? pkData : null;
const schemaRes = DB.exec(`PRAGMA table_info("${CURRENT_TABLE}");`);
const fields = schemaRes[0].values.map(row => ({
name: row[1],
type: row[2],
dflt_value: row[4]
}));
let formHtml = '';
const values = {};
if (hasPK) {
// Construir WHERE dinámico
const whereClause = Object.keys(pkData)
.map(k => `"${k}" = ?`)
.join(' AND ');
const sql = `SELECT * FROM "${CURRENT_TABLE}" WHERE ${whereClause}`;
const params = Object.values(pkData);
const dataRes = DB.exec(sql, params);
if (dataRes.length && dataRes[0].values.length) {
const rowValues = dataRes[0].values[0];
dataRes[0].columns.forEach((col, i) => {
values[col] = rowValues[i];
});
}
$title.text('Edit Record');
} else {
$title.text('New Record');
}
fields.forEach(field => {
let val = '';
if (hasPK) {
val = values[field.name] ?? '';
} else {
val = field.dflt_value ?? '';
val = cleanDefaultValue(val, field.type);
}
formHtml += `
<div class="form-group row mb-1">
<label class="col-sm-4 col-form-label">${escapeHtml(field.name)} (${field.type})</label>
<div class="col-sm-8">
<input type="text"
class="form-control"
name="${field.name}"
value="${escapeHtml(String(val))}"
data-type="${field.type}">
</div>
</div>
`;
});
$form.html(formHtml);
$('#overlay').show();
}
// Función para limpiar valores por defecto de SQLite
function cleanDefaultValue(value, type) {
if (value === null || value === undefined || value === '') {
return '';
}
// Si es un número, devolver tal cual
if (type === 'INTEGER' || type === 'REAL') {
// Quitar comillas si las tiene
return String(value).replace(/^["']|["']$/g, '');
}
// Si es TEXT o BLOB, quitar comillas externas
if (type === 'TEXT' || type === 'BLOB') {
// Quitar comillas simples o dobles del inicio y fin
return String(value).replace(/^["']|["']$/g, '');
}
// Para otros tipos, devolver tal cual
return String(value);
}
function saveEditRecord() {
const $form = $('#recordForm');
const formData = {};
$form.find('[name]').each(function () {
const $el = $(this);
const name = $el.attr('name');
let value = $el.val();
if (value === '' || value === null || value === undefined) {
formData[name] = null;
} else {
const type = $el.data('type');
if (type === 'INTEGER' || type === 'REAL') {
const num = parseFloat(value);
formData[name] = isNaN(num) ? null : num;
} else {
formData[name] = value;
}
}
});
const fieldNames = Object.keys(formData);
const values = Object.values(formData);
try {
if (window.currentPK) {
// UPDATE
const setClause = fieldNames
.map(name => `"${name}" = ?`)
.join(', ');
const whereClause = Object.keys(currentPK)
.map(k => `"${k}" = ?`)
.join(' AND ');
const sql = `
UPDATE "${CURRENT_TABLE}"
SET ${setClause}
WHERE ${whereClause};
`;
DB.run(sql, [...values, ...Object.values(currentPK)]);
alert('Registry updated successfully');
} else {
// INSERT
const cols = fieldNames.map(n => `"${n}"`).join(', ');
const placeholders = fieldNames.map(() => '?').join(', ');
DB.run(
`INSERT INTO "${CURRENT_TABLE}" (${cols}) VALUES (${placeholders});`,
values
);
alert('Record created successfully');
}
renderData();
$('#overlay').hide();
} catch (err) {
alert('Error while saving: ' + err.message);
console.error(err);
}
}
// === CREAR TABLA MEJORADA ===
function openCreateTableOverlay() {
if (!DB) {
document.getElementById("tableList").innerHTML = '<div class="alert alert-danger mb-0">First you must have an active database.</div>';
return;
}
overlayMode = 'create-table';
const $form = $('#recordForm');
const $title = $('#overlay-title');
$title.text('Create New Table');
let formHtml = `
<div class="form-group">
<label>Table Name</label>
<input type="text" class="form-control" id="newTableName" required placeholder="ej. users">
</div>
<h6>Initial Fields</h6>
<div id="fieldsContainer"></div>
<button type="button" class="btn btn-sm btn-outline-secondary mt-2" id="addFieldBtn">+ Add Field</button>
`;
$form.html(formHtml);
addFieldRowForTable();
$('#addFieldBtn').off('click').on('click', addFieldRowForTable);
$('#overlay').show();
}
function addFieldRowForTable() {
const fieldHtml = `
<div class="field-row d-flex flex-wrap align-items-end gap-2">
<input type="text" class="form-control fieldName" placeholder="name" style="flex:2; min-width:120px;">
<select class="form-control fieldType mx-1" style="flex:1; min-width:100px;">
<option value="TEXT">TEXT</option>
<option value="INTEGER">INTEGER</option>
<option value="REAL">REAL</option>
<option value="BLOB">BLOB</option>
</select>
<input type="text" class="form-control defaultValue mx-1" placeholder="DEFAULT" style="flex:1; min-width:100px;">
<div class="form-check mx-1" title="NOT NULL - It cannot be null">
<input class="form-check-input isNotNull" type="checkbox">
<label class="form-check-label">NN</label>
</div>
<div class="form-check mx-1" title="PRIMARY KEY">
<input class="form-check-input isPK" type="checkbox">
<label class="form-check-label">PK</label>
</div>
<div class="form-check mx-1" title="UNIQUE - Unique value in the table">
<input class="form-check-input isUnique" type="checkbox">
<label class="form-check-label">UQ</label>
</div>
<div class="form-check mx-2" title="AUTOINCREMENT (only INTEGER PK)">
<input class="form-check-input isAutoinc" type="checkbox" disabled>
<label class="form-check-label">AI</label>
</div>
<button type="button" class="btn btn-sm btn-danger removeField fas fa-times"></button>
</div>
`;
// Agregar el nuevo campo
const $newRow = $(fieldHtml);
$('#fieldsContainer').append($newRow);
// Evento para eliminar campo (solo en este row)
$newRow.find('.removeField').on('click', function() {
$(this).closest('.field-row').remove();
});
// Evento para validar todos los checkboxes y tipo (solo en este row)
$newRow.on('change', '.isPK, .isUnique, .isNotNull, .fieldType', function() {
const $row = $(this).closest('.field-row');
validateFieldRow($row);
});
// Validación inicial al crear el campo
validateFieldRow($newRow);
}
// Función auxiliar para validar el campo completo
function validateFieldRow($row) {
const isPK = $row.find('.isPK').prop('checked');
const isUnique = $row.find('.isUnique').prop('checked');
const isNotNull = $row.find('.isNotNull').prop('checked');
const type = $row.find('.fieldType').val();
const $ai = $row.find('.isAutoinc');
const $unique = $row.find('.isUnique');
const $notNull = $row.find('.isNotNull');
// Si es PK, deshabilitar UNIQUE (es redundante)
if (isPK) {
$unique.prop('disabled', true);
} else {
$unique.prop('disabled', false);
}
// Si es PK, automáticamente marcar NOT NULL (PK implica NOT NULL)
if (isPK) {
$notNull.prop('checked', true).prop('disabled', true);
} else {
$notNull.prop('disabled', false);
}
// AUTOINCREMENT solo si es PK y tipo es INTEGER
if (isPK && type === 'INTEGER') {
$ai.prop('disabled', false);
} else {
$ai.prop('disabled', true).prop('checked', false);
}
}
function saveCreateTable() {
const tableName = $('#newTableName').val().trim();
if (!tableName) { alert('Required table name'); return; }
const fields = [];
$('#fieldsContainer .field-row').each(function() {
const $row = $(this);
const name = $row.find('.fieldName').val().trim();
const type = $row.find('.fieldType').val();
const isPK = $row.find('.isPK').prop('checked');
const isUnique = $row.find('.isUnique').prop('checked');
const isNotNull = $row.find('.isNotNull').prop('checked');
const isAI = $row.find('.isAutoinc').prop('checked');
const def = $row.find('.defaultValue').val().trim();
if (!name) return;
let colDef = `"${name}" ${type}`;
// Agregar restricciones
if (isPK) {
colDef += " PRIMARY KEY";
// PRIMARY KEY ya implica UNIQUE y NOT NULL
if (isAI && type === 'INTEGER') {
colDef += " AUTOINCREMENT";
}
} else {
// Si no es PK, agregar UNIQUE si está marcado
if (isUnique) {
colDef += " UNIQUE";
}
// Si no es PK, agregar NOT NULL si está marcado
if (isNotNull) {
colDef += " NOT NULL";
}
// AUTOINCREMENT solo funciona con PK INTEGER, así que lo ignoramos aquí
}
// Agregar DEFAULT si existe
if (def) {
colDef += ` DEFAULT ${processDefaultValue(def, type)}`;
}
fields.push(colDef);
});
if (fields.length === 0) { alert('You must define at least one field.'); return; }
const sql = `CREATE TABLE "${tableName}" (${fields.join(', ')});`;
try {
DB.run(sql);
loadTables();
selectTable(tableName);
$('#overlay').hide();
} catch (err) {
alert('Error while creating table: ' + err.message+'.\nSQL: '+sql);
}
}
// Función para procesar el valor por defecto según el tipo
function processDefaultValue(value, type) {
// Si está vacío, devolver tal cual
if (!value) return value;
// Verificar si ya tiene comillas (dobles o simples)
const hasSingleQuotes = /^'.*'$/.test(value);
const hasDoubleQuotes = /^".*"$/.test(value);
const hasQuotes = hasSingleQuotes || hasDoubleQuotes;
// Para tipos TEXT, BLOB: necesitan comillas
if (type === 'TEXT' || type === 'BLOB') {
if (hasQuotes) {
return value; // Ya tiene comillas, devolver tal cual
} else {
// Agregar comillas simples automáticamente
return `'${value}'`;
}
}
// Para tipos INTEGER, REAL: no deben tener comillas
if (type === 'INTEGER' || type === 'REAL') {
if (hasQuotes) {
// Quitar comillas si las tiene
return value.replace(/^["']|["']$/g, '');
} else {
return value; // Devolver tal cual
}
}
// Para otros tipos, devolver tal cual
return value;
}
// Función auxiliar para validar AUTOINCREMENT
function validateAutoIncrement($row) {
const isPK = $row.find('.isPK').prop('checked');
const type = $row.find('.fieldType').val();
const $ai = $row.find('.isAutoinc');
if (isPK && type === 'INTEGER') {
$ai.prop('disabled', false);
} else {
$ai.prop('disabled', true).prop('checked', false);
}
}
function openEditTableOverlay() {
if (!DB || !CURRENT_TABLE) {
document.getElementById("tableList").innerHTML = '<div class="alert alert-danger mb-0">First you must select a table.</div>';
return;
}
overlayMode = 'edit-table';
const $form = $('#recordForm');
const $title = $('#overlay-title');
$title.text(`Editar Tabla: ${CURRENT_TABLE}`);
// Cargar estructura de la tabla
const schemaRes = DB.exec(`PRAGMA table_info("${CURRENT_TABLE}");`);
if (!schemaRes || !schemaRes[0] || !schemaRes[0].values) {
alert('Could not load table structure.');
return;
}
const fields = schemaRes[0].values.map(row => ({
cid: row[0], // Column ID
name: row[1], // Nombre
type: row[2], // Tipo
notnull: row[3], // NOT NULL (1 = sí, 0 = no)
dflt_value: row[4], // DEFAULT
pk: row[5] // PRIMARY KEY (0 = no, >0 = sí)
}));