-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpgmacs.el
3583 lines (3363 loc) · 171 KB
/
pgmacs.el
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
;;; pgmacs.el --- Emacs is editing a PostgreSQL database -*- lexical-binding: t; -*-
;; Copyright (C) 2023-2025 Eric Marsden
;; Author: Eric Marsden <[email protected]>
;; Version: 0.22
;; Package-Requires: ((emacs "29.1") (pg "0.48"))
;; URL: https://github.com/emarsden/pgmacs/
;; Keywords: data, PostgreSQL, database
;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Commentary:
;;
;; See README.md at https://github.com/emarsden/pgmacs/
;;; Code:
(require 'cl-lib)
(require 'eieio)
(require 'button)
(require 'widget)
(require 'wid-edit)
(require 'cus-edit)
(require 'svg)
(require 'rx)
(require 'sql)
(require 'pg)
(require 'pgmacstbl)
(require 'pgmacs-sql-keywords)
(defgroup pgmacs nil
"Browse and edit a PostgreSQL database from Emacs."
:prefix "pgmacs-"
:group 'tools
:link '(url-link :tag "Github" "https://github.com/emarsden/pgmacs/"))
(defface pgmacs-table-data
'((t (:inherit fixed-pitch-serif
:foreground "black")))
"Face used to display data in a PGmacs database table."
:group 'pgmacs)
(defface pgmacs-column-foreign-key
'((t (:inherit pgmacs-table-data
:foreground "blue")))
"Face used to display data in a column that references another table."
:group 'pgmacs)
(defface pgmacs-column-primary-key
'((t (:inherit pgmacs-table-data
:bold t)))
"Face used to display data in a column that is part of a primary key."
:group 'pgmacs)
(defface pgmacs-table-header
'((((class color) (background light))
:bold t
:background "lightgray"
:foreground "darkolivegreen")
(((class color) (background dark))
:bold t
:background "darkolivegreen"
:foreground "lightgreen"))
"Face used to display a PGmacs database table header."
:group 'pgmacs)
(defface pgmacs-where-filter
'((((class color) (background light))
;; This is a pale purple color
:background "#E6E6FA")
(((class color) (background dark))
:foreground "#E6E6FA"))
"Face used to display a PGmacs WHERE filter in a row-list buffer."
:group 'pgmacs)
(defface pgmacs-highlighted
'((((class color) (background light))
:weight bold
:foreground "blue")
(((class color) (background dark))
:weight bold
:foreground "lightblue"))
"Face used to draw attention to text."
:group 'pgmacs)
(defface pgmacs-muted
'((((class color) (background light))
:foreground "gray")
(((class color) (background dark))
:foreground "grey30"))
"Face used to display muted text."
:group 'pgmacs)
(defcustom pgmacs-deleted-color
"red"
"The background color used for table rows pending deletion."
:type 'color
:group 'pgmacs)
(defcustom pgmacs-row-colors
'("#D9CEB4" "#D9B96C")
"The colors used for alternating rows in a database table."
:type '(list color color)
:group 'pgmacs)
(defcustom pgmacs-row-limit 200
"The maximum number of rows to retrieve per database query.
If more rows are present in the PostgreSQL query result, the display of results
will be paginated. You may wish to set this to a low value if accessing
PostgreSQL over a slow network link."
:type 'number
:group 'pgmacs)
(defcustom pgmacs-large-database-threshold 100000000
"Avoid index/table scans for databases above this size in octets.
For a database larger than this value (queried via PostgreSQL
function pg_database_size), PGmacs will estimate table row counts
using an imprecise method that does not require a full index (or
table) scan, but will provide invalid results for tables that
have not been VACUUMed or ANALYZEd. For sizes below this
threshold, a more accurate SELECT COUNT(*) FROM table_name query
will be used.
If set to zero, full index/table scans will never be issued (this
may be a safe option on large production databases)."
:type 'number
:group 'pgmacs)
(defcustom pgmacs-max-column-width 60
"The maximal width in characters of a table column."
:type 'number
:group 'pgmacs)
(defcustom pgmacs-enable-query-logging nil
"Whether SQL queries sent to PostgreSQL should be logged."
:type 'boolean
:group 'pgmacs)
;; To run SchemaSpy on the current database or on the current table, and display images describing
;; the schema. The default setting runs SchemaSpy in a Docker/Podman software container, using
;; Podman or Docker. This is the easiest way of running SchemaSpy, because all necessary
;; dependencies are preinstalled. Alternatively (see commented commandline), you can run the
;; SchemaSpy java application natively, which requires the following software to be installed:
;;
;; - SchemaSpy (see schemaspy.org)
;; - Java
;; - GraphViz
;; - JDBC support for PostgreSQL (here in /usr/share/java/postgresql-jdbc4.jar, installable for example
;; using "sudo apt install libpostgresql-jdbc-java")
;;
;; The commandline below with "--userns=keep-id" is suitable for running a container in rootless
;; mode with Podman. This is because the SchemaSpy Dockerfile creates a new user "java" then runs as
;; that user. We can't map that new user id to our own id, because the java uid is not known prior
;; to the container running. With the --userns=keep-id option however, the USER will be mapped to
;; our own uid when running rootless.
(defcustom pgmacs-schemaspy-cmdline
"podman run -v %D:/output --userns=keep-id --network=host docker.io/schemaspy/schemaspy:latest -t pgsql11 -host %h -port %P -u %u -p %p -db %d -imageformat svg"
"Commandline for running the SchemaSpy application or container.
This commandline will be used both for generating an image
representing the relations between tables in the current
database, and for generating an image representing the schema of
the current table. In the latter case, the string ` -s %s -i %t'
will be appended to the commandline (with `%s' replaced by the
table schema name and `%t' by the table name).
SchemaSpy can be run as a Java application installed on the local
machine, or (probably easier for most users) in a Docker/Podman
software container that contains the necessary dependencies.
In this commandline, %d is replaced by the database name, %h by
the hostname on which PostgreSQL is running, %P by the port it is
running on, %u by the user, %p by the password, %s by the current
table schema name, %t by the current table name and %D by the
directory (which will be created in the system temporary
directory) in which output files are created by SchemaSpy. The %s
and %t values will only be used when generating illustrations
concerning a specific table, rather than the entire database."
:type 'string
:group 'pgmacs)
(defun pgmacs--maybe-svg-icon (svg-fn)
(if (and (display-graphic-p)
(image-type-available-p 'svg))
(let ((svg (funcall svg-fn)))
(propertize " " 'display svg 'rear-nonsticky t 'cursor-intangible t))
""))
(defcustom pgmacs-use-header-line t
"If non-nil, use header line to display information on PostgreSQL connection."
:type 'boolean
:group 'pgmacs)
;; This is set to a value which displays information on the current PostgreSQL connection in
;; function pgmacs-open.
(defvar pgmacs-header-line nil
"Header-line to use in PGmacs buffers. Nil to disable.")
(defcustom pgmacs-mode-hook nil
"Mode hook for `pgmacs-mode'."
:type 'hook
:group 'pgmacs)
(defcustom pgmacs-row-list-hook nil
"Functions to run after opening a PGmacs row-list buffer."
:type 'hook
:group 'pgmacs)
(defcustom pgmacs-timestamp-format "%Y-%m-%dT%T"
"Format string to be used for timestamp/timestamptz/datetime output."
:type 'string
:group 'pgmacs)
(defcustom pgmacs-timestamp-zone nil
"Time zone to be used for timestamp/timestamptz/datetime output,
e.g. `UTC' or `Europe/Berlin'. Nil for local OS timezone."
:type 'string
:group 'pgmacs)
;; TODO: it would be cleaner to hold these all in a pgmacs-connection object.
(defvar-local pgmacs--con nil)
(defvar-local pgmacs--table nil)
(defvar-local pgmacs--column-type-names nil)
(defvar-local pgmacs--offset nil)
(defvar-local pgmacs--db-buffer nil)
(defvar-local pgmacs--where-filter nil)
(defvar-local pgmacs--marked-rows (list))
(defvar-local pgmacs--completions nil)
(defclass pgmacs-shortcut-button ()
((label :initarg :label :type string)
;; Condition, if defined, is a function called with zero arguments that determines whether this
;; button should be inserted, bassed on characteristics of the current table, for example. It can
;; use buffer-local variables pgmacs--con and pgmacs--table.
(condition :initarg :condition :initform nil)
(action :initarg :action)
(help-echo :initarg :help-echo :initform nil)))
;; Insert OBJECT into the current buffer. Returns non-nil if the content was inserted (if its
;; condition slot evaluated to non-nil).
(cl-defgeneric pgmacs--insert (object))
(cl-defmethod pgmacs--insert ((btn pgmacs-shortcut-button))
(with-slots (label condition action help-echo) btn
(let ((disabled nil))
(when condition
(unless (funcall condition)
(setq disabled t)))
(unless disabled
(insert-text-button label 'action action 'help-echo help-echo)))))
;; It is possible to customize the row of text buttons that is displayed above the list of tables in
;; the main PGmacs buffer. Add an object that implements pgmacs--insert (such as a
;; pgmacs-shortcut-button object) to the pgmacs-table-list-buttons list.
(defvar pgmacs-table-list-buttons
(list (pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(questdb spanner))))
:label "Display procedures"
:action #'pgmacs--display-procedures)
(pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(cratedb questdb spanner))))
:label "Display running queries"
:action #'pgmacs--display-running-queries)
(pgmacs-shortcut-button
:label "Display databases"
:action #'pgmacs--display-database-list)
(pgmacs-shortcut-button
:label "Disconnect"
:action #'pgmacs-disconnect
:help-echo "Close this connection to PostgreSQL")
(pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(spanner))))
:label "More backend information"
:action #'pgmacs--display-backend-information)
(pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(questdb))))
:label "PostgreSQL settings"
:action (lambda (&rest _ignore)
(pgmacs-show-result pgmacs--con "SELECT * FROM pg_settings")))
(pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(cratedb questdb spanner))))
:label "Stat activity"
:action #'pgmacs--display-stat-activity
:help-echo "Show information from the pg_stat_activity table")
(pgmacs-shortcut-button
:condition (lambda () (not (member (pgcon-server-variant pgmacs--con) '(cratedb questdb spanner))))
:label "Replication stats"
:action #'pgmacs--display-replication-stats
:help-echo "Show information on PostgreSQL replication status"))
"List of shortcut buttons to display on the main table-list buffer.")
(defvar pgmacs-row-list-buttons
(list (pgmacs-shortcut-button
:label "Export table to CSV buffer"
:action #'pgmacs--table-to-csv
:help-echo "Export this table to a CSV buffer")
(pgmacs-shortcut-button
:condition (lambda () (null (pgmacs--table-primary-keys pgmacs--con pgmacs--table)))
:label "Add primary key to table"
:action #'pgmacs--add-primary-key
:help-echo "Add a PRIMARY KEY to enable editing")
(pgmacs-shortcut-button
:label "Count rows"
:action #'pgmacs--run-count
:help-echo "Count rows in this table")
(pgmacs-shortcut-button
;; CrateDB only supports ANALYZE on the whole database, not on a single table.
:condition (lambda () (not (eq (pgcon-server-variant pgmacs--con) 'cratedb)))
:label "ANALYZE this table"
:action #'pgmacs--run-analyze
:help-echo "Run ANALYZE on this table")
(pgmacs-shortcut-button
:condition (lambda ()
(unless (eq (pgcon-server-variant pgmacs--con) 'cratedb)
(null (pg-table-comment pgmacs--con pgmacs--table))))
:label "Add table comment"
:action (lambda (&rest _ignore)
(let ((comment (read-from-minibuffer "Table comment: ")))
(setf (pg-table-comment pgmacs--con pgmacs--table) comment))
(pgmacs--display-table pgmacs--table))
:help-echo "Add an SQL comment to the table")))
(defun pgmacs--widget-setup ()
"Set up the appearance of widgets used in PGmacs.
Uses customizations implemented in Emacs' customize support."
;; cus-edit.el has this rather rude keymap binding which adds to widget-field-keymap
;; bindings that are not relevant to us. So we revert it back to widget-field-keymap.
(widget-put (get 'editable-field 'widget-type) :keymap widget-field-keymap)
(setq-local widget-button-face custom-button
widget-button-pressed-face custom-button-pressed
widget-mouse-face custom-button-mouse)
(when custom-raised-buttons
(setq-local widget-push-button-prefix ""
widget-push-button-suffix ""
widget-link-prefix ""
widget-link-suffix "")))
(defvar-keymap pgmacs-table-list-map
:doc "Keymap for PGmacs table-list buffers"
(kbd "q") #'bury-buffer
(kbd "h") #'pgmacs--table-list-help
(kbd "?") #'pgmacs--table-list-help
(kbd "g") #'pgmacs--table-list-redraw
(kbd "o") #'pgmacs-open-table
(kbd "e") #'pgmacs-run-sql
(kbd "E") #'pgmacs-run-buffer-sql
(kbd "T") #'pgmacs--switch-to-database-buffer)
(define-key global-map [menu-bar tools PGmacs]
(cons "PGmacs" (make-sparse-keymap "PGmacs")))
(define-key global-map [menu-bar tools PGmacs open-uri]
'("Open PostgreSQL URI" . pgmacs-open-uri))
(define-key global-map [menu-bar tools PGmacs open-string]
'("Open PostgreSQL connection string" . pgmacs-open-string))
(define-key pgmacs-table-list-map [menu-bar tools PGmacs run-sql]
'("Run SQL query" . pgmacs-run-sql))
(defun pgmacs-mode ()
"Mode for browsing and editing data in a PostgreSQL database.
PGmacs provides an editing interface for PostgreSQL. The main
PGmacs table-list buffer that is displayed when you connect to a
database backend allows you to:
- browse the list of tables in the database
- browse/edit a table (type `RET' on the table name or `o' to be
prompted for a table name in the minibuffer)
- delete a table (type `DEL' on the table name)
- rename a table (type `r' on the table name)
- modify the SQL comment on a table (type `RET' in the `comment' column)
- show the output from an SQL query in table mode (type `e' to enter the
SQL query in the minibuffer)
- run SchemaSpy on the database to view its structure (type `S', only
available in graphical mode)
- type `h' to show buffer-specific help and keybindings
In a row-list buffer, which displays the rows of data in a
database table along with metainformation on the table (column
types and associated SQL constraints, on-disk size, table owner),
you can:
- browse the table contents row by row, in paginated mode for large
tables. Type `n' and `p' to move to the next/previous page in a
paginated buffer.
- use `M-right' and `M-left' to move to the next/previous column,
type a number to move to that column (numbering is zero-based)
- edit the data value at point (type `RET' on the value you want to
modify to edit it in the minibuffer, or `w' to open a dedicated
widget-based editing buffer)
- insert a new row by typing `+' (you will be prompted in the minibuffer
for new values, unless an SQL default value is defined) or by typing
`i' (opens a dedicated widget-based buffer for you to enter the new
values).
- copy the current row to the kill ring in JSON format (type `j' on the
row you want to serialize to JSON)
- delete a row (type `DEL' on the row you wish to delete)
- copy/paste rows of a database table (type `k' to copy, `y' to paste)
- export the contents of a table to CSV using a dedicated button
- type `S' to run SchemaSpy on the current table and display its structure
- type `o' to open a new row-list buffer for another table
- type `T' to jump back to the main table-list buffer
- type `h' to show buffer-specific help and keybindings
Please note that edits, insertions and deletions are made immediately on
the live PostgreSQL database.
See the `pgmacs' customization group for a list of user options.
Entering this mode runs the functions on `pgmacs-mode-hook'.
"
(setq major-mode 'pgmacs-mode
mode-name "PGmacs")
(when (and pgmacs-use-header-line pgmacs-header-line)
(setq header-line-format pgmacs-header-line))
;; Not appropriate for user to type stuff into our buffers.
(put 'pgmacs-mode 'mode-class 'special)
(use-local-map pgmacs-table-list-map)
(pgmacs--widget-setup)
(cursor-intangible-mode 1)
(buffer-disable-undo)
(run-mode-hooks 'pgmacs-mode-hook))
(defvar-keymap pgmacs-row-list-map
:doc "Keymap for PGmacs row-list buffers"
(kbd "q") #'bury-buffer
(kbd "h") #'pgmacs--row-list-help
(kbd "?") #'pgmacs--row-list-help
(kbd "g") #'pgmacs--row-list-redraw
(kbd "i") #'pgmacs--insert-row-empty
(kbd "o") #'pgmacs-open-table
(kbd "e") #'pgmacs-run-sql
(kbd "E") #'pgmacs-run-buffer-sql
(kbd "W") #'pgmacs--add-where-filter
(kbd "S") #'pgmacs--schemaspy-table
(kbd "T") #'pgmacs--switch-to-database-buffer)
(defvar-keymap pgmacs-transient-map
:doc "Keymap for PGmacs transient buffers"
(kbd "q") #'bury-buffer
(kbd "o") #'pgmacs-open-table
(kbd "e") #'pgmacs-run-sql
(kbd "E") #'pgmacs-run-buffer-sql
(kbd "T") #'pgmacs--switch-to-database-buffer)
(define-minor-mode pgmacs-transient-mode
"Minor mode for transient PGmacs buffers."
:global nil
:init-value nil
:keymap pgmacs-transient-map)
(defvar-keymap pgmacs-paginated-map
:doc "Additional keymap for paginated PGmacs row-list buffers"
(kbd "n") #'pgmacs--paginated-next
(kbd "p") #'pgmacs--paginated-prev)
(define-minor-mode pgmacs-paginated-mode
"Minor mode for paginated PGmacs table buffers."
:global nil
:init-value nil
:keymap pgmacs-paginated-map)
;; Used for updating on progress retrieving information from PostgreSQL.
;; FIXME: these should be per-PostgreSQL-connection rather than per-Emacs-instance.
(defvar pgmacs--progress nil)
(defvar pgmacs--progress-timer nil)
(defun pgmacs--start-progress-reporter (msg)
"Create a progress reporter that displays message MSG."
(setq pgmacs--progress (make-progress-reporter msg))
(setq pgmacs--progress-timer
(run-with-timer 0.2 0.2 (lambda ()
(when pgmacs--progress
(progress-reporter-update pgmacs--progress)))))
(run-with-timer 10 nil #'pgmacs--stop-progress-reporter))
(defun pgmacs--update-progress (msg)
"Update the progress reporter with message MSG."
(when pgmacs--progress
(progress-reporter-update msg)))
(defun pgmacs--stop-progress-reporter ()
"Stop the progress reporter."
(when pgmacs--progress
(message "Stopping the PGmacs progress reporter")
(progress-reporter-done pgmacs--progress))
(when pgmacs--progress-timer
(cancel-timer pgmacs--progress-timer)
(setq pgmacs--progress-timer nil))
(when pgmacs--progress
(setq pgmacs--progress nil)))
(defvar-local pgmacs--kill-ring nil
"Used for copying and pasting rows in a buffer's table.")
(defvar pgmacs--column-display-functions (make-hash-table :test #'equal))
;; Allow the user to register a dedicated display function for a particular column in a particular
;; table. The display-function takes three arguments: the cell-value, max-width, table.
;;
;; This functionality can be used to display BYTEA columns as inline images, for example.
(defun pgmacs-register-column-displayer (table column display-function)
(puthash (cons table column) display-function pgmacs--column-display-functions))
(defun pgmacs--lookup-column-displayer (table column)
(gethash (cons table column) pgmacs--column-display-functions nil))
(defun pgmacs-disconnect (&rest _ignore)
(unless pgmacs--con
(user-error "This function must be called from a PGmacs buffer"))
(pgmacs--stop-progress-reporter)
(pg-disconnect pgmacs--con)
(setq pgmacs--con nil)
(kill-buffer (current-buffer)))
;; We can have several table-list buffers open, corresponding to different PostgreSQL databases. The
;; buffer-local pgmacs--db-buffer is kept up to date in each PGmacs buffer to point to its main
;; table-list buffer.
(defun pgmacs--switch-to-database-buffer (&rest _ignore)
"Switch to the main table-list buffer for the current PostgreSQL database."
(interactive)
(switch-to-buffer pgmacs--db-buffer))
(defun pgmacs--notify (fmt &rest args)
"Display a notification regarding PGmacs activity.
Applies format string FMT to ARGS."
(message (concat "PostgreSQL> " (apply #'format (cons fmt args)))))
(defun pgmacs--value-formatter-not-null (type-name)
"Return a function that formats a non-NULL value of type TYPE-NAME."
(cond ((string= type-name "date")
(lambda (val) (format-time-string "%Y-%m-%d" val)))
((or (string= type-name "timestamp")
(string= type-name "timestamptz")
(string= type-name "datetime"))
;; these are represented as a `decode-time' structure
(lambda (val) (format-time-string pgmacs-timestamp-format val pgmacs-timestamp-zone)))
((or (string= type-name "text")
(string= type-name "varchar")
(string= type-name "name"))
(lambda (s) (or s "")))
((string= type-name "bpchar")
#'char-to-string)
((string= type-name "hstore")
(lambda (ht)
(let ((items (list)))
(maphash (lambda (k v) (push (format "\"%s\"=>\"%s\"" k v) items)) ht)
(string-join items ","))))
((string= type-name "json")
#'json-serialize)
((string= type-name "jsonb")
#'json-serialize)
((string= type-name "vector")
(lambda (val)
(concat "[" (string-join (mapcar #'prin1-to-string val) ",") "]")))
(t
(lambda (val) (format "%s" val)))))
(defun pgmacs--value-formatter (type-name)
"Return a function that formats a value of type TYPE-NAME."
(let ((fmt (pgmacs--value-formatter-not-null type-name)))
(lambda (val) (if val (funcall fmt val) ""))))
(defun pgmacs--value-width (type-name)
"Width for a column containing elements of type TYPE-NAME."
(pcase type-name
("smallint" 4)
("int2" 4)
("int4" 6)
("int8" 10)
("oid" 10)
("bool" 4)
("bit" 4)
("varbit" 10)
("char" 4)
("char2" 4)
("char4" 6)
("char8" 10)
("char16" 20)
("text" 25)
("varchar" 25)
("bpchar" 7)
("name" 25)
("bytea" 10)
("json" 40)
("jsonb" 40)
("uuid" 36)
("hstore" 20)
("numeric" 10)
("float4" 10)
("float8" 10)
("date" 16)
("timestamp" 20)
("timestamptz" 20)
("datetime" 20)
("time" 12)
("reltime" 10)
("timespan" 12)
(_ 10)))
(defun pgmacs--alignment-for (type-name)
"Return the alignment for type TYPE-NAME, either \='left or \='right."
(pcase type-name
("smallint" 'right)
("int2" 'right)
("int4" 'right)
("int8" 'right)
("oid" 'right)
("bool" 'left)
("bit" 'right)
("varbit" 'right)
(_ 'left)))
;; Name may be a qualified name or a simple string. Transform this into a string for display to the
;; user. We only want to show the outer ?" characters if they are necessary (if some characters in
;; the identifier require quoting).
(defun pgmacs--display-identifier (name)
"Return the PostgreSQL identifier NAME in a form suitable for display to the user."
(cl-labels ((safe-p (ch)
(string-match-p "[0-9a-zA-Z_]" (string ch)))
(user-facing (nm)
(if (cl-every #'safe-p nm)
nm
(pg-escape-identifier nm))))
(cond ((pg-qualified-name-p name)
(let ((schema (pg-qualified-name-schema name))
(name (pg-qualified-name-name name)))
(if (and schema (not (string= "public" schema)))
(format "%s.%s"
(user-facing schema)
(user-facing name))
(user-facing name))))
(t
(user-facing name)))))
(defun pgmacs--row-as-json (current-row)
"Copy the CURRENT-ROW as JSON to the kill ring."
(unless (json-available-p)
(message "Emacs is not compiled with JSON support")
(cl-return-from pgmacs--row-as-json))
(cl-labels ((jsonable-p (val)
(cl-typecase val
(number t)
(string t)
(vector (cl-every #'jsonable-p val))
(hash-table t)
(t nil))))
(let* ((tbl (pgmacstbl-current-table))
(cols (pgmacstbl-columns tbl))
(ht (make-hash-table :test #'equal))
(ce (pgcon-client-encoding pgmacs--con)))
(cl-loop
for col-id from 0
for col in cols
for col-type = (aref pgmacs--column-type-names col-id)
for raw in current-row
for v = (if (jsonable-p raw) raw
(pg-serialize raw col-type ce))
do (puthash (pgmacstbl-column-name col) v ht))
(kill-new (json-serialize ht))
(message "JSON copied to kill ring"))))
(defun pgmacs--read-value-minibuffer (name type prompt current-value)
"Read a value for column NAME in the minibuffer using PROMPT.
The column has SQL type TYPE and has current value CURRENT-VALUE."
(let* ((prompt (format prompt name type)))
(read-string prompt (and current-value (format "%s" current-value)))))
;; TODO: perhaps if the field value is very long or of BYTEA type, prompt "really want to edit in
;; minibuffer" and suggest using the widget editing mode instead.
(defun pgmacs--read-value (name type prompt current-value)
"Read a value for column NAME of SQL type TYPE.
Use PROMPT in the minibuffer and show the current value CURRENT-VALUE."
(let* ((user-provided (pgmacs--read-value-minibuffer name type prompt current-value))
(parser (pg-lookup-parser type))
(ce (pgcon-client-encoding pgmacs--con)))
(if parser (funcall parser user-provided ce) user-provided)))
(defun pgmacs-funcall-cell (function)
"Call FUNCTION on the content of current cell. Does not modify database.
FUNCTION takes a single argument which is the value of the cell at point."
(let* ((col-id (or (pgmacstbl-current-column)
(user-error "Not on a pgmacstbl column")))
(current-row (or (pgmacstbl-current-object)
(user-error "Cursor is not on a pgmacstbl row")))
(current (nth col-id current-row)))
(funcall function current)))
(defun pgmacs--setf-cell (row primary-keys function)
"Call FUNCTION on current cell and update the database.
FUNCTION is called on (old-value col-name col-type) and returns the new value."
(let* ((pgmacstbl (or (pgmacstbl-current-table)
(user-error "Cursor is not in a pgmacstbl")))
(current-row (or (pgmacstbl-current-object)
(user-error "Cursor is not on a pgmacstbl row")))
(cols (pgmacstbl-columns pgmacstbl))
(col-id (or (pgmacstbl-current-column)
(user-error "Not on a pgmacstbl column")))
(col (nth col-id cols))
(col-name (pgmacstbl-column-name col))
(col-type (aref pgmacs--column-type-names col-id))
(pk (cl-first primary-keys))
(pk-col-id (or (cl-position pk cols :key #'pgmacstbl-column-name :test #'string=)
(error "Can't find primary key %s in the pgmacstbl column list" pk)))
(pk-col-type (and pk-col-id (aref pgmacs--column-type-names pk-col-id)))
(pk-value (and pk-col-id (nth pk-col-id row))))
(let* ((current (funcall (pgmacstbl-column-formatter col)
(nth col-id current-row)))
(new-value (funcall function current col-name col-type)))
(when (null primary-keys)
(user-error "Can't edit content of a table that has no PRIMARY KEY"))
(unless pk-value
(error "Can't find value for primary key %s" pk))
(let* ((sql (format "UPDATE %s SET %s = $1 WHERE %s = $2"
(pg-escape-identifier pgmacs--table)
(pg-escape-identifier col-name)
(pg-escape-identifier pk)))
(res (pg-exec-prepared pgmacs--con sql
`((,new-value . ,col-type)
(,pk-value . ,pk-col-type)))))
(pgmacs--notify "%s" (pg-result res :status)))
(let ((new-row (copy-sequence current-row)))
(setf (nth col-id new-row) new-value)
;; pgmacstbl-update-object doesn't work, so insert then delete old row
(pgmacstbl-insert-object pgmacstbl new-row current-row)
(pgmacstbl-remove-object pgmacstbl current-row)
;; redrawing is necessary to ensure that all keybindings are present for the newly inserted
;; row.
(forward-line -1)
(pgmacs--redraw-pgmacstbl))
new-value)))
(defun pgmacs--edit-value-minibuffer (row primary-keys)
"Edit and update in PostgreSQL the column value at point.
The new value in database row ROW is read in the minibuffer.
Editing requires the database table to have primary keys named in the list
PRIMARY-KEYS."
(unless primary-keys
(user-error "Cannot edit a table that has no PRIMARY KEY"))
(let ((get-value (lambda (old-value col-name col-type)
(pgmacs--read-value (substring-no-properties col-name)
(substring-no-properties col-type)
"Change %s (%s) to: "
old-value))))
(pgmacs--setf-cell row primary-keys get-value)))
(defvar pgmacs--shell-command-history nil)
(defun pgmacs--shell-command-on-value (current-row primary-keys)
"Run a Unix filter shell command with the current cell value as input.
When called without a prefix argument, output is diplayed in the
echo area. When called with a prefix argument, replace the
current cell value with the output
(updating the database).
For example, to count the number of characters in the current cell,
! wc -c
To downcase the value of a text cell (and modify the value in the
database) use
C-u ! tr '[:upper:]' '[:lower]'
To reverse the order of the characters in the cell (and modify
the value in the database), use
C-u ! rev
Works on the CURRENT-ROW and on a table with PRIMARY-KEYS."
(let ((get-value
(lambda (old-value &rest _ignore)
(let* ((prompt "Shell command: ")
(cmd (read-string prompt nil 'pgmacs--shell-command-history))
(new-value (with-temp-buffer
(insert old-value)
(let ((status (shell-command-on-region
(point-min) (point-max) cmd t t
" *PGmacs shell command error*" t)))
(when (zerop status)
(buffer-substring-no-properties (point-min) (point-max)))))))
(unless new-value
(error "Shell command failed: check *PGmacs shell command error* buffer"))
new-value))))
(if (not current-prefix-arg)
(let ((result (pgmacs-funcall-cell get-value)))
(message "PostgreSQL shell: %s" result))
;; With a prefix argument, we update the value in the PostgreSQL database and in the
;; displayed pgmacstbl.
(pgmacs--setf-cell current-row primary-keys get-value))))
(defvar pgmacs--async-command-history nil)
(defun pgmacs--async-command-on-value (&rest _ignore)
"Run a command asynchronously with the current cell value as first argument.
The command should be the name of a program, which will be
searched for in `exec-path' (it is run via `start-process',
without a shell). Command output will be displayed in a buffer
called *PGmacs async command*.
For example, if the cell contains a filename, you can open the
filename in the default application on your system by entering
`xdg-open' (or `open' on a MacOS machine).
Works on the CURRENT-ROW and on a table with PRIMARY-KEYS."
(pgmacs-funcall-cell
(lambda (cell-value)
(let* ((prompt "Async command: ")
(cmd (read-string prompt nil 'pgmacs--async-command-history))
(buf (get-buffer-create "*PGmacs async command*")))
(start-process "PGmacs-async-command" buf cmd cell-value)))))
(defun pgmacs--downcase-value (current-row primary-keys)
"Downcase the value in the cell at point and update PostgreSQL.
Operates on the CURRENT-ROW and on a table with PRIMARY-KEYS."
(let ((get-value
(lambda (old-value _col-name col-type)
(unless (or (string= "text" col-type)
(string= "varchar" col-type)
(string= "name" col-type))
(user-error "Can only downcase text values"))
(with-temp-buffer
(insert old-value)
(downcase-region (point-min) (point-max))
(buffer-substring-no-properties (point-min) (point-max))))))
(pgmacs--setf-cell current-row primary-keys get-value)))
(defun pgmacs--upcase-value (current-row primary-keys)
"Upcase the value in the cell at point and update PostgreSQL.
Operates on the CURRENT-ROW and on a table with PRIMARY-KEYS."
(let ((get-value
(lambda (old-value _col-name col-type)
(unless (or (string= "text" col-type)
(string= "varchar" col-type)
(string= "name" col-type))
(user-error "Can only upcase text values"))
(with-temp-buffer
(insert old-value)
(upcase-region (point-min) (point-max))
(buffer-substring-no-properties (point-min) (point-max))))))
(pgmacs--setf-cell current-row primary-keys get-value)))
(defun pgmacs--capitalize-value (current-row primary-keys)
"Capitalize the value in the cell at point and update PostgreSQL.
Operates on the CURRENT-ROW and on a table with PRIMARY-KEYS."
(let ((get-value
(lambda (old-value _col-name col-type)
(unless (or (string= "text" col-type)
(string= "varchar" col-type)
(string= "name" col-type))
(user-error "Can only capitalize text values"))
(with-temp-buffer
(insert old-value)
(capitalize-region (point-min) (point-max))
(buffer-substring-no-properties (point-min) (point-max))))))
(pgmacs--setf-cell current-row primary-keys get-value)))
(define-widget 'pgmacs-hstore-widget 'list
"Widget to edit a PostgreSQL HSTORE key-value map."
:tag "HSTORE key-value mapping"
:format "%v"
:offset 2
;; Convert from the hashtable format used to represent an hstore column in Emacs Lisp to an alist
;; that is suitable for display using our widget.
:value-to-internal (lambda (_widget ht)
(let* ((entries (list)))
(maphash (lambda (k v) (push (cons k v) entries)) ht)
entries))
;; Convert from the alist display format back to a hashtable.
:value-to-external (lambda (_widget alist)
(let ((ht (make-hash-table :test #'equal)))
(dolist (kv alist)
(puthash (car kv) (cdr kv) ht))
ht))
:args `((editable-list :inline t
;; don't display the [INS] button on each line (which would be inserted if
;; the %i escape were present here), because the order of entries in the
;; HSTORE is not relevant.
:entry-format "%d %v\n"
(cons :format "%v"
(editable-field :size 25
:tag "Key"
:format ,(if (char-displayable-p ?⟶) "%v ⟶ " "%v --> "))
(editable-field :size 40 :tag "Value")))))
(define-widget 'pgmacs-json-widget 'text
"Widget to edit PostgreSQL JSON/JSONB values."
:tag "JSON/JSONB value"
:format "%v"
:offset 2
;; The pg-el library deserializes JSON and JSONB values to hashtables using Emacs' native JSON
;; support. Here we use the native JSON support plus pretty-printing support from json.el.
:value-to-internal (lambda (_widget ht)
(with-temp-buffer
(insert (json-serialize ht))
(json-pretty-print-buffer)
(buffer-string)))
:value-to-external (lambda (_widget str) (json-parse-string str))
:args '((string :inline t :size 500)))
;; function org-read-date provides a convenient interface
;; and see complicated widget lib https://github.com/aki2o/emacs-date-field/blob/master/date-field.el
(define-widget 'pgmacs-date-widget 'text
"Widget to edit a PostgreSQL date column."
:tag "Date"
:format "%v"
:offset 2
:valid-regexp (rx (+ digit) ?- (repeat 2 digit) ?- (repeat 2 digit))
:value-to-internal (lambda (_widget val)
(format-time-string "%Y-%m-%d" val))
:value-to-external (lambda (_widget str)
(pg-date-parser str nil))
:args '((string :inline t :size 20)))
(define-widget 'pgmacs-timestamp-widget 'text
"Widget to edit a timestamp."
:tag "Timestamp"
:format "%v"
:offset 2
:value-to-internal (lambda (_widget val)
(if (stringp val)
val
(format-time-string pgmacs-timestamp-format val)))
:value-to-external (lambda (_widget str)
(pg-isodate-without-timezone-parser str nil))
:args '((string :inline t :size 25)))
(define-widget 'pgmacs-timestamptz-widget 'text
"Widget to edit a timestamptz."
:tag "Timestamptz"
:format "%v"
:offset 2
:value-to-internal (lambda (_widget val)
(if (stringp val)
val
(format-time-string pgmacs-timestamp-format val)))
:value-to-external (lambda (_widget str)
(pg-isodate-with-timezone-parser str nil))
:args '((string :inline t :size 25)))
;; https://www.postgresql.org/docs/current/datatype-uuid.html
(define-widget 'pgmacs-uuid-widget 'list
"Widget to edit a PostgreSQL UUID column."
:tag "UUID"
:format "%v"
:offset 2
:value-to-internal (lambda (_widget uuid-string)
(split-string uuid-string "-"))
:value-to-external (lambda (_widget uuid-elements)
(apply #'format (cons "%s-%s-%s-%s-%s" uuid-elements)))
:error "Invalid format for a UUID."
:args '((list :inline t :format "%v"
(editable-field :size 8
:valid-regexp (rx (repeat 8 xdigit))
:error "Invalid format for UUID component"
:format "%v-")
(editable-field :size 4 :valid-regexp (rx (repeat 4 xdigit)) :format "%v-")
(editable-field :size 4 :valid-regexp (rx (repeat 4 xdigit)) :format "%v-")
(editable-field :size 4 :valid-regexp (rx (repeat 4 xdigit)) :format "%v-")
(editable-field :size 12 :valid-regexp (rx (repeat 12 xdigit)) :format "%v"))))
(defun pgmacs--widget-for (type current-value)
"Create a widget for TYPE and CURRENT-VALUE in the current buffer."
(pcase type
("bool"
(widget-create 'boolean (or current-value nil)))
((or "smallint" "int2" "int4" "int8" "oid")
(widget-create 'integer (or current-value "")))
((or "numeric" "float4" "float8")
(widget-create 'float (or current-value "")))
((or "char" "bpchar")
(widget-create 'character (or current-value "")))
((or "text" "varchar")
(let ((default (or current-value "")))
(widget-create 'string
:size (max 80 (min 200 (+ 5 (length default))))
:value default)))
;; represented as "[44,33,5,78]" on the wire. Parsed to an elisp vector of integers.
("vector"
(widget-create '(vector integer) :value (or current-value (vector))))
("hstore"
(widget-create 'pgmacs-hstore-widget :value (or current-value (make-hash-table))))
((or "json" "jsonb")
(widget-create 'pgmacs-json-widget :value (or current-value (make-hash-table))))
("date"
(widget-create 'pgmacs-date-widget (or current-value "")))
;; A timestamp and timestamptz is represented as an elisp timestamp, which is (v29) a cons of
;; two integers. We want to edit it as a timestamp string.
("timestamp"
(widget-create 'pgmacs-timestamp-widget :value (or current-value (current-time-string))))
("timestamptz"