16 #include <unistd.h> /* for write() */
18 #include <io.h> /* for _write() */
22 #include <postgres_ext.h>
27 #include "variables.h"
33 #define popen(x,y) _popen(x,y)
34 #define pclose(x) _pclose(x)
35 #define write(a,b,c) _write(a,b,c)
42 * "Safe" wrapper around strdup()
43 * (Using this also avoids writing #ifdef HAVE_STRDUP in every file :)
46 xstrdup(const char *string)
52 fprintf(stderr, "xstrdup: Cannot duplicate null pointer.\n");
68 * -- handler for -o command line option and \o command
70 * Tries to open file fname (or pipe if fname starts with '|')
71 * and stores the file handle in pset)
72 * Upon failure, sets stdout and returns false.
75 setQFout(const char *fname)
79 /* Close old file/pipe */
80 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
82 if (pset.queryFoutPipe)
83 pclose(pset.queryFout);
85 fclose(pset.queryFout);
88 /* If no filename, set stdout */
89 if (!fname || fname[0] == '\0')
91 pset.queryFout = stdout;
92 pset.queryFoutPipe = false;
94 else if (*fname == '|')
96 pset.queryFout = popen(fname + 1, "w");
97 pset.queryFoutPipe = true;
101 pset.queryFout = fopen(fname, "w");
102 pset.queryFoutPipe = false;
105 if (!(pset.queryFout))
107 fprintf(stderr, "%s: %s: %s\n", pset.progname, fname, strerror(errno));
108 pset.queryFout = stdout;
109 pset.queryFoutPipe = false;
115 if (pset.queryFoutPipe)
116 pqsignal(SIGPIPE, SIG_IGN);
118 pqsignal(SIGPIPE, SIG_DFL);
129 * Generalized function especially intended for reading in usernames and
130 * password interactively. Reads from stdin.
132 * prompt: The prompt to print
133 * maxlen: How many characters to accept
134 * echo: Set to false if you want to hide what is entered (for passwords)
136 * Returns a malloc()'ed string with the input (w/o trailing newline).
139 simple_prompt(const char *prompt, int maxlen, bool echo)
144 #ifdef HAVE_TERMIOS_H
145 struct termios t_orig,
150 destination = (char *) malloc(maxlen + 2);
154 fputs(prompt, stdout);
156 #ifdef HAVE_TERMIOS_H
162 tcsetattr(0, TCSADRAIN, &t);
166 fgets(destination, maxlen, stdin);
168 #ifdef HAVE_TERMIOS_H
171 tcsetattr(0, TCSADRAIN, &t_orig);
176 length = strlen(destination);
177 if (length > 0 && destination[length - 1] != '\n')
179 /* eat rest of the line */
184 fgets(buf, 512, stdin);
185 } while (buf[strlen(buf) - 1] != '\n');
188 if (length > 0 && destination[length - 1] == '\n')
189 /* remove trailing newline */
190 destination[length - 1] = '\0';
198 * Code to support query cancellation
200 * Before we start a query, we enable a SIGINT signal catcher that sends a
201 * cancel request to the backend. Note that sending the cancel directly from
202 * the signal handler is safe because PQrequestCancel() is written to make it
203 * so. We have to be very careful what else we do in the signal handler. This
204 * includes using write() for output.
207 static PGconn *cancelConn;
209 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
212 handle_sigint(SIGNAL_ARGS)
214 if (cancelConn == NULL)
216 /* Try to send cancel request */
217 if (PQrequestCancel(cancelConn))
218 write_stderr("\nCancel request sent\n");
221 write_stderr("\nCould not send cancel request: ");
222 write_stderr(PQerrorMessage(cancelConn));
231 * This is the way to send "backdoor" queries (those not directly entered
232 * by the user). It is subject to -E but not -e.
235 PSQLexec(const char *query)
242 fputs("You are currently not connected to a database.\n", stderr);
246 var = GetVariable(pset.vars, "ECHO_HIDDEN");
249 printf("********* QUERY *********\n%s\n*************************\n\n", query);
253 if (var && strcmp(var, "noexec") == 0)
256 cancelConn = pset.db;
258 pqsignal(SIGINT, handle_sigint); /* control-C => cancel */
261 res = PQexec(pset.db, query);
264 pqsignal(SIGINT, SIG_DFL); /* now control-C is back to normal */
267 if (PQstatus(pset.db) == CONNECTION_BAD)
269 if (!pset.cur_cmd_interactive)
271 fprintf(stderr, "%s: connection to server was lost", pset.progname);
274 fputs("The connection to the server was lost. Attempting reset: ", stderr);
276 if (PQstatus(pset.db) == CONNECTION_BAD)
278 fputs("Failed.\n", stderr);
282 SetVariable(pset.vars, "DBNAME", NULL);
283 SetVariable(pset.vars, "HOST", NULL);
284 SetVariable(pset.vars, "PORT", NULL);
285 SetVariable(pset.vars, "USER", NULL);
289 fputs("Succeeded.\n", stderr);
292 if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
293 PQresultStatus(res) == PGRES_TUPLES_OK ||
294 PQresultStatus(res) == PGRES_COPY_IN ||
295 PQresultStatus(res) == PGRES_COPY_OUT)
300 fputs(PQerrorMessage(pset.db), stderr);
309 * SendQuery: send the query string to the backend
310 * (and print out results)
312 * Note: This is the "front door" way to send a query. That is, use it to
313 * send queries actually entered by the user. These queries will be subject to
315 * To send "back door" queries (generated by slash commands, etc.) in a
316 * controlled way, use PSQLexec().
318 * Returns true if the query executed successfully, false otherwise.
321 SendQuery(const char *query)
323 bool success = false;
329 fputs("You are currently not connected to a database.\n", stderr);
333 if (GetVariableBool(pset.vars, "SINGLESTEP"))
337 printf("***(Single step mode: Verify query)*********************************************\n"
339 "***(press return to proceed or enter x and return to cancel)********************\n",
342 fgets(buf, 3, stdin);
348 const char * var = GetVariable(pset.vars, "ECHO");
349 if (var && strcmp(var, "brief")==0)
353 cancelConn = pset.db;
355 pqsignal(SIGINT, handle_sigint);
358 results = PQexec(pset.db, query);
361 pqsignal(SIGINT, SIG_DFL);
366 fputs(PQerrorMessage(pset.db), pset.queryFout);
371 switch (PQresultStatus(results))
373 case PGRES_TUPLES_OK:
374 /* write output to \g argument, if any */
377 FILE * queryFout_copy = pset.queryFout;
378 bool queryFoutPipe_copy = pset.queryFoutPipe;
379 pset.queryFout = NULL; /* so it doesn't get closed */
382 if (!setQFout(pset.gfname))
388 printQuery(results, &pset.popt, pset.queryFout);
390 /* close file/pipe */
396 pset.queryFout = queryFout_copy;
397 pset.queryFoutPipe = queryFoutPipe_copy;
405 printQuery(results, &pset.popt, pset.queryFout);
408 case PGRES_EMPTY_QUERY:
411 case PGRES_COMMAND_OK:
416 sprintf(buf, "%u", (unsigned int)PQoidValue(results));
418 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
419 SetVariable(pset.vars, "LASTOID", buf);
423 success = handleCopyOut(pset.db, pset.queryFout);
427 if (pset.cur_cmd_interactive && !QUIET())
428 puts("Enter data to be copied followed by a newline.\n"
429 "End with a backslash and a period on a line by itself.");
431 success = handleCopyIn(pset.db, pset.cur_cmd_source,
432 pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
435 case PGRES_NONFATAL_ERROR:
436 case PGRES_FATAL_ERROR:
437 case PGRES_BAD_RESPONSE:
439 fputs(PQerrorMessage(pset.db), stderr);
443 fflush(pset.queryFout);
445 if (PQstatus(pset.db) == CONNECTION_BAD)
447 if (!pset.cur_cmd_interactive)
449 fprintf(stderr, "%s: connection to server was lost", pset.progname);
452 fputs("The connection to the server was lost. Attempting reset: ", stderr);
454 if (PQstatus(pset.db) == CONNECTION_BAD)
456 fputs("Failed.\n", stderr);
460 SetVariable(pset.vars, "DBNAME", NULL);
461 SetVariable(pset.vars, "HOST", NULL);
462 SetVariable(pset.vars, "PORT", NULL);
463 SetVariable(pset.vars, "USER", NULL);
467 fputs("Succeeded.\n", stderr);
470 /* check for asynchronous notification returns */
471 while ((notify = PQnotifies(pset.db)) != NULL)
473 fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
474 notify->relname, notify->be_pid);
476 fflush(pset.queryFout);