Repository navigation
Expand file tree
/
Copy pathjson_gui.py
More file actions
982 lines (881 loc) · 37.7 KB
/
Copy pathjson_gui.py
File metadata and controls
982 lines (881 loc) · 37.7 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
"""PyQt6 GUI application for editing JSON tables as a database."""
from __future__ import annotations
import os
import sys
import json
from typing import Any, Dict, List
from PyQt6 import QtCore, QtGui, QtWidgets
from database import JSONDatabase
def natural_key(val: Any) -> Any:
"""Helper for natural sorting of numeric strings."""
if val is None:
return (0, "")
if isinstance(val, str):
try:
return (1, int(val))
except ValueError:
try:
return (1, float(val))
except ValueError:
return (2, val.lower())
return (1, val)
class TableModel(QtCore.QAbstractTableModel):
"""Table model backed by the JSON database.
The model exposes helper methods so rows can be inserted, updated or
removed while notifying any attached views properly. Qt views expect the
model to signal structural changes with `beginInsertRows`/`endInsertRows`
and friends. Without these signals the view can become out of sync and the
application may crash when modifying the data repeatedly.
"""
def __init__(self, db: JSONDatabase, table: str = "") -> None:
super().__init__()
self.db = db
self.table = table
# API required by Qt -------------------------------------------------
def rowCount(self, parent: QtCore.QModelIndex | QtCore.QObject = None) -> int: # type: ignore[override]
return len(self.db.tables.get(self.table, []))
def columnCount(self, parent: QtCore.QModelIndex | QtCore.QObject = None) -> int: # type: ignore[override]
return len(self.db.types.get(self.table, {}))
def data(self, index: QtCore.QModelIndex, role: int = QtCore.Qt.ItemDataRole.DisplayRole) -> Any: # type: ignore[override]
if not index.isValid() or role != QtCore.Qt.ItemDataRole.DisplayRole:
return None
rows = self.db.tables.get(self.table, [])
cols = list(self.db.types.get(self.table, {}))
if index.row() >= len(rows) or index.column() >= len(cols):
return None
row = rows[index.row()]
value = row.get(cols[index.column()])
if value is True:
return "True"
if value is False:
return "False"
return "" if value is None else str(value)
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = QtCore.Qt.ItemDataRole.DisplayRole) -> Any: # type: ignore[override]
if role == QtCore.Qt.ItemDataRole.DisplayRole and orientation == QtCore.Qt.Orientation.Horizontal:
cols = list(self.db.types.get(self.table, {}))
if 0 <= section < len(cols):
return cols[section]
return super().headerData(section, orientation, role)
def sort(self, column: int, order: QtCore.Qt.SortOrder = QtCore.Qt.SortOrder.AscendingOrder) -> None: # type: ignore[override]
if not self.table:
return
cols = list(self.db.types.get(self.table, {}))
if not (0 <= column < len(cols)):
return
col = cols[column]
def sort_key(row: Dict[str, Any]) -> Any:
val = row.get(col)
return natural_key(val)
self.db.tables[self.table].sort(key=sort_key, reverse=order == QtCore.Qt.SortOrder.DescendingOrder)
self.layoutChanged.emit()
# Helpers ------------------------------------------------------------
def set_table(self, table: str) -> None:
"""Switch the model to a different table and reset the view."""
self.beginResetModel()
self.table = table
self.endResetModel()
def insert_row(self, row: Dict[str, Any]) -> int:
"""Insert ``row`` at the end of the current table.
Returns the index of the inserted row.
"""
self.db.check_row(self.table, row)
rows = self.db.tables[self.table]
row_idx = len(rows)
self.beginInsertRows(QtCore.QModelIndex(), row_idx, row_idx)
self.db.add_row(self.table, row)
self.endInsertRows()
return row_idx
def update_row(self, index: int, row: Dict[str, Any]) -> None:
"""Update a row and notify the view."""
self.db.check_row(self.table, row, index)
self.db.update_row(self.table, index, row)
top_left = self.index(index, 0)
bottom_right = self.index(index, self.columnCount() - 1)
self.dataChanged.emit(top_left, bottom_right)
def remove_row(self, index: int) -> None:
"""Remove a row from the current table."""
self.beginRemoveRows(QtCore.QModelIndex(), index, index)
self.db.delete_row(self.table, index)
self.endRemoveRows()
class FilterProxyModel(QtCore.QSortFilterProxyModel):
"""Proxy model implementing text filtering across rows."""
def __init__(self) -> None:
super().__init__()
self.search_text = ""
self.search_column: str | None = None
def set_search(self, text: str, column: str | None) -> None:
self.search_text = text.lower()
self.search_column = None if column in (None, "All") else column
self.invalidateFilter()
def filterAcceptsRow(self, source_row: int, source_parent: QtCore.QModelIndex) -> bool: # type: ignore[override]
model: TableModel = self.sourceModel() # type: ignore[assignment]
if source_row >= model.rowCount():
return False
if not self.search_text:
return True
row = model.db.tables.get(model.table, [])[source_row]
if self.search_column:
val = row.get(self.search_column)
txt = "none" if val is None else str(val).lower()
return self.search_text in txt
for val in row.values():
txt = "none" if val is None else str(val).lower()
if self.search_text in txt:
return True
return False
def lessThan(self, left: QtCore.QModelIndex, right: QtCore.QModelIndex) -> bool: # type: ignore[override]
lval = left.data()
rval = right.data()
def conv(v: Any) -> Any:
if v is None or v == "":
return None
if isinstance(v, str):
try:
return int(v)
except ValueError:
try:
return float(v)
except ValueError:
return v.lower()
return v
lconv = conv(lval)
rconv = conv(rval)
return (lconv is None, lconv) < (rconv is None, rconv)
class RowDialog(QtWidgets.QDialog):
data_ready = QtCore.pyqtSignal(dict)
def __init__(
self,
parent: QtWidgets.QWidget | None,
db: JSONDatabase,
table: str,
data: Dict[str, Any] | None = None,
focus_col: str | None = None,
row_index: int | None = None,
) -> None:
super().__init__(parent)
self.db = db
self.table = table
self.data = data or {}
self.focus_col = focus_col
self.row_index = row_index
self.edits: Dict[str, QtWidgets.QWidget] = {}
self.result_data: Dict[str, Any] | None = None
self.setWindowTitle("Edit Row")
self.layout = QtWidgets.QFormLayout(self)
for col, coltype in self.db.types.get(table, {}).items():
value = self.data.get(col)
link = self.db.get_link(table, col)
if coltype is bool:
cb = QtWidgets.QCheckBox()
cb.setChecked(bool(value))
self.edits[col] = cb
self.layout.addRow(f"{col} (bool)", cb)
elif link:
combo = QtWidgets.QComboBox()
combo.setEditable(False)
ids = [r.get(link['target_column']) for r in self.db.tables.get(link['target_table'], [])]
ids = [v for v in ids if v is not None]
for item in ["<None>", "<Add new…>"] + [str(v) for v in sorted(ids, key=natural_key)]:
combo.addItem(item)
if value is None:
combo.setCurrentIndex(0)
else:
idx = combo.findText(str(value))
if idx >= 0:
combo.setCurrentIndex(idx)
else:
combo.addItem(str(value))
combo.setCurrentText(str(value))
combo.currentIndexChanged.connect(
lambda i, c=col, l=link, w=combo: self._handle_link_combo(i, c, l, w)
)
self.edits[col] = combo
self.layout.addRow(f"{col} ({coltype.__name__})", combo)
elif coltype in (str, int, float):
e = QtWidgets.QLineEdit(str(value) if value is not None else "")
self.edits[col] = e
self.layout.addRow(f"{col} ({coltype.__name__})", e)
else:
txt = json.dumps(value, ensure_ascii=False, indent=2) if value is not None else "null"
view = QtWidgets.QPlainTextEdit(txt)
view.setReadOnly(True)
self.layout.addRow(f"{col} ({coltype.__name__}, read-only)", view)
btn_box = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.StandardButton.Ok
| QtWidgets.QDialogButtonBox.StandardButton.Cancel
)
btn_box.accepted.connect(self.handle_accept)
btn_box.rejected.connect(self.reject)
self.layout.addWidget(btn_box)
if self.focus_col and self.focus_col in self.edits:
widget = self.edits[self.focus_col]
widget.setFocus()
if isinstance(widget, QtWidgets.QLineEdit):
widget.selectAll()
def handle_accept(self) -> None:
data: Dict[str, Any] = {
c: self.data.get(c)
for c in self.db.types.get(self.table, {})
if c not in self.edits
}
for col, widget in self.edits.items():
coltype = self.db.types[self.table].get(col, str)
if isinstance(widget, QtWidgets.QCheckBox):
data[col] = widget.isChecked()
continue
if isinstance(widget, QtWidgets.QComboBox):
text = widget.currentText().strip()
if text == "<None>":
data[col] = None
continue
else:
text = widget.text().strip()
if text == "":
data[col] = None
continue
try:
if coltype is int:
data[col] = int(text)
elif coltype is float:
data[col] = float(text)
elif coltype is bool:
data[col] = text.lower() in {"1", "true", "yes"}
else:
data[col] = text
except Exception:
QtWidgets.QMessageBox.critical(self, "Error", f"Invalid value for {col}")
return
try:
self.db.check_row(self.table, data, self.row_index)
except ValueError as e:
parent = self.parent()
if hasattr(parent, "_handle_link_error"):
parent._handle_link_error(str(e))
else:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
self.result_data = data
self.data_ready.emit(data)
self.accept()
def _handle_link_combo(
self,
index: int,
column: str,
link: Dict[str, str],
combo: QtWidgets.QComboBox,
) -> None:
if combo.itemText(index) != "<Add new…>":
return
template = {
c: (self.db.next_id.get(link["target_table"], 1) if c == "id" else None)
for c in self.db.types.get(link["target_table"], {})
}
parent = self.parent()
def on_accept(row: Dict[str, Any]) -> None:
try:
self.db.add_row(link["target_table"], row)
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
combo.setCurrentIndex(0)
return
ids = [r.get(link['target_column']) for r in self.db.tables.get(link['target_table'], []) if r.get(link['target_column']) is not None]
combo.blockSignals(True)
combo.clear()
for item in ["<None>", "<Add new…>"] + [str(v) for v in sorted(ids, key=natural_key)]:
combo.addItem(item)
combo.setCurrentText(str(row.get(link['target_column'])))
combo.blockSignals(False)
if hasattr(parent, 'populate_tables'):
parent.populate_tables(True)
if hasattr(parent, 'mark_dirty'):
parent.mark_dirty()
if hasattr(parent, '_open_row_dialog'):
parent._open_row_dialog(link["target_table"], template, link["target_column"], None, on_accept)
else:
dlg = RowDialog(parent, self.db, link["target_table"], template, focus_col=link["target_column"])
dlg.data_ready.connect(on_accept)
dlg.show()
def get_data(self) -> Dict[str, Any] | None:
if self.exec() != QtWidgets.QDialog.DialogCode.Accepted:
return None
return self.result_data
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, db: JSONDatabase) -> None:
super().__init__()
self.db = db
self.setWindowTitle("JSON Database Editor")
self.resize(1000, 600)
QtWidgets.QApplication.setStyle("Fusion")
self.current_table: str | None = None
self.current_columns: list[str] = []
self._links_win: QtWidgets.QDialog | None = None
self._row_dialogs: list[QtWidgets.QDialog] = []
self.dirty: bool = False
self.build_ui()
self.populate_tables()
# ------------------------------------------------------------------
def mark_dirty(self) -> None:
if not self.dirty:
self.dirty = True
self.setWindowTitle("JSON Database Editor *")
def clear_dirty(self) -> None:
if self.dirty:
self.dirty = False
self.setWindowTitle("JSON Database Editor")
# UI -----------------------------------------------------------------
def build_ui(self) -> None:
central = QtWidgets.QWidget()
self.setCentralWidget(central)
layout = QtWidgets.QHBoxLayout(central)
self.table_list = QtWidgets.QListWidget()
self.table_list.itemSelectionChanged.connect(self.on_table_selected)
layout.addWidget(self.table_list, 1)
right = QtWidgets.QVBoxLayout()
layout.addLayout(right, 4)
top_bar = QtWidgets.QHBoxLayout()
right.addLayout(top_bar)
self.search_column = QtWidgets.QComboBox()
self.search_column.addItem("All")
self.search_column.currentTextChanged.connect(self.refresh_table)
top_bar.addWidget(self.search_column)
self.search_box = QtWidgets.QLineEdit()
self.search_box.setPlaceholderText("Search…")
self.search_box.returnPressed.connect(self.refresh_table)
top_bar.addWidget(self.search_box, 1)
search_btn = QtWidgets.QPushButton("Search")
search_btn.clicked.connect(self.refresh_table)
top_bar.addWidget(search_btn)
self.sort_chk = QtWidgets.QCheckBox("Enable Sorting")
self.sort_chk.setChecked(False)
self.sort_chk.toggled.connect(self.toggle_sorting)
top_bar.addWidget(self.sort_chk)
self.add_table_btn = QtWidgets.QPushButton("Add Table")
self.add_table_btn.clicked.connect(self.add_table)
top_bar.addWidget(self.add_table_btn)
self.del_table_btn = QtWidgets.QPushButton("Remove Table")
self.del_table_btn.clicked.connect(self.remove_table)
top_bar.addWidget(self.del_table_btn)
self.links_btn = QtWidgets.QPushButton("Manage Links")
self.links_btn.clicked.connect(self.manage_links)
top_bar.addWidget(self.links_btn)
self.meta_btn = QtWidgets.QPushButton("Metadata")
self.meta_btn.clicked.connect(self.manage_metadata)
top_bar.addWidget(self.meta_btn)
self.save_btn = QtWidgets.QPushButton("Save")
self.save_btn.clicked.connect(self.save)
top_bar.addWidget(self.save_btn)
self.model = TableModel(self.db)
self.proxy = FilterProxyModel()
self.proxy.setSourceModel(self.model)
self.table = QtWidgets.QTableView()
self.table.setModel(self.proxy)
self.table.setSortingEnabled(False)
self.table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
self.table.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)
self.table.doubleClicked.connect(self.edit_row)
right.addWidget(self.table, 1)
self.toggle_sorting(False)
row_btns = QtWidgets.QHBoxLayout()
right.addLayout(row_btns)
add_btn = QtWidgets.QPushButton("Add Row")
add_btn.clicked.connect(self.add_row)
row_btns.addWidget(add_btn)
edit_btn = QtWidgets.QPushButton("Edit Row")
edit_btn.clicked.connect(self.edit_row)
row_btns.addWidget(edit_btn)
del_btn = QtWidgets.QPushButton("Delete Row")
del_btn.clicked.connect(self.delete_row)
row_btns.addWidget(del_btn)
add_col_btn = QtWidgets.QPushButton("Add Column")
add_col_btn.clicked.connect(self.add_column)
row_btns.addWidget(add_col_btn)
del_col_btn = QtWidgets.QPushButton("Remove Column")
del_col_btn.clicked.connect(self.remove_column)
row_btns.addWidget(del_col_btn)
# Table management ---------------------------------------------------
def populate_tables(self, keep_current: bool = False) -> None:
current = self.current_table if keep_current else None
names = sorted(self.db.tables)
self.table_list.clear()
for name in names:
self.table_list.addItem(name)
if current and current in self.db.tables:
self.table_list.setCurrentRow(names.index(current))
elif self.db.tables:
self.table_list.setCurrentRow(0)
def on_table_selected(self) -> None:
items = self.table_list.selectedItems()
if not items:
return
self.current_table = items[0].text()
self.refresh_table()
def refresh_table(self) -> None:
table = self.current_table
if not table:
return
self.current_columns = list(self.db.types.get(table, {}))
self.search_column.blockSignals(True)
self.search_column.clear()
self.search_column.addItem("All")
for col in self.current_columns:
self.search_column.addItem(col)
self.search_column.blockSignals(False)
self.model.set_table(table)
self.proxy.set_search(self.search_box.text(), self.search_column.currentText())
def toggle_sorting(self, enabled: bool) -> None:
self.table.setSortingEnabled(enabled)
if enabled:
self.table.sortByColumn(0, QtCore.Qt.SortOrder.AscendingOrder)
else:
self.proxy.sort(-1)
# Actions -----------------------------------------------------------
def add_table(self) -> None:
name, ok = QtWidgets.QInputDialog.getText(self, "Add Table", "Table name:")
if not ok or not name:
return
try:
self.db.add_table(name)
except ValueError as e:
self._handle_link_error(str(e))
return
self.populate_tables()
self.mark_dirty()
def remove_table(self) -> None:
table = self.current_table
if not table:
return
if QtWidgets.QMessageBox.question(self, "Confirm", f"Delete table {table}?") != QtWidgets.QMessageBox.StandardButton.Yes:
return
self.db.remove_table(table)
removed = self.db.prune_links()
self.populate_tables()
if removed:
msg = "The following invalid link(s) were removed:\n" + "\n".join(
f"{l['source_table']}.{l['source_column']} -> {l['target_table']}.{l['target_column']}"
for l in removed
)
QtWidgets.QMessageBox.information(self, "Links updated", msg)
self.mark_dirty()
def add_column(self) -> None:
table = self.current_table
if not table:
return
dlg = QtWidgets.QDialog(self)
dlg.setWindowTitle("Add Column")
layout = QtWidgets.QFormLayout(dlg)
name_edit = QtWidgets.QLineEdit()
layout.addRow("Name", name_edit)
type_box = QtWidgets.QComboBox()
type_box.addItems(["str", "int", "float", "bool"])
layout.addRow("Type", type_box)
default_edit = QtWidgets.QLineEdit()
layout.addRow("Default", default_edit)
link_chk = QtWidgets.QCheckBox("Create link")
layout.addRow(link_chk)
tgt_table = QtWidgets.QComboBox()
tgt_table.addItems(sorted(self.db.tables))
tgt_col = QtWidgets.QComboBox()
def upd_tgt_cols() -> None:
table_name = tgt_table.currentText()
tgt_col.clear()
tgt_col.addItems(self.db.types.get(table_name, {}).keys())
tgt_table.currentTextChanged.connect(upd_tgt_cols)
upd_tgt_cols()
layout.addRow("Target table", tgt_table)
layout.addRow("Target column", tgt_col)
def update_dtype() -> None:
if not link_chk.isChecked():
return
dtype = self.db.types.get(tgt_table.currentText(), {}).get(
tgt_col.currentText(), str
)
name = {str: "str", int: "int", float: "float", bool: "bool"}.get(dtype, "str")
type_box.setCurrentText(name)
def toggle_link(enabled: bool) -> None:
tgt_table.setEnabled(enabled)
tgt_col.setEnabled(enabled)
type_box.setEnabled(not enabled)
update_dtype()
tgt_table.currentTextChanged.connect(update_dtype)
tgt_col.currentTextChanged.connect(update_dtype)
link_chk.toggled.connect(toggle_link)
toggle_link(False)
btn_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.StandardButton.Ok | QtWidgets.QDialogButtonBox.StandardButton.Cancel)
layout.addWidget(btn_box)
btn_box.accepted.connect(dlg.accept)
btn_box.rejected.connect(dlg.reject)
if dlg.exec() != QtWidgets.QDialog.DialogCode.Accepted:
return
name = name_edit.text().strip()
if not name:
return
dtype_name = type_box.currentText()
raw = default_edit.text().strip()
if raw == "":
default = None
else:
try:
if dtype_name == "int":
default = int(raw)
elif dtype_name == "float":
default = float(raw)
elif dtype_name == "bool":
default = raw.lower() in {"1", "true", "yes"}
else:
default = raw
except ValueError:
QtWidgets.QMessageBox.critical(self, "Error", "Invalid default value")
return
try:
dtype = {"str": str, "int": int, "float": float, "bool": bool}[dtype_name]
self.db.add_column(table, name, default, dtype)
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
return
if link_chk.isChecked():
try:
self.db.add_link(
table,
name,
tgt_table.currentText(),
tgt_col.currentText(),
)
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
# proceed without link
self.refresh_table()
self.mark_dirty()
def remove_column(self) -> None:
table = self.current_table
if not table:
return
column, ok = QtWidgets.QInputDialog.getText(self, "Remove Column", "Column name:")
if not ok or not column:
return
self.db.remove_column(table, column)
removed = self.db.prune_links()
self.refresh_table()
if removed:
msg = "The following invalid link(s) were removed:\n" + "\n".join(
f"{l['source_table']}.{l['source_column']} -> {l['target_table']}.{l['target_column']}"
for l in removed
)
QtWidgets.QMessageBox.information(self, "Links updated", msg)
self.mark_dirty()
def _open_row_dialog(
self,
table: str,
data: Dict[str, Any] | None,
focus_col: str | None,
row_index: int | None,
callback,
) -> None:
dlg = RowDialog(self, self.db, table, data, focus_col=focus_col, row_index=row_index)
dlg.setAttribute(QtCore.Qt.WidgetAttribute.WA_DeleteOnClose)
self._row_dialogs.append(dlg)
def finalize(*args: Any, dlg=dlg) -> None:
if dlg in self._row_dialogs:
self._row_dialogs.remove(dlg)
dlg.destroyed.connect(finalize)
if callback:
dlg.data_ready.connect(callback)
dlg.show()
def add_row(self) -> None:
table = self.current_table
if not table:
return
template = {col: (self.db.next_id.get(table, 1) if col == 'id' else None) for col in self.db.types.get(table, {})}
def on_accept(data: Dict[str, Any], tbl=table) -> None:
try:
if self.model.table == tbl:
row_idx = self.model.insert_row(data)
self.proxy.invalidate()
proxy_index = self.proxy.mapFromSource(self.model.index(row_idx, 0))
if proxy_index.isValid():
self.table.selectRow(proxy_index.row())
else:
self.db.add_row(tbl, data)
self.mark_dirty()
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
self._open_row_dialog(table, template, None, None, on_accept)
def edit_row(self, index: QtCore.QModelIndex | None = None) -> None:
table = self.current_table
if not table:
return
if index is not None and index.isValid():
src = self.proxy.mapToSource(index)
row_idx = src.row()
focus_col = self.current_columns[src.column()]
else:
rows = self.table.selectionModel().selectedRows()
if rows:
src = self.proxy.mapToSource(rows[0])
row_idx = src.row()
else:
row_idx = self.proxy.mapToSource(self.table.currentIndex()).row()
if row_idx < 0:
return
focus_col = None
row_data = self.db.tables[table][row_idx]
def on_accept(data: Dict[str, Any], tbl=table, r=row_idx) -> None:
try:
if self.model.table == tbl:
self.model.update_row(r, data)
self.proxy.invalidate()
proxy_row = self.proxy.mapFromSource(self.model.index(r, 0)).row()
if proxy_row >= 0:
self.table.selectRow(proxy_row)
else:
self.db.update_row(tbl, r, data)
self.mark_dirty()
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
self._open_row_dialog(table, row_data, focus_col, row_index=row_idx, callback=on_accept)
def delete_row(self) -> None:
table = self.current_table
if not table:
return
rows = self.table.selectionModel().selectedRows()
if not rows:
return
index = self.proxy.mapToSource(rows[0]).row()
if QtWidgets.QMessageBox.question(self, "Confirm", "Delete selected row?") != QtWidgets.QMessageBox.StandardButton.Yes:
return
self.model.remove_row(index)
self.proxy.invalidate()
self.mark_dirty()
def save(self) -> None:
self.db.save()
QtWidgets.QMessageBox.information(self, "Saved", "Changes saved")
self.clear_dirty()
def _handle_link_error(self, msg: str) -> None:
if "not found in" not in msg:
QtWidgets.QMessageBox.critical(self, "Error", msg)
return
if QtWidgets.QMessageBox.question(
self,
"Missing value",
msg + "\nAdd it now?",
) != QtWidgets.QMessageBox.StandardButton.Yes:
return
try:
rest = msg.split(" in ")[1]
target_table, target_col = rest.split(".")
value = msg.split("Value ")[1].split(" ")[0].strip("'\"")
except Exception:
QtWidgets.QMessageBox.critical(self, "Error", msg)
return
template = {
col: (
self.db.next_id.get(target_table, 1) if col == "id" else None
)
for col in self.db.types.get(target_table, {})
}
template[target_col] = value
def on_accept(row: Dict[str, Any]) -> None:
try:
self.db.add_row(target_table, row)
self.populate_tables(True)
self.mark_dirty()
except ValueError as e:
QtWidgets.QMessageBox.critical(self, "Error", str(e))
self._open_row_dialog(target_table, template, target_col, None, on_accept)
def manage_links(self) -> None:
if hasattr(self, "_links_win") and self._links_win is not None:
self._links_win.raise_()
self._links_win.activateWindow()
return
dlg = QtWidgets.QDialog(self)
dlg.setAttribute(QtCore.Qt.WidgetAttribute.WA_DeleteOnClose)
dlg.destroyed.connect(lambda *_: setattr(self, "_links_win", None))
dlg.setWindowTitle("Manage Links")
vbox = QtWidgets.QVBoxLayout(dlg)
tree = QtWidgets.QTreeWidget()
tree.setHeaderHidden(True)
removed = self.db.prune_links()
if removed:
self.mark_dirty()
msg = "The following invalid link(s) were removed:\n" + "\n".join(
f"{l['source_table']}.{l['source_column']} -> {l['target_table']}.{l['target_column']}"
for l in removed
)
QtWidgets.QMessageBox.information(dlg, "Links updated", msg)
def refresh_links() -> None:
tree.clear()
groups: dict[str, QtWidgets.QTreeWidgetItem] = {}
for idx, link in sorted(
enumerate(self.db.links),
key=lambda p: (
p[1]["source_table"],
p[1]["target_table"],
p[1]["source_column"],
p[1]["target_column"],
),
):
key = link["source_table"]
parent = groups.get(key)
if parent is None:
parent = QtWidgets.QTreeWidgetItem([key])
parent.setFlags(QtCore.Qt.ItemFlag.ItemIsEnabled)
tree.addTopLevelItem(parent)
groups[key] = parent
child = QtWidgets.QTreeWidgetItem(
[f"{link['source_column']} -> {link['target_table']}.{link['target_column']}"]
)
child.setData(0, QtCore.Qt.ItemDataRole.UserRole, idx)
parent.addChild(child)
for item in groups.values():
item.setExpanded(True)
refresh_links()
vbox.addWidget(tree)
btn_box = QtWidgets.QHBoxLayout()
add_btn = QtWidgets.QPushButton("Add")
rem_btn = QtWidgets.QPushButton("Remove")
btn_box.addWidget(add_btn)
btn_box.addWidget(rem_btn)
vbox.addLayout(btn_box)
close_btn = QtWidgets.QPushButton("Close")
vbox.addWidget(close_btn)
def add_link(_checked: bool = False) -> None:
ad = QtWidgets.QDialog(dlg)
ad.setWindowTitle("Add Link")
form = QtWidgets.QFormLayout(ad)
src_table = QtWidgets.QComboBox()
src_table.addItems(sorted(self.db.tables))
src_col = QtWidgets.QComboBox()
tgt_table = QtWidgets.QComboBox()
tgt_table.addItems(sorted(self.db.tables))
tgt_col = QtWidgets.QComboBox()
def upd_src() -> None:
src_col.clear()
src_col.addItems(self.db.types.get(src_table.currentText(), {}).keys())
def upd_tgt() -> None:
tgt_col.clear()
tgt_col.addItems(self.db.types.get(tgt_table.currentText(), {}).keys())
src_table.currentTextChanged.connect(upd_src)
tgt_table.currentTextChanged.connect(upd_tgt)
upd_src()
upd_tgt()
form.addRow("Source table", src_table)
form.addRow("Source column", src_col)
form.addRow("Target table", tgt_table)
form.addRow("Target column", tgt_col)
bb = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.StandardButton.Ok
| QtWidgets.QDialogButtonBox.StandardButton.Cancel
)
form.addWidget(bb)
bb.accepted.connect(ad.accept)
bb.rejected.connect(ad.reject)
if ad.exec() != QtWidgets.QDialog.DialogCode.Accepted:
return
try:
self.db.add_link(
src_table.currentText(),
src_col.currentText(),
tgt_table.currentText(),
tgt_col.currentText(),
)
refresh_links()
self.mark_dirty()
except ValueError as e:
QtWidgets.QMessageBox.critical(dlg, "Error", str(e))
def remove_link(_checked: bool = False) -> None:
item = tree.currentItem()
if not item:
return
idx = item.data(0, QtCore.Qt.ItemDataRole.UserRole)
if idx is None:
return
self.db.remove_link(int(idx))
refresh_links()
self.mark_dirty()
add_btn.clicked.connect(add_link)
rem_btn.clicked.connect(remove_link)
close_btn.clicked.connect(dlg.close)
self._links_win = dlg
dlg.show()
def manage_metadata(self) -> None:
table = self.current_table
if not table:
return
meta = dict(self.db.meta.get(table, {}))
dlg = QtWidgets.QDialog(self)
dlg.setWindowTitle(f"Metadata: {table}")
vbox = QtWidgets.QVBoxLayout(dlg)
form = QtWidgets.QFormLayout()
vbox.addLayout(form)
edits: Dict[str, QtWidgets.QLineEdit] = {}
removed: set[str] = set()
for key, val in meta.items():
if key == "last_updated":
lbl = QtWidgets.QLabel("" if val is None else str(val))
form.addRow(key, lbl)
continue
le = QtWidgets.QLineEdit("" if val is None else str(val))
edits[key] = le
form.addRow(key, le)
btn_row = QtWidgets.QHBoxLayout()
add_field_btn = QtWidgets.QPushButton("Add Field")
remove_field_btn = QtWidgets.QPushButton("Remove Field")
btn_row.addWidget(add_field_btn)
btn_row.addWidget(remove_field_btn)
vbox.addLayout(btn_row)
apply_all_chk = QtWidgets.QCheckBox("Apply to all tables")
vbox.addWidget(apply_all_chk)
bb = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.StandardButton.Ok
| QtWidgets.QDialogButtonBox.StandardButton.Cancel
)
vbox.addWidget(bb)
def add_field() -> None:
name, ok = QtWidgets.QInputDialog.getText(dlg, "Add Field", "Field name:")
if not ok or not name or name in edits or name in meta or name in {"table", "rows", "last_updated"}:
return
le = QtWidgets.QLineEdit()
edits[name] = le
form.addRow(name, le)
def remove_field() -> None:
fields = [k for k in edits if k not in {"table", "rows", "last_updated"}]
if not fields:
return
field, ok = QtWidgets.QInputDialog.getItem(dlg, "Remove Field", "Field:", fields, 0, False)
if not ok or not field:
return
widget = edits.pop(field)
form.removeRow(widget)
removed.add(field)
add_field_btn.clicked.connect(add_field)
remove_field_btn.clicked.connect(remove_field)
bb.accepted.connect(dlg.accept)
bb.rejected.connect(dlg.reject)
if dlg.exec() != QtWidgets.QDialog.DialogCode.Accepted:
return
updates = {k: (None if e.text().strip() == "" else e.text().strip()) for k, e in edits.items()}
self.db.update_metadata(table, updates, apply_all_chk.isChecked())
for field in removed:
self.db.remove_metadata_field(field, table, apply_all_chk.isChecked())
self.populate_tables(True)
self.mark_dirty()
def closeEvent(self, event: QtGui.QCloseEvent) -> None:
if self.dirty:
res = QtWidgets.QMessageBox.question(
self,
"Unsaved changes",
"You have unsaved changes. Quit anyway?",
QtWidgets.QMessageBox.StandardButton.Yes | QtWidgets.QMessageBox.StandardButton.No,
)
if res != QtWidgets.QMessageBox.StandardButton.Yes:
event.ignore()
return
event.accept()
def main() -> None:
db = JSONDatabase(os.getcwd())
app = QtWidgets.QApplication(sys.argv)
win = MainWindow(db)
win.show()
app.exec()
if __name__ == "__main__":
main()