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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
|
#!/usr/bin/env ruby
#
# an interactive front-end to postgreSQL
#
# Original source code is written by C.
# Copyright (c) 1996, Regents of the University of California
#
# ruby version is written by ematsu
# Copyright (c) 1997 Eiji-usagi-MATSUmoto <ematsu@pfu.co.jp>
#
# Changes:
#
# Fri 12 Dec 19:56:34 JST 1997
# * replace puts -> print
#
# $Id: psql.rb,v 1.1.1.3 2002/04/24 05:46:44 noboru Exp $
#
require "postgres"
require "parsearg.rb"
require "psqlHelp.rb"
PROMPT = "=> "
MAX_QUERY_BUFFER = 20000
DEFAULT_SHELL = "/bin/sh"
DEFAULT_EDITOR = "vi"
DEFAULT_FIELD_SEP= "|"
PsqlSettings = Struct.new("PsqlSettings", :db, :queryFout, :opt, :prompt,
:gfname, :notty,:pipe, :echoQuery,:quiet,
:singleStep, :singleLineMode, :useReadline)
PrintOpt = Struct.new("PrintOpt", :header, :align, :standard, :html3,
:expanded, :pager, :fieldSep, :tableOpt,
:caption, :fieldName)
$readline_ok = TRUE
def usage()
printf("Usage: psql.rb [options] [dbname]\n")
printf("\t -a authsvc set authentication service\n")
printf("\t -A turn off alignment when printing out attributes\n")
printf("\t -c query run single query (slash commands too)\n")
printf("\t -d dbName specify database name\n")
printf("\t -e echo the query sent to the backend\n")
printf("\t -f filename use file as a source of queries\n")
printf("\t -F sep set the field separator (default is \" \")\n")
printf("\t -h host set database server host\n")
printf("\t -H turn on html3.0 table output\n")
printf("\t -l list available databases\n")
printf("\t -n don't use readline library\n")
printf("\t -o filename send output to filename or (|pipe)\n")
printf("\t -p port set port number\n")
printf("\t -q run quietly (no messages, no prompts)\n")
printf("\t -s single step mode (prompts for each query)\n")
printf("\t -S single line mode (i.e. query terminated by newline)\n")
printf("\t -t turn off printing of headings and row count\n")
printf("\t -T html set html3.0 table command options (cf. -H)\n")
printf("\t -x turn on expanded output (field names on left)\n")
exit(1)
end
$USAGE = 'usage'
def slashUsage(ps)
printf(" \\? -- help\n")
printf(" \\a -- toggle field-alignment (currenty %s)\n", on(ps.opt.align))
printf(" \\C [<captn>] -- set html3 caption (currently '%s')\n", ps.opt.caption );
printf(" \\connect <dbname> -- connect to new database (currently '%s')\n", ps.db.db)
printf(" \\copy {<table> to <file> | <file> from <table>}\n")
printf(" \\d [<table>] -- list tables in database or columns in <table>, * for all\n")
printf(" \\da -- list aggregates\n")
printf(" \\di -- list only indices\n")
printf(" \\ds -- list only sequences\n")
printf(" \\dS -- list system tables and indexes\n")
printf(" \\dt -- list only tables\n")
printf(" \\dT -- list types\n")
printf(" \\e [<fname>] -- edit the current query buffer or <fname>\n")
printf(" \\E [<fname>] -- edit the current query buffer or <fname>, and execute\n")
printf(" \\f [<sep>] -- change field separater (currently '%s')\n", ps.opt.fieldSep)
printf(" \\g [<fname>] [|<cmd>] -- send query to backend [and results in <fname> or pipe]\n")
printf(" \\h [<cmd>] -- help on syntax of sql commands, * for all commands\n")
printf(" \\H -- toggle html3 output (currently %s)\n", on(ps.opt.html3))
printf(" \\i <fname> -- read and execute queries from filename\n")
printf(" \\l -- list all databases\n")
printf(" \\m -- toggle monitor-like table display (currently %s)\n", on(ps.opt.standard))
printf(" \\o [<fname>] [|<cmd>] -- send all query results to stdout, <fname>, or pipe\n")
printf(" \\p -- print the current query buffer\n")
printf(" \\q -- quit\n")
printf(" \\r -- reset(clear) the query buffer\n")
printf(" \\s [<fname>] -- print history or save it in <fname>\n")
printf(" \\t -- toggle table headings and row count (currently %s)\n", on(ps.opt.header))
printf(" \\T [<html>] -- set html3.0 <table ...> options (currently '%s')\n", ps.opt.tableOpt)
printf(" \\x -- toggle expanded output (currently %s)\n", on(ps.opt.expanded))
printf(" \\! [<cmd>] -- shell escape or command\n")
end
def on(f)
if f
return "on"
else
return "off"
end
end
def toggle(settings, sw, msg)
sw = !sw
if !settings.quiet
printf(STDERR, "turned %s %s\n", on(sw), msg)
end
return sw
end
def gets(prompt, source)
if source == STDIN
if ($readline_ok)
line = Readline.readline(prompt,source)
else
STDOUT.print(prompt)
STDOUT.flush()
line = source.gets
end
end
if line == nil
return nil
else
if line.length > MAX_QUERY_BUFFER
printf(STDERR, "line read exceeds maximum length. Truncating at %d\n",
MAX_QUERY_BUFFER)
return line[0..MAX_QUERY_BUFFER-1]
else
return line
end
end
end
def PSQLexec(ps, query)
res = ps.db.exec(query)
if res == nil
printf(STDERR, "%s\n", ps.db.error())
else
if (res.status() == PGresult::COMMAND_OK ||
res.status() == PGresult::TUPLES_OK)
return res
end
if !ps.quiet
printf(STDERR, "%s\n", ps.db.error())
end
res.clear()
end
end
def listAllDbs(ps)
query = "select * from pg_database;"
if (results = PSQLexec(ps, query)) == nil
return 1
else
results.print(ps.queryFout, ps.opt)
results.clear()
return 0
end
end
def tableList(ps, deep_tablelist, info_type, system_tables)
listbuf = "SELECT usename, relname, relkind, relhasrules"
listbuf += " FROM pg_class, pg_user "
listbuf += "WHERE usesysid = relowner "
case info_type
when 't'
listbuf += "and ( relkind = 'r') "
when 'i'
listbuf += "and ( relkind = 'i') "
haveIndexes = true
when 'S'
listbuf += "and ( relkind = 'S') "
else
listbuf += "and ( relkind = 'r' OR relkind = 'i' OR relkind='S') "
haveIndexes = true
end
if (!system_tables)
listbuf += "and relname !~ '^pg_' "
else
listbuf += "and relname ~ '^pg_' "
end
if (haveIndexes)
listbuf += "and (relkind != 'i' OR relname !~'^xinx')"
end
listbuf += " ORDER BY relname "
res = PSQLexec(ps, listbuf)
if res == nil
return
end
# first, print out the attribute names
nColumns = res.num_tuples
if nColumns > 0
if deep_tablelist
table = res.result
res.clear
for i in 0..nColumns-1
tableDesc(ps, table[i][1])
end
else
# Display the information
printf("\nDatabase = %s\n", ps.db.db)
printf(" +------------------+----------------------------------+----------+\n")
printf(" | Owner | Relation | Type |\n")
printf(" +------------------+----------------------------------+----------+\n")
# next, print out the instances
for i in 0..res.num_tuples-1
printf(" | %-16.16s", res.getvalue(i, 0))
printf(" | %-32.32s | ", res.getvalue(i, 1))
rk = res.getvalue(i, 2)
rr = res.getvalue(i, 3)
if (rk.eql?("r"))
printf("%-8.8s |", if (rr[0] == 't') then "view?" else "table" end)
else
printf("%-8.8s |", "index")
end
printf("\n")
end
printf(" +------------------+----------------------------------+----------+\n")
res.clear()
end
else
printf(STDERR, "Couldn't find any tables!\n")
end
end
def tableDesc(ps, table)
descbuf = "SELECT a.attnum, a.attname, t.typname, a.attlen"
descbuf += " FROM pg_class c, pg_attribute a, pg_type t "
descbuf += " WHERE c.relname = '"
descbuf += table
descbuf += "'"
descbuf += " and a.attnum > 0 "
descbuf += " and a.attrelid = c.oid "
descbuf += " and a.atttypid = t.oid "
descbuf += " ORDER BY attnum "
res = PSQLexec(ps, descbuf)
if res == nil
return
end
# first, print out the attribute names
nColumns = res.num_tuples()
if nColumns > 0
#
# Display the information
#
printf("\nTable = %s\n", table)
printf("+----------------------------------+----------------------------------+-------+\n")
printf("| Field | Type | Length|\n")
printf("+----------------------------------+----------------------------------+-------+\n")
# next, print out the instances
for i in 0..res.num_tuples-1
printf("| %-32.32s | ", res.getvalue(i, 1))
rtype = res.getvalue(i, 2);
rsize = res.getvalue(i, 3).to_i
if (rtype.eql?("text"))
printf("%-32.32s |", rtype)
printf("%6s |", "var")
elsif (rtype.eql?("bpchar"))
printf("%-32.32s |", "(bp)char")
printf("%6i |", if (rsize > 0) then rsize - 4 else 0 end)
elsif (rtype.eql?("varchar"))
printf("%-32.32s |", rtype)
printf("%6d |", if (rsize > 0) then rsize - 4 else 0 end)
else
# array types start with an underscore
if (rtype[0, 1] != '_')
printf("%-32.32s |", rtype)
else
newname = rtype + "[]"
printf("%-32.32s |", newname)
end
if (rsize > 0)
printf("%6d |", rsize)
else
printf("%6s |", "var")
end
end
printf("\n")
end
printf("+----------------------------------+----------------------------------+-------+\n")
res.clear()
else
printf(STDERR, "Couldn't find table %s!\n", table)
end
end
def unescape(source)
dest = source.gsub(/(\\n|\\r|\\t|\\f|\\\\)/) {
|c|
case c
when "\\n"
"\n"
when "\\r"
"\r"
when "\\t"
"\t"
when "\\f"
"\f"
when "\\\\"
"\\"
end
}
return dest
end
def do_shell(command)
if !command
command = ENV["SHELL"]
if shellName == nil
command = DEFAULT_SHELL
end
end
system(command);
end
def do_help(topic)
if !topic
printf("type \\h <cmd> where <cmd> is one of the following:\n")
left_center_right = 'L' # Start with left column
for i in 0..QL_HELP.length-1
case left_center_right
when 'L'
printf(" %-25s", QL_HELP[i][0])
left_center_right = 'C'
when 'C'
printf("%-25s", QL_HELP[i][0])
left_center_right = 'R'
when 'R'
printf("%-25s\n", QL_HELP[i][0])
left_center_right = 'L'
end
end
if (left_center_right != 'L')
STDOUT.print("\n")
end
printf("type \\h * for a complete description of all commands\n")
else
help_found = FALSE
for i in 0..QL_HELP.length-1
if QL_HELP[i][0] == topic || topic == "*"
help_found = TRUE
printf("Command: %s\n", QL_HELP[i][0])
printf("Description: %s\n", QL_HELP[i][1])
printf("Syntax:\n")
printf("%s\n", QL_HELP[i][2])
printf("\n")
end
end
if !help_found
printf("command not found, ")
printf("try \\h with no arguments to see available help\n")
end
end
end
def do_edit(filename_arg, query)
if filename_arg
fname = filename_arg
error = FALSE
else
fname = sprintf("/tmp/psql.rb.%d", $$)
p fname
if test(?e, fname)
File.unlink(fname)
end
if query
begin
fd = File.new(fname, "w")
if query[query.length-1, 1] != "\n"
query += "\n"
end
if fd.print(query) != query.length
fd.close
File.unlink(fname)
error = TRUE
else
error = FALSE
end
fd.close
rescue
error = TRUE
end
else
error = FALSE
end
end
if error
status = 1
else
editFile(fname)
begin
fd = File.new(fname, "r")
query = fd.read
fd.close
if query == nil
status = 1
else
query.sub!(/[ \t\f\r\n]*$/, "")
if query.length != 0
status = 3
else
query = nil
status = 1
end
end
rescue
status = 1
ensure
if !filename_arg
if test(?e, fname)
File.unlink(fname)
end
end
end
end
return status, query
end
def editFile(fname)
editorName = ENV["EDITOR"]
if editorName == nil
editorName = DEFAULT_EDITOR
end
system(editorName + " " + fname)
end
def do_connect(settings, new_dbname)
dbname = settings.db.db
if !new_dbname
printf(STDERR, "\\connect must be followed by a database name\n");
else
olddb = settings.db
begin
printf("closing connection to database: %s\n", dbname);
settings.db = PGconn.connect(olddb.host, olddb.port, "", "", new_dbname)
printf("connecting to new database: %s\n", new_dbname)
olddb.finish()
rescue
printf(STDERR, "%s\n", $!)
printf("reconnecting to %s\n", dbname)
settings.db = PGconn.connect(olddb.host, olddb.port,"", "", dbname)
ensure
settings.prompt = settings.db.db + PROMPT
end
end
end
def do_copy(settings, table, from_p, file)
if (table == nil || from_p == nil || file == nil)
printf("Syntax error, reffer \\copy help with \\? \n")
return
end
if from_p.upcase! == "FROM"
from = TRUE
else
from = FALSE
end
query = "COPY "
query += table
if from
query += " FROM stdin"
copystream = File.new(file, "r")
else
query += " TO stdout"
copystream = File.new(file, "w")
end
begin
success = SendQuery(settings, query, from, !from, copystream);
copystream.close
if !settings.quiet
if success
printf("Successfully copied.\n");
else
printf("Copy failed.\n");
end
end
rescue
printf(STDERR, "Unable to open file %s which to copy.",
if from then "from" else "to" end)
end
end
def handleCopyOut(settings, copystream)
copydone = FALSE
while !copydone
copybuf = settings.db.getline
if !copybuf
copydone = TRUE
else
if copybuf == "\\."
copydone = TRUE
else
copystream.print(copybuf + "\n")
end
end
end
copystream.flush
settings.db.endcopy
end
def handleCopyIn(settings, mustprompt, copystream)
copydone = FALSE
if mustprompt
STDOUT.print("Enter info followed by a newline\n")
STDOUT.print("End with a backslash and a ")
STDOUT.print("period on a line by itself.\n")
end
while !copydone
if mustprompt
STDOUT.print(">> ")
STDOUT.flush
end
copybuf = copystream.gets
if copybuf == nil
settings.db.putline("\\.\n")
copydone = TRUE
break
end
settings.db.putline(copybuf)
if copybuf == "\\.\n"
copydone = TRUE
end
end
settings.db.endcopy
end
def setFout(ps, fname)
if (ps.queryFout && ps.queryFout != STDOUT)
ps.queryFout.close
end
if !fname
ps.queryFout = STDOUT
else
begin
if fname[0, 1] == "|"
dumy, ps.queryFout = pipe(fname)
ps.pipe = TRUE
else
ps.queryFout = File.new(fname, "w+")
ps.pipe = FALSE
end
rescue
ps.queryFout = STDOUT
ps.pipe = FALSE
end
end
end
def HandleSlashCmds(settings, line, query)
status = 1
cmd = unescape(line[1, line.length])
args = cmd.split
case args[0]
when 'a' # toggles to align fields on output
settings.opt.align =
toggle(settings, settings.opt.align, "field alignment")
when 'C' # define new caption
if !args[1]
settings.opt.caption = ""
else
settings.opt.caption = args[1]
end
when 'c', 'connect' # connect new database
do_connect(settings, args[1])
when 'copy' # copy from file
do_copy(settings, args[1], args[2], args[3])
when 'd' # \d describe tables or columns in a table
if !args[1]
tableList(settings, FALSE, 'b', FALSE)
elsif args[1] == "*"
tableList(settings, FALSE, 'b', FALSE)
tableList(settings, TRUE, 'b', FALSE)
else
tableDesc(settings, args[1])
end
when 'da'
descbuf = "SELECT a.aggname AS aggname, t.typname AS type, "
descbuf += "obj_description (a.oid) as description "
descbuf += "FROM pg_aggregate a, pg_type t "
descbuf += "WHERE a.aggbasetype = t.oid "
if (args[1])
descbuf += "AND a.aggname ~ '^"
descbuf += args[1]
descbuf += "' "
end
descbuf += "UNION SELECT a.aggname AS aggname, "
descbuf += "'all types' as type, obj_description (a.oid) "
descbuf += "as description FROM pg_aggregate a "
descbuf += "WHERE a.aggbasetype = 0"
if (args[1])
descbuf += "AND a.aggname ~ '^"
descbuf += args[1]
descbuf += "' "
end
descbuf += "ORDER BY aggname, type;"
res = SendQuery(settings, descbuf, FALSE, FALSE, 0)
when 'di'
tableList(settings, FALSE, 'i', FALSE)
when 'ds'
tableList(settings, FALSE, 'S', FALSE)
when 'dS'
tableList(settings, FALSE, 'b', TRUE)
when 'dt'
tableList(settings, FALSE, 't', FALSE)
when 'e' # edit
status, query = do_edit(args[1], query)
when 'E'
if args[1]
begin
lastfile = args[1]
File.file?(lastfile) && (mt = File.mtime(lastfile))
editFile(lastfile)
File.file?(lastfile) && (mt2 = File.mtime(lastfile))
fd = File.new(lastfile, "r")
if mt != mt2
MainLoop(settings, fd)
fd.close()
else
if !settings.quiet
printf(STDERR, "warning: %s not modified. query not executed\n", lastfile)
end
fd.close()
end
rescue
#
end
else
printf(STDERR, "\\r must be followed by a file name initially\n");
end
when 'f'
if args[1]
settings.opt.fieldSep = args[1]
if !settings.quiet
printf(STDERR, "field separater changed to '%s'\n", settings.opt.fieldSep)
end
end
when 'g' # \g means send query
if !args[1]
settings.gfname = nil
else
settings.gfname = args[1]
end
status = 0
when 'h' # help
if args[2]
args[1] += " " + args[2]
end
do_help(args[1])
when 'i' # \i is include file
if args[1]
begin
fd = File.open(args[1], "r")
MainLoop(settings, fd)
fd.close()
rescue Errno::ENOENT
printf(STDERR, "file named %s could not be opened\n", args[1])
end
else
printf(STDERR, "\\i must be followed by a file name\n")
end
when 'l' # \l is list database
listAllDbs(settings)
when 'H'
settings.opt.html3 =
toggle(settings, settings.opt.html3, "HTML3.0 tabular output")
if settings.opt.html3
settings.opt.standard = FALSE
end
when 'o'
setFout(settings, args[1])
when 'p'
if query
File.print(query)
File.print("\n")
end
when 'q' # \q is quit
status = 2
when 'r' # reset(clear) the buffer
query = nil
if !settings.quiet
printf(STDERR, "buffer reset(cleared)\n")
end
when 's' # \s is save history to a file
begin
if (args[1])
fd = File.open(args[1], "w")
else
fd = STDOUT
end
Readline::HISTORY.each do |his|
fd.write (his + "\n")
end
if !fd.tty?
begin
fd.close
end
end
rescue
printf(STDERR, "cannot write history \n");
end
when 'm' # monitor like type-setting
settings.opt.standard =
toggle(settings, settings.opt.standard, "standard SQL separaters and padding")
if settings.opt.standard
settings.opt.html3 = FALSE
settings.opt.expanded = FALSE
settings.opt.align = TRUE
settings.opt.header = TRUE
if settings.opt.fieldSep
settings.opt.fieldSep = ""
end
settings.opt.fieldSep = "|"
if !settings.quiet
printf(STDERR, "field separater changed to '%s'\n", settings.opt.fieldSep)
end
else
if settings.opt.fieldSep
settings.opt.fieldSep = ""
end
settings.opt.fieldSep = DEFAULT_FIELD_SEP
if !settings.quiet
printf(STDERR, "field separater changed to '%s'\n", settings.opt.fieldSep)
end
end
when 't' # toggle headers
settings.opt.header =
toggle(settings, settings.opt.header, "output headings and row count")
when 'T' # define html <table ...> option
if !args[1]
settings.opt.tableOpt = nil
else
settings.opt.tableOpt = args[1]
end
when 'x'
settings.opt.expanded =
toggle(settings, settings.opt.expanded, "expanded table representation")
when '!'
do_shell(args[1])
when '?' # \? is help
slashUsage(settings)
end
return status, query
end
def SendQuery(settings, query, copy_in, copy_out, copystream)
if settings.singleStep
printf("\n**************************************")
printf("*****************************************\n")
end
if (settings.echoQuery || settings.singleStep)
printf(STDERR, "QUERY: %s\n", query);
end
if settings.singleStep
printf("\n**************************************");
printf("*****************************************\n")
STDOUT.flush
printf("\npress return to continue ..\n");
gets("", STDIN);
end
begin
results = settings.db.exec(query)
case results.status
when PGresult::TUPLES_OK
success = TRUE
if settings.gfname
setFout(settings, settings.gfname)
settings.gfname = nil
results.print(settings.queryFout, settings.opt)
settings.queryFout.flush
if settings.queryFout != STDOUT
settings.queryFout.close
settings.queryFout = STDOUT
end
else
results.print(settings.queryFout, settings.opt)
settings.queryFout.flush
end
results.clear
when PGresult::EMPTY_QUERY
success = TRUE
when PGresult::COMMAND_OK
success = TRUE
if !settings.quiet
printf("%s\n", results.cmdstatus)
end
when PGresult::COPY_OUT
success = TRUE
if copy_out
handleCopyOut(settings, copystream)
else
if !settings.quiet
printf("Copy command returns...\n")
end
handleCopyOut(settings, STDOUT)
end
when PGresult::COPY_IN
success = TRUE
if copy_in
handleCopyIn(settings, FALSE, copystream)
else
handleCopyIn(settings, !settings.quiet, STDIN)
end
end
if (settings.db.status == PGconn::CONNECTION_BAD)
printf(STDERR, "We have lost the connection to the backend, so ")
printf(STDERR, "further processing is impossible. ")
printf(STDERR, "Terminating.\n")
exit(2)
end
# check for asynchronous returns
# notify = settings.db.notifies()
# if notify
# printf(STDERR,"ASYNC NOTIFY of '%s' from backend pid '%d' received\n",
# notify.relname, notify.be_pid)
# end
rescue
printf(STDERR, "%s", $!)
success = FALSE
end
return success
end
def MainLoop(settings, source)
success = TRUE
interactive = TRUE
insideQuote = FALSE
querySent = FALSE
done = FALSE
query = nil
queryWaiting = nil
slashCmdStatus = -1
interactive = (source == STDIN && !settings.notty)
if settings.quiet
settings.prompt = nil
else
settings.prompt = settings.db.db + PROMPT
end
while !done
if slashCmdStatus == 3
line = query
query = nil
else
if interactive && !settings.quiet
if insideQuote
settings.prompt[settings.prompt.length-3,1] = "\'"
elsif (queryWaiting != nil && !querySent)
settings.prompt[settings.prompt.length-3,1] = "-"
else
settings.prompt[settings.prompt.length-3,1] = "="
end
end
line = gets(settings.prompt, source)
end
if line == nil
printf("EOF\n")
done = TRUE
else
### debbegging information ###
if !interactive && !settings.singleStep && !settings.quiet
printf(STDERR, "%s\n", line)
end
### ommit comment ###
begin_comment = line.index("--")
if begin_comment
line = line[0, begin_comment]
end
### erase unnecessary characters ###
line.gsub!(/[ \t\f\n\r]+\z/, "")
if line.length == 0
next
end
### begin slash command handling ###
if line[0, 1] == "\\"
query = line
slashCmdStatus, query = HandleSlashCmds(settings, line, nil)
if slashCmdStatus == 0 && query != nil
success = SendQuery(settings, query, FALSE, FALSE, 0) && success
querySent = TRUE
elsif slashCmdStatus == 1
query = nil
elsif slashCmdStatus == 2
break
end
line = nil
next
end
### begin query command handling ###
slashCmdStatus = -1
if settings.singleLineMode
success = SendQuery(settings, line, FALSE, FALSE, 0) && success
querySent = TRUE
else
if queryWaiting
queryWaiting += " " + line
else
queryWaiting = line
end
for i in 0..line.length-1
if line[i, 1] == "\'"
insideQuote = !insideQuote
end
end
if !insideQuote
if line[line.length-1, 1] == ";"
query = queryWaiting
queryWaiting = nil
success = SendQuery(settings, query, FALSE, FALSE, 0) && success
querySent = TRUE
else
querySent = FALSE
end
else
querySent = FALSE
end
end
end
end # while
return success
end
def main
dbname = nil
host = "localhost"
port = 5432
qfilename = nil
singleQuery = nil
settings = PsqlSettings.new(nil, nil, nil, nil, nil, FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE)
settings.opt = PrintOpt.new(FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, nil, nil, nil, nil)
listDatabases = FALSE
successResult = TRUE
singleSlashCmd = FALSE
settings.opt.align = TRUE
settings.opt.header = TRUE
settings.queryFout = STDOUT
settings.opt.fieldSep = DEFAULT_FIELD_SEP.dup
settings.opt.pager = TRUE
settings.quiet = FALSE
settings.notty = FALSE
settings.useReadline = TRUE
parsed = parseArgs(0, nil, "AelHnsqStx", "a:", "c:", "d:", "f:", "F:",
"h:", "o:", "p:", "T:")
if $OPT_A
settings.opt.align = FALSE
end
if $OPT_a
#fe_setauthsvc(optarg, errbuf);
printf("not implemented, sorry.\n")
exit(1)
end
if $OPT_c
singleQuery = $OPT_c
if singleQuery[0, 1] == "\\"
singleSlashCmd = TRUE
end
end
if $OPT_d
dbname = $OPT_d
end
if $OPT_e
settings.echoQuery = TRUE
end
if $OPT_f
qfilename = $OPT_f
end
if $OPT_F
settings.opt.fieldSep = $OPT_F
end
if $OPT_l
listDatabases = TRUE
end
if $OPT_h
host = $OPT_h
end
if $OPT_H
settings.opt.html3 = TRUE
end
if $OPT_n
settings.useReadline = FALSE
end
if $OPT_o
setFout(settings, $OPT_o)
end
if $OPT_p
port = $OPT_p.to_i
end
if $OPT_q
settings.quiet = TRUE
end
if $OPT_s
settings.singleStep = TRUE
end
if $OPT_S
settings.singleLineMode = TRUE
end
if $OPT_t
settings.opt.header = FALSE
end
if $OPT_T
settings.opt.tableOpt = $OPT_T
end
if $OPT_x
settings.opt.expanded = TRUE
end
if ARGV.length == 1
dbname = ARGV[0]
end
if listDatabases
dbname = "template1"
end
settings.db = PGconn.connect(host, port, "", "", dbname);
dbname = settings.db.db
if settings.db.status() == PGconn::CONNECTION_BAD
printf(STDERR, "Connection to database '%s' failed.\n", dbname)
printf(STDERR, "%s", settings.db.error)
exit(1)
end
if listDatabases
exit(listAllDbs(settings))
end
if (!settings.quiet && !singleQuery && !qfilename)
printf("Welcome to the POSTGRESQL interactive sql monitor:\n")
printf(" Please read the file COPYRIGHT for copyright terms of POSTGRESQL\n\n")
printf(" type \\? for help on slash commands\n")
printf(" type \\q to quit\n")
printf(" type \\g or terminate with semicolon to execute query\n")
printf(" You are currently connected to the database: %s\n\n", dbname)
end
if (qfilename || singleSlashCmd)
if singleSlashCmd
line = singleQuery
else
line = sprintf("\\i %s", qfilename)
end
HandleSlashCmds(settings, line, "")
else
if settings.useReadline
begin
require "readline"
$readline_ok = TRUE
rescue
$readline_ok = FALSE
end
else
$readline_ok = FALSE
end
if singleQuery
success = SendQuery(settings, singleQuery, false, false, 0)
successResult = success
else
successResult = MainLoop(settings, STDIN)
end
end
settings.db.finish()
return !successResult
end
main
|