1 /*-------------------------------------------------------------------------
4 * an interactive front-end to postgreSQL
6 * Copyright (c) 1996, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/bin/psql/Attic/psql.c,v 1.53 1997/01/25 22:51:56 scrappy Exp $
12 *-------------------------------------------------------------------------
18 #include <sys/types.h>
19 #include <sys/param.h> /* for MAXPATHLEN */
27 #include "stringutils.h"
33 #ifndef HAVE_LIBREADLINE
36 # ifdef HAVE_READLINE_H
37 # include <readline.h>
38 # if defined(HAVE_HISTORY) || defined(HAVE_LIBHISTORY)
42 # include <readline/readline.h>
43 # if defined(HAVE_HISTORY) || defined(HAVE_LIBHISTORY)
44 # include <readline/history.h>
51 #define MAX_QUERY_BUFFER 20000
53 #define COPYBUFSIZ 8192
55 #define DEFAULT_FIELD_SEP "|"
56 #define DEFAULT_EDITOR "vi"
57 #define DEFAULT_SHELL "/bin/sh"
59 typedef struct _psqlSettings {
60 PGconn *db; /* connection to backend */
61 FILE *queryFout; /* where to send the query results */
62 PQprintOpt opt; /* options to be passed to PQprint */
63 char *prompt; /* prompt to display */
64 char *gfname; /* one-shot file output argument for \g */
65 bool notty; /* input or output is not a tty */
66 bool pipe; /* queryFout is from a popen() */
67 bool echoQuery; /* echo the query before sending it */
68 bool quiet; /* run quietly, no messages, no promt */
69 bool singleStep; /* prompt before for each query */
70 bool singleLineMode; /* query terminated by newline */
71 bool useReadline;/* use libreadline routines */
74 /* declarations for functions in this file */
75 static void usage(char *progname);
76 static void slashUsage();
77 static void handleCopyOut(PGresult * res, bool quiet, FILE * copystream);
79 handleCopyIn(PGresult * res, const bool mustprompt,
81 static int tableList(PsqlSettings * ps, bool deep_tablelist);
82 static int tableDesc(PsqlSettings * ps, char *table);
84 char *gets_noreadline(char *prompt, FILE * source);
85 char *gets_readline(char *prompt, FILE * source);
86 char *gets_fromFile(char *prompt, FILE * source);
87 int listAllDbs(PsqlSettings * settings);
89 SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
90 const bool copy_in, const bool copy_out, FILE * copystream);
92 HandleSlashCmds(PsqlSettings * settings,
95 int MainLoop(PsqlSettings * settings, FILE * source);
96 /* probably should move this into libpq */
103 FILE *setFout(PsqlSettings * ps, char *fname);
106 * usage print out usage for command line arguments
110 usage(char *progname)
112 fprintf(stderr, "Usage: %s [options] [dbname]\n", progname);
113 fprintf(stderr, "\t -a authsvc set authentication service\n");
114 fprintf(stderr, "\t -A turn off alignment when printing out attributes\n");
115 fprintf(stderr, "\t -c query run single query (slash commands too)\n");
116 fprintf(stderr, "\t -d dbName specify database name\n");
117 fprintf(stderr, "\t -e echo the query sent to the backend\n");
118 fprintf(stderr, "\t -f filename use file as a source of queries\n");
119 fprintf(stderr, "\t -F sep set the field separator (default is " ")\n");
120 fprintf(stderr, "\t -h host set database server host\n");
121 fprintf(stderr, "\t -H turn on html3.0 table output\n");
122 fprintf(stderr, "\t -l list available databases\n");
123 fprintf(stderr, "\t -n don't use readline library\n");
124 fprintf(stderr, "\t -o filename send output to filename or (|pipe)\n");
125 fprintf(stderr, "\t -p port set port number\n");
126 fprintf(stderr, "\t -q run quietly (no messages, no prompts)\n");
127 fprintf(stderr, "\t -s single step mode (prompts for each query)\n");
128 fprintf(stderr, "\t -S single line mode (i.e. query terminated by newline)\n");
129 fprintf(stderr, "\t -t turn off printing of headings and row count\n");
130 fprintf(stderr, "\t -T html set html3.0 table command options (cf. -H)\n");
131 fprintf(stderr, "\t -x turn on expanded output (field names on left)\n");
136 * slashUsage print out usage for the backslash commands
142 return f ? "on" : "off";
146 slashUsage(PsqlSettings * ps)
148 fprintf(stderr, " \\? -- help\n");
149 fprintf(stderr, " \\a -- toggle field-alignment (currenty %s)\n", on(ps->opt.align));
150 fprintf(stderr, " \\C [<captn>] -- set html3 caption (currently '%s')\n", ps->opt.caption ? ps->opt.caption : "");
151 fprintf(stderr, " \\connect <dbname> -- connect to new database (currently '%s')\n", PQdb(ps->db));
152 fprintf(stderr, " \\copy {<table> to <file> | <file> from <table>}\n");
153 fprintf(stderr, " \\d [<table>] -- list tables in database or columns in <table>, * for all\n");
154 fprintf(stderr, " \\e [<fname>] -- edit the current query buffer or <fname>, \\E execute too\n");
155 fprintf(stderr, " \\f [<sep>] -- change field separater (currently '%s')\n", ps->opt.fieldSep);
156 fprintf(stderr, " \\g [<fname>] [|<cmd>] -- send query to backend [and results in <fname> or pipe]\n");
157 fprintf(stderr, " \\h [<cmd>] -- help on syntax of sql commands, * for all commands\n");
158 fprintf(stderr, " \\H -- toggle html3 output (currently %s)\n", on(ps->opt.html3));
159 fprintf(stderr, " \\i <fname> -- read and execute queries from filename\n");
160 fprintf(stderr, " \\l -- list all databases\n");
161 fprintf(stderr, " \\m -- toggle monitor-like table display (currently %s)\n", on(ps->opt.standard));
162 fprintf(stderr, " \\o [<fname>] [|<cmd>] -- send all query results to stdout, <fname>, or pipe\n");
163 fprintf(stderr, " \\p -- print the current query buffer\n");
164 fprintf(stderr, " \\q -- quit\n");
165 fprintf(stderr, " \\r -- reset(clear) the query buffer\n");
166 fprintf(stderr, " \\s [<fname>] -- print history or save it in <fname>\n");
167 fprintf(stderr, " \\t -- toggle table headings and row count (currently %s)\n", on(ps->opt.header));
168 fprintf(stderr, " \\T [<html>] -- set html3.0 <table ...> options (currently '%s')\n", ps->opt.tableOpt ? ps->opt.tableOpt : "");
169 fprintf(stderr, " \\x -- toggle expanded output (currently %s)\n", on(ps->opt.expanded));
170 fprintf(stderr, " \\! [<cmd>] -- shell escape or command\n");
174 PSQLexec(PsqlSettings * ps, char *query)
176 PGresult *res = PQexec(ps->db, query);
178 fputs(PQerrorMessage(ps->db), stderr);
180 if (PQresultStatus(res) == PGRES_COMMAND_OK ||
181 PQresultStatus(res) == PGRES_TUPLES_OK)
184 fputs(PQerrorMessage(ps->db), stderr);
192 * list all the databases in the system returns 0 if all went well
198 listAllDbs(PsqlSettings * ps)
201 char *query = "select * from pg_database;";
203 if (!(results = PSQLexec(ps, query)))
206 PQprint(ps->queryFout,
215 * List The Database Tables returns 0 if all went well
219 tableList(PsqlSettings * ps, bool deep_tablelist)
230 strcat(listbuf, "SELECT usename, relname, relkind, relhasrules");
231 strcat(listbuf, " FROM pg_class, pg_user ");
232 strcat(listbuf, "WHERE ( relkind = 'r' OR relkind = 'i') ");
233 strcat(listbuf, " and relname !~ '^pg_'");
234 strcat(listbuf, " and relname !~ '^Inv[0-9]+'");
236 * the usesysid = relowner won't work on stock 1.0 dbs, need to add in
237 * the int4oideq function
239 strcat(listbuf, " and usesysid = relowner");
240 strcat(listbuf, " ORDER BY relname ");
241 if (!(res = PSQLexec(ps, listbuf)))
244 /* first, print out the attribute names */
245 nColumns = PQntuples(res);
247 if (deep_tablelist) {
248 /* describe everything here */
250 table = (char **) malloc(nColumns * sizeof(char *));
254 /* load table table */
255 for (i = 0; i < nColumns; i++) {
256 table[i] = (char *) malloc(PQgetlength(res, i, 1) * sizeof(char) + 1);
257 if (table[i] == NULL)
259 strcpy(table[i], PQgetvalue(res, i, 1));
263 for (i = 0; i < nColumns; i++) {
264 tableDesc(ps, table[i]);
268 /* Display the information */
270 printf("\nDatabase = %s\n", PQdb(ps->db));
271 printf(" +------------------+----------------------------------+----------+\n");
272 printf(" | Owner | Relation | Type |\n");
273 printf(" +------------------+----------------------------------+----------+\n");
275 /* next, print out the instances */
276 for (i = 0; i < PQntuples(res); i++) {
277 printf(" | %-16.16s", PQgetvalue(res, i, 0));
278 printf(" | %-32.32s | ", PQgetvalue(res, i, 1));
279 rk = PQgetvalue(res, i, 2);
280 rr = PQgetvalue(res, i, 3);
281 if (strcmp(rk, "r") == 0)
282 printf("%-8.8s |", (rr[0] == 't') ? "view?" : "table");
284 printf("%-8.8s |", "index");
287 printf(" +------------------+----------------------------------+----------+\n");
293 fprintf(stderr, "Couldn't find any tables!\n");
301 * Describe the columns in a database table. returns 0 if all went well
306 tableDesc(PsqlSettings * ps, char *table)
316 /* Build the query */
319 strcat(descbuf, "SELECT a.attnum, a.attname, t.typname, a.attlen");
320 strcat(descbuf, " FROM pg_class c, pg_attribute a, pg_type t ");
321 strcat(descbuf, " WHERE c.relname = '");
322 strcat(descbuf, table);
323 strcat(descbuf, "'");
324 strcat(descbuf, " and a.attnum > 0 ");
325 strcat(descbuf, " and a.attrelid = c.oid ");
326 strcat(descbuf, " and a.atttypid = t.oid ");
327 strcat(descbuf, " ORDER BY attnum ");
328 if (!(res = PSQLexec(ps, descbuf)))
330 /* first, print out the attribute names */
331 nColumns = PQntuples(res);
334 * * Display the information
337 printf("\nTable = %s\n", table);
338 printf("+----------------------------------+----------------------------------+-------+\n");
339 printf("| Field | Type | Length|\n");
340 printf("+----------------------------------+----------------------------------+-------+\n");
342 /* next, print out the instances */
343 for (i = 0; i < PQntuples(res); i++) {
344 printf("| %-32.32s | ", PQgetvalue(res, i, 1));
345 rtype = PQgetvalue(res, i, 2);
346 rsize = atoi(PQgetvalue(res, i, 3));
347 if (strcmp(rtype, "text") == 0) {
348 printf("%-32.32s |", rtype);
349 printf("%6s |", "var");
350 } else if (strcmp(rtype, "bpchar") == 0) {
351 printf("%-32.32s |", "(bp)char");
352 printf("%6i |", rsize > 0 ? rsize - 4 : 0);
353 } else if (strcmp(rtype, "varchar") == 0) {
354 printf("%-32.32s |", rtype);
355 printf("%6i |", rsize > 0 ? rsize - 4 : 0);
357 /* array types start with an underscore */
359 printf("%-32.32s |", rtype);
362 newname = malloc(strlen(rtype) + 2);
363 strcpy(newname, rtype + 1);
364 strcat(newname, "[]");
365 printf("%-32.32s |", newname);
369 printf("%6i |", rsize);
371 printf("%6s |", "var");
375 printf("+----------------------------------+----------------------------------+-------+\n");
381 fprintf(stderr, "Couldn't find table %s!\n", table);
386 typedef char *(*READ_ROUTINE) (char *prompt, FILE * source);
389 * gets_noreadline prompt source gets a line of input without calling
390 * readline, the source is ignored
393 gets_noreadline(char *prompt, FILE * source)
395 fputs(prompt, stdout);
397 return (gets_fromFile(prompt, stdin));
401 * gets_readline prompt source the routine to get input from GNU readline(),
402 * the source is ignored the prompt argument is used as the prompting string
405 gets_readline(char *prompt, FILE * source)
407 char *s = readline(prompt);
414 * gets_fromFile prompt source
416 * the routine to read from a file, the prompt argument is ignored the source
417 * argument is a FILE *
420 gets_fromFile(char *prompt, FILE * source)
425 line = malloc(MAX_QUERY_BUFFER + 1);
427 /* read up to MAX_QUERY_BUFFER characters */
428 if (fgets(line, MAX_QUERY_BUFFER, source) == NULL)
431 line[MAX_QUERY_BUFFER - 1] = '\0';
433 if (len == MAX_QUERY_BUFFER) {
434 fprintf(stderr, "line read exceeds maximum length. Truncating at %d\n",
441 * SendQuery: send the query string to the backend return *success_p = 1 if
442 * the query executed successfully returns *success_p = 0 otherwise
445 SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
446 const bool copy_in, const bool copy_out, FILE * copystream)
452 if (settings->singleStep)
453 fprintf(stdout, "\n**************************************"
454 "*****************************************\n");
456 if (settings->echoQuery || settings->singleStep) {
457 fprintf(stderr, "QUERY: %s\n", query);
460 if (settings->singleStep) {
461 fprintf(stdout, "\n**************************************"
462 "*****************************************\n");
464 printf("\npress return to continue ..\n");
465 gets_fromFile("", stdin);
467 results = PQexec(settings->db, query);
468 if (results == NULL) {
469 fprintf(stderr, "%s", PQerrorMessage(settings->db));
472 switch (PQresultStatus(results)) {
473 case PGRES_TUPLES_OK:
474 if (settings->gfname) {
475 PsqlSettings ps = *settings;
477 ps.queryFout = stdout;
478 fp = setFout(&ps, settings->gfname);
479 if (!fp || fp == stdout) {
491 free(settings->gfname);
492 settings->gfname = NULL;
496 PQprint(settings->queryFout,
499 fflush(settings->queryFout);
503 case PGRES_EMPTY_QUERY:
506 case PGRES_COMMAND_OK:
508 if (!settings->quiet)
509 fprintf(stdout, "%s\n", PQcmdStatus(results));
514 handleCopyOut(results, settings->quiet, copystream);
516 if (!settings->quiet)
517 fprintf(stdout, "Copy command returns...\n");
519 handleCopyOut(results, settings->quiet, stdout);
525 handleCopyIn(results, false, copystream);
527 handleCopyIn(results, !settings->quiet, stdin);
529 case PGRES_NONFATAL_ERROR:
530 case PGRES_FATAL_ERROR:
531 case PGRES_BAD_RESPONSE:
533 fprintf(stderr, "%s", PQerrorMessage(settings->db));
537 if (PQstatus(settings->db) == CONNECTION_BAD) {
539 "We have lost the connection to the backend, so "
540 "further processing is impossible. "
542 exit(2); /* we are out'ta here */
544 /* check for asynchronous returns */
545 notify = PQnotifies(settings->db);
548 "ASYNC NOTIFY of '%s' from backend pid '%d' received\n",
549 notify->relname, notify->be_pid);
558 editFile(char *fname)
562 editorName = getenv("EDITOR");
564 editorName = DEFAULT_EDITOR;
565 sys = malloc(strlen(editorName) + strlen(fname) + 32 + 1);
570 sprintf(sys, "exec '%s' '%s'", editorName, fname);
576 toggle(PsqlSettings * settings, bool * sw, char *msg)
579 if (!settings->quiet)
580 fprintf(stderr, "turned %s %s\n", on(*sw), msg);
587 unescape(char *dest, const char *source)
589 /*-----------------------------------------------------------------------------
590 Return as the string <dest> the value of string <source> with escape
591 sequences turned into the bytes they represent.
592 -----------------------------------------------------------------------------*/
594 bool esc; /* Last character we saw was the escape
597 esc = false; /* Haven't seen escape character yet */
598 for (p = (char *) source; *p; p++) {
599 char c; /* Our output character */
622 } else if (*p == '\\') {
624 c = ' '; /* meaningless, but compiler doesn't know
633 *dest = '\0'; /* Terminating null character */
639 parse_slash_copy(const char *args, char *table, const int table_len,
640 char *file, const int file_len,
641 bool * from_p, bool * error_p)
646 * A copy of the \copy command arguments, except that we modify it as we
647 * parse to suit our parsing needs.
649 char *table_tok, *fromto_tok;
651 strncpy(work_args, args, sizeof(work_args));
652 work_args[sizeof(work_args) - 1] = '\0';
654 *error_p = false; /* initial assumption */
656 table_tok = strtok(work_args, " ");
657 if (table_tok == NULL) {
658 fprintf(stderr, "\\copy needs arguments.\n");
661 strncpy(table, table_tok, table_len);
662 file[table_len - 1] = '\0';
664 fromto_tok = strtok(NULL, " ");
665 if (fromto_tok == NULL) {
666 fprintf(stderr, "'FROM' or 'TO' must follow table name.\n");
669 if (strcasecmp(fromto_tok, "from") == 0)
671 else if (strcasecmp(fromto_tok, "to") == 0)
675 "Unrecognized token found where "
676 "'FROM' or 'TO' expected: '%s'.\n",
683 file_tok = strtok(NULL, " ");
684 if (file_tok == NULL) {
685 fprintf(stderr, "A file pathname must follow '%s'.\n",
689 strncpy(file, file_tok, file_len);
690 file[file_len - 1] = '\0';
691 if (strtok(NULL, " ") != NULL) {
693 "You have extra tokens after the filename.\n");
705 do_copy(const char *args, PsqlSettings * settings)
707 /*---------------------------------------------------------------------------
708 Execute a \copy command (frontend copy). We have to open a file, then
709 submit a COPY query to the backend and either feed it data from the
710 file or route its response into the file.
712 We do a text copy with default (tab) column delimiters. Some day, we
713 should do all the things a backend copy can do.
715 ----------------------------------------------------------------------------*/
717 /* The COPY command we send to the back end */
719 /* The direction of the copy is from a file to a table. */
720 char file[MAXPATHLEN + 1];
721 /* The pathname of the file from/to which we copy */
722 char table[NAMEDATALEN + 1];
723 /* The name of the table from/to which we copy */
725 /* The \c command has invalid syntax */
728 parse_slash_copy(args, table, sizeof(table), file, sizeof(file),
729 &from, &syntax_error);
732 strcpy(query, "COPY ");
733 strcat(query, table);
736 strcat(query, " FROM stdin");
738 strcat(query, " TO stdout");
741 copystream = fopen(file, "r");
743 copystream = fopen(file, "w");
745 if (copystream == NULL)
747 "Unable to open file %s which to copy, errno = %s (%d).",
748 from ? "from" : "to", strerror(errno), errno);
750 bool success; /* The query succeeded at the backend */
752 SendQuery(&success, settings, query, from, !from, copystream);
754 if (!settings->quiet) {
756 fprintf(stdout, "Successfully copied.\n");
758 fprintf(stdout, "Copy failed.\n");
766 do_connect(const char *new_dbname, PsqlSettings * settings)
769 char *dbname = PQdb(settings->db);
771 fprintf(stderr, "\\connect must be followed by a database name\n");
773 PGconn *olddb = settings->db;
775 printf("closing connection to database: %s\n", dbname);
776 settings->db = PQsetdb(PQhost(olddb), PQport(olddb),
777 NULL, NULL, new_dbname);
778 printf("connecting to new database: %s\n", new_dbname);
779 if (PQstatus(settings->db) == CONNECTION_BAD) {
780 fprintf(stderr, "%s\n", PQerrorMessage(settings->db));
781 printf("reconnecting to %s\n", dbname);
782 settings->db = PQsetdb(PQhost(olddb), PQport(olddb),
784 if (PQstatus(settings->db) == CONNECTION_BAD) {
786 "could not reconnect to %s. exiting\n", dbname);
791 free(settings->prompt);
792 settings->prompt = malloc(strlen(PQdb(settings->db)) + 10);
793 sprintf(settings->prompt, "%s%s", PQdb(settings->db), PROMPT);
800 do_edit(const char *filename_arg, char *query, int *status_p)
807 const int ql = strlen(query);
811 fname = (char *) filename_arg;
814 sprintf(tmp, "/tmp/psql.%ld.%ld", (long) geteuid(), (long) getpid());
818 if ((fd = open(tmp, O_EXCL | O_CREAT | O_WRONLY, 0600)) == -1) {
822 if (query[ql - 1] != '\n')
824 if (write(fd, query, ql) != ql) {
841 if ((fd = open(fname, O_RDONLY)) == -1) {
847 if ((cc = read(fd, query, MAX_QUERY_BUFFER)) == -1) {
868 do_help(const char *topic)
872 char left_center_right; /* Which column we're
874 int i; /* Index into QL_HELP[] */
876 printf("type \\h <cmd> where <cmd> is one of the following:\n");
878 left_center_right = 'L';/* Start with left column */
880 while (QL_HELP[i].cmd != NULL) {
881 switch (left_center_right) {
883 printf(" %-25s", QL_HELP[i].cmd);
884 left_center_right = 'C';
887 printf("%-25s", QL_HELP[i].cmd);
888 left_center_right = 'R';
891 printf("%-25s\n", QL_HELP[i].cmd);
892 left_center_right = 'L';
897 if (left_center_right != 'L')
899 printf("type \\h * for a complete description of all commands\n");
901 int i; /* Index into QL_HELP[] */
902 bool help_found; /* We found the help he asked for */
904 help_found = false; /* Haven't found it yet */
905 for (i = 0; QL_HELP[i].cmd; i++) {
906 if (strcmp(QL_HELP[i].cmd, topic) == 0 ||
907 strcmp(topic, "*") == 0) {
909 printf("Command: %s\n", QL_HELP[i].cmd);
910 printf("Description: %s\n", QL_HELP[i].help);
912 printf("%s\n", QL_HELP[i].syntax);
917 printf("command not found, "
918 "try \\h with no arguments to see available help\n");
925 do_shell(const char *command)
932 shellName = getenv("SHELL");
933 if (shellName == NULL)
934 shellName = DEFAULT_SHELL;
935 sys = malloc(strlen(shellName) + 16);
940 sprintf(sys, "exec %s", shellName);
952 * Handles all the different commands that start with \ db_ptr is a pointer to
953 * the TgDb* structure line is the current input line prompt_ptr is a pointer
954 * to the prompt string, a pointer is used because the prompt can be used
955 * with a connection to a new database returns a status: 0 - send currently
956 * constructed query to backend (i.e. we got a \g) 1 - skip processing of
957 * this line, continue building up query 2 - terminate processing of this
958 * query entirely, 3 - new query supplied by edit
961 HandleSlashCmds(PsqlSettings * settings,
968 * Pointer inside the <cmd> string to the argument of the slash command,
969 * assuming it is a one-character slash command. If it's not a
970 * one-character command, this is meaningless.
974 * Pointer inside the <cmd> string to the argument of the slash command
975 * assuming it's not a one-character command. If it's a one-character
976 * command, this is meaningless.
980 * String: value of the slash command, less the slash and with escape
984 /* Offset within <cmd> of first blank */
986 cmd = malloc(strlen(line)); /* unescaping better not make string grow. */
988 unescape(cmd, line + 1); /* sets cmd string */
991 * Originally, there were just single character commands. Now, we define
992 * some longer, friendly commands, but we have to keep the old single
993 * character commands too. \c used to be what \connect is now.
994 * Complicating matters is the fact that with the single-character
995 * commands, you can start the argument right after the single character,
996 * so "\copy" would mean "connect to database named 'opy'".
1000 optarg = cmd + 1 + strspn(cmd + 1, " \t");
1004 blank_loc = strcspn(cmd, " \t");
1008 optarg2 = cmd + blank_loc + strspn(cmd + blank_loc, " \t");
1012 case 'a': /* toggles to align fields on output */
1013 toggle(settings, &settings->opt.align, "field alignment");
1015 case 'C': /* define new caption */
1016 if (settings->opt.caption)
1017 free(settings->opt.caption);
1020 if (settings->opt.caption)
1021 free(settings->opt.caption);
1022 settings->opt.caption = NULL;
1024 else if (!(settings->opt.caption = strdup(optarg))) {
1030 if (strncmp(cmd, "copy ", strlen("copy ")) == 0)
1031 do_copy(optarg2, settings);
1032 else if (strncmp(cmd, "connect ", strlen("connect ")) == 0)
1033 do_connect(optarg2, settings);
1035 do_connect(optarg, settings);
1038 case 'd': /* \d describe tables or columns in a table */
1040 tableList(settings, 0);
1043 if (strcmp(optarg, "*") == 0) {
1044 tableList(settings, 0);
1045 tableList(settings, 1);
1047 tableDesc(settings, optarg);
1050 case 'e': /* edit */
1052 do_edit(optarg, query, &status);
1058 static char *lastfile;
1059 struct stat st, st2;
1063 lastfile = malloc(strlen(optarg + 1));
1068 strcpy(lastfile, optarg);
1069 } else if (!lastfile) {
1070 fprintf(stderr, "\\r must be followed by a file name initially\n");
1073 stat(lastfile, &st);
1075 if ((stat(lastfile, &st2) == -1) || ((fd = fopen(lastfile, "r")) == NULL)) {
1079 if (st2.st_mtime == st.st_mtime) {
1080 if (!settings->quiet)
1081 fprintf(stderr, "warning: %s not modified. query not executed\n", lastfile);
1085 MainLoop(settings, fd);
1091 char *fs = DEFAULT_FIELD_SEP;
1094 if (settings->opt.fieldSep)
1095 free(settings->opt.fieldSep);
1096 if (!(settings->opt.fieldSep = strdup(fs))) {
1100 if (!settings->quiet)
1101 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1104 case 'g': /* \g means send query */
1106 settings->gfname = NULL;
1107 else if (!(settings->gfname = strdup(optarg))) {
1113 case 'h': /* help */
1118 case 'i': /* \i is include file */
1123 fprintf(stderr, "\\i must be followed by a file name\n");
1126 if ((fd = fopen(optarg, "r")) == NULL) {
1127 fprintf(stderr, "file named %s could not be opened\n", optarg);
1130 MainLoop(settings, fd);
1134 case 'l': /* \l is list database */
1135 listAllDbs(settings);
1138 if (toggle(settings, &settings->opt.html3, "HTML3.0 tabular output"))
1139 settings->opt.standard = 0;
1142 setFout(settings, optarg);
1146 fputs(query, stdout);
1147 fputc('\n', stdout);
1150 case 'q': /* \q is quit */
1153 case 'r': /* reset(clear) the buffer */
1155 if (!settings->quiet)
1156 fprintf(stderr, "buffer reset(cleared)\n");
1158 case 's': /* \s is save history to a file */
1160 optarg = "/dev/tty";
1161 if (write_history(optarg) != 0)
1162 fprintf(stderr, "cannot write history to %s\n", optarg);
1164 case 'm': /* monitor like type-setting */
1165 if (toggle(settings, &settings->opt.standard, "standard SQL separaters and padding")) {
1166 settings->opt.html3 = settings->opt.expanded = 0;
1167 settings->opt.align = settings->opt.header = 1;
1168 if (settings->opt.fieldSep)
1169 free(settings->opt.fieldSep);
1170 settings->opt.fieldSep = strdup("|");
1171 if (!settings->quiet)
1172 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1174 if (settings->opt.fieldSep)
1175 free(settings->opt.fieldSep);
1176 settings->opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
1177 if (!settings->quiet)
1178 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1181 case 't': /* toggle headers */
1182 toggle(settings, &settings->opt.header, "output headings and row count");
1184 case 'T': /* define html <table ...> option */
1185 if (settings->opt.tableOpt)
1186 free(settings->opt.tableOpt);
1188 settings->opt.tableOpt = NULL;
1189 else if (!(settings->opt.tableOpt = strdup(optarg))) {
1195 toggle(settings, &settings->opt.expanded, "expanded table representation");
1201 case '?': /* \? is help */
1202 slashUsage(settings);
1210 * MainLoop: main processing loop for reading lines of input and sending them
1213 * this loop is re-entrant. May be called by \i command which reads input from
1216 * db_ptr must be initialized and set
1220 MainLoop(PsqlSettings * settings, FILE * source)
1222 char *line; /* line of input */
1223 int len; /* length of the line */
1224 char query[MAX_QUERY_BUFFER]; /* multi-line query storage */
1225 int successResult = 1;
1226 int slashCmdStatus = 0;
1228 * slashCmdStatus can be: 0 - send currently constructed query to backend
1229 * (i.e. we got a \g) 1 - skip processing of this line, continue building
1230 * up query 2 - terminate processing of this query entirely 3 - new query
1234 bool querySent = false;
1236 READ_ROUTINE GetNextLine;
1238 /* We've reached the end of our command input. */
1241 bool was_bslash; /* backslash */
1246 interactive = ((source == stdin) && !settings->notty);
1248 if (settings->prompt)
1249 free(settings->prompt);
1251 malloc(strlen(PQdb(settings->db)) + strlen(PROMPT) + 1);
1252 if (settings->quiet)
1253 settings->prompt[0] = '\0';
1255 sprintf(settings->prompt, "%s%s", PQdb(settings->db), PROMPT);
1256 if (settings->useReadline) {
1258 GetNextLine = gets_readline;
1260 GetNextLine = gets_noreadline;
1262 GetNextLine = gets_fromFile;
1267 slashCmdStatus = -1; /* set default */
1269 /* main loop for getting queries and executing them */
1271 if (slashCmdStatus == 3) {
1273 line = strdup(query);
1276 if (interactive && !settings->quiet) {
1278 settings->prompt[strlen(settings->prompt)-3] = '\'';
1279 else if (query[0] != '\0' && !querySent)
1280 settings->prompt[strlen(settings->prompt)-3] = '-';
1282 settings->prompt[strlen(settings->prompt)-3] = '=';
1284 line = GetNextLine(settings->prompt, source);
1285 if (interactive && settings->useReadline && line != NULL)
1286 add_history(line); /* save non-empty lines in history */
1291 if (line == NULL) { /* No more input. Time to quit */
1292 if (!settings->quiet)
1293 printf("EOF\n"); /* Goes on prompt line */
1296 /* remove whitespaces on the right, incl. \n's */
1297 line = rightTrim(line);
1299 if (!interactive && !settings->singleStep && !settings->quiet)
1300 fprintf(stderr, "%s\n", line);
1302 if (line[0] == '\0') {
1309 if (settings->singleLineMode) {
1310 SendQuery(&success, settings, line, false, false, 0);
1311 successResult &= success;
1318 for (i = 0; i < len; i++) {
1319 if (!in_quote && line[i] == '\\') {
1320 char hold_char = line[i];
1323 if (query_start[0] != '\0') {
1324 if (query[0] != '\0') {
1325 strcat(query, "\n");
1326 strcat(query, query_start);
1328 strcpy(query, query_start);
1330 line[i] = hold_char;
1331 query_start = line + i;
1332 break; /* handle command */
1334 if (querySent && !isspace(line[i])) {
1338 if (!in_quote && was_dash && line[i] == '-') {
1339 /* print comment at top of query */
1340 if (settings->singleStep)
1341 fprintf(stdout, "%s\n", line + i - 1);
1342 line[i - 1] = '\0'; /* remove comment */
1347 if (!in_quote && !paren_level &&
1349 char hold_char = line[i + 1];
1352 if (query_start[0] != '\0') {
1353 if (query[0] != '\0') {
1354 strcat(query, "\n");
1355 strcat(query, query_start);
1357 strcpy(query, query_start);
1359 SendQuery(&success, settings, query, false, false, 0);
1360 successResult &= success;
1361 line[i + 1] = hold_char;
1362 query_start = line + i + 1;
1367 else if (line[i] == '\\')
1369 else if (line[i] == '\'')
1371 else if (!in_quote && line[i] == '(')
1373 else if (!in_quote && paren_level && line[i] == ')')
1375 else if (!in_quote && line[i] == '-')
1380 slashCmdStatus = -1;
1381 /* slash commands have to be on their own line */
1382 if (!in_quote && query_start[0] == '\\') {
1383 slashCmdStatus = HandleSlashCmds(settings,
1386 if (slashCmdStatus == 1) {
1387 if (query[0] == '\0')
1392 if (slashCmdStatus == 2) {
1396 } else if (strlen(query) + strlen(query_start) > MAX_QUERY_BUFFER) {
1397 fprintf(stderr, "query buffer max length of %d exceeded\n",
1399 fprintf(stderr, "query line ignored\n");
1401 if (query_start[0] != '\0') {
1403 if (query[0] != '\0') {
1404 strcat(query, "\n");
1405 strcat(query, query_start);
1407 strcpy(query, query_start);
1411 if (slashCmdStatus == 0) {
1412 SendQuery(&success, settings, query, false, false, 0);
1413 successResult &= success;
1416 free(line); /* free storage malloc'd by GetNextLine */
1419 return successResult;
1423 main(int argc, char **argv)
1425 extern char *optarg;
1428 char *dbname = NULL;
1431 char *qfilename = NULL;
1432 char errbuf[ERROR_MSG_LENGTH];
1434 PsqlSettings settings;
1436 char *singleQuery = NULL;
1438 bool listDatabases = 0;
1439 int successResult = 1;
1440 bool singleSlashCmd = 0;
1443 memset(&settings, 0, sizeof settings);
1444 settings.opt.align = 1;
1445 settings.opt.header = 1;
1446 settings.queryFout = stdout;
1447 settings.opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
1448 settings.opt.pager = 1;
1449 if (!isatty(0) || !isatty(1))
1450 settings.quiet = settings.notty = 1;
1453 settings.useReadline = 1;
1456 while ((c = getopt(argc, argv, "Aa:c:d:ef:F:lh:Hnso:p:qStT:x")) != EOF) {
1459 settings.opt.align = 0;
1462 fe_setauthsvc(optarg, errbuf);
1465 singleQuery = optarg;
1466 if (singleQuery[0] == '\\') {
1474 settings.echoQuery = 1;
1480 settings.opt.fieldSep = optarg;
1489 settings.opt.html3 = 1;
1492 settings.useReadline = 0;
1495 setFout(&settings, optarg);
1504 settings.singleStep = 1;
1507 settings.singleLineMode = 1;
1510 settings.opt.header = 0;
1513 settings.opt.tableOpt = optarg;
1516 settings.opt.expanded = 1;
1523 /* if we still have an argument, use it as the database name */
1524 if (argc - optind == 1)
1525 dbname = argv[optind];
1528 dbname = "template1";
1530 settings.db = PQsetdb(host, port, NULL, NULL, dbname);
1531 dbname = PQdb(settings.db);
1533 if (PQstatus(settings.db) == CONNECTION_BAD) {
1534 fprintf(stderr, "Connection to database '%s' failed.\n", dbname);
1535 fprintf(stderr, "%s", PQerrorMessage(settings.db));
1538 if (listDatabases) {
1539 exit(listAllDbs(&settings));
1541 if (!settings.quiet && !singleQuery && !qfilename) {
1542 printf("Welcome to the POSTGRESQL interactive sql monitor:\n");
1543 printf(" Please read the file COPYRIGHT for copyright terms "
1544 "of POSTGRESQL\n\n");
1545 printf(" type \\? for help on slash commands\n");
1546 printf(" type \\q to quit\n");
1547 printf(" type \\g or terminate with semicolon to execute query\n");
1548 printf(" You are currently connected to the database: %s\n\n", dbname);
1550 if (qfilename || singleSlashCmd) {
1552 * read in a file full of queries instead of reading in queries
1557 if (singleSlashCmd) {
1558 /* Not really a query, but "Do what I mean, not what I say." */
1561 line = malloc(strlen(qfilename) + 5);
1562 sprintf(line, "\\i %s", qfilename);
1564 HandleSlashCmds(&settings, line, "");
1567 bool success; /* The query succeeded at the backend */
1568 SendQuery(&success, &settings, singleQuery, false, false, 0);
1569 successResult = success;
1571 successResult = MainLoop(&settings, stdin);
1574 PQfinish(settings.db);
1576 return !successResult;
1579 #define COPYBUFSIZ 8192
1582 handleCopyOut(PGresult * res, bool quiet, FILE * copystream)
1585 char copybuf[COPYBUFSIZ];
1588 copydone = false; /* Can't be done; haven't started. */
1591 ret = PQgetline(res->conn, copybuf, COPYBUFSIZ);
1593 if (copybuf[0] == '\\' &&
1594 copybuf[1] == '.' &&
1595 copybuf[2] == '\0') {
1596 copydone = true; /* don't print this... */
1598 fputs(copybuf, copystream);
1604 fputc('\n', copystream);
1612 PQendcopy(res->conn);
1618 handleCopyIn(PGresult * res, const bool mustprompt, FILE * copystream)
1620 bool copydone = false;
1623 char copybuf[COPYBUFSIZ];
1629 fputs("Enter info followed by a newline\n", stdout);
1630 fputs("End with a backslash and a "
1631 "period on a line by itself.\n", stdout);
1633 while (!copydone) { /* for each input line ... */
1635 fputs(">> ", stdout);
1640 while (!linedone) { /* for each buffer ... */
1642 buflen = COPYBUFSIZ;
1643 for (; buflen > 1 &&
1644 !(linedone = (c = getc(copystream)) == '\n' || c == EOF);
1649 PQputline(res->conn, "\\.");
1654 PQputline(res->conn, copybuf);
1656 if (!strcmp(copybuf, "\\.")) {
1662 PQputline(res->conn, "\n");
1664 PQendcopy(res->conn);
1670 * try to open fname and return a FILE *, if it fails, use stdout, instead
1674 setFout(PsqlSettings * ps, char *fname)
1676 if (ps->queryFout && ps->queryFout != stdout) {
1678 pclose(ps->queryFout);
1680 fclose(ps->queryFout);
1683 ps->queryFout = stdout;
1684 pqsignal(SIGPIPE, SIG_DFL);
1687 if (*fname == '|') {
1688 pqsignal(SIGPIPE, SIG_IGN);
1689 ps->queryFout = popen(fname + 1, "w");
1692 ps->queryFout = fopen(fname, "w");
1693 pqsignal(SIGPIPE, SIG_DFL);
1696 if (!ps->queryFout) {
1698 ps->queryFout = stdout;
1701 return ps->queryFout;