-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgBrowse.tcl
executable file
·1097 lines (914 loc) · 31 KB
/
pgBrowse.tcl
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
#!/usr/bin/env wish
#
# Filename: PgBrowse.tcl
# Version: 1.9
# Released: Oct 27, 2004
#
# Sorta Authored by: Jerry LeVan http://homepage.mac.com/levanj
# Email: jerry.levan@eku.edu
#
# This program is an enhanced version of the tcl client
# found in the books "PostgreSQL" by Douglas and Douglas.
#
# It also contains features from my BiggerSql Cocoa based
# browser.
#
# This program will allow the user to browse and interact
# with PostgreSQL databases.
# Requirements:
# TkTable (any recent version)
# PostgreSQL
# Tcl/Tk
package require Tcl 8.6
package require Tk
package require Ttk
set VERSION 1.9
proc main { } {
global ui_vars
global connect_parms
global psql
global windows
global macosx
global linux
global tcl_platform
wm withdraw .
image create photo applicationIcon -file [file join [file dirname [info script]] Support "icone.png"];wm iconphoto . -default applicationIcon
set psql [findPsql]
set results [connect]
if { $results != {} } {
set ui_vars(conn) [lindex $results 0]
set conn $ui_vars(conn)
set dsn [lindex $results 1]
set items [split $dsn " "]
foreach item $items {
if {[string equal $item "" ] } continue
set itemlist [split $item '=']
set connect_parms([lindex $itemlist 0]) [lindex $itemlist 1]
}
# parray connect_parms
# set some global bindings for...
# event add <<Copy>> <Control-Key-c>
# event add <<Paste>> <Control-Key-v>
# do some extra if running under macosx
set macosx 0
if { $tcl_platform(os) eq "Darwin" && [ tk windowingsystem ] eq "aqua" } {
set macosx 1
}
set windows 0
if {$tcl_platform(platform) eq "windows" } {
set windows 1
}
set linux 0
if { [tk windowingsystem ] eq "x11"} {
set linux 1
}
# build the user interface
build_ui $conn
# register a handler to get messages from the back end
pg_notice_handler $conn "insertMessage "
# create application menus
build_menus $conn
#check for the scripts library directory and try to create...
if { ![file exists "~/SQLScripts" ] } {
file mkdir "~/SQLScripts"
$ui_vars(cmdStatus) insert end "\nCreated ~/SQLScripts directory."
} elseif { [file isfile "~/SQLScripts"] } {
$ui_vars(cmdStatus) insert end "~/SQLScripts is an ordinary file not a \
directory. The Scripts Library Directory cannot be created." }
if { $psql != ""} {
$ui_vars(cmdStatus) insert end "\nPsql found at $psql."
} else {
$ui_vars(cmdStatus) insert end "\nPsql not found."
}
Init_History
$ui_vars(cmdStatus) insert end "\nReady...\n"
wm deiconify .
tkwait window .
pg_disconnect $conn
}
}
proc sendSelectionToPsql {} {
global ui_vars
$ui_vars(cmdStatus) delete "1.0" end
set startTime [clock clicks -milliseconds]
if { [$ui_vars(code) tag ranges sel ] != "" } {
set command [$ui_vars(code) get sel.first sel.last ]
sendToPsql $command
}
set finishTime [clock clicks -milliseconds]
set lapsedTime [expr {abs($finishTime - $startTime)}]
$ui_vars(cmdStatus) insert end "\nPsql done in $lapsedTime milliseconds\n"
$ui_vars(cmdStatus) see end
}
proc findPsql {} {
if { [file exists /usr/bin/psql]} {return /usr/bin/psql}
if { [file exists /usr/local/bin/psql]} {return /usr/local/bin/psql}
if { [file exists /usr/local/pgsql/bin/psql]} {return /usr/local/pgsql/bin/psql}
return ""
}
proc sendToPsql { cmd } {
global ui_vars
global connect_parms
global psql
# build the connect string
foreach key { user dbname host port } {
set key ""
}
foreach {key value} [array get connect_parms] {
if { $key== "user"} { set user $value }
if { $key == "dbname"} { set dbname $value }
if { $key == "host"} { set host $value }
if { $key == "port" } { set port $value }
}
#set results [exec $psql -U $user -d $dbname -h $host -p $port -c $cmd]
if {[catch { exec $psql -U $user -d $dbname -h $host -p $port -c $cmd } results]} {
$ui_vars(cmdStatus) insert end [append results "\n"] red
} else {
$ui_vars(code) insert end $results
$ui_vars(code) see end
}
}
proc insertMessage {mesg} {
global ui_vars
$ui_vars(cmdStatus) insert end $mesg magenta
}
proc BuildScriptMenu { amenu adir } {
set old_dir [pwd]
cd $adir
set file_list [lsort -dictionary [glob -nocomplain *]]
#puts $file_list
foreach item $file_list {
if { [file isdirectory $item ]} {
$amenu add cascade -label $item -menu [menu $amenu.[string tolower $item]]
BuildScriptMenu $amenu.[string tolower $item] $adir/$item/
continue
}
if { [string compare [string tolower [file extension $item]] ".sql" ]} { continue }
#puts $item
$amenu add command -label $item -command "loadSQL \"$adir$item\""
}
cd $old_dir
}
proc loadSQL { fileName } {
global ui_vars
if { $fileName != "" } {
$ui_vars(code) delete 1.0 end
set f [open $fileName r]
set fileContents [ read $f ]
$ui_vars(code) insert 1.0 $fileContents
close $f
}
}
proc build_menus {conn} {
global ui_vars
global tcl_platform
global macosx
global windows
global linux
global psql
global displayNULL
global sendSingle
global longField
global hasImg
global basedir
global hasHtml
set longField 0
# try to be platform independent
if {[string equal [tk windowingsystem] "classic"]
|| [string equal [tk windowingsystem] "aqua"]} {
set modifier Command
} elseif {$tcl_platform(platform) == "windows"} {
set modifier Control
} else {
set modifier Control
}
# Create a "menu bar"
menu .menubar
# make it the menu for the application window
. config -menu .menubar
# create the File menu
menu .menubar.file -tearoff 0
# add this menu to the menubar
.menubar add cascade -label "File" -menu .menubar.file
# add the menu items with actions
.menubar.file add command -label "Load SQL File..." -accelerator $modifier-O -command { openFile}
.menubar.file add command -label "Save SQL Window..." -command saveSqlWindow
.menubar.file add separator
.menubar.file add command -label "Save SQL Results As CSV File..." -accelerator $modifier-S -command { saveFile }
.menubar.file add command -label "Save SQL Results As Formatted File..." -command { saveFormattedFile }
.menubar.file add separator
.menubar.file add command -label "Table Editor & Information..." -command "showTableInfo $conn"
.menubar.file add check -label "Display null as <NULL>" -variable displayNULL
.menubar.file add check -label "Send Single Statements" -variable sendSingle
.menubar.file add check -label "Show Long Fields" -variable longField
.menubar.file add separator
.menubar.file add command -label "Run Editor Window" -accelerator $modifier-R \
-command "getStringAndProcess $conn $ui_vars(table) 0 "
.menubar.file add command -label "Run Selection" \
-command "getStringAndProcess $conn $ui_vars(table) 1 "
if { $psql != "" } {
.menubar.file add command -label "Send Selection To Psql" \
-command "sendSelectionToPsql"
}
.menubar.file add separator
.menubar.file add command -label "Quit" -accelerator $modifier-Q \
-command {save_history ; exit }
# create the help menu
menu .menubar.help -tearoff 0
.menubar add cascade -label "Help" -menu .menubar.help
.menubar.help add command -label "Help" -accelerator $modifier-H -command Help
.menubar.help add command -label "Show Readme" -command Readme
if {$hasHtml } {
.menubar.help add separator
.menubar.help add command -label "Postgresql Documentation" \
-command [list showPgDoc [file join $basedir Support pgdoc index.html]]
}
#create a "Scripts" menu
# add a scripts menu
menu .menubar.scripts -tearoff 0
.menubar add cascade -label "Scripts" -menu .menubar.scripts
.menubar.scripts add command -label "Refresh Scripts Menu" -command RebuildScriptsMenu
if { $macosx && [file isdirectory "~/SQLScripts" ] } {
.menubar.scripts add command -label "Open Scripts Folder" -command OpenScriptsFolder
}
if { $windows && [file isdirectory "~/SQLScripts" ] } {
.menubar.scripts add command -label "Open Scripts Folder" -command OpenScriptsFolder
}
if {$linux && [file isdirectory "~/SQLScripts" ] } {
.menubar.scripts add command -label "Open Scripts Folder" -command OpenScriptsFolder
}
.menubar.scripts add separator
# Add the menu items
if { [file isdirectory "~/SQLScripts" ]} {
BuildScriptMenu .menubar.scripts "~/SQLScripts/"
}
# Some global bindings
bind all <$modifier-q> {save_history ; exit}
bind all <$modifier-o> {openFile}
bind all <$modifier-s> {saveFile}
bind all <$modifier-h> {Help}
# build the popup menu
menu $ui_vars(table).menu
$ui_vars(table).menu add command -label "View As Text" -command showText
$ui_vars(table).menu add command -label "View As Bytea Text" -command showByteaText
$ui_vars(table).menu add command -label "View As Large Object Text" \
-command showLOBJText
$ui_vars(table).menu add separator
if { $hasImg } {
$ui_vars(table).menu add command -label "View As Bytea Image" -command showByteaImage
$ui_vars(table).menu add command -label "View As Large Object Image" \
-command showLOBJImage
$ui_vars(table).menu add separator
} else { insertMessage \
"Warning Img package missing. Images cannot be viewed."
}
$ui_vars(table).menu add command -label "Export Text Field..."\
-command exportTextField
$ui_vars(table).menu add command -label "Export Bytea Field..."\
-command exportByteaField
$ui_vars(table).menu add command -label "Export Large Object Field..." \
-command exportLargeObjectField
bind $ui_vars(table) <Control-Button-1> {
#tk_popup $table(table).menu %X %Y
#puts "x=%x, y=%y\nX=%X, Y=%Y\n cell: [$table(table) get @%x,%y]\n @%x,%y\n"
processTable %x %y %X %Y
}
}
proc OpenScriptsFolder {} {
global macosx
global windows
global linux
if {$macosx} {
exec open [glob ~/SQLScripts]
}
if {$windows} {
catch { eval exec explorer {[file nativename ~/SQLScripts]} }
}
if { $linux } {
exec xdg-open [glob ~/SQLScripts] &
}
}
proc RebuildScriptsMenu {} {
global macosx
global windows
global linux
foreach w [winfo children .menubar.scripts ] { destroy $w }
.menubar.scripts delete 0 end
.menubar.scripts add command -label "Refresh Scripts Menu" -command RebuildScriptsMenu
if { $macosx || $windows || $linux} {
if { [file isdirectory "~/SQLScripts" ] } {
.menubar.scripts add command -label "Open Scripts Folder" -command OpenScriptsFolder
}
}
.menubar.scripts add separator
# Add the menu items
if { [file isdirectory "~/SQLScripts" ]} {
BuildScriptMenu .menubar.scripts "~/SQLScripts/"
}
# workaround for menu bug in the Aqua distribution
if { [tk windowingsystem] eq "aqua" } {
toplevel .tiny -height 1 -width 1
update idletasks
destroy .tiny
}
}
proc processTable { x y globalx globaly } {
global ui_vars
global lastTag
set lastTag @$x,$y
$ui_vars(table) activate @$x,$y
tk_popup $ui_vars(table).menu $globalx $globaly
}
proc exportTextField {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set rowValues [pg_result $lastResult -getTuple $theRow]
set val [lindex $rowValues $theCol]
set theDir [tk_getSaveFile ]
if { $theDir != "" } {
if { [catch {
set fd [open $theDir w]
puts $fd $val
close $fd } result]
} {
tk_messageBox -message "Write failed : $result" -type ok
} else {
tk_messageBox -message "File $theDir OK" -type ok
}
}
}
proc exportByteaField {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set rowValues [pg_result $lastResult -getTuple $theRow]
#set val [lindex $rowValues $theCol]
set val [subst -nocommands -novariables [lindex $rowValues $theCol]]
set theDir [tk_getSaveFile ]
if { $theDir != "" } {
if { [catch {
set fd [open $theDir w]
fconfigure $fd -translation binary
puts -nonewline $fd $val
close $fd } result ]
} {
tk_messageBox -message "Write failed : $result" -type ok
} else {
tk_messageBox -message "File $theDir OK" -type ok
}
}
}
proc exportLargeObjectField {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set theStr ""
set rowValues [pg_result $lastResult -getTuple $theRow]
set val [lindex $rowValues $theCol]
# here we have the large object oid...
set res [pg_exec $ui_vars(conn) "begin"]
pg_result $res -clear
set lfd [pg_lo_open $ui_vars(conn) $val r]
set size [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_END]
set tmp [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_SET]
pg_lo_read $ui_vars(conn) $lfd theStr $size
set res [pg_lo_close $ui_vars(conn) $lfd]
set res [pg_exec $ui_vars(conn) "end"]
pg_result $res -clear
set theDir [tk_getSaveFile ]
if { $theDir != "" } {
if { [catch {
set fd [open $theDir w]
fconfigure $fd -translation binary
puts -nonewline $fd $theStr
close $fd } result]
} {
tk_messageBox -message "Write failed : $result" -type ok
} else {
tk_messageBox -message "File $theDir OK" -type ok
}
}
}
proc showText {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set rowValues [pg_result $lastResult -getTuple $theRow]
set val [lindex $rowValues $theCol]
#set val [$ui_vars(table) get active]
showAsText $val
}
proc showByteaText {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set rowValues [pg_result $lastResult -getTuple $theRow]
#puts [lindex $rowValues $theCol]
#set val [PQunescapeBytea [lindex $rowValues $theCol] ]
set val [subst -nocommands -novariables [lindex $rowValues $theCol]]
showAsText $val
}
proc showLOBJText {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set theStr ""
set rowValues [pg_result $lastResult -getTuple $theRow]
set val [lindex $rowValues $theCol]
# here we have the large object oid...
set res [pg_exec $ui_vars(conn) "begin"]
pg_result $res -clear
set lfd [pg_lo_open $ui_vars(conn) $val r]
set size [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_END]
set tmp [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_SET]
pg_lo_read $ui_vars(conn) $lfd theStr $size
set res [pg_lo_close $ui_vars(conn) $lfd]
set res [pg_exec $ui_vars(conn) "end"]
pg_result $res -clear
showAsText $theStr
}
proc showByteaImage {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set rowValues [pg_result $lastResult -getTuple $theRow]
#puts [lindex $rowValues $theCol]
#set val [PQunescapeBytea [lindex $rowValues $theCol] ]
set val [subst -nocommands -novariables [lindex $rowValues $theCol]]
showAsImage $val
}
proc showLOBJImage {} {
global ui_vars
global lastResult
global lastTag
set theRow [$ui_vars(table) index $lastTag row]
set theCol [$ui_vars(table) index $lastTag col]
set theStr ""
set rowValues [pg_result $lastResult -getTuple $theRow]
set val [lindex $rowValues $theCol]
# here we have the large object oid...
set res [pg_exec $ui_vars(conn) "begin"]
pg_result $res -clear
set lfd [pg_lo_open $ui_vars(conn) $val r]
set size [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_END]
set tmp [pg_lo_lseek $ui_vars(conn) $lfd 0 SEEK_SET]
pg_lo_read $ui_vars(conn) $lfd theStr $size
set res [pg_lo_close $ui_vars(conn) $lfd]
set res [pg_exec $ui_vars(conn) "end"]
pg_result $res -clear
showAsImage $theStr
}
proc openFile {} {
global ui_vars
set fileName [tk_getOpenFile]
if { $fileName != "" } {
$ui_vars(code) delete 1.0 end
set f [open $fileName r]
set fileContents [ read $f ]
$ui_vars(code) insert 1.0 $fileContents
close $f
}
}
proc saveFile {} {
global lastResult
set sep "|"
set fname [tk_getSaveFile]
if {$fname !=""} {
set f [open $fname "w"]
set col_cnt [pg_result $lastResult -numAttrs]
set col_names [pg_result $lastResult -attributes]
#write the column names
set line ""
for {set i 0} {$i < $col_cnt } { incr i} {
append line [lindex $col_names $i] $sep
}
set line [string range $line 0 end-1]
# write the header line
puts $f $line
# write the rest of the result set
set row_cnt [pg_result $lastResult -numTuples ]
for { set row 0} { $row < $row_cnt } { incr row } {
set tuple [pg_result $lastResult -getTuple $row]
set line ""
for { set i 0} {$i <$col_cnt} { incr i} {
append line [lindex $tuple $i] $sep
}
set line [string range $line 0 end-1]
puts $f $line
}
close $f
tk_messageBox -title PgBrowse \
-message "Save File Completed" \
-type ok
}
}
proc saveSqlWindow {} {
global ui_vars
set fname [tk_getSaveFile -initialdir "~/SQLScripts" \
-defaultextension ".sql"]
if { $fname != "" } {
set f [open $fname "w"]
set content [$ui_vars(code) get 1.0 end ]
puts $f $content
close $f
tk_messageBox -message "Write Completed" -icon info
}
}
proc saveFormattedFile {} {
global lastResult
global col_widths
set sep "|"
set fname [tk_getSaveFile]
if {$fname != "" } {
set f [open $fname "w"]
set col_cnt [pg_result $lastResult -numAttrs]
set col_names [pg_result $lastResult -attributes]
set col_attrs [pg_result $lastResult -lAttributes]
set strheader ""
for {set col 0} { $col < $col_cnt } {incr col } {
set thisColAttr [lindex $col_attrs $col]
if { [isNumeric [lindex $thisColAttr 1] ] } {
append strheader " %$col_widths($col)s |"
} else {
append strheader " %-$col_widths($col)s |"
}
}
set strheader [string range $strheader 0 end-1]
set line [eval "format \"$strheader\" $col_names"]
puts $f "$line"
set lineLen [string length $line ]
set borderline ""
for { set i 0} {$i < $col_cnt} { incr i} {
for {set j 0 } { $j < $col_widths($i) } { incr j} {
append borderline "-"
}
append borderline "--+"
}
set borderline [string range $borderline 0 end-1 ]
puts $f "$borderline"
# write the rest of the result set
set row_cnt [pg_result $lastResult -numTuples ]
for { set row 0} { $row < $row_cnt } { incr row } {
set tuple [pg_result $lastResult -getTuple $row]
set line [eval "format \"$strheader\" $tuple"]
puts $f "$line"
}
close $f
tk_messageBox -title PgBrowse \
-message "Save File Completed." \
-type ok
}
}
proc build_ui { conn } {
global VERSION
global tcl_platform
global ui_vars
global connect_parms
panedwindow .top -orient vertical -showhandle 1 -bg white
pack .top -expand yes -fill both
if { [catch {
wm title . \
"PgBrowse Postgresql Client ($VERSION) - \
user: $connect_parms(user) host: $connect_parms(host) dbname: $connect_parms(dbname)"
} result ] } {
wm title . "PgBrowse PostgreSQL Client ($VERION)"
}
if {[string equal [tk windowingsystem] "classic"]
|| [string equal [tk windowingsystem] "aqua"]} {
set modifier Command
} elseif {$tcl_platform(platform) == "windows"} {
set modifier Control
} else {
set modifier Control
}
#####
# Create 2 labelframe widgets, each containing a
# gridded text and scrollbar assembly.
#-font system
foreach {w label} {code "[SQL]" cmdStatus "[Status]"} {
set f [labelframe .top.$w -text $label -fg blue -bg white]
text $f.t -height 15 -width 80 \
-wrap none \
-relief groove \
-borderwidth 3 \
-xscrollcommand [list $f.xbar set] \
-yscrollcommand [list $f.ybar set]
ttk::scrollbar $f.xbar -orient horizontal \
-command [list $f.t xview]
ttk::scrollbar $f.ybar -orient vertical \
-command [list $f.t yview]
grid $f.t -row 0 -column 0 -sticky news -padx 2 -pady 2
grid $f.ybar -row 0 -column 1 -sticky ns -padx 2 -pady 2
grid $f.xbar -row 1 -column 0 -sticky ew -padx 2 -pady 2
grid columnconfigure $f 0 -weight 1
grid rowconfigure $f 0 -weight 1
# Add the frame assembly to the panedwindow
.top add $f -minsize 1i -padx 4 -pady 6
set ui_vars($w) $f.t
}
# cut down on the size of the status window
$ui_vars(cmdStatus) configure -height 5
$ui_vars(cmdStatus) configure -bg lightgray
$ui_vars(code) configure -bg white
# build and configure the table to show the selection results
set f [labelframe .top.resFrame -text {[Selection Results]} -fg blue -bg white]
set table [make_table $f]
ttk::scrollbar $f.sx -orient horizontal -command [list $table xview]
ttk::scrollbar $f.sy -command " $table yview"
grid $table -row 0 -column 0 -sticky news -padx 2 -pady 2
grid $f.sx -row 1 -column 0 -sticky ew -padx 2 -pady 2
grid $f.sy -row 0 -column 1 -sticky ns -padx 2 -pady 2
grid $f -row 0 -column 0 -sticky news -padx 2 -pady 2
grid columnconfigure $f 0 -weight 1
grid rowconfigure $f 0 -weight 1
.top add $f -minsize 1i -padx 4 -pady 6
set ui_vars(table) $table
# set up some important bindings...
# Scrolling in the Displayed table
bind $ui_vars(table) <KeyPress-space> {
$ui_vars(table) yview scroll +1 pages
}
bind $ui_vars(table) <Shift-space> {
$ui_vars(table) yview scroll -1 pages
}
#Support the MouseWheel
bind $ui_vars(table) <Button-4> { $ui_vars(table) yview scroll -5 units }
bind $ui_vars(table) <Button-5> { $ui_vars(table) yview scroll +5 units }
bind $ui_vars(code) <Button-4> { $ui_vars(code) yview scroll -5 units }
bind $ui_vars(code) <Button-5> { $ui_vars(code) yview scroll +5 units }
bind $ui_vars(table) <MouseWheel> {
if { %D < 0} {
$ui_vars(table) yview scroll +5 units
} else {
$ui_vars(table) yview scroll -5 units
}
}
# Process the whole sql window contents
bind $ui_vars(code) <$modifier-r> \
"getStringAndProcess $conn $table 0 ; break"
# Process the selection or the line containing the insertion point
bind $ui_vars(code) <Shift_L><Return> \
"getStringAndProcess $conn $table 1 ; break"
# set up copy
bind $ui_vars(code) <$modifier-c> "tk_textCopy $ui_vars(code) ; break"
# Set up paste
bind $ui_vars(code) <$modifier-v> "tk_textPaste $ui_vars(code) ; break"
#Set up the history retrieval bindings
bind $ui_vars(code) <$modifier-Up> "next_history ; break"
bind $ui_vars(code) <$modifier-Down> "prev_history ; break"
# Set up the colors for printing status messages
$ui_vars(cmdStatus) tag configure red -foreground red
$ui_vars(cmdStatus) tag configure blue -foreground blue
$ui_vars(cmdStatus) tag configure magenta -foreground magenta
# Set up mouse wheel for the code window
focus -force $ui_vars(code)
}
# -font system
proc make_table { parent } {
table $parent.table \
-variable table_data \
-yscrollcommand "$parent.sy set" \
-xscrollcommand "$parent.sx set" \
-selecttype row \
-titlerows 1 \
-titlecols 1 \
-roworigin -1 \
-colorigin -1 \
-colstretchmode last \
-padx 4 \
-coltagcommand colproc \
-rowtagcommand rowproc
$parent.table tag config anchorcenter -anchor c
$parent.table tag config anchorwest -anchor w
$parent.table tag config anchoreast -anchor e
$parent.table tag config rowColor -bg "lightcyan1"
$parent.table tag config title -bg lightblue
$parent.table tag config title -fg black
$parent.table tag col anchoreast -1
$parent.table tag row anchorcenter -1
$parent.table config -bg white
return $parent.table
}
proc colproc col { if { $col >= 0 } { return "anchorwest" } }
proc rowproc row { if { $row >= 0 && $row%2 } { return "rowColor" } }
# a very simple parser, we assume a semicolon is
# a statement separator if it is preceeded by an
# even number of single quotes
proc parse {workingStr} {
set theLength [string length $workingStr]
set inQuote 0
set start 0
set theList {}
for { set i 0 } { $i < $theLength } { incr i } {
set nextch [string index $workingStr $i]
if { $nextch == ";" && !$inQuote } {
lappend theList [string range $workingStr $start [expr {$i -1}]]
set start [ expr {$i + 1}]
}
if { $nextch == "\'" } {
set inQuote [expr {$inQuote?0:1 }]
}
}
lappend theList [string range $workingStr $start [expr {$i -1}]]
return $theList
}
proc getStringAndProcess { conn table flag } {
global ui_vars
global sendSingle
if { $flag } {
if { [$ui_vars(code) tag ranges sel ] != "" } {
set commands [$ui_vars(code) get sel.first sel.last ]
} else {
set commands [$ui_vars(code) get "insert linestart" "insert lineend"]
}
} else {
set commands [$ui_vars(code) get 1.0 end ]
}
$ui_vars(cmdStatus) delete 1.0 end
# set commandList [split $commands ";"]
set startTime [clock clicks -milliseconds]
if { $sendSingle } {
set commandList [parse $commands]
foreach command $commandList {
if { $command != "" } { process_command $conn $table $command }
}
} else { process_command $conn $table $commands }
set finishTime [clock clicks -milliseconds ]
set lapsedTime [expr {abs( $finishTime - $startTime) }]
$ui_vars(cmdStatus) insert end "Done in $lapsedTime milliseconds.\n"
}
proc saveSelection {res} {
global lastResult
catch {pg_result lastResult -clear}
set lastResult $res
}
proc process_command { conn table command } {
global ui_vars
add_history $command
insertMessage "Working...\n"
update idletasks
if { [string index $command 0] == "\\" } {
sendToPsql $command
return
}
$ui_vars(code) config -cursor watch
update idletasks
set result_set [pg_exec $conn $command]
$ui_vars(code) config -cursor xterm
switch [pg_result $result_set -status] {
"PGRES_EMPTY_QUERY" {
$ui_vars(cmdStatus) insert end "Empty query...Ok\n"
}
"PGRES_TUPLES_OK" {
set col_cnt [pg_result $result_set -numAttrs]
set row_cnt [pg_result $result_set -numTuples]
$ui_vars(cmdStatus) insert end "$row_cnt rows, $col_cnt columns.\n" blue
#$ui_vars(cmdStatus) insert end "Done.\n"
load_table $table $result_set
saveSelection $result_set
return
}
"PGRES_COMMAND_OK" {
# -cmdStatus not implemented yet in Pgtcl 1.5 set a trap
catch {
set str1 [ pg_result $result_set -cmdStatus]
if { [string length $str1] > 0 } {
$ui_vars(cmdStatus) insert end "$str1\n" blue
}
}
set str2 [pg_result $result_set -cmdTuples ]
if { [string length $str2] > 0 } {
$ui_vars(cmdStatus) insert end "$str2 rows affected\n" blue
}
#$ui_vars(cmdStatus) insert end "Done.\n"
}
default
{
$ui_vars(cmdStatus) insert end [pg_result $result_set -status] red
$ui_vars(cmdStatus) insert end "\n"
$ui_vars(cmdStatus) insert end [pg_result $result_set -error] red
$ui_vars(cmdStatus) insert end "\n"
}
}
pg_result $result_set -clear
}
proc load_table { table result_set } {
size_table $table $result_set
set_column_headers $table $result_set
fill_table $table $result_set
size_columns $table $result_set
}
proc size_table { table result_set } {
set col_cnt [pg_result $result_set -numAttrs]
set row_cnt [pg_result $result_set -numTuples]
$table configure \
-rows [expr {$row_cnt + 1 }] \
-cols [expr {$col_cnt + 1 }]
}
proc isNumeric { aType } {
if { [lsearch { 20 21 23 26 700 701 190 1700 } $aType] == -1} {
return 0
} else {
return 1
}
}
proc set_column_headers { table result_set } {
global col_widths
set col_cnt [pg_result $result_set -numAttrs]
set col_names [pg_result $result_set -attributes]
set col_attrs [pg_result $result_set -lAttributes]
for {set col 0} {$col < $col_cnt} {incr col} {
set col_name [lindex $col_names $col]
$table set -1,$col $col_name
set col_widths($col) [string length $col_name]
set thisColAttr [lindex $col_attrs $col]