1 /*-------------------------------------------------------------------------
4 * an interactive front-end to postgres95
6 * Copyright (c) 1996, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/bin/psql/Attic/psql.c,v 1.30 1996/11/20 22:34:36 momjian Exp $
12 *-------------------------------------------------------------------------
18 #include <sys/types.h>
24 #include "stringutils.h"
31 /* from the GNU readline library */
36 #include <readline/readline.h>
37 #include <readline/history.h>
41 #define MAX_QUERY_BUFFER 20000
43 #define COPYBUFSIZ 8192
45 #define DEFAULT_FIELD_SEP "|"
46 #define DEFAULT_EDITOR "vi"
47 #define DEFAULT_SHELL "/bin/sh"
49 typedef struct _psqlSettings {
50 PGconn *db; /* connection to backend */
51 FILE *queryFout; /* where to send the query results */
52 PQprintOpt opt; /* options to be passed to PQprint */
53 char *prompt; /* prompt to display */
54 char *gfname; /* one-shot file output argument for \g */
55 bool notty; /* input or output is not a tty */
56 bool pipe; /* queryFout is from a popen() */
57 bool echoQuery; /* echo the query before sending it */
58 bool quiet; /* run quietly, no messages, no promt */
59 bool singleStep; /* prompt before for each query */
60 bool singleLineMode; /* query terminated by newline */
61 bool useReadline;/* use libreadline routines */
64 /* declarations for functions in this file */
65 static void usage(char *progname);
66 static void slashUsage();
67 static void handleCopyOut(PGresult * res, bool quiet, FILE * copystream);
69 handleCopyIn(PGresult * res, const bool mustprompt,
71 static int tableList(PsqlSettings * ps, bool deep_tablelist);
72 static int tableDesc(PsqlSettings * ps, char *table);
74 char *gets_noreadline(char *prompt, FILE * source);
75 char *gets_readline(char *prompt, FILE * source);
76 char *gets_fromFile(char *prompt, FILE * source);
77 int listAllDbs(PsqlSettings * settings);
79 SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
80 const bool copy_in, const bool copy_out, FILE * copystream);
82 HandleSlashCmds(PsqlSettings * settings,
85 int MainLoop(PsqlSettings * settings, FILE * source);
86 /* probably should move this into libpq */
93 FILE *setFout(PsqlSettings * ps, char *fname);
96 * usage print out usage for command line arguments
100 usage(char *progname)
102 fprintf(stderr, "Usage: %s [options] [dbname]\n", progname);
103 fprintf(stderr, "\t -a authsvc set authentication service\n");
104 fprintf(stderr, "\t -A turn off alignment when printing out attributes\n");
105 fprintf(stderr, "\t -c query run single query (slash commands too)\n");
106 fprintf(stderr, "\t -d dbName specify database name\n");
107 fprintf(stderr, "\t -e echo the query sent to the backend\n");
108 fprintf(stderr, "\t -f filename use file as a source of queries\n");
109 fprintf(stderr, "\t -F sep set the field separator (default is " ")\n");
110 fprintf(stderr, "\t -h host set database server host\n");
111 fprintf(stderr, "\t -H turn on html3.0 table output\n");
112 fprintf(stderr, "\t -l list available databases\n");
113 fprintf(stderr, "\t -n don't use readline library\n");
114 fprintf(stderr, "\t -o filename send output to filename or (|pipe)\n");
115 fprintf(stderr, "\t -p port set port number\n");
116 fprintf(stderr, "\t -q run quietly (no messages, no prompts)\n");
117 fprintf(stderr, "\t -s single step mode (prompts for each query)\n");
118 fprintf(stderr, "\t -S single line mode (i.e. query terminated by newline)\n");
119 fprintf(stderr, "\t -t turn off printing of headings and row count\n");
120 fprintf(stderr, "\t -T html set html3.0 table command options (cf. -H)\n");
121 fprintf(stderr, "\t -x turn on expanded output (field names on left)\n");
126 * slashUsage print out usage for the backslash commands
132 return f ? "on" : "off";
136 slashUsage(PsqlSettings * ps)
138 fprintf(stderr, " \\? -- help\n");
139 fprintf(stderr, " \\a -- toggle field-alignment (currenty %s)\n", on(ps->opt.align));
140 fprintf(stderr, " \\C [<captn>] -- set html3 caption (currently '%s')\n", ps->opt.caption ? ps->opt.caption : "");
141 fprintf(stderr, " \\connect <dbname> -- connect to new database (currently '%s')\n", PQdb(ps->db));
142 fprintf(stderr, " \\copy <dbname> -- copy table to/from a file\n");
143 fprintf(stderr, " \\d [<table>] -- list tables in database or columns in <table>, * for all\n");
144 fprintf(stderr, " \\e [<fname>] -- edit the current query buffer or <fname>, \\E execute too\n");
145 fprintf(stderr, " \\f [<sep>] -- change field separater (currently '%s')\n", ps->opt.fieldSep);
146 fprintf(stderr, " \\g [<fname>] [|<cmd>] -- send query to backend [and results in <fname> or pipe]\n");
147 fprintf(stderr, " \\h [<cmd>] -- help on syntax of sql commands, * for all commands\n");
148 fprintf(stderr, " \\H -- toggle html3 output (currently %s)\n", on(ps->opt.html3));
149 fprintf(stderr, " \\i <fname> -- read and execute queries from filename\n");
150 fprintf(stderr, " \\l -- list all databases\n");
151 fprintf(stderr, " \\m -- toggle monitor-like table display (currently %s)\n", on(ps->opt.standard));
152 fprintf(stderr, " \\o [<fname>] [|<cmd>] -- send all query results to stdout, <fname>, or pipe\n");
153 fprintf(stderr, " \\p -- print the current query buffer\n");
154 fprintf(stderr, " \\q -- quit\n");
155 fprintf(stderr, " \\r -- reset(clear) the query buffer\n");
156 fprintf(stderr, " \\s [<fname>] -- print history or save it in <fname>\n");
157 fprintf(stderr, " \\t -- toggle table headings and row count (currently %s)\n", on(ps->opt.header));
158 fprintf(stderr, " \\T [<html>] -- set html3.0 <table ...> options (currently '%s')\n", ps->opt.tableOpt ? ps->opt.tableOpt : "");
159 fprintf(stderr, " \\x -- toggle expanded output (currently %s)\n", on(ps->opt.expanded));
160 fprintf(stderr, " \\! [<cmd>] -- shell escape or command\n");
164 PSQLexec(PsqlSettings * ps, char *query)
166 PGresult *res = PQexec(ps->db, query);
168 fputs(PQerrorMessage(ps->db), stderr);
170 if (PQresultStatus(res) == PGRES_COMMAND_OK ||
171 PQresultStatus(res) == PGRES_TUPLES_OK)
174 fputs(PQerrorMessage(ps->db), stderr);
182 * list all the databases in the system returns 0 if all went well
188 listAllDbs(PsqlSettings * ps)
191 char *query = "select * from pg_database;";
193 if (!(results = PSQLexec(ps, query)))
196 PQprint(ps->queryFout,
205 * List The Database Tables returns 0 if all went well
209 tableList(PsqlSettings * ps, bool deep_tablelist)
220 strcat(listbuf, "SELECT usename, relname, relkind, relhasrules");
221 strcat(listbuf, " FROM pg_class, pg_user ");
222 strcat(listbuf, "WHERE ( relkind = 'r' OR relkind = 'i') ");
223 strcat(listbuf, " and relname !~ '^pg_'");
224 strcat(listbuf, " and relname !~ '^Inv[0-9]+'");
226 * the usesysid = relowner won't work on stock 1.0 dbs, need to add in
227 * the int4oideq function
229 strcat(listbuf, " and usesysid = relowner");
230 strcat(listbuf, " ORDER BY relname ");
231 if (!(res = PSQLexec(ps, listbuf)))
234 /* first, print out the attribute names */
235 nColumns = PQntuples(res);
237 if (deep_tablelist) {
238 /* describe everything here */
240 table = (char **) malloc(nColumns * sizeof(char *));
244 /* load table table */
245 for (i = 0; i < nColumns; i++) {
246 table[i] = (char *) malloc(PQgetlength(res, i, 1) * sizeof(char) + 1);
247 if (table[i] == NULL)
249 strcpy(table[i], PQgetvalue(res, i, 1));
253 for (i = 0; i < nColumns; i++) {
254 tableDesc(ps, table[i]);
258 /* Display the information */
260 printf("\nDatabase = %s\n", PQdb(ps->db));
261 printf(" +------------------+----------------------------------+----------+\n");
262 printf(" | Owner | Relation | Type |\n");
263 printf(" +------------------+----------------------------------+----------+\n");
265 /* next, print out the instances */
266 for (i = 0; i < PQntuples(res); i++) {
267 printf(" | %-16.16s", PQgetvalue(res, i, 0));
268 printf(" | %-32.32s | ", PQgetvalue(res, i, 1));
269 rk = PQgetvalue(res, i, 2);
270 rr = PQgetvalue(res, i, 3);
271 if (strcmp(rk, "r") == 0)
272 printf("%-8.8s |", (rr[0] == 't') ? "view?" : "table");
274 printf("%-8.8s |", "index");
277 printf(" +------------------+----------------------------------+----------+\n");
283 fprintf(stderr, "Couldn't find any tables!\n");
291 * Describe the columns in a database table. returns 0 if all went well
296 tableDesc(PsqlSettings * ps, char *table)
306 /* Build the query */
309 strcat(descbuf, "SELECT a.attnum, a.attname, t.typname, a.attlen");
310 strcat(descbuf, " FROM pg_class c, pg_attribute a, pg_type t ");
311 strcat(descbuf, " WHERE c.relname = '");
312 strcat(descbuf, table);
313 strcat(descbuf, "'");
314 strcat(descbuf, " and a.attnum > 0 ");
315 strcat(descbuf, " and a.attrelid = c.oid ");
316 strcat(descbuf, " and a.atttypid = t.oid ");
317 strcat(descbuf, " ORDER BY attnum ");
318 if (!(res = PSQLexec(ps, descbuf)))
320 /* first, print out the attribute names */
321 nColumns = PQntuples(res);
324 * * Display the information
327 printf("\nTable = %s\n", table);
328 printf("+----------------------------------+----------------------------------+-------+\n");
329 printf("| Field | Type | Length|\n");
330 printf("+----------------------------------+----------------------------------+-------+\n");
332 /* next, print out the instances */
333 for (i = 0; i < PQntuples(res); i++) {
334 printf("| %-32.32s | ", PQgetvalue(res, i, 1));
335 rtype = PQgetvalue(res, i, 2);
336 rsize = atoi(PQgetvalue(res, i, 3));
337 if (strcmp(rtype, "text") == 0) {
338 printf("%-32.32s |", rtype);
339 printf("%6s |", "var");
340 } else if (strcmp(rtype, "bpchar") == 0) {
341 printf("%-32.32s |", "(bp)char");
342 printf("%6i |", rsize > 0 ? rsize - 4 : 0);
343 } else if (strcmp(rtype, "varchar") == 0) {
344 printf("%-32.32s |", rtype);
345 printf("%6i |", rsize > 0 ? rsize - 4 : 0);
347 /* array types start with an underscore */
349 printf("%-32.32s |", rtype);
352 newname = malloc(strlen(rtype) + 2);
353 strcpy(newname, rtype + 1);
354 strcat(newname, "[]");
355 printf("%-32.32s |", newname);
359 printf("%6i |", rsize);
361 printf("%6s |", "var");
365 printf("+----------------------------------+----------------------------------+-------+\n");
371 fprintf(stderr, "Couldn't find table %s!\n", table);
376 typedef char *(*READ_ROUTINE) (char *prompt, FILE * source);
379 * gets_noreadline prompt source gets a line of input without calling
380 * readline, the source is ignored
383 gets_noreadline(char *prompt, FILE * source)
385 fputs(prompt, stdout);
387 return (gets_fromFile(prompt, stdin));
391 * gets_readline prompt source the routine to get input from GNU readline(),
392 * the source is ignored the prompt argument is used as the prompting string
395 gets_readline(char *prompt, FILE * source)
397 return (readline(prompt));
401 * gets_fromFile prompt source
403 * the routine to read from a file, the prompt argument is ignored the source
404 * argument is a FILE *
407 gets_fromFile(char *prompt, FILE * source)
412 line = malloc(MAX_QUERY_BUFFER + 1);
414 /* read up to MAX_QUERY_BUFFER characters */
415 if (fgets(line, MAX_QUERY_BUFFER, source) == NULL)
418 line[MAX_QUERY_BUFFER - 1] = '\0';
420 if (len == MAX_QUERY_BUFFER) {
421 fprintf(stderr, "line read exceeds maximum length. Truncating at %d\n",
428 * SendQuery: send the query string to the backend return *success_p = 1 if
429 * the query executed successfully returns *success_p = 0 otherwise
432 SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
433 const bool copy_in, const bool copy_out, FILE * copystream)
439 if (settings->singleStep)
440 fprintf(stdout, "\n**************************************"
441 "*****************************************\n");
443 if (settings->echoQuery || settings->singleStep) {
444 fprintf(stderr, "QUERY: %s\n", query);
447 if (settings->singleStep) {
448 fprintf(stdout, "\n**************************************"
449 "*****************************************\n");
451 printf("\npress return to continue ..\n");
452 gets_fromFile("", stdin);
454 results = PQexec(settings->db, query);
455 if (results == NULL) {
456 fprintf(stderr, "%s", PQerrorMessage(settings->db));
459 switch (PQresultStatus(results)) {
460 case PGRES_TUPLES_OK:
461 if (settings->gfname) {
462 PsqlSettings ps = *settings;
464 ps.queryFout = stdout;
465 fp = setFout(&ps, settings->gfname);
466 if (!fp || fp == stdout) {
478 free(settings->gfname);
479 settings->gfname = NULL;
483 PQprint(settings->queryFout,
486 fflush(settings->queryFout);
490 case PGRES_EMPTY_QUERY:
493 case PGRES_COMMAND_OK:
495 if (!settings->quiet)
496 fprintf(stdout, "%s\n", PQcmdStatus(results));
501 handleCopyOut(results, settings->quiet, copystream);
503 if (!settings->quiet)
504 fprintf(stdout, "Copy command returns...\n");
506 handleCopyOut(results, settings->quiet, stdout);
512 handleCopyIn(results, false, copystream);
516 * eat extra newline still in input buffer
520 if ((c = getc(stdin)) != '\n' && c != EOF)
521 (void) ungetc(c, stdin);
522 handleCopyIn(results, !settings->quiet, stdin);
525 case PGRES_NONFATAL_ERROR:
526 case PGRES_FATAL_ERROR:
527 case PGRES_BAD_RESPONSE:
529 fprintf(stderr, "%s", PQerrorMessage(settings->db));
533 if (PQstatus(settings->db) == CONNECTION_BAD) {
535 "We have lost the connection to the backend, so "
536 "further processing is impossible. "
538 exit(2); /* we are out'ta here */
540 /* check for asynchronous returns */
541 notify = PQnotifies(settings->db);
544 "ASYNC NOTIFY of '%s' from backend pid '%d' received\n",
545 notify->relname, notify->be_pid);
554 editFile(char *fname)
558 editorName = getenv("EDITOR");
560 editorName = DEFAULT_EDITOR;
561 sys = malloc(strlen(editorName) + strlen(fname) + 32 + 1);
566 sprintf(sys, "exec '%s' '%s'", editorName, fname);
572 toggle(PsqlSettings * settings, bool * sw, char *msg)
575 if (!settings->quiet)
576 fprintf(stderr, "turned %s %s\n", on(*sw), msg);
583 unescape(char *dest, const char *source)
585 /*-----------------------------------------------------------------------------
586 Return as the string <dest> the value of string <source> with escape
587 sequences turned into the bytes they represent.
588 -----------------------------------------------------------------------------*/
590 bool esc; /* Last character we saw was the escape
593 esc = false; /* Haven't seen escape character yet */
594 for (p = (char *) source; *p; p++) {
595 char c; /* Our output character */
618 } else if (*p == '\\') {
620 c = ' '; /* meaningless, but compiler doesn't know
629 *dest = '\0'; /* Terminating null character */
635 parse_slash_copy(const char *args, char *table, const int table_len,
636 char *file, const int file_len,
637 bool * from_p, bool * error_p)
642 * A copy of the \copy command arguments, except that we modify it as we
643 * parse to suit our parsing needs.
645 char *table_tok, *fromto_tok;
647 strncpy(work_args, args, sizeof(work_args));
648 work_args[sizeof(work_args) - 1] = '\0';
650 *error_p = false; /* initial assumption */
652 table_tok = strtok(work_args, " ");
653 if (table_tok == NULL) {
654 fprintf(stderr, "\\copy needs arguments.\n");
657 strncpy(table, table_tok, table_len);
658 file[table_len - 1] = '\0';
660 fromto_tok = strtok(NULL, " ");
661 if (fromto_tok == NULL) {
662 fprintf(stderr, "'FROM' or 'TO' must follow table name.\n");
665 if (strcasecmp(fromto_tok, "from") == 0)
667 else if (strcasecmp(fromto_tok, "to") == 0)
671 "Unrecognized token found where "
672 "'FROM' or 'TO' expected: '%s'.\n",
679 file_tok = strtok(NULL, " ");
680 if (file_tok == NULL) {
681 fprintf(stderr, "A file pathname must follow '%s'.\n",
685 strncpy(file, file_tok, file_len);
686 file[file_len - 1] = '\0';
687 if (strtok(NULL, " ") != NULL) {
689 "You have extra tokens after the filename.\n");
701 do_copy(const char *args, PsqlSettings * settings)
703 /*---------------------------------------------------------------------------
704 Execute a \copy command (frontend copy). We have to open a file, then
705 submit a COPY query to the backend and either feed it data from the
706 file or route its response into the file.
708 We do a text copy with default (tab) column delimiters. Some day, we
709 should do all the things a backend copy can do.
711 ----------------------------------------------------------------------------*/
713 /* The COPY command we send to the back end */
715 /* The direction of the copy is from a file to a table. */
716 char file[MAXPATHLEN + 1];
717 /* The pathname of the file from/to which we copy */
718 char table[NAMEDATALEN + 1];
719 /* The name of the table from/to which we copy */
721 /* The \c command has invalid syntax */
724 parse_slash_copy(args, table, sizeof(table), file, sizeof(file),
725 &from, &syntax_error);
728 strcpy(query, "COPY ");
729 strcat(query, table);
732 strcat(query, " FROM stdin");
734 strcat(query, " TO stdout");
737 copystream = fopen(file, "r");
739 copystream = fopen(file, "w");
743 "Unable to open file %s which to copy, errno = %s (%d).",
744 from ? "from" : "to", strerror(errno), errno);
746 bool success; /* The query succeeded at the backend */
748 SendQuery(&success, settings, query, from, !from, copystream);
750 if (!settings->quiet) {
752 fprintf(stdout, "Successfully copied.\n");
754 fprintf(stdout, "Copy failed.\n");
762 do_connect(const char *new_dbname, PsqlSettings * settings)
765 char *dbname = PQdb(settings->db);
767 fprintf(stderr, "\\connect must be followed by a database name\n");
769 PGconn *olddb = settings->db;
771 printf("closing connection to database: %s\n", dbname);
772 settings->db = PQsetdb(PQhost(olddb), PQport(olddb),
773 NULL, NULL, new_dbname);
774 printf("connecting to new database: %s\n", new_dbname);
775 if (PQstatus(settings->db) == CONNECTION_BAD) {
776 fprintf(stderr, "%s\n", PQerrorMessage(settings->db));
777 printf("reconnecting to %s\n", dbname);
778 settings->db = PQsetdb(PQhost(olddb), PQport(olddb),
780 if (PQstatus(settings->db) == CONNECTION_BAD) {
782 "could not reconnect to %s. exiting\n", dbname);
787 free(settings->prompt);
788 settings->prompt = malloc(strlen(PQdb(settings->db)) + 10);
789 sprintf(settings->prompt, "%s=> ", PQdb(settings->db));
796 do_edit(const char *filename_arg, char *query, int *status_p)
803 const int ql = strlen(query);
807 fname = (char *) filename_arg;
810 sprintf(tmp, "/tmp/psql.%ld.%ld", (long) geteuid(), (long) getpid());
814 if ((fd = open(tmp, O_EXCL | O_CREAT | O_WRONLY, 0600)) == -1) {
818 if (query[ql - 1] != '\n')
820 if (write(fd, query, ql) != ql) {
837 if ((fd = open(fname, O_RDONLY)) == -1) {
843 if ((cc = read(fd, query, MAX_QUERY_BUFFER)) == -1) {
864 do_help(const char *topic)
868 char left_center_right; /* Which column we're
870 int i; /* Index into QL_HELP[] */
872 printf("type \\h <cmd> where <cmd> is one of the following:\n");
874 left_center_right = 'L';/* Start with left column */
876 while (QL_HELP[i].cmd != NULL) {
877 switch (left_center_right) {
879 printf(" %-25s", QL_HELP[i].cmd);
880 left_center_right = 'C';
883 printf("%-25s", QL_HELP[i].cmd);
884 left_center_right = 'R';
887 printf("%-25s\n", QL_HELP[i].cmd);
888 left_center_right = 'L';
893 if (left_center_right != 'L')
895 printf("type \\h * for a complete description of all commands\n");
897 int i; /* Index into QL_HELP[] */
898 bool help_found; /* We found the help he asked for */
900 help_found = false; /* Haven't found it yet */
901 for (i = 0; QL_HELP[i].cmd; i++) {
902 if (strcmp(QL_HELP[i].cmd, topic) == 0 ||
903 strcmp(topic, "*") == 0) {
905 printf("Command: %s\n", QL_HELP[i].cmd);
906 printf("Description: %s\n", QL_HELP[i].help);
908 printf("%s\n", QL_HELP[i].syntax);
913 printf("command not found, "
914 "try \\h with no arguments to see available help\n");
921 do_shell(const char *command)
928 shellName = getenv("SHELL");
929 if (shellName == NULL)
930 shellName = DEFAULT_SHELL;
931 sys = malloc(strlen(shellName) + 16);
936 sprintf(sys, "exec %s", shellName);
948 * Handles all the different commands that start with \ db_ptr is a pointer to
949 * the TgDb* structure line is the current input line prompt_ptr is a pointer
950 * to the prompt string, a pointer is used because the prompt can be used
951 * with a connection to a new database returns a status: 0 - send currently
952 * constructed query to backend (i.e. we got a \g) 1 - skip processing of
953 * this line, continue building up query 2 - terminate processing of this
954 * query entirely, 3 - new query supplied by edit
957 HandleSlashCmds(PsqlSettings * settings,
964 * Pointer inside the <cmd> string to the argument of the slash command,
965 * assuming it is a one-character slash command. If it's not a
966 * one-character command, this is meaningless.
970 * Pointer inside the <cmd> string to the argument of the slash command
971 * assuming it's not a one-character command. If it's a one-character
972 * command, this is meaningless.
976 * String: value of the slash command, less the slash and with escape
980 /* Offset within <cmd> of first blank */
982 cmd = malloc(strlen(line)); /* unescaping better not make string grow. */
984 unescape(cmd, line + 1); /* sets cmd string */
987 * Originally, there were just single character commands. Now, we define
988 * some longer, friendly commands, but we have to keep the old single
989 * character commands too. \c used to be what \connect is now.
990 * Complicating matters is the fact that with the single-character
991 * commands, you can start the argument right after the single character,
992 * so "\copy" would mean "connect to database named 'opy'".
996 optarg = cmd + 1 + strspn(cmd + 1, " \t");
1000 blank_loc = strcspn(cmd, " \t");
1004 optarg2 = cmd + blank_loc + strspn(cmd + blank_loc, " \t");
1008 case 'a': /* toggles to align fields on output */
1009 toggle(settings, &settings->opt.align, "field alignment");
1011 case 'C': /* define new caption */
1012 if (settings->opt.caption)
1013 free(settings->opt.caption);
1016 if (settings->opt.caption)
1017 free(settings->opt.caption);
1018 settings->opt.caption = NULL;
1020 else if (!(settings->opt.caption = strdup(optarg))) {
1026 if (strncmp(cmd, "copy ", strlen("copy ")) == 0)
1027 do_copy(optarg2, settings);
1028 else if (strncmp(cmd, "connect ", strlen("connect ")) == 0)
1029 do_connect(optarg2, settings);
1031 do_connect(optarg, settings);
1034 case 'd': /* \d describe tables or columns in a table */
1036 tableList(settings, 0);
1039 if (strcmp(optarg, "*") == 0) {
1040 tableList(settings, 0);
1041 tableList(settings, 1);
1043 tableDesc(settings, optarg);
1046 case 'e': /* edit */
1048 do_edit(optarg, query, &status);
1054 static char *lastfile;
1055 struct stat st, st2;
1059 lastfile = malloc(strlen(optarg + 1));
1064 strcpy(lastfile, optarg);
1065 } else if (!lastfile) {
1066 fprintf(stderr, "\\r must be followed by a file name initially\n");
1069 stat(lastfile, &st);
1071 if ((stat(lastfile, &st2) == -1) || ((fd = fopen(lastfile, "r")) == NULL)) {
1075 if (st2.st_mtime == st.st_mtime) {
1076 if (!settings->quiet)
1077 fprintf(stderr, "warning: %s not modified. query not executed\n", lastfile);
1081 MainLoop(settings, fd);
1087 char *fs = DEFAULT_FIELD_SEP;
1090 if (settings->opt.fieldSep);
1091 free(settings->opt.fieldSep);
1092 if (!(settings->opt.fieldSep = strdup(fs))) {
1096 if (!settings->quiet)
1097 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1100 case 'g': /* \g means send query */
1101 settings->gfname = strdup(optarg);
1104 case 'h': /* help */
1109 case 'i': /* \i is include file */
1114 fprintf(stderr, "\\i must be followed by a file name\n");
1117 if ((fd = fopen(optarg, "r")) == NULL) {
1118 fprintf(stderr, "file named %s could not be opened\n", optarg);
1121 MainLoop(settings, fd);
1125 case 'l': /* \l is list database */
1126 listAllDbs(settings);
1129 if (toggle(settings, &settings->opt.html3, "HTML3.0 tabular output"))
1130 settings->opt.standard = 0;
1133 setFout(settings, optarg);
1137 fputs(query, stdout);
1138 fputc('\n', stdout);
1141 case 'q': /* \q is quit */
1144 case 'r': /* reset(clear) the buffer */
1146 if (!settings->quiet)
1147 fprintf(stderr, "buffer reset(cleared)\n");
1149 case 's': /* \s is save history to a file */
1151 optarg = "/dev/tty";
1152 if (write_history(optarg) != 0)
1153 fprintf(stderr, "cannot write history to %s\n", optarg);
1155 case 'm': /* monitor like type-setting */
1156 if (toggle(settings, &settings->opt.standard, "standard SQL separaters and padding")) {
1157 settings->opt.html3 = settings->opt.expanded = 0;
1158 settings->opt.align = settings->opt.header = 1;
1159 if (settings->opt.fieldSep)
1160 free(settings->opt.fieldSep);
1161 settings->opt.fieldSep = strdup("|");
1162 if (!settings->quiet)
1163 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1165 if (settings->opt.fieldSep)
1166 free(settings->opt.fieldSep);
1167 settings->opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
1168 if (!settings->quiet)
1169 fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
1172 case 't': /* toggle headers */
1173 toggle(settings, &settings->opt.header, "output headings and row count");
1175 case 'T': /* define html <table ...> option */
1176 if (settings->opt.tableOpt)
1177 free(settings->opt.tableOpt);
1179 settings->opt.tableOpt = NULL;
1180 else if (!(settings->opt.tableOpt = strdup(optarg))) {
1186 toggle(settings, &settings->opt.expanded, "expanded table representation");
1192 case '?': /* \? is help */
1193 slashUsage(settings);
1201 * MainLoop: main processing loop for reading lines of input and sending them
1204 * this loop is re-entrant. May be called by \i command which reads input from
1207 * db_ptr must be initialized and set
1211 MainLoop(PsqlSettings * settings, FILE * source)
1213 char *line; /* line of input */
1214 int len; /* length of the line */
1215 char query[MAX_QUERY_BUFFER]; /* multi-line query storage */
1216 int successResult = 1;
1217 int slashCmdStatus = 0;
1219 * slashCmdStatus can be: 0 - send currently constructed query to backend
1220 * (i.e. we got a \g) 1 - skip processing of this line, continue building
1221 * up query 2 - terminate processing of this query entirely 3 - new query
1225 bool querySent = false;
1227 READ_ROUTINE GetNextLine;
1229 /* We've reached the end of our command input. */
1232 bool was_bslash; /* backslash */
1237 interactive = ((source == stdin) && !settings->notty);
1238 #define PROMPT "=> "
1240 if (settings->prompt)
1241 free(settings->prompt);
1243 malloc(strlen(PQdb(settings->db)) + strlen(PROMPT) + 1);
1244 if (settings->quiet)
1245 settings->prompt[0] = '\0';
1247 sprintf(settings->prompt, "%s%s", PQdb(settings->db), PROMPT);
1248 if (settings->useReadline) {
1250 GetNextLine = gets_readline;
1252 GetNextLine = gets_noreadline;
1254 GetNextLine = gets_fromFile;
1259 slashCmdStatus = -1; /* set default */
1261 /* main loop for getting queries and executing them */
1263 if (slashCmdStatus == 3) {
1264 line = strdup(query);
1267 line = GetNextLine(settings->prompt, source);
1268 if (interactive && settings->useReadline && line != NULL)
1269 add_history(line); /* save non-empty lines in history */
1274 if (line == NULL) { /* No more input. Time to quit */
1275 printf("EOF\n"); /* Goes on prompt line */
1278 if (!interactive && !settings->singleStep && !settings->quiet)
1279 fprintf(stderr, "%s\n", line);
1281 /* remove whitespaces on the right, incl. \n's */
1282 line = rightTrim(line);
1284 if (line[0] == '\0') {
1291 if (settings->singleLineMode) {
1292 SendQuery(&success, settings, line, false, false, 0);
1293 successResult &= success;
1300 for (i = 0; i < len; i++) {
1301 if (!in_quote && line[i] == '\\') {
1302 char hold_char = line[i];
1305 if (query_start[0] != '\0') {
1306 if (query[0] != '\0') {
1307 strcat(query, "\n");
1308 strcat(query, query_start);
1310 strcpy(query, query_start);
1312 line[i] = hold_char;
1313 query_start = line + i;
1314 break; /* handle command */
1316 if (querySent && !isspace(line[i])) {
1320 if (!in_quote && was_dash && line[i] == '-') {
1321 /* print comment at top of query */
1322 if (settings->singleStep)
1323 fprintf(stdout, "%s\n", line + i - 1);
1324 line[i - 1] = '\0'; /* remove comment */
1329 if (!in_quote && !paren_level &&
1331 char hold_char = line[i + 1];
1334 if (query_start[0] != '\0') {
1335 if (query[0] != '\0') {
1336 strcat(query, "\n");
1337 strcat(query, query_start);
1339 strcpy(query, query_start);
1341 SendQuery(&success, settings, query, false, false, 0);
1342 successResult &= success;
1343 line[i + 1] = hold_char;
1344 query_start = line + i + 1;
1349 else if (line[i] == '\\')
1351 else if (line[i] == '\'')
1353 else if (!in_quote && line[i] == '(')
1355 else if (!in_quote && paren_level && line[i] == ')')
1357 else if (!in_quote && line[i] == '-')
1362 slashCmdStatus = -1;
1363 /* slash commands have to be on their own line */
1364 if (!in_quote && query_start[0] == '\\') {
1365 slashCmdStatus = HandleSlashCmds(settings,
1368 if (slashCmdStatus == 1) {
1372 if (slashCmdStatus == 2) {
1376 } else if (strlen(query) + strlen(query_start) > MAX_QUERY_BUFFER) {
1377 fprintf(stderr, "query buffer max length of %d exceeded\n",
1379 fprintf(stderr, "query line ignored\n");
1381 if (query_start[0] != '\0') {
1383 if (query[0] != '\0') {
1384 strcat(query, "\n");
1385 strcat(query, query_start);
1387 strcpy(query, query_start);
1391 if (slashCmdStatus == 0) {
1392 SendQuery(&success, settings, query, false, false, 0);
1393 successResult &= success;
1396 free(line); /* free storage malloc'd by GetNextLine */
1399 return successResult;
1403 main(int argc, char **argv)
1405 extern char *optarg;
1408 char *dbname = NULL;
1411 char *qfilename = NULL;
1412 char errbuf[ERROR_MSG_LENGTH];
1414 PsqlSettings settings;
1416 char *singleQuery = NULL;
1418 bool listDatabases = 0;
1419 int successResult = 1;
1420 bool singleSlashCmd = 0;
1423 memset(&settings, 0, sizeof settings);
1424 settings.opt.align = 1;
1425 settings.opt.header = 1;
1426 settings.queryFout = stdout;
1427 settings.opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
1428 settings.opt.pager = 1;
1429 if (!isatty(0) || !isatty(1))
1430 settings.quiet = settings.notty = 1;
1433 settings.useReadline = 1;
1436 while ((c = getopt(argc, argv, "Aa:c:d:ef:F:lh:Hnso:p:qStT:x")) != EOF) {
1439 settings.opt.align = 0;
1442 fe_setauthsvc(optarg, errbuf);
1445 singleQuery = optarg;
1446 if (singleQuery[0] == '\\') {
1454 settings.echoQuery = 1;
1460 settings.opt.fieldSep = optarg;
1469 settings.opt.html3 = 1;
1472 settings.useReadline = 0;
1475 setFout(&settings, optarg);
1484 settings.singleStep = 1;
1487 settings.singleLineMode = 1;
1490 settings.opt.header = 0;
1493 settings.opt.tableOpt = optarg;
1496 settings.opt.expanded = 1;
1503 /* if we still have an argument, use it as the database name */
1504 if (argc - optind == 1)
1505 dbname = argv[optind];
1508 dbname = "template1";
1510 settings.db = PQsetdb(host, port, NULL, NULL, dbname);
1511 dbname = PQdb(settings.db);
1513 if (PQstatus(settings.db) == CONNECTION_BAD) {
1514 fprintf(stderr, "Connection to database '%s' failed.\n", dbname);
1515 fprintf(stderr, "%s", PQerrorMessage(settings.db));
1518 if (listDatabases) {
1519 exit(listAllDbs(&settings));
1521 if (!settings.quiet && !singleQuery && !qfilename) {
1522 printf("Welcome to the POSTGRES95 interactive sql monitor:\n");
1523 printf(" Please read the file COPYRIGHT for copyright terms "
1524 "of POSTGRES95\n\n");
1525 printf(" type \\? for help on slash commands\n");
1526 printf(" type \\q to quit\n");
1527 printf(" type \\g or terminate with semicolon to execute query\n");
1528 printf(" You are currently connected to the database: %s\n\n", dbname);
1530 if (qfilename || singleSlashCmd) {
1532 * read in a file full of queries instead of reading in queries
1537 if (singleSlashCmd) {
1538 /* Not really a query, but "Do what I mean, not what I say." */
1541 line = malloc(strlen(qfilename) + 5);
1542 sprintf(line, "\\i %s", qfilename);
1544 HandleSlashCmds(&settings, line, "");
1547 bool success; /* The query succeeded at the backend */
1548 SendQuery(&success, &settings, singleQuery, false, false, 0);
1549 successResult = success;
1551 successResult = MainLoop(&settings, stdin);
1554 PQfinish(settings.db);
1556 return !successResult;
1559 #define COPYBUFSIZ 8192
1562 handleCopyOut(PGresult * res, bool quiet, FILE * copystream)
1565 char copybuf[COPYBUFSIZ];
1568 copydone = false; /* Can't be done; haven't started. */
1571 ret = PQgetline(res->conn, copybuf, COPYBUFSIZ);
1573 if (copybuf[0] == '\\' &&
1574 copybuf[1] == '.' &&
1575 copybuf[2] == '\0') {
1576 copydone = true; /* don't print this... */
1578 fputs(copybuf, copystream);
1584 fputc('\n', copystream);
1592 PQendcopy(res->conn);
1598 handleCopyIn(PGresult * res, const bool mustprompt, FILE * copystream)
1600 bool copydone = false;
1603 char copybuf[COPYBUFSIZ];
1609 fputs("Enter info followed by a newline\n", stdout);
1610 fputs("End with a backslash and a "
1611 "period on a line by itself.\n", stdout);
1613 while (!copydone) { /* for each input line ... */
1615 fputs(">> ", stdout);
1620 while (!linedone) { /* for each buffer ... */
1622 buflen = COPYBUFSIZ;
1623 for (; buflen > 1 &&
1624 !(linedone = (c = getc(copystream)) == '\n' || c == EOF);
1629 PQputline(res->conn, "\\.");
1634 PQputline(res->conn, copybuf);
1636 if (!strcmp(copybuf, "\\.")) {
1642 PQputline(res->conn, "\n");
1644 PQendcopy(res->conn);
1650 * try to open fname and return a FILE *, if it fails, use stdout, instead
1654 setFout(PsqlSettings * ps, char *fname)
1656 if (ps->queryFout && ps->queryFout != stdout) {
1658 pclose(ps->queryFout);
1660 fclose(ps->queryFout);
1663 ps->queryFout = stdout;
1665 if (*fname == '|') {
1666 signal(SIGPIPE, SIG_IGN);
1667 ps->queryFout = popen(fname + 1, "w");
1670 ps->queryFout = fopen(fname, "w");
1673 if (!ps->queryFout) {
1675 ps->queryFout = stdout;
1678 return ps->queryFout;