LCOV - code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 76.0 % 1048 797
Test Date: 2026-10-21 22:15:57 Functions: 92.9 % 42 39
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 65.0 % 800 520

             Branch data     Line data    Source code
       1                 :             : /*
       2                 :             :  * psql - the PostgreSQL interactive terminal
       3                 :             :  *
       4                 :             :  * Copyright (c) 2000-2026, PostgreSQL Global Development Group
       5                 :             :  *
       6                 :             :  * src/bin/psql/common.c
       7                 :             :  */
       8                 :             : #include "postgres_fe.h"
       9                 :             : 
      10                 :             : #include <ctype.h>
      11                 :             : #include <limits.h>
      12                 :             : #include <math.h>
      13                 :             : #include <pwd.h>
      14                 :             : #include <signal.h>
      15                 :             : #ifndef WIN32
      16                 :             : #include <unistd.h>               /* for write() */
      17                 :             : #else
      18                 :             : #include <io.h>                   /* for _write() */
      19                 :             : #include <win32.h>
      20                 :             : #endif
      21                 :             : 
      22                 :             : #include "command.h"
      23                 :             : #include "common.h"
      24                 :             : #include "common/logging.h"
      25                 :             : #include "copy.h"
      26                 :             : #include "crosstabview.h"
      27                 :             : #include "fe_utils/cancel.h"
      28                 :             : #include "fe_utils/mbprint.h"
      29                 :             : #include "fe_utils/string_utils.h"
      30                 :             : #include "mainloop.h"
      31                 :             : #include "mb/pg_wchar.h"
      32                 :             : #include "portability/instr_time.h"
      33                 :             : #include "settings.h"
      34                 :             : 
      35                 :             : static bool DescribeQuery(const char *query, double *elapsed_msec);
      36                 :             : static int  ExecQueryAndProcessResults(const char *query,
      37                 :             :                                        double *elapsed_msec,
      38                 :             :                                        bool *svpt_gone_p,
      39                 :             :                                        int num_copy_from_stdin,
      40                 :             :                                        bool is_watch,
      41                 :             :                                        int min_rows,
      42                 :             :                                        const printQueryOpt *opt,
      43                 :             :                                        FILE *printQueryFout);
      44                 :             : static bool command_no_begin(const char *query);
      45                 :             : 
      46                 :             : 
      47                 :             : /*
      48                 :             :  * openQueryOutputFile --- attempt to open a query output file
      49                 :             :  *
      50                 :             :  * fname == NULL selects stdout, else an initial '|' selects a pipe,
      51                 :             :  * else plain file.
      52                 :             :  *
      53                 :             :  * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
      54                 :             :  * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
      55                 :             :  *
      56                 :             :  * On error, reports suitable error message and returns false.
      57                 :             :  */
      58                 :             : bool
      59                 :       11118 : openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
      60                 :             : {
      61   [ +  +  -  + ]:       11118 :     if (!fname || fname[0] == '\0')
      62                 :             :     {
      63                 :       11086 :         *fout = stdout;
      64                 :       11086 :         *is_pipe = false;
      65                 :             :     }
      66         [ +  + ]:          32 :     else if (*fname == '|')
      67                 :             :     {
      68                 :           4 :         fflush(NULL);
      69                 :           4 :         *fout = popen(fname + 1, "w");
      70                 :           4 :         *is_pipe = true;
      71                 :             :     }
      72                 :             :     else
      73                 :             :     {
      74                 :          28 :         *fout = fopen(fname, "w");
      75                 :          28 :         *is_pipe = false;
      76                 :             :     }
      77                 :             : 
      78         [ -  + ]:       11118 :     if (*fout == NULL)
      79                 :             :     {
      80                 :           0 :         pg_log_error("%s: %m", fname);
      81                 :           0 :         return false;
      82                 :             :     }
      83                 :             : 
      84                 :       11118 :     return true;
      85                 :             : }
      86                 :             : 
      87                 :             : /*
      88                 :             :  * Check if an output stream for \g needs to be opened, and if yes,
      89                 :             :  * open it and update the caller's gfile_fout and is_pipe state variables.
      90                 :             :  * Return true if OK, false if an error occurred.
      91                 :             :  */
      92                 :             : static bool
      93                 :       96608 : SetupGOutput(FILE **gfile_fout, bool *is_pipe)
      94                 :             : {
      95                 :             :     /* If there is a \g file or program, and it's not already open, open it */
      96   [ +  +  +  + ]:       96608 :     if (pset.gfname != NULL && *gfile_fout == NULL)
      97                 :             :     {
      98         [ +  - ]:          20 :         if (openQueryOutputFile(pset.gfname, gfile_fout, is_pipe))
      99                 :             :         {
     100         [ +  + ]:          20 :             if (*is_pipe)
     101                 :           4 :                 disable_sigpipe_trap();
     102                 :             :         }
     103                 :             :         else
     104                 :           0 :             return false;
     105                 :             :     }
     106                 :       96608 :     return true;
     107                 :             : }
     108                 :             : 
     109                 :             : /*
     110                 :             :  * Close the output stream for \g, if we opened it.
     111                 :             :  */
     112                 :             : static void
     113                 :      252883 : CloseGOutput(FILE *gfile_fout, bool is_pipe)
     114                 :             : {
     115         [ +  + ]:      252883 :     if (gfile_fout)
     116                 :             :     {
     117         [ +  + ]:          20 :         if (is_pipe)
     118                 :             :         {
     119                 :           4 :             SetShellResultVariables(pclose(gfile_fout));
     120                 :           4 :             restore_sigpipe_trap();
     121                 :             :         }
     122                 :             :         else
     123                 :          16 :             fclose(gfile_fout);
     124                 :             :     }
     125                 :      252883 : }
     126                 :             : 
     127                 :             : /*
     128                 :             :  * Reset pset pipeline state
     129                 :             :  */
     130                 :             : static void
     131                 :           0 : pipelineReset(void)
     132                 :             : {
     133                 :           0 :     pset.piped_syncs = 0;
     134                 :           0 :     pset.piped_commands = 0;
     135                 :           0 :     pset.available_results = 0;
     136                 :           0 :     pset.requested_results = 0;
     137                 :           0 : }
     138                 :             : 
     139                 :             : /*
     140                 :             :  * setQFout
     141                 :             :  * -- handler for -o command line option and \o command
     142                 :             :  *
     143                 :             :  * On success, updates pset with the new output file and returns true.
     144                 :             :  * On failure, returns false without changing pset state.
     145                 :             :  */
     146                 :             : bool
     147                 :       11098 : setQFout(const char *fname)
     148                 :             : {
     149                 :             :     FILE       *fout;
     150                 :             :     bool        is_pipe;
     151                 :             : 
     152                 :             :     /* First make sure we can open the new output file/pipe */
     153         [ -  + ]:       11098 :     if (!openQueryOutputFile(fname, &fout, &is_pipe))
     154                 :           0 :         return false;
     155                 :             : 
     156                 :             :     /* Close old file/pipe */
     157   [ +  -  +  +  :       11098 :     if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
                   +  - ]
     158                 :             :     {
     159         [ -  + ]:          12 :         if (pset.queryFoutPipe)
     160                 :           0 :             SetShellResultVariables(pclose(pset.queryFout));
     161                 :             :         else
     162                 :          12 :             fclose(pset.queryFout);
     163                 :             :     }
     164                 :             : 
     165                 :       11098 :     pset.queryFout = fout;
     166                 :       11098 :     pset.queryFoutPipe = is_pipe;
     167                 :             : 
     168                 :             :     /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
     169                 :       11098 :     set_sigpipe_trap_state(is_pipe);
     170                 :       11098 :     restore_sigpipe_trap();
     171                 :             : 
     172                 :       11098 :     return true;
     173                 :             : }
     174                 :             : 
     175                 :             : 
     176                 :             : /*
     177                 :             :  * Variable-fetching callback for flex lexer
     178                 :             :  *
     179                 :             :  * If the specified variable exists, return its value as a string (malloc'd
     180                 :             :  * and expected to be freed by the caller); else return NULL.
     181                 :             :  *
     182                 :             :  * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
     183                 :             :  * escaped for the specified quoting requirement.  (Failure in escaping
     184                 :             :  * should lead to printing an error and returning NULL.)
     185                 :             :  *
     186                 :             :  * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
     187                 :             :  * In psql, passthrough points to a ConditionalStack, which we check to
     188                 :             :  * determine whether variable expansion is allowed.
     189                 :             :  */
     190                 :             : char *
     191                 :        2939 : psql_get_variable(const char *varname, PsqlScanQuoteType quote,
     192                 :             :                   void *passthrough)
     193                 :             : {
     194                 :        2939 :     char       *result = NULL;
     195                 :             :     const char *value;
     196                 :             : 
     197                 :             :     /* In an inactive \if branch, suppress all variable substitutions */
     198   [ +  -  +  + ]:        2939 :     if (passthrough && !conditional_active((ConditionalStack) passthrough))
     199                 :          48 :         return NULL;
     200                 :             : 
     201                 :        2891 :     value = GetVariable(pset.vars, varname);
     202         [ +  + ]:        2891 :     if (!value)
     203                 :         333 :         return NULL;
     204                 :             : 
     205   [ +  +  -  - ]:        2558 :     switch (quote)
     206                 :             :     {
     207                 :        1850 :         case PQUOTE_PLAIN:
     208                 :        1850 :             result = pg_strdup(value);
     209                 :        1850 :             break;
     210                 :         708 :         case PQUOTE_SQL_LITERAL:
     211                 :             :         case PQUOTE_SQL_IDENT:
     212                 :             :             {
     213                 :             :                 /*
     214                 :             :                  * For these cases, we use libpq's quoting functions, which
     215                 :             :                  * assume the string is in the connection's client encoding.
     216                 :             :                  */
     217                 :             :                 char       *escaped_value;
     218                 :             : 
     219         [ -  + ]:         708 :                 if (!pset.db)
     220                 :             :                 {
     221                 :           0 :                     pg_log_error("cannot escape without active connection");
     222                 :           0 :                     return NULL;
     223                 :             :                 }
     224                 :             : 
     225         [ +  + ]:         708 :                 if (quote == PQUOTE_SQL_LITERAL)
     226                 :             :                     escaped_value =
     227                 :         687 :                         PQescapeLiteral(pset.db, value, strlen(value));
     228                 :             :                 else
     229                 :             :                     escaped_value =
     230                 :          21 :                         PQescapeIdentifier(pset.db, value, strlen(value));
     231                 :             : 
     232         [ -  + ]:         708 :                 if (escaped_value == NULL)
     233                 :             :                 {
     234                 :           0 :                     const char *error = PQerrorMessage(pset.db);
     235                 :             : 
     236                 :           0 :                     pg_log_info("%s", error);
     237                 :           0 :                     return NULL;
     238                 :             :                 }
     239                 :             : 
     240                 :             :                 /*
     241                 :             :                  * Rather than complicate the lexer's API with a notion of
     242                 :             :                  * which free() routine to use, just pay the price of an extra
     243                 :             :                  * strdup().
     244                 :             :                  */
     245                 :         708 :                 result = pg_strdup(escaped_value);
     246                 :         708 :                 PQfreemem(escaped_value);
     247                 :         708 :                 break;
     248                 :             :             }
     249                 :           0 :         case PQUOTE_SHELL_ARG:
     250                 :             :             {
     251                 :             :                 /*
     252                 :             :                  * For this we use appendShellStringNoError, which is
     253                 :             :                  * encoding-agnostic, which is fine since the shell probably
     254                 :             :                  * is too.  In any case, the only special character is "'",
     255                 :             :                  * which is not known to appear in valid multibyte characters.
     256                 :             :                  */
     257                 :             :                 PQExpBufferData buf;
     258                 :             : 
     259                 :           0 :                 initPQExpBuffer(&buf);
     260         [ #  # ]:           0 :                 if (!appendShellStringNoError(&buf, value))
     261                 :             :                 {
     262                 :           0 :                     pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
     263                 :             :                                  value);
     264                 :           0 :                     free(buf.data);
     265                 :           0 :                     return NULL;
     266                 :             :                 }
     267                 :           0 :                 result = buf.data;
     268                 :           0 :                 break;
     269                 :             :             }
     270                 :             : 
     271                 :             :             /* No default: we want a compiler warning for missing cases */
     272                 :             :     }
     273                 :             : 
     274                 :        2558 :     return result;
     275                 :             : }
     276                 :             : 
     277                 :             : 
     278                 :             : /*
     279                 :             :  * for backend Notice messages (INFO, WARNING, etc)
     280                 :             :  */
     281                 :             : void
     282                 :      184133 : NoticeProcessor(void *arg, const char *message)
     283                 :             : {
     284                 :             :     (void) arg;                 /* not used */
     285                 :      184133 :     pg_log_info("%s", message);
     286                 :      184133 : }
     287                 :             : 
     288                 :             : 
     289                 :             : 
     290                 :             : /*
     291                 :             :  * Code to support query cancellation
     292                 :             :  *
     293                 :             :  * Before we start a query, we enable the SIGINT signal catcher to send a
     294                 :             :  * cancel request to the backend.
     295                 :             :  *
     296                 :             :  * SIGINT is supposed to abort all long-running psql operations, not only
     297                 :             :  * database queries.  In most places, this is accomplished by checking
     298                 :             :  * cancel_pressed during long-running loops.  However, that won't work when
     299                 :             :  * blocked on user input (in readline() or fgets()).  In those places, we
     300                 :             :  * set sigint_interrupt_enabled true while blocked, instructing the signal
     301                 :             :  * catcher to longjmp through sigint_interrupt_jmp.  We assume readline and
     302                 :             :  * fgets are coded to handle possible interruption.
     303                 :             :  *
     304                 :             :  * On Windows, currently this does not work, so control-C is less useful
     305                 :             :  * there.
     306                 :             :  */
     307                 :             : volatile sig_atomic_t sigint_interrupt_enabled = false;
     308                 :             : 
     309                 :             : sigjmp_buf  sigint_interrupt_jmp;
     310                 :             : 
     311                 :             : static void
     312                 :           1 : psql_cancel_callback(void)
     313                 :             : {
     314                 :             : #ifndef WIN32
     315                 :             :     /* if we are waiting for input, longjmp out of it */
     316         [ -  + ]:           1 :     if (sigint_interrupt_enabled)
     317                 :             :     {
     318                 :           0 :         sigint_interrupt_enabled = false;
     319                 :           0 :         siglongjmp(sigint_interrupt_jmp, 1);
     320                 :             :     }
     321                 :             : #endif
     322                 :             : 
     323                 :             :     /* else, set cancel flag to stop any long-running loops */
     324                 :           1 :     cancel_pressed = true;
     325                 :           1 : }
     326                 :             : 
     327                 :             : void
     328                 :       11090 : psql_setup_cancel_handler(void)
     329                 :             : {
     330                 :       11090 :     setup_cancel_handler(psql_cancel_callback);
     331                 :       11090 : }
     332                 :             : 
     333                 :             : 
     334                 :             : /*
     335                 :             :  * ConnectionUp
     336                 :             :  *
     337                 :             :  * Returns whether our backend connection is still there.
     338                 :             :  */
     339                 :             : static bool
     340                 :      283362 : ConnectionUp(void)
     341                 :             : {
     342                 :      283362 :     return PQstatus(pset.db) != CONNECTION_BAD;
     343                 :             : }
     344                 :             : 
     345                 :             : 
     346                 :             : 
     347                 :             : /*
     348                 :             :  * CheckConnection
     349                 :             :  *
     350                 :             :  * Verify that we still have a good connection to the backend, and if not,
     351                 :             :  * see if it can be restored.
     352                 :             :  *
     353                 :             :  * Returns true if either the connection was still there, or it could be
     354                 :             :  * restored successfully; false otherwise.  If, however, there was no
     355                 :             :  * connection and the session is non-interactive, this will exit the program
     356                 :             :  * with a code of EXIT_BADCONN.
     357                 :             :  */
     358                 :             : static bool
     359                 :      283182 : CheckConnection(void)
     360                 :             : {
     361                 :             :     bool        OK;
     362                 :             : 
     363                 :      283182 :     OK = ConnectionUp();
     364         [ +  + ]:      283182 :     if (!OK)
     365                 :             :     {
     366         [ +  - ]:          12 :         if (!pset.cur_cmd_interactive)
     367                 :             :         {
     368                 :          12 :             pg_log_error("connection to server was lost");
     369                 :          12 :             exit(EXIT_BADCONN);
     370                 :             :         }
     371                 :             : 
     372                 :           0 :         fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
     373                 :           0 :         PQreset(pset.db);
     374                 :           0 :         pipelineReset();
     375                 :           0 :         OK = ConnectionUp();
     376         [ #  # ]:           0 :         if (!OK)
     377                 :             :         {
     378                 :           0 :             fprintf(stderr, _("Failed.\n"));
     379                 :             : 
     380                 :             :             /*
     381                 :             :              * Transition to having no connection; but stash away the failed
     382                 :             :              * connection so that we can still refer to its parameters in a
     383                 :             :              * later \connect attempt.  Keep the state cleanup here in sync
     384                 :             :              * with do_connect().
     385                 :             :              */
     386         [ #  # ]:           0 :             if (pset.dead_conn)
     387                 :           0 :                 PQfinish(pset.dead_conn);
     388                 :           0 :             pset.dead_conn = pset.db;
     389                 :           0 :             pset.db = NULL;
     390                 :           0 :             ResetCancelConn();
     391                 :           0 :             UnsyncVariables();
     392                 :             :         }
     393                 :             :         else
     394                 :             :         {
     395                 :           0 :             fprintf(stderr, _("Succeeded.\n"));
     396                 :             : 
     397                 :             :             /*
     398                 :             :              * Re-sync, just in case anything changed.  Keep this in sync with
     399                 :             :              * do_connect().
     400                 :             :              */
     401                 :           0 :             SyncVariables();
     402                 :           0 :             connection_warnings(false); /* Must be after SyncVariables */
     403                 :             :         }
     404                 :             :     }
     405                 :             : 
     406                 :      283170 :     return OK;
     407                 :             : }
     408                 :             : 
     409                 :             : 
     410                 :             : 
     411                 :             : 
     412                 :             : /*
     413                 :             :  * AcceptResult
     414                 :             :  *
     415                 :             :  * Checks whether a result is valid, giving an error message if necessary;
     416                 :             :  * and ensures that the connection to the backend is still up.
     417                 :             :  *
     418                 :             :  * Returns true for valid result, false for error state.
     419                 :             :  */
     420                 :             : static bool
     421                 :      285243 : AcceptResult(const PGresult *result, bool show_error)
     422                 :             : {
     423                 :             :     bool        OK;
     424                 :             : 
     425         [ -  + ]:      285243 :     if (!result)
     426                 :           0 :         OK = false;
     427                 :             :     else
     428      [ +  +  + ]:      285243 :         switch (PQresultStatus(result))
     429                 :             :         {
     430                 :      254976 :             case PGRES_COMMAND_OK:
     431                 :             :             case PGRES_TUPLES_OK:
     432                 :             :             case PGRES_TUPLES_CHUNK:
     433                 :             :             case PGRES_EMPTY_QUERY:
     434                 :             :             case PGRES_COPY_IN:
     435                 :             :             case PGRES_COPY_OUT:
     436                 :             :             case PGRES_PIPELINE_SYNC:
     437                 :             :                 /* Fine, do nothing */
     438                 :      254976 :                 OK = true;
     439                 :      254976 :                 break;
     440                 :             : 
     441                 :       30266 :             case PGRES_PIPELINE_ABORTED:
     442                 :             :             case PGRES_BAD_RESPONSE:
     443                 :             :             case PGRES_NONFATAL_ERROR:
     444                 :             :             case PGRES_FATAL_ERROR:
     445                 :       30266 :                 OK = false;
     446                 :       30266 :                 break;
     447                 :             : 
     448                 :           1 :             default:
     449                 :           1 :                 OK = false;
     450                 :           1 :                 pg_log_error("unexpected PQresultStatus: %d",
     451                 :             :                              PQresultStatus(result));
     452                 :           1 :                 break;
     453                 :             :         }
     454                 :             : 
     455   [ +  +  +  + ]:      285243 :     if (!OK && show_error)
     456                 :             :     {
     457                 :           4 :         const char *error = PQerrorMessage(pset.db);
     458                 :             : 
     459         [ +  - ]:           4 :         if (strlen(error))
     460                 :           4 :             pg_log_info("%s", error);
     461                 :             : 
     462                 :           4 :         CheckConnection();
     463                 :             :     }
     464                 :             : 
     465                 :      285243 :     return OK;
     466                 :             : }
     467                 :             : 
     468                 :             : 
     469                 :             : /*
     470                 :             :  * Set special variables from a query result
     471                 :             :  * - ERROR: true/false, whether an error occurred on this query
     472                 :             :  * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
     473                 :             :  * - ROW_COUNT: how many rows were returned or affected, or "0"
     474                 :             :  * - LAST_ERROR_SQLSTATE: same for last error
     475                 :             :  * - LAST_ERROR_MESSAGE: message of last error
     476                 :             :  *
     477                 :             :  * Note: current policy is to apply this only to the results of queries
     478                 :             :  * entered by the user, not queries generated by slash commands.
     479                 :             :  */
     480                 :             : static void
     481                 :      252835 : SetResultVariables(PGresult *result, bool success)
     482                 :             : {
     483         [ +  + ]:      252835 :     if (success)
     484                 :             :     {
     485                 :      222330 :         const char *ntuples = PQcmdTuples(result);
     486                 :             : 
     487                 :      222330 :         SetVariable(pset.vars, "ERROR", "false");
     488                 :      222330 :         SetVariable(pset.vars, "SQLSTATE", "00000");
     489         [ +  + ]:      222330 :         SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
     490                 :             :     }
     491                 :             :     else
     492                 :             :     {
     493                 :       30505 :         const char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
     494                 :       30505 :         const char *mesg = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
     495                 :             : 
     496                 :       30505 :         SetVariable(pset.vars, "ERROR", "true");
     497                 :             : 
     498                 :             :         /*
     499                 :             :          * If there is no SQLSTATE code, use an empty string.  This can happen
     500                 :             :          * for libpq-detected errors (e.g., lost connection, ENOMEM).
     501                 :             :          */
     502         [ +  + ]:       30505 :         if (code == NULL)
     503                 :         106 :             code = "";
     504                 :       30505 :         SetVariable(pset.vars, "SQLSTATE", code);
     505                 :       30505 :         SetVariable(pset.vars, "ROW_COUNT", "0");
     506                 :       30505 :         SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
     507         [ +  + ]:       30505 :         SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
     508                 :             :     }
     509                 :      252835 : }
     510                 :             : 
     511                 :             : 
     512                 :             : /*
     513                 :             :  * Set special variables from a shell command result
     514                 :             :  * - SHELL_ERROR: true/false, whether command returned exit code 0
     515                 :             :  * - SHELL_EXIT_CODE: exit code according to shell conventions
     516                 :             :  *
     517                 :             :  * The argument is a wait status as returned by wait(2) or waitpid(2),
     518                 :             :  * which also applies to pclose(3) and system(3).
     519                 :             :  */
     520                 :             : void
     521                 :           4 : SetShellResultVariables(int wait_result)
     522                 :             : {
     523                 :             :     char        buf[32];
     524                 :             : 
     525         [ +  - ]:           4 :     SetVariable(pset.vars, "SHELL_ERROR",
     526                 :             :                 (wait_result == 0) ? "false" : "true");
     527                 :           4 :     snprintf(buf, sizeof(buf), "%d", wait_result_to_exit_code(wait_result));
     528                 :           4 :     SetVariable(pset.vars, "SHELL_EXIT_CODE", buf);
     529                 :           4 : }
     530                 :             : 
     531                 :             : 
     532                 :             : /*
     533                 :             :  * Set special pipeline variables
     534                 :             :  * - PIPELINE_SYNC_COUNT: The number of piped syncs
     535                 :             :  * - PIPELINE_COMMAND_COUNT: The number of piped commands
     536                 :             :  * - PIPELINE_RESULT_COUNT: The number of results available to read
     537                 :             :  */
     538                 :             : static void
     539                 :      253876 : SetPipelineVariables(void)
     540                 :             : {
     541                 :             :     char        buf[32];
     542                 :             : 
     543                 :      253876 :     snprintf(buf, sizeof(buf), "%d", pset.piped_syncs);
     544                 :      253876 :     SetVariable(pset.vars, "PIPELINE_SYNC_COUNT", buf);
     545                 :      253876 :     snprintf(buf, sizeof(buf), "%d", pset.piped_commands);
     546                 :      253876 :     SetVariable(pset.vars, "PIPELINE_COMMAND_COUNT", buf);
     547                 :      253876 :     snprintf(buf, sizeof(buf), "%d", pset.available_results);
     548                 :      253876 :     SetVariable(pset.vars, "PIPELINE_RESULT_COUNT", buf);
     549                 :      253876 : }
     550                 :             : 
     551                 :             : 
     552                 :             : /*
     553                 :             :  * ClearOrSaveResult
     554                 :             :  *
     555                 :             :  * If the result represents an error, remember it for possible display by
     556                 :             :  * \errverbose.  Otherwise, just PQclear() it.
     557                 :             :  *
     558                 :             :  * Note: current policy is to apply this to the results of all queries,
     559                 :             :  * including "back door" queries, for debugging's sake.  It's OK to use
     560                 :             :  * PQclear() directly on results known to not be error results, however.
     561                 :             :  */
     562                 :             : static void
     563                 :      254717 : ClearOrSaveResult(PGresult *result)
     564                 :             : {
     565         [ +  + ]:      254717 :     if (result)
     566                 :             :     {
     567         [ +  + ]:      254183 :         switch (PQresultStatus(result))
     568                 :             :         {
     569                 :       30404 :             case PGRES_NONFATAL_ERROR:
     570                 :             :             case PGRES_FATAL_ERROR:
     571                 :       30404 :                 PQclear(pset.last_error_result);
     572                 :       30404 :                 pset.last_error_result = result;
     573                 :       30404 :                 break;
     574                 :             : 
     575                 :      223779 :             default:
     576                 :      223779 :                 PQclear(result);
     577                 :      223779 :                 break;
     578                 :             :         }
     579                 :             :     }
     580                 :      254717 : }
     581                 :             : 
     582                 :             : 
     583                 :             : /*
     584                 :             :  * Consume all results
     585                 :             :  */
     586                 :             : static void
     587                 :           0 : ClearOrSaveAllResults(void)
     588                 :             : {
     589                 :             :     PGresult   *result;
     590                 :             : 
     591         [ #  # ]:           0 :     while ((result = PQgetResult(pset.db)) != NULL)
     592                 :           0 :         ClearOrSaveResult(result);
     593                 :           0 : }
     594                 :             : 
     595                 :             : 
     596                 :             : /*
     597                 :             :  * Print microtiming output.  Always print raw milliseconds; if the interval
     598                 :             :  * is >= 1 second, also break it down into days/hours/minutes/seconds.
     599                 :             :  */
     600                 :             : static void
     601                 :           2 : PrintTiming(double elapsed_msec)
     602                 :             : {
     603                 :             :     double      seconds;
     604                 :             :     double      minutes;
     605                 :             :     double      hours;
     606                 :             :     double      days;
     607                 :             : 
     608         [ +  - ]:           2 :     if (elapsed_msec < 1000.0)
     609                 :             :     {
     610                 :             :         /* This is the traditional (pre-v10) output format */
     611                 :           2 :         printf(_("Time: %.3f ms\n"), elapsed_msec);
     612                 :           2 :         return;
     613                 :             :     }
     614                 :             : 
     615                 :             :     /*
     616                 :             :      * Note: we could print just seconds, in a format like %06.3f, when the
     617                 :             :      * total is less than 1min.  But that's hard to interpret unless we tack
     618                 :             :      * on "s" or otherwise annotate it.  Forcing the display to include
     619                 :             :      * minutes seems like a better solution.
     620                 :             :      */
     621                 :           0 :     seconds = elapsed_msec / 1000.0;
     622                 :           0 :     minutes = floor(seconds / 60.0);
     623                 :           0 :     seconds -= 60.0 * minutes;
     624         [ #  # ]:           0 :     if (minutes < 60.0)
     625                 :             :     {
     626                 :           0 :         printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
     627                 :             :                elapsed_msec, (int) minutes, seconds);
     628                 :           0 :         return;
     629                 :             :     }
     630                 :             : 
     631                 :           0 :     hours = floor(minutes / 60.0);
     632                 :           0 :     minutes -= 60.0 * hours;
     633         [ #  # ]:           0 :     if (hours < 24.0)
     634                 :             :     {
     635                 :           0 :         printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
     636                 :             :                elapsed_msec, (int) hours, (int) minutes, seconds);
     637                 :           0 :         return;
     638                 :             :     }
     639                 :             : 
     640                 :           0 :     days = floor(hours / 24.0);
     641                 :           0 :     hours -= 24.0 * days;
     642                 :           0 :     printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
     643                 :             :            elapsed_msec, days, (int) hours, (int) minutes, seconds);
     644                 :             : }
     645                 :             : 
     646                 :             : 
     647                 :             : /*
     648                 :             :  * PSQLexec
     649                 :             :  *
     650                 :             :  * This is the way to send "backdoor" queries (those not directly entered
     651                 :             :  * by the user). It is subject to -E but not -e.
     652                 :             :  *
     653                 :             :  * Caller is responsible for handling the ensuing processing if a COPY
     654                 :             :  * command is sent.
     655                 :             :  *
     656                 :             :  * Note: we don't bother to check PQclientEncoding; it is assumed that no
     657                 :             :  * caller uses this path to issue "SET CLIENT_ENCODING".
     658                 :             :  */
     659                 :             : PGresult *
     660                 :       30755 : PSQLexec(const char *query)
     661                 :             : {
     662                 :             :     PGresult   *res;
     663                 :             : 
     664         [ -  + ]:       30755 :     if (!pset.db)
     665                 :             :     {
     666                 :           0 :         pg_log_error("You are currently not connected to a database.");
     667                 :           0 :         return NULL;
     668                 :             :     }
     669                 :             : 
     670         [ -  + ]:       30755 :     if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
     671                 :             :     {
     672                 :           0 :         printf(_("/**** INTERNAL QUERY ****/\n"
     673                 :             :                  "%s\n"
     674                 :             :                  "/************************/\n\n"), query);
     675                 :           0 :         fflush(stdout);
     676         [ #  # ]:           0 :         if (pset.logfile)
     677                 :             :         {
     678                 :           0 :             fprintf(pset.logfile,
     679                 :           0 :                     _("/**** INTERNAL QUERY ****/\n"
     680                 :             :                       "%s\n"
     681                 :             :                       "/************************/\n\n"), query);
     682                 :           0 :             fflush(pset.logfile);
     683                 :             :         }
     684                 :             : 
     685         [ #  # ]:           0 :         if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
     686                 :           0 :             return NULL;
     687                 :             :     }
     688                 :             : 
     689                 :       30755 :     SetCancelConn(pset.db);
     690                 :             : 
     691                 :       30755 :     res = PQexec(pset.db, query);
     692                 :             : 
     693                 :       30755 :     ResetCancelConn();
     694                 :             : 
     695         [ -  + ]:       30755 :     if (!AcceptResult(res, true))
     696                 :             :     {
     697                 :           0 :         ClearOrSaveResult(res);
     698                 :           0 :         res = NULL;
     699                 :             :     }
     700                 :             : 
     701                 :       30755 :     return res;
     702                 :             : }
     703                 :             : 
     704                 :             : 
     705                 :             : /*
     706                 :             :  * PSQLexecWatch
     707                 :             :  *
     708                 :             :  * This function is used for \watch command to send the query to
     709                 :             :  * the server and print out the result.
     710                 :             :  *
     711                 :             :  * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
     712                 :             :  * e.g., because of the interrupt, -1 on error.
     713                 :             :  */
     714                 :             : int
     715                 :         125 : PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
     716                 :             : {
     717                 :         125 :     bool        timing = pset.timing;
     718                 :         125 :     double      elapsed_msec = 0;
     719                 :             :     int         res;
     720                 :             : 
     721         [ -  + ]:         125 :     if (!pset.db)
     722                 :             :     {
     723                 :           0 :         pg_log_error("You are currently not connected to a database.");
     724                 :           0 :         return 0;
     725                 :             :     }
     726                 :             : 
     727                 :         125 :     SetCancelConn(pset.db);
     728                 :             : 
     729                 :         125 :     res = ExecQueryAndProcessResults(query,
     730                 :             :                                      &elapsed_msec, NULL,
     731                 :             :                                      -1,
     732                 :             :                                      true, min_rows,
     733                 :             :                                      opt, printQueryFout);
     734                 :             : 
     735                 :         123 :     ResetCancelConn();
     736                 :             : 
     737                 :             :     /* Possible microtiming output */
     738         [ -  + ]:         123 :     if (timing)
     739                 :           0 :         PrintTiming(elapsed_msec);
     740                 :             : 
     741                 :         123 :     return res;
     742                 :             : }
     743                 :             : 
     744                 :             : 
     745                 :             : /*
     746                 :             :  * PrintNotifications: check for asynchronous notifications, and print them out
     747                 :             :  */
     748                 :             : static void
     749                 :      253810 : PrintNotifications(void)
     750                 :             : {
     751                 :             :     PGnotify   *notify;
     752                 :             : 
     753                 :      253810 :     PQconsumeInput(pset.db);
     754         [ +  + ]:      253822 :     while ((notify = PQnotifies(pset.db)) != NULL)
     755                 :             :     {
     756                 :             :         /* for backward compatibility, only show payload if nonempty */
     757         [ +  + ]:          12 :         if (notify->extra[0])
     758                 :          11 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
     759                 :             :                     notify->relname, notify->extra, notify->be_pid);
     760                 :             :         else
     761                 :           1 :             fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
     762                 :             :                     notify->relname, notify->be_pid);
     763                 :          12 :         fflush(pset.queryFout);
     764                 :          12 :         PQfreemem(notify);
     765                 :          12 :         PQconsumeInput(pset.db);
     766                 :             :     }
     767                 :      253810 : }
     768                 :             : 
     769                 :             : 
     770                 :             : /*
     771                 :             :  * PrintQueryTuples: assuming query result is OK, print its tuples
     772                 :             :  *
     773                 :             :  * We use the options given by opt unless that's NULL, in which case
     774                 :             :  * we use pset.popt.
     775                 :             :  *
     776                 :             :  * Output is to printQueryFout unless that's NULL, in which case
     777                 :             :  * we use pset.queryFout.
     778                 :             :  *
     779                 :             :  * Returns true if successful, false otherwise.
     780                 :             :  */
     781                 :             : static bool
     782                 :       95840 : PrintQueryTuples(const PGresult *result, const printQueryOpt *opt,
     783                 :             :                  FILE *printQueryFout)
     784                 :             : {
     785                 :       95840 :     bool        ok = true;
     786         [ +  + ]:       95840 :     FILE       *fout = printQueryFout ? printQueryFout : pset.queryFout;
     787                 :             : 
     788         [ +  + ]:       95840 :     printQuery(result, opt ? opt : &pset.popt, fout, false, pset.logfile);
     789                 :       95840 :     fflush(fout);
     790         [ -  + ]:       95840 :     if (ferror(fout))
     791                 :             :     {
     792                 :           0 :         pg_log_error("could not print result table: %m");
     793                 :           0 :         ok = false;
     794                 :             :     }
     795                 :             : 
     796                 :       95840 :     return ok;
     797                 :             : }
     798                 :             : 
     799                 :             : 
     800                 :             : /*
     801                 :             :  * StoreQueryTuple: assuming query result is OK, save data into variables
     802                 :             :  *
     803                 :             :  * Returns true if successful, false otherwise.
     804                 :             :  */
     805                 :             : static bool
     806                 :         597 : StoreQueryTuple(const PGresult *result)
     807                 :             : {
     808                 :         597 :     bool        success = true;
     809                 :             : 
     810         [ +  + ]:         597 :     if (PQntuples(result) < 1)
     811                 :             :     {
     812                 :          12 :         pg_log_error("no rows returned for \\gset");
     813                 :          12 :         success = false;
     814                 :             :     }
     815         [ +  + ]:         585 :     else if (PQntuples(result) > 1)
     816                 :             :     {
     817                 :           8 :         pg_log_error("more than one row returned for \\gset");
     818                 :           8 :         success = false;
     819                 :             :     }
     820                 :             :     else
     821                 :             :     {
     822                 :             :         int         i;
     823                 :             : 
     824         [ +  + ]:        1272 :         for (i = 0; i < PQnfields(result); i++)
     825                 :             :         {
     826                 :         699 :             char       *colname = PQfname(result, i);
     827                 :             :             char       *varname;
     828                 :             :             char       *value;
     829                 :             : 
     830                 :             :             /* concatenate prefix and column name */
     831                 :         699 :             varname = psprintf("%s%s", pset.gset_prefix, colname);
     832                 :             : 
     833         [ +  + ]:         699 :             if (VariableHasHook(pset.vars, varname))
     834                 :             :             {
     835                 :           4 :                 pg_log_warning("attempt to \\gset into specially treated variable \"%s\" ignored",
     836                 :             :                                varname);
     837                 :           4 :                 continue;
     838                 :             :             }
     839                 :             : 
     840         [ +  + ]:         695 :             if (!PQgetisnull(result, 0, i))
     841                 :         687 :                 value = PQgetvalue(result, 0, i);
     842                 :             :             else
     843                 :             :             {
     844                 :             :                 /* for NULL value, unset rather than set the variable */
     845                 :           8 :                 value = NULL;
     846                 :             :             }
     847                 :             : 
     848         [ +  + ]:         695 :             if (!SetVariable(pset.vars, varname, value))
     849                 :             :             {
     850                 :           4 :                 pfree(varname);
     851                 :           4 :                 success = false;
     852                 :           4 :                 break;
     853                 :             :             }
     854                 :             : 
     855                 :         691 :             pfree(varname);
     856                 :             :         }
     857                 :             :     }
     858                 :             : 
     859                 :         597 :     return success;
     860                 :             : }
     861                 :             : 
     862                 :             : 
     863                 :             : /*
     864                 :             :  * ExecQueryTuples: assuming query result is OK, execute each query
     865                 :             :  * result field as a SQL statement
     866                 :             :  *
     867                 :             :  * Returns true if successful, false otherwise.
     868                 :             :  */
     869                 :             : static bool
     870                 :          29 : ExecQueryTuples(const PGresult *result)
     871                 :             : {
     872                 :          29 :     bool        success = true;
     873                 :          29 :     int         nrows = PQntuples(result);
     874                 :          29 :     int         ncolumns = PQnfields(result);
     875                 :             :     int         r,
     876                 :             :                 c;
     877                 :             : 
     878                 :             :     /*
     879                 :             :      * We must turn off gexec_flag to avoid infinite recursion.
     880                 :             :      */
     881                 :          29 :     pset.gexec_flag = false;
     882                 :             : 
     883         [ +  + ]:         290 :     for (r = 0; r < nrows; r++)
     884                 :             :     {
     885         [ +  + ]:         534 :         for (c = 0; c < ncolumns; c++)
     886                 :             :         {
     887         [ +  + ]:         273 :             if (!PQgetisnull(result, r, c))
     888                 :             :             {
     889                 :         269 :                 const char *query = PQgetvalue(result, r, c);
     890                 :             : 
     891                 :             :                 /* Abandon execution if cancel_pressed */
     892         [ -  + ]:         269 :                 if (cancel_pressed)
     893                 :           0 :                     goto loop_exit;
     894                 :             : 
     895                 :             :                 /*
     896                 :             :                  * ECHO_ALL mode should echo these queries, but SendQuery
     897                 :             :                  * assumes that MainLoop did that, so we have to do it here.
     898                 :             :                  */
     899   [ +  +  +  - ]:         269 :                 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
     900                 :             :                 {
     901                 :         264 :                     puts(query);
     902                 :         264 :                     fflush(stdout);
     903                 :             :                 }
     904                 :             : 
     905         [ +  + ]:         269 :                 if (!SendQuery(query, -1))
     906                 :             :                 {
     907                 :             :                     /* Error - abandon execution if ON_ERROR_STOP */
     908                 :           4 :                     success = false;
     909         [ -  + ]:           4 :                     if (pset.on_error_stop)
     910                 :           0 :                         goto loop_exit;
     911                 :             :                 }
     912                 :             :             }
     913                 :             :         }
     914                 :             :     }
     915                 :             : 
     916                 :          29 : loop_exit:
     917                 :             : 
     918                 :             :     /*
     919                 :             :      * Restore state.  We know gexec_flag was on, else we'd not be here. (We
     920                 :             :      * also know it'll get turned off at end of command, but that's not ours
     921                 :             :      * to do here.)
     922                 :             :      */
     923                 :          29 :     pset.gexec_flag = true;
     924                 :             : 
     925                 :             :     /* Return true if all queries were successful */
     926                 :          29 :     return success;
     927                 :             : }
     928                 :             : 
     929                 :             : 
     930                 :             : /*
     931                 :             :  * Marshal the COPY data.  Either path will get the
     932                 :             :  * connection out of its COPY state, then call PQresultStatus()
     933                 :             :  * once and report any error.  Return whether all was ok.
     934                 :             :  *
     935                 :             :  * For COPY OUT, direct the output to copystream, or discard if that's NULL.
     936                 :             :  * For COPY IN, read from copystream (which mustn't be NULL).
     937                 :             :  *
     938                 :             :  * Update *resultp if further processing is necessary; set to NULL otherwise.
     939                 :             :  * Return a result when queryFout can safely output a result status: on COPY
     940                 :             :  * IN, or on COPY OUT if written to something other than pset.queryFout.
     941                 :             :  * Returning NULL prevents the command status from being printed, which we
     942                 :             :  * want if the status line doesn't get taken as part of the COPY data.
     943                 :             :  */
     944                 :             : static bool
     945                 :        1144 : HandleCopyResult(PGresult **resultp, FILE *copystream)
     946                 :             : {
     947                 :             :     bool        success;
     948                 :             :     PGresult   *copy_result;
     949                 :        1144 :     ExecStatusType result_status = PQresultStatus(*resultp);
     950                 :             : 
     951                 :             :     Assert(result_status == PGRES_COPY_OUT ||
     952                 :             :            result_status == PGRES_COPY_IN);
     953                 :             : 
     954                 :        1144 :     SetCancelConn(pset.db);
     955                 :             : 
     956         [ +  + ]:        1144 :     if (result_status == PGRES_COPY_OUT)
     957                 :             :     {
     958                 :         499 :         success = handleCopyOut(pset.db,
     959                 :             :                                 copystream,
     960                 :             :                                 &copy_result)
     961   [ +  +  +  - ]:         499 :             && (copystream != NULL);
     962                 :             : 
     963                 :             :         /*
     964                 :             :          * Suppress status printing if the report would go to the same place
     965                 :             :          * as the COPY data just went.  Note this doesn't prevent error
     966                 :             :          * reporting, since handleCopyOut did that.
     967                 :             :          */
     968         [ +  + ]:         499 :         if (copystream == pset.queryFout)
     969                 :             :         {
     970                 :         482 :             PQclear(copy_result);
     971                 :         482 :             copy_result = NULL;
     972                 :             :         }
     973                 :             :     }
     974                 :             :     else
     975                 :             :     {
     976                 :             :         /* COPY IN */
     977                 :             :         Assert(copystream);
     978                 :         645 :         success = handleCopyIn(pset.db,
     979                 :             :                                copystream,
     980                 :         645 :                                PQbinaryTuples(*resultp),
     981                 :             :                                &copy_result);
     982                 :             :     }
     983                 :        1144 :     ResetCancelConn();
     984                 :             : 
     985                 :             :     /*
     986                 :             :      * Replace the PGRES_COPY_OUT/IN result with COPY command's exit status,
     987                 :             :      * or with NULL if we want to suppress printing anything.
     988                 :             :      */
     989                 :        1144 :     PQclear(*resultp);
     990                 :        1144 :     *resultp = copy_result;
     991                 :             : 
     992                 :        1144 :     return success;
     993                 :             : }
     994                 :             : 
     995                 :             : /*
     996                 :             :  * PrintQueryStatus: report command status as required
     997                 :             :  */
     998                 :             : static void
     999                 :      222564 : PrintQueryStatus(PGresult *result, FILE *printQueryFout)
    1000                 :             : {
    1001                 :             :     char        buf[16];
    1002                 :      222564 :     const char *cmdstatus = PQcmdStatus(result);
    1003         [ +  - ]:      222564 :     FILE       *fout = printQueryFout ? printQueryFout : pset.queryFout;
    1004                 :             : 
    1005                 :             :     /* Do nothing if it's a TUPLES_OK result that isn't from RETURNING */
    1006         [ +  + ]:      222564 :     if (PQresultStatus(result) == PGRES_TUPLES_OK)
    1007                 :             :     {
    1008         [ +  + ]:       96602 :         if (!(strncmp(cmdstatus, "INSERT", 6) == 0 ||
    1009         [ +  + ]:       96068 :               strncmp(cmdstatus, "UPDATE", 6) == 0 ||
    1010         [ +  + ]:       95713 :               strncmp(cmdstatus, "DELETE", 6) == 0 ||
    1011         [ +  + ]:       95561 :               strncmp(cmdstatus, "MERGE", 5) == 0))
    1012                 :       95449 :             return;
    1013                 :             :     }
    1014                 :             : 
    1015         [ +  + ]:      127115 :     if (!pset.quiet)
    1016                 :             :     {
    1017         [ -  + ]:         505 :         if (pset.popt.topt.format == PRINT_HTML)
    1018                 :             :         {
    1019                 :           0 :             fputs("<p>", fout);
    1020                 :           0 :             html_escaped_print(cmdstatus, fout);
    1021                 :           0 :             fputs("</p>\n", fout);
    1022                 :             :         }
    1023                 :             :         else
    1024                 :         505 :             fprintf(fout, "%s\n", cmdstatus);
    1025                 :         505 :         fflush(fout);
    1026                 :             :     }
    1027                 :             : 
    1028         [ -  + ]:      127115 :     if (pset.logfile)
    1029                 :           0 :         fprintf(pset.logfile, "%s\n", cmdstatus);
    1030                 :             : 
    1031                 :      127115 :     snprintf(buf, sizeof(buf), "%u", PQoidValue(result));
    1032                 :      127115 :     SetVariable(pset.vars, "LASTOID", buf);
    1033                 :             : }
    1034                 :             : 
    1035                 :             : 
    1036                 :             : /*
    1037                 :             :  * PrintQueryResult: print out (or store or execute) query result as required
    1038                 :             :  *
    1039                 :             :  * last is true if this is the last result of a command string.
    1040                 :             :  * opt and printQueryFout are defined as for PrintQueryTuples.
    1041                 :             :  * printStatusFout is where to send command status; NULL means pset.queryFout.
    1042                 :             :  *
    1043                 :             :  * Returns true if the query executed successfully, false otherwise.
    1044                 :             :  */
    1045                 :             : static bool
    1046                 :      223205 : PrintQueryResult(PGresult *result, bool last,
    1047                 :             :                  const printQueryOpt *opt, FILE *printQueryFout,
    1048                 :             :                  FILE *printStatusFout)
    1049                 :             : {
    1050                 :             :     bool        success;
    1051                 :             : 
    1052         [ -  + ]:      223205 :     if (!result)
    1053                 :           0 :         return false;
    1054                 :             : 
    1055   [ +  +  +  -  :      223205 :     switch (PQresultStatus(result))
                   -  - ]
    1056                 :             :     {
    1057                 :       96571 :         case PGRES_TUPLES_OK:
    1058                 :             :             /* store or execute or print the data ... */
    1059   [ +  +  +  + ]:       96571 :             if (last && pset.gset_prefix)
    1060                 :         597 :                 success = StoreQueryTuple(result);
    1061   [ +  +  +  + ]:       95974 :             else if (last && pset.gexec_flag)
    1062                 :          29 :                 success = ExecQueryTuples(result);
    1063   [ +  +  +  + ]:       95945 :             else if (last && pset.crosstab_flag)
    1064                 :          96 :                 success = PrintResultInCrosstab(result);
    1065   [ +  +  +  + ]:       95849 :             else if (last || pset.show_all_results)
    1066                 :       95840 :                 success = PrintQueryTuples(result, opt, printQueryFout);
    1067                 :             :             else
    1068                 :           9 :                 success = true;
    1069                 :             : 
    1070                 :             :             /*
    1071                 :             :              * If it's INSERT/UPDATE/DELETE/MERGE RETURNING, also print
    1072                 :             :              * status.
    1073                 :             :              */
    1074   [ +  +  +  + ]:       96571 :             if (last || pset.show_all_results)
    1075                 :       96562 :                 PrintQueryStatus(result, printStatusFout);
    1076                 :             : 
    1077                 :       96571 :             break;
    1078                 :             : 
    1079                 :      125962 :         case PGRES_COMMAND_OK:
    1080   [ +  +  +  - ]:      125962 :             if (last || pset.show_all_results)
    1081                 :      125962 :                 PrintQueryStatus(result, printStatusFout);
    1082                 :      125962 :             success = true;
    1083                 :      125962 :             break;
    1084                 :             : 
    1085                 :         672 :         case PGRES_EMPTY_QUERY:
    1086                 :         672 :             success = true;
    1087                 :         672 :             break;
    1088                 :             : 
    1089                 :           0 :         case PGRES_COPY_OUT:
    1090                 :             :         case PGRES_COPY_IN:
    1091                 :             :             /* nothing to do here: already processed */
    1092                 :           0 :             success = true;
    1093                 :           0 :             break;
    1094                 :             : 
    1095                 :           0 :         case PGRES_PIPELINE_ABORTED:
    1096                 :             :         case PGRES_BAD_RESPONSE:
    1097                 :             :         case PGRES_NONFATAL_ERROR:
    1098                 :             :         case PGRES_FATAL_ERROR:
    1099                 :           0 :             success = false;
    1100                 :           0 :             break;
    1101                 :             : 
    1102                 :           0 :         default:
    1103                 :           0 :             success = false;
    1104                 :           0 :             pg_log_error("unexpected PQresultStatus: %d",
    1105                 :             :                          PQresultStatus(result));
    1106                 :           0 :             break;
    1107                 :             :     }
    1108                 :             : 
    1109                 :      223205 :     return success;
    1110                 :             : }
    1111                 :             : 
    1112                 :             : /*
    1113                 :             :  * SendQuery: send the query string to the backend
    1114                 :             :  * (and print out result)
    1115                 :             :  *
    1116                 :             :  * Note: This is the "front door" way to send a query. That is, use it to
    1117                 :             :  * send queries actually entered by the user. These queries will be subject to
    1118                 :             :  * single step mode.
    1119                 :             :  * To send "back door" queries (generated by slash commands, etc.) in a
    1120                 :             :  * controlled way, use PSQLexec().
    1121                 :             :  *
    1122                 :             :  * In the most common case, the caller can determine whether the query
    1123                 :             :  * includes any COPY FROM STDIN command(s); if so, pass the count of them.
    1124                 :             :  * Otherwise pass num_copy_from_stdin == -1 and we'll compute it locally.
    1125                 :             :  *
    1126                 :             :  * Returns true if the query executed successfully, false otherwise.
    1127                 :             :  */
    1128                 :             : bool
    1129                 :      253824 : SendQuery(const char *query, int num_copy_from_stdin)
    1130                 :             : {
    1131                 :      253824 :     bool        timing = pset.timing;
    1132                 :             :     PGTransactionStatusType transaction_status;
    1133                 :      253824 :     double      elapsed_msec = 0;
    1134                 :      253824 :     bool        OK = false;
    1135                 :             :     int         i;
    1136                 :      253824 :     bool        on_error_rollback_savepoint = false;
    1137                 :      253824 :     bool        svpt_gone = false;
    1138                 :             : 
    1139         [ -  + ]:      253824 :     if (!pset.db)
    1140                 :             :     {
    1141                 :           0 :         pg_log_error("You are currently not connected to a database.");
    1142                 :           0 :         goto sendquery_cleanup;
    1143                 :             :     }
    1144                 :             : 
    1145         [ -  + ]:      253824 :     if (pset.singlestep)
    1146                 :             :     {
    1147                 :             :         char        buf[3];
    1148                 :             : 
    1149                 :           0 :         fflush(stderr);
    1150                 :           0 :         printf(_("/**(Single step mode: verify command)******************************************/\n"
    1151                 :             :                  "%s\n"
    1152                 :             :                  "/**(press return to proceed or enter x and return to cancel)*******************/\n"),
    1153                 :             :                query);
    1154                 :           0 :         fflush(stdout);
    1155         [ #  # ]:           0 :         if (fgets(buf, sizeof(buf), stdin) != NULL)
    1156         [ #  # ]:           0 :             if (buf[0] == 'x')
    1157                 :           0 :                 goto sendquery_cleanup;
    1158         [ #  # ]:           0 :         if (cancel_pressed)
    1159                 :           0 :             goto sendquery_cleanup;
    1160                 :             :     }
    1161         [ +  + ]:      253824 :     else if (pset.echo == PSQL_ECHO_QUERIES)
    1162                 :             :     {
    1163                 :          82 :         puts(query);
    1164                 :          82 :         fflush(stdout);
    1165                 :             :     }
    1166                 :             : 
    1167         [ -  + ]:      253824 :     if (pset.logfile)
    1168                 :             :     {
    1169                 :           0 :         fprintf(pset.logfile,
    1170                 :           0 :                 _("/******** QUERY *********/\n"
    1171                 :             :                   "%s\n"
    1172                 :             :                   "/************************/\n\n"), query);
    1173                 :           0 :         fflush(pset.logfile);
    1174                 :             :     }
    1175                 :             : 
    1176                 :      253824 :     SetCancelConn(pset.db);
    1177                 :             : 
    1178                 :      253824 :     transaction_status = PQtransactionStatus(pset.db);
    1179                 :             : 
    1180         [ +  + ]:      253824 :     if (transaction_status == PQTRANS_IDLE &&
    1181         [ +  + ]:      224902 :         !pset.autocommit &&
    1182         [ +  + ]:          56 :         !command_no_begin(query))
    1183                 :             :     {
    1184                 :             :         PGresult   *result;
    1185                 :             : 
    1186                 :          48 :         result = PQexec(pset.db, "BEGIN");
    1187         [ -  + ]:          48 :         if (PQresultStatus(result) != PGRES_COMMAND_OK)
    1188                 :             :         {
    1189                 :           0 :             pg_log_info("%s", PQerrorMessage(pset.db));
    1190                 :           0 :             ClearOrSaveResult(result);
    1191                 :           0 :             goto sendquery_cleanup;
    1192                 :             :         }
    1193                 :          48 :         ClearOrSaveResult(result);
    1194                 :          48 :         transaction_status = PQtransactionStatus(pset.db);
    1195                 :             :     }
    1196                 :             : 
    1197         [ +  + ]:      253824 :     if (transaction_status == PQTRANS_INTRANS &&
    1198         [ +  + ]:       27321 :         pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
    1199         [ +  - ]:         104 :         (pset.cur_cmd_interactive ||
    1200         [ +  - ]:         104 :          pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
    1201                 :             :     {
    1202                 :             :         PGresult   *result;
    1203                 :             : 
    1204                 :         104 :         result = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
    1205         [ -  + ]:         104 :         if (PQresultStatus(result) != PGRES_COMMAND_OK)
    1206                 :             :         {
    1207                 :           0 :             pg_log_info("%s", PQerrorMessage(pset.db));
    1208                 :           0 :             ClearOrSaveResult(result);
    1209                 :           0 :             goto sendquery_cleanup;
    1210                 :             :         }
    1211                 :         104 :         ClearOrSaveResult(result);
    1212                 :         104 :         on_error_rollback_savepoint = true;
    1213                 :             :     }
    1214                 :             : 
    1215         [ +  + ]:      253824 :     if (pset.gdesc_flag)
    1216                 :             :     {
    1217                 :             :         /* Describe query's result columns, without executing it */
    1218                 :          57 :         OK = DescribeQuery(query, &elapsed_msec);
    1219                 :             :     }
    1220                 :             :     else
    1221                 :             :     {
    1222                 :             :         /* Default fetch-and-print mode */
    1223                 :      253767 :         OK = (ExecQueryAndProcessResults(query,
    1224                 :             :                                          &elapsed_msec, &svpt_gone,
    1225                 :             :                                          num_copy_from_stdin,
    1226                 :             :                                          false, 0,
    1227                 :             :                                          NULL, NULL) > 0);
    1228                 :             :     }
    1229                 :             : 
    1230   [ +  +  +  + ]:      253810 :     if (!OK && pset.echo == PSQL_ECHO_ERRORS)
    1231                 :           4 :         pg_log_info("STATEMENT:  %s", query);
    1232                 :             : 
    1233                 :             :     /* If we made a temporary savepoint, possibly release/rollback */
    1234         [ +  + ]:      253810 :     if (on_error_rollback_savepoint)
    1235                 :             :     {
    1236                 :         104 :         const char *svptcmd = NULL;
    1237                 :             : 
    1238                 :         104 :         transaction_status = PQtransactionStatus(pset.db);
    1239                 :             : 
    1240   [ +  +  +  - ]:         104 :         switch (transaction_status)
    1241                 :             :         {
    1242                 :          28 :             case PQTRANS_INERROR:
    1243                 :             :                 /* We always rollback on an error */
    1244                 :          28 :                 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
    1245                 :          28 :                 break;
    1246                 :             : 
    1247                 :          28 :             case PQTRANS_IDLE:
    1248                 :             :                 /* If they are no longer in a transaction, then do nothing */
    1249                 :          28 :                 break;
    1250                 :             : 
    1251                 :          48 :             case PQTRANS_INTRANS:
    1252                 :             : 
    1253                 :             :                 /*
    1254                 :             :                  * Release our savepoint, but do nothing if they are messing
    1255                 :             :                  * with savepoints themselves
    1256                 :             :                  */
    1257         [ +  + ]:          48 :                 if (!svpt_gone)
    1258                 :          44 :                     svptcmd = "RELEASE pg_psql_temporary_savepoint";
    1259                 :          48 :                 break;
    1260                 :             : 
    1261                 :           0 :             case PQTRANS_ACTIVE:
    1262                 :             :             case PQTRANS_UNKNOWN:
    1263                 :             :             default:
    1264                 :           0 :                 OK = false;
    1265                 :             :                 /* PQTRANS_UNKNOWN is expected given a broken connection. */
    1266   [ #  #  #  # ]:           0 :                 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
    1267                 :           0 :                     pg_log_error("unexpected transaction status (%d)",
    1268                 :             :                                  transaction_status);
    1269                 :           0 :                 break;
    1270                 :             :         }
    1271                 :             : 
    1272         [ +  + ]:         104 :         if (svptcmd)
    1273                 :             :         {
    1274                 :             :             PGresult   *svptres;
    1275                 :             : 
    1276                 :          72 :             svptres = PQexec(pset.db, svptcmd);
    1277         [ -  + ]:          72 :             if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
    1278                 :             :             {
    1279                 :           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
    1280                 :           0 :                 ClearOrSaveResult(svptres);
    1281                 :           0 :                 OK = false;
    1282                 :             : 
    1283                 :           0 :                 goto sendquery_cleanup;
    1284                 :             :             }
    1285                 :          72 :             PQclear(svptres);
    1286                 :             :         }
    1287                 :             :     }
    1288                 :             : 
    1289                 :             :     /* Possible microtiming output */
    1290         [ +  + ]:      253810 :     if (timing)
    1291                 :           2 :         PrintTiming(elapsed_msec);
    1292                 :             : 
    1293                 :             :     /* check for events that may occur during query execution */
    1294                 :             : 
    1295   [ +  +  +  - ]:      253836 :     if (pset.encoding != PQclientEncoding(pset.db) &&
    1296                 :          26 :         PQclientEncoding(pset.db) >= 0)
    1297                 :             :     {
    1298                 :             :         /* track effects of SET CLIENT_ENCODING */
    1299                 :          26 :         pset.encoding = PQclientEncoding(pset.db);
    1300                 :          26 :         pset.popt.topt.encoding = pset.encoding;
    1301                 :          26 :         SetVariable(pset.vars, "ENCODING",
    1302                 :             :                     pg_encoding_to_char(pset.encoding));
    1303                 :             :     }
    1304                 :             : 
    1305                 :      253810 :     PrintNotifications();
    1306                 :             : 
    1307                 :             :     /* perform cleanup that should occur after any attempted query */
    1308                 :             : 
    1309                 :      253810 : sendquery_cleanup:
    1310                 :             : 
    1311                 :             :     /* global cancellation reset */
    1312                 :      253810 :     ResetCancelConn();
    1313                 :             : 
    1314                 :             :     /* reset \g's output-to-filename trigger */
    1315         [ +  + ]:      253810 :     if (pset.gfname)
    1316                 :             :     {
    1317                 :          20 :         free(pset.gfname);
    1318                 :          20 :         pset.gfname = NULL;
    1319                 :             :     }
    1320                 :             : 
    1321                 :             :     /* restore print settings if \g changed them */
    1322         [ +  + ]:      253810 :     if (pset.gsavepopt)
    1323                 :             :     {
    1324                 :         110 :         restorePsetInfo(&pset.popt, pset.gsavepopt);
    1325                 :         110 :         pset.gsavepopt = NULL;
    1326                 :             :     }
    1327                 :             : 
    1328                 :             :     /* clean up after extended protocol queries */
    1329                 :      253810 :     clean_extended_state();
    1330                 :             : 
    1331                 :             :     /* reset \gset trigger */
    1332         [ +  + ]:      253810 :     if (pset.gset_prefix)
    1333                 :             :     {
    1334                 :         597 :         free(pset.gset_prefix);
    1335                 :         597 :         pset.gset_prefix = NULL;
    1336                 :             :     }
    1337                 :             : 
    1338                 :             :     /* reset \gdesc trigger */
    1339                 :      253810 :     pset.gdesc_flag = false;
    1340                 :             : 
    1341                 :             :     /* reset \gexec trigger */
    1342                 :      253810 :     pset.gexec_flag = false;
    1343                 :             : 
    1344                 :             :     /* reset \crosstabview trigger */
    1345                 :      253810 :     pset.crosstab_flag = false;
    1346         [ +  + ]:     1269050 :     for (i = 0; i < lengthof(pset.ctv_args); i++)
    1347                 :             :     {
    1348                 :     1015240 :         pg_free(pset.ctv_args[i]);
    1349                 :     1015240 :         pset.ctv_args[i] = NULL;
    1350                 :             :     }
    1351                 :             : 
    1352                 :      253810 :     return OK;
    1353                 :             : }
    1354                 :             : 
    1355                 :             : 
    1356                 :             : /*
    1357                 :             :  * DescribeQuery: describe the result columns of a query, without executing it
    1358                 :             :  *
    1359                 :             :  * Returns true if the operation executed successfully, false otherwise.
    1360                 :             :  *
    1361                 :             :  * If pset.timing is on, total query time (exclusive of result-printing) is
    1362                 :             :  * stored into *elapsed_msec.
    1363                 :             :  */
    1364                 :             : static bool
    1365                 :          57 : DescribeQuery(const char *query, double *elapsed_msec)
    1366                 :             : {
    1367                 :          57 :     bool        timing = pset.timing;
    1368                 :             :     PGresult   *result;
    1369                 :             :     bool        OK;
    1370                 :             :     instr_time  before,
    1371                 :             :                 after;
    1372                 :             : 
    1373                 :          57 :     *elapsed_msec = 0;
    1374                 :             : 
    1375         [ -  + ]:          57 :     if (timing)
    1376                 :           0 :         INSTR_TIME_SET_CURRENT(before);
    1377                 :             :     else
    1378                 :          57 :         INSTR_TIME_SET_ZERO(before);
    1379                 :             : 
    1380                 :             :     /*
    1381                 :             :      * To parse the query but not execute it, we prepare it, using the unnamed
    1382                 :             :      * prepared statement.  This is invisible to psql users, since there's no
    1383                 :             :      * way to access the unnamed prepared statement from psql user space. The
    1384                 :             :      * next Parse or Query protocol message would overwrite the statement
    1385                 :             :      * anyway.  (So there's no great need to clear it when done, which is a
    1386                 :             :      * good thing because libpq provides no easy way to do that.)
    1387                 :             :      */
    1388                 :          57 :     result = PQprepare(pset.db, "", query, 0, NULL);
    1389         [ +  + ]:          57 :     if (PQresultStatus(result) != PGRES_COMMAND_OK)
    1390                 :             :     {
    1391                 :          21 :         pg_log_info("%s", PQerrorMessage(pset.db));
    1392                 :          21 :         SetResultVariables(result, false);
    1393                 :          21 :         ClearOrSaveResult(result);
    1394                 :          21 :         return false;
    1395                 :             :     }
    1396                 :          36 :     PQclear(result);
    1397                 :             : 
    1398                 :          36 :     result = PQdescribePrepared(pset.db, "");
    1399   [ +  -  +  - ]:          72 :     OK = AcceptResult(result, true) &&
    1400                 :          36 :         (PQresultStatus(result) == PGRES_COMMAND_OK);
    1401   [ +  -  +  - ]:          36 :     if (OK && result)
    1402                 :             :     {
    1403         [ +  + ]:          36 :         if (PQnfields(result) > 0)
    1404                 :             :         {
    1405                 :             :             PQExpBufferData buf;
    1406                 :             :             int         i;
    1407                 :             : 
    1408                 :          24 :             initPQExpBuffer(&buf);
    1409                 :             : 
    1410                 :          24 :             printfPQExpBuffer(&buf,
    1411                 :             :                               "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
    1412                 :             :                               "FROM (VALUES ",
    1413                 :             :                               gettext_noop("Column"),
    1414                 :             :                               gettext_noop("Type"));
    1415                 :             : 
    1416         [ +  + ]:         108 :             for (i = 0; i < PQnfields(result); i++)
    1417                 :             :             {
    1418                 :             :                 const char *name;
    1419                 :             :                 char       *escname;
    1420                 :             : 
    1421         [ +  + ]:          84 :                 if (i > 0)
    1422                 :          60 :                     appendPQExpBufferChar(&buf, ',');
    1423                 :             : 
    1424                 :          84 :                 name = PQfname(result, i);
    1425                 :          84 :                 escname = PQescapeLiteral(pset.db, name, strlen(name));
    1426                 :             : 
    1427         [ -  + ]:          84 :                 if (escname == NULL)
    1428                 :             :                 {
    1429                 :           0 :                     pg_log_info("%s", PQerrorMessage(pset.db));
    1430                 :           0 :                     PQclear(result);
    1431                 :           0 :                     termPQExpBuffer(&buf);
    1432                 :           0 :                     return false;
    1433                 :             :                 }
    1434                 :             : 
    1435                 :          84 :                 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
    1436                 :             :                                   escname,
    1437                 :             :                                   PQftype(result, i),
    1438                 :             :                                   PQfmod(result, i));
    1439                 :             : 
    1440                 :          84 :                 PQfreemem(escname);
    1441                 :             :             }
    1442                 :             : 
    1443                 :          24 :             appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
    1444                 :          24 :             PQclear(result);
    1445                 :             : 
    1446                 :          24 :             result = PQexec(pset.db, buf.data);
    1447                 :          24 :             OK = AcceptResult(result, true);
    1448                 :             : 
    1449         [ -  + ]:          24 :             if (timing)
    1450                 :             :             {
    1451                 :           0 :                 INSTR_TIME_SET_CURRENT(after);
    1452                 :           0 :                 INSTR_TIME_SUBTRACT(after, before);
    1453                 :           0 :                 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
    1454                 :             :             }
    1455                 :             : 
    1456   [ +  -  +  - ]:          24 :             if (OK && result)
    1457                 :          24 :                 OK = PrintQueryResult(result, true, NULL, NULL, NULL);
    1458                 :             : 
    1459                 :          24 :             termPQExpBuffer(&buf);
    1460                 :             :         }
    1461                 :             :         else
    1462                 :          12 :             fprintf(pset.queryFout,
    1463                 :          12 :                     _("The command has no result, or the result has no columns.\n"));
    1464                 :             :     }
    1465                 :             : 
    1466                 :          36 :     SetResultVariables(result, OK);
    1467                 :          36 :     ClearOrSaveResult(result);
    1468                 :             : 
    1469                 :          36 :     return OK;
    1470                 :             : }
    1471                 :             : 
    1472                 :             : /*
    1473                 :             :  * Read and discard all results in an aborted pipeline.
    1474                 :             :  *
    1475                 :             :  * If a synchronisation point is found, we can stop discarding results as
    1476                 :             :  * the pipeline will switch back to a clean state.  If no synchronisation
    1477                 :             :  * point is available, we need to stop when there are no more pending
    1478                 :             :  * results, otherwise, calling PQgetResult() would block.
    1479                 :             :  */
    1480                 :             : static PGresult *
    1481                 :         108 : discardAbortedPipelineResults(void)
    1482                 :             : {
    1483                 :             :     for (;;)
    1484                 :         196 :     {
    1485                 :         304 :         PGresult   *res = PQgetResult(pset.db);
    1486                 :         304 :         ExecStatusType result_status = PQresultStatus(res);
    1487                 :             : 
    1488         [ +  + ]:         304 :         if (result_status == PGRES_PIPELINE_SYNC)
    1489                 :             :         {
    1490                 :             :             /*
    1491                 :             :              * Found a synchronisation point.  The sync counter is decremented
    1492                 :             :              * by the caller.
    1493                 :             :              */
    1494                 :          52 :             return res;
    1495                 :             :         }
    1496   [ +  +  -  + ]:         252 :         else if (res != NULL && result_status == PGRES_FATAL_ERROR)
    1497                 :             :         {
    1498                 :             :             /*
    1499                 :             :              * Found a FATAL error sent by the backend, and we cannot recover
    1500                 :             :              * from this state.  Instead, return the last result and let the
    1501                 :             :              * outer loop handle it.
    1502                 :             :              */
    1503                 :             :             PGresult   *fatal_res PG_USED_FOR_ASSERTS_ONLY;
    1504                 :             : 
    1505                 :             :             /*
    1506                 :             :              * Fetch result to consume the end of the current query being
    1507                 :             :              * processed.
    1508                 :             :              */
    1509                 :           0 :             fatal_res = PQgetResult(pset.db);
    1510                 :             :             Assert(fatal_res == NULL);
    1511                 :           0 :             return res;
    1512                 :             :         }
    1513         [ +  + ]:         252 :         else if (res == NULL)
    1514                 :             :         {
    1515                 :             :             /*
    1516                 :             :              * A query was processed, decrement the counters.
    1517                 :             :              *
    1518                 :             :              * It is possible to get here with available_results == 0 when an
    1519                 :             :              * error is generated by the Sync message processing itself. Such
    1520                 :             :              * errors are not counted in available_results because they are
    1521                 :             :              * not associated with a piped command.  In that case, skip the
    1522                 :             :              * counter decrements and continue to find the Sync result.
    1523                 :             :              *
    1524                 :             :              * If the connection has been lost, there will never be any more
    1525                 :             :              * results to read, so bail out.
    1526                 :             :              */
    1527         [ -  + ]:         180 :             if (!ConnectionUp())
    1528                 :           0 :                 return NULL;
    1529         [ +  + ]:         180 :             if (pset.available_results > 0)
    1530                 :         152 :                 pset.available_results--;
    1531         [ +  - ]:         180 :             if (pset.requested_results > 0)
    1532                 :         180 :                 pset.requested_results--;
    1533                 :             :         }
    1534                 :             : 
    1535         [ +  + ]:         252 :         if (pset.requested_results == 0)
    1536                 :             :         {
    1537                 :             :             /* We have read all the requested results, leave */
    1538                 :          56 :             return res;
    1539                 :             :         }
    1540                 :             : 
    1541   [ +  +  -  + ]:         196 :         if (pset.available_results == 0 && pset.piped_syncs == 0)
    1542                 :             :         {
    1543                 :             :             /*
    1544                 :             :              * There are no more results to get and there is no
    1545                 :             :              * synchronisation point to stop at.  This will leave the pipeline
    1546                 :             :              * in an aborted state.
    1547                 :             :              */
    1548                 :           0 :             return res;
    1549                 :             :         }
    1550                 :             : 
    1551                 :             :         /*
    1552                 :             :          * An aborted pipeline will have either NULL results or results in an
    1553                 :             :          * PGRES_PIPELINE_ABORTED status.
    1554                 :             :          */
    1555                 :             :         Assert(res == NULL || result_status == PGRES_PIPELINE_ABORTED);
    1556                 :         196 :         PQclear(res);
    1557                 :             :     }
    1558                 :             : }
    1559                 :             : 
    1560                 :             : /*
    1561                 :             :  * ExecQueryAndProcessResults: utility function for use by SendQuery()
    1562                 :             :  * and PSQLexecWatch().
    1563                 :             :  *
    1564                 :             :  * Sends query and cycles through PGresult objects.
    1565                 :             :  *
    1566                 :             :  * If our command string contained a COPY FROM STDIN or COPY TO STDOUT, the
    1567                 :             :  * PGresult associated with these commands must be processed by providing an
    1568                 :             :  * input or output stream.  In that event, we'll marshal data for the COPY.
    1569                 :             :  *
    1570                 :             :  * For other commands, the results are processed normally, depending on their
    1571                 :             :  * status and the status of a pipeline.
    1572                 :             :  *
    1573                 :             :  * When invoked from \watch, is_watch is true and min_rows is the value
    1574                 :             :  * of that option, or 0 if it wasn't set.
    1575                 :             :  *
    1576                 :             :  * Returns 1 on complete success, 0 on interrupt and -1 or errors.  Possible
    1577                 :             :  * failure modes include purely client-side problems; check the transaction
    1578                 :             :  * status for the server-side opinion.
    1579                 :             :  *
    1580                 :             :  * Note that on a combined query, failure does not mean that nothing was
    1581                 :             :  * committed.
    1582                 :             :  */
    1583                 :             : static int
    1584                 :      253892 : ExecQueryAndProcessResults(const char *query,
    1585                 :             :                            double *elapsed_msec, bool *svpt_gone_p,
    1586                 :             :                            int num_copy_from_stdin,
    1587                 :             :                            bool is_watch, int min_rows,
    1588                 :             :                            const printQueryOpt *opt, FILE *printQueryFout)
    1589                 :             : {
    1590                 :      253892 :     bool        timing = pset.timing;
    1591                 :      253892 :     bool        success = false;
    1592                 :      253892 :     bool        return_early = false;
    1593                 :      253892 :     bool        end_pipeline = false;
    1594                 :             :     instr_time  before,
    1595                 :             :                 after;
    1596                 :             :     PGresult   *result;
    1597                 :      253892 :     FILE       *gfile_fout = NULL;
    1598                 :      253892 :     bool        gfile_is_pipe = false;
    1599                 :             : 
    1600         [ +  + ]:      253892 :     if (timing)
    1601                 :           2 :         INSTR_TIME_SET_CURRENT(before);
    1602                 :             :     else
    1603                 :      253890 :         INSTR_TIME_SET_ZERO(before);
    1604                 :             : 
    1605   [ +  +  +  +  :      253892 :     switch (pset.send_mode)
          +  +  +  +  +  
                +  +  - ]
    1606                 :             :     {
    1607                 :          25 :         case PSQL_SEND_EXTENDED_CLOSE:
    1608                 :          25 :             success = PQsendClosePrepared(pset.db, pset.stmtName);
    1609   [ +  -  +  + ]:          25 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1610                 :          12 :                 pset.piped_commands++;
    1611                 :          25 :             break;
    1612                 :          67 :         case PSQL_SEND_EXTENDED_PARSE:
    1613                 :          67 :             success = PQsendPrepare(pset.db, pset.stmtName, query, 0, NULL);
    1614   [ +  -  +  + ]:          67 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1615                 :          44 :                 pset.piped_commands++;
    1616                 :          67 :             break;
    1617                 :         492 :         case PSQL_SEND_EXTENDED_QUERY_PARAMS:
    1618                 :             :             Assert(pset.stmtName == NULL);
    1619                 :         984 :             success = PQsendQueryParams(pset.db, query,
    1620                 :             :                                         pset.bind_nparams, NULL,
    1621                 :         492 :                                         (const char *const *) pset.bind_params,
    1622                 :             :                                         NULL, NULL, 0);
    1623   [ +  -  +  + ]:         492 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1624                 :         433 :                 pset.piped_commands++;
    1625                 :         492 :             break;
    1626                 :          80 :         case PSQL_SEND_EXTENDED_QUERY_PREPARED:
    1627                 :             :             Assert(pset.stmtName != NULL);
    1628                 :         160 :             success = PQsendQueryPrepared(pset.db, pset.stmtName,
    1629                 :             :                                           pset.bind_nparams,
    1630                 :          80 :                                           (const char *const *) pset.bind_params,
    1631                 :             :                                           NULL, NULL, 0);
    1632   [ +  -  +  + ]:          80 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1633                 :          32 :                 pset.piped_commands++;
    1634                 :          80 :             break;
    1635                 :         225 :         case PSQL_SEND_START_PIPELINE_MODE:
    1636                 :         225 :             success = PQenterPipelineMode(pset.db);
    1637                 :         225 :             break;
    1638                 :         225 :         case PSQL_SEND_END_PIPELINE_MODE:
    1639                 :         225 :             success = PQpipelineSync(pset.db);
    1640   [ +  +  +  - ]:         225 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1641                 :             :             {
    1642                 :             :                 /*
    1643                 :             :                  * End of the pipeline, all queued commands need to be
    1644                 :             :                  * processed.
    1645                 :             :                  */
    1646                 :         221 :                 end_pipeline = true;
    1647                 :         221 :                 pset.piped_syncs++;
    1648                 :             : 
    1649                 :             :                 /*
    1650                 :             :                  * The server will send a ReadyForQuery after a Sync is
    1651                 :             :                  * processed, flushing all the results back to the client.
    1652                 :             :                  */
    1653                 :         221 :                 pset.available_results += pset.piped_commands;
    1654                 :         221 :                 pset.piped_commands = 0;
    1655                 :             : 
    1656                 :             :                 /* We want to read all results */
    1657                 :         221 :                 pset.requested_results = pset.available_results + pset.piped_syncs;
    1658                 :             :             }
    1659                 :         225 :             break;
    1660                 :          95 :         case PSQL_SEND_PIPELINE_SYNC:
    1661                 :          95 :             success = PQsendPipelineSync(pset.db);
    1662   [ +  -  +  - ]:          95 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1663                 :             :             {
    1664                 :          95 :                 pset.piped_syncs++;
    1665                 :             : 
    1666                 :             :                 /*
    1667                 :             :                  * The server will send a ReadyForQuery after a Sync is
    1668                 :             :                  * processed, flushing all the results back to the client.
    1669                 :             :                  */
    1670                 :          95 :                 pset.available_results += pset.piped_commands;
    1671                 :          95 :                 pset.piped_commands = 0;
    1672                 :             :             }
    1673                 :          95 :             break;
    1674                 :          12 :         case PSQL_SEND_FLUSH:
    1675                 :          12 :             success = PQflush(pset.db);
    1676                 :          12 :             break;
    1677                 :          44 :         case PSQL_SEND_FLUSH_REQUEST:
    1678                 :          44 :             success = PQsendFlushRequest(pset.db);
    1679   [ +  -  +  - ]:          44 :             if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1680                 :             :             {
    1681                 :             :                 /*
    1682                 :             :                  * With the flush request, all commands in the pipeline are
    1683                 :             :                  * pushed and the server will flush the results back to the
    1684                 :             :                  * client, making them available.
    1685                 :             :                  */
    1686                 :          44 :                 pset.available_results += pset.piped_commands;
    1687                 :          44 :                 pset.piped_commands = 0;
    1688                 :             :             }
    1689                 :          44 :             break;
    1690                 :         124 :         case PSQL_SEND_GET_RESULTS:
    1691   [ +  +  +  + ]:         124 :             if (pset.available_results == 0 && pset.piped_syncs == 0)
    1692                 :             :             {
    1693                 :             :                 /*
    1694                 :             :                  * If no sync or flush request were sent, PQgetResult() would
    1695                 :             :                  * block as there are no results available.  Forbid any
    1696                 :             :                  * attempt to get pending results should we try to reach this
    1697                 :             :                  * state.
    1698                 :             :                  */
    1699                 :          16 :                 pg_log_info("No pending results to get");
    1700                 :          16 :                 success = false;
    1701                 :          16 :                 pset.requested_results = 0;
    1702                 :             :             }
    1703                 :             :             else
    1704                 :             :             {
    1705                 :         108 :                 success = true;
    1706                 :             : 
    1707                 :             :                 /*
    1708                 :             :                  * Cap requested_results to the maximum number of known
    1709                 :             :                  * results.
    1710                 :             :                  */
    1711         [ +  + ]:         108 :                 if (pset.requested_results == 0 ||
    1712         [ -  + ]:          44 :                     pset.requested_results > (pset.available_results + pset.piped_syncs))
    1713                 :          64 :                     pset.requested_results = pset.available_results + pset.piped_syncs;
    1714                 :             :             }
    1715                 :         124 :             break;
    1716                 :      252503 :         case PSQL_SEND_QUERY:
    1717         [ +  + ]:      252503 :             if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1718                 :             :             {
    1719                 :          76 :                 success = PQsendQueryParams(pset.db, query,
    1720                 :             :                                             0, NULL, NULL, NULL, NULL, 0);
    1721         [ +  - ]:          76 :                 if (success)
    1722                 :          76 :                     pset.piped_commands++;
    1723                 :             :             }
    1724                 :             :             else
    1725                 :      252427 :                 success = PQsendQuery(pset.db, query);
    1726                 :      252503 :             break;
    1727                 :             :     }
    1728                 :             : 
    1729         [ +  + ]:      253892 :     if (!success)
    1730                 :             :     {
    1731                 :          32 :         const char *error = PQerrorMessage(pset.db);
    1732                 :             : 
    1733         [ +  + ]:          32 :         if (strlen(error))
    1734                 :           4 :             pg_log_info("%s", error);
    1735                 :             : 
    1736                 :          32 :         CheckConnection();
    1737                 :             : 
    1738                 :          32 :         SetPipelineVariables();
    1739                 :             : 
    1740                 :          32 :         return -1;
    1741                 :             :     }
    1742                 :             : 
    1743   [ +  +  +  -  :      507391 :     if (pset.requested_results == 0 && !end_pipeline &&
                   +  + ]
    1744                 :      253531 :         PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1745                 :             :     {
    1746                 :             :         /*
    1747                 :             :          * We are in a pipeline and have not reached the pipeline end, or
    1748                 :             :          * there was no request to read pipeline results.  Update the psql
    1749                 :             :          * variables tracking the pipeline activity and exit.
    1750                 :             :          */
    1751                 :         961 :         SetPipelineVariables();
    1752                 :         961 :         return 1;
    1753                 :             :     }
    1754                 :             : 
    1755                 :             :     /*
    1756                 :             :      * Fetch the result in chunks if FETCH_COUNT is set, except when:
    1757                 :             :      *
    1758                 :             :      * * SHOW_ALL_RESULTS is false, since that requires us to complete the
    1759                 :             :      * query before we can tell if its results should be displayed.
    1760                 :             :      *
    1761                 :             :      * * We're doing \crosstab, which likewise needs to see all the rows at
    1762                 :             :      * once.
    1763                 :             :      *
    1764                 :             :      * * We're doing \gexec: we must complete the data fetch to make the
    1765                 :             :      * connection free for issuing the resulting commands.
    1766                 :             :      *
    1767                 :             :      * * We're doing \gset: only one result row is allowed anyway.
    1768                 :             :      *
    1769                 :             :      * * We're doing \watch: users probably don't want us to force use of the
    1770                 :             :      * pager for that, plus chunking could break the min_rows check.
    1771                 :             :      */
    1772   [ +  +  +  - ]:      252899 :     if (pset.fetch_count > 0 && pset.show_all_results &&
    1773   [ +  -  +  + ]:          89 :         !pset.crosstab_flag && !pset.gexec_flag &&
    1774   [ +  +  +  - ]:          85 :         !pset.gset_prefix && !is_watch)
    1775                 :             :     {
    1776         [ +  + ]:          69 :         if (!PQsetChunkedRowsMode(pset.db, pset.fetch_count))
    1777                 :           4 :             pg_log_warning("fetching results in chunked mode failed");
    1778                 :             :     }
    1779                 :             : 
    1780                 :             :     /*
    1781                 :             :      * If SIGINT is sent while the query is processing, the interrupt will be
    1782                 :             :      * consumed.  The user's intention, though, is to cancel the entire watch
    1783                 :             :      * process, so detect a sent cancellation request and exit in this case.
    1784                 :             :      */
    1785   [ +  +  -  + ]:      252899 :     if (is_watch && cancel_pressed)
    1786                 :             :     {
    1787                 :           0 :         ClearOrSaveAllResults();
    1788                 :           0 :         return 0;
    1789                 :             :     }
    1790                 :             : 
    1791                 :             :     /*
    1792                 :             :      * If the caller didn't count the number of COPY FROM STDIN command(s) in
    1793                 :             :      * the query string, we must do so now.
    1794                 :             :      */
    1795         [ +  + ]:      252899 :     if (num_copy_from_stdin < 0)
    1796                 :             :     {
    1797                 :             :         PsqlScanState scan_state;
    1798                 :             :         PQExpBuffer query_buf;
    1799                 :             :         promptStatus_t prompt_tmp;
    1800                 :             :         PsqlScanResult scan_result;
    1801                 :             : 
    1802                 :        2209 :         scan_state = psql_scan_create(&psqlscan_callbacks);
    1803                 :        2209 :         psql_scan_setup(scan_state, query, strlen(query),
    1804                 :        2209 :                         pset.encoding, standard_strings());
    1805                 :        2209 :         query_buf = createPQExpBuffer();
    1806                 :             : 
    1807                 :             :         /*
    1808                 :             :          * A semicolon ends only one sub-command; keep scanning so that COPY
    1809                 :             :          * FROM STDIN commands past the first semicolon are counted too.  The
    1810                 :             :          * count accumulates in scan_state across the psql_scan() calls.
    1811                 :             :          */
    1812                 :             :         do
    1813                 :             :         {
    1814                 :        3035 :             scan_result = psql_scan(scan_state, query_buf, &prompt_tmp);
    1815         [ +  + ]:        3035 :         } while (scan_result == PSCAN_SEMICOLON);
    1816                 :             : 
    1817                 :             :         /*
    1818                 :             :          * We expect the result now to be PSCAN_EOL.  If it is PSCAN_BACKSLASH
    1819                 :             :          * or PSCAN_INCOMPLETE, the server will get a parse error and refuse
    1820                 :             :          * to execute any part of the command string, so don't expect any
    1821                 :             :          * PGRES_COPY_IN results.  (This will mean that we don't attempt to
    1822                 :             :          * discard any following data, but this seems consistent with the
    1823                 :             :          * general contract of psql_scan_count_copy_from_stdin, which is that
    1824                 :             :          * it only promises to count syntactically-valid COPY commands.)
    1825                 :             :          */
    1826         [ +  + ]:        2209 :         if (scan_result == PSCAN_EOL)
    1827                 :        2192 :             num_copy_from_stdin = psql_scan_count_copy_from_stdin(scan_state);
    1828                 :             :         else
    1829                 :          17 :             num_copy_from_stdin = 0;
    1830                 :             : 
    1831                 :        2209 :         destroyPQExpBuffer(query_buf);
    1832                 :        2209 :         psql_scan_destroy(scan_state);
    1833                 :             :     }
    1834                 :             : 
    1835                 :             :     /* first result */
    1836                 :      252899 :     result = PQgetResult(pset.db);
    1837   [ +  +  +  - ]:      252899 :     if (min_rows > 0 && PQntuples(result) < min_rows)
    1838                 :             :     {
    1839                 :           1 :         return_early = true;
    1840                 :             :     }
    1841                 :             : 
    1842         [ +  + ]:      507307 :     while (result != NULL)
    1843                 :             :     {
    1844                 :             :         ExecStatusType result_status;
    1845                 :      254424 :         bool        is_chunked_result = false;
    1846                 :      254424 :         PGresult   *next_result = NULL;
    1847                 :             :         bool        last;
    1848                 :             : 
    1849         [ +  + ]:      254424 :         if (!AcceptResult(result, false))
    1850                 :       30251 :         {
    1851                 :             :             /*
    1852                 :             :              * Some error occurred, either a server-side failure or a failure
    1853                 :             :              * to submit the command string.  Record that.
    1854                 :             :              */
    1855                 :       30263 :             const char *error = PQresultErrorMessage(result);
    1856                 :             : 
    1857         [ +  + ]:       30263 :             if (strlen(error))
    1858                 :       30242 :                 pg_log_info("%s", error);
    1859                 :             : 
    1860                 :       30263 :             CheckConnection();
    1861         [ +  + ]:       30251 :             if (!is_watch)
    1862                 :       30249 :                 SetResultVariables(result, false);
    1863                 :             : 
    1864                 :             :             /* keep the result status before clearing it */
    1865                 :       30251 :             result_status = PQresultStatus(result);
    1866                 :       30251 :             ClearOrSaveResult(result);
    1867                 :       30251 :             success = false;
    1868                 :             : 
    1869         [ +  + ]:       30251 :             if (result_status == PGRES_PIPELINE_ABORTED)
    1870                 :          20 :                 pg_log_info("Pipeline aborted, command did not run");
    1871                 :             : 
    1872                 :             :             /*
    1873                 :             :              * switch to next result
    1874                 :             :              */
    1875   [ +  +  +  - ]:       30251 :             if (result_status == PGRES_COPY_BOTH ||
    1876         [ -  + ]:       30250 :                 result_status == PGRES_COPY_OUT ||
    1877                 :             :                 result_status == PGRES_COPY_IN)
    1878                 :             :             {
    1879                 :             :                 /*
    1880                 :             :                  * For some obscure reason PQgetResult does *not* return a
    1881                 :             :                  * NULL in copy cases despite the result having been cleared,
    1882                 :             :                  * but keeps returning an "empty" result that we have to
    1883                 :             :                  * ignore manually.
    1884                 :             :                  */
    1885                 :           1 :                 result = NULL;
    1886                 :             :             }
    1887   [ +  +  +  + ]:       30250 :             else if ((end_pipeline || pset.requested_results > 0)
    1888         [ +  - ]:         108 :                      && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1889                 :             :             {
    1890                 :             :                 /*
    1891                 :             :                  * Error within a pipeline.  All commands are aborted until
    1892                 :             :                  * the next synchronisation point.  We need to consume all the
    1893                 :             :                  * results until this synchronisation point, or stop when
    1894                 :             :                  * there are no more result to discard.
    1895                 :             :                  *
    1896                 :             :                  * Checking the pipeline status is necessary for the case
    1897                 :             :                  * where the connection was reset.  The new connection is not
    1898                 :             :                  * in any kind of pipeline state and thus has no result to
    1899                 :             :                  * discard.
    1900                 :             :                  */
    1901                 :         108 :                 result = discardAbortedPipelineResults();
    1902                 :             :             }
    1903                 :             :             else
    1904                 :       30142 :                 result = PQgetResult(pset.db);
    1905                 :             : 
    1906                 :             :             /*
    1907                 :             :              * Get current timing measure in case an error occurs
    1908                 :             :              */
    1909         [ +  + ]:       30251 :             if (timing)
    1910                 :             :             {
    1911                 :           1 :                 INSTR_TIME_SET_CURRENT(after);
    1912                 :           1 :                 INSTR_TIME_SUBTRACT(after, before);
    1913                 :           1 :                 *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
    1914                 :             :             }
    1915                 :             : 
    1916                 :       30251 :             continue;
    1917                 :             :         }
    1918   [ +  +  +  + ]:      224161 :         else if (svpt_gone_p && !*svpt_gone_p)
    1919                 :             :         {
    1920                 :             :             /*
    1921                 :             :              * Check if the user ran any command that would destroy our
    1922                 :             :              * internal savepoint: If the user did COMMIT AND CHAIN, RELEASE
    1923                 :             :              * or ROLLBACK, our savepoint is gone. If they issued a SAVEPOINT,
    1924                 :             :              * releasing ours would remove theirs.
    1925                 :             :              */
    1926                 :      223979 :             const char *cmd = PQcmdStatus(result);
    1927                 :             : 
    1928                 :      667998 :             *svpt_gone_p = (strcmp(cmd, "COMMIT") == 0 ||
    1929         [ +  + ]:      220040 :                             strcmp(cmd, "SAVEPOINT") == 0 ||
    1930   [ +  +  +  + ]:      663200 :                             strcmp(cmd, "RELEASE") == 0 ||
    1931         [ +  + ]:      443160 :                             strcmp(cmd, "ROLLBACK") == 0);
    1932                 :             :         }
    1933                 :             : 
    1934                 :      224161 :         result_status = PQresultStatus(result);
    1935                 :             : 
    1936                 :             :         /* must handle COPY before changing the current result */
    1937                 :             :         Assert(result_status != PGRES_COPY_BOTH);
    1938   [ +  +  +  + ]:      224161 :         if (result_status == PGRES_COPY_IN ||
    1939                 :             :             result_status == PGRES_COPY_OUT)
    1940                 :             :         {
    1941                 :        1148 :             FILE       *copy_stream = NULL;
    1942                 :             : 
    1943         [ +  + ]:        1148 :             if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    1944                 :             :             {
    1945                 :             :                 /*
    1946                 :             :                  * Running COPY within a pipeline can break the protocol
    1947                 :             :                  * synchronisation in multiple ways, and psql shows its limits
    1948                 :             :                  * when it comes to tracking this information.
    1949                 :             :                  *
    1950                 :             :                  * While in COPY mode, the backend process ignores additional
    1951                 :             :                  * Sync messages and will not send the matching ReadyForQuery
    1952                 :             :                  * expected by the frontend.
    1953                 :             :                  *
    1954                 :             :                  * Additionally, libpq automatically sends a Sync with the
    1955                 :             :                  * Copy message, creating an unexpected synchronisation point.
    1956                 :             :                  * A failure during COPY would leave the pipeline in an
    1957                 :             :                  * aborted state while the backend would be in a clean state,
    1958                 :             :                  * ready to process commands.
    1959                 :             :                  *
    1960                 :             :                  * Improving those issues would require modifications in how
    1961                 :             :                  * libpq handles pipelines and COPY.  Hence, for the time
    1962                 :             :                  * being, we forbid the use of COPY within a pipeline,
    1963                 :             :                  * aborting the connection to avoid an inconsistent state on
    1964                 :             :                  * psql side if trying to use a COPY command.
    1965                 :             :                  */
    1966                 :           4 :                 pg_log_info("COPY in a pipeline is not supported, aborting connection");
    1967                 :           4 :                 exit(EXIT_BADCONN);
    1968                 :             :             }
    1969                 :             : 
    1970                 :             :             /* Select data source or sink. */
    1971         [ +  + ]:        1144 :             if (result_status == PGRES_COPY_OUT)
    1972                 :             :             {
    1973                 :             :                 /*
    1974                 :             :                  * For COPY OUT, direct the output to the default place
    1975                 :             :                  * (probably a pager pipe) for \watch, or to pset.copyStream
    1976                 :             :                  * for \copy, otherwise to pset.gfname if that's set,
    1977                 :             :                  * otherwise to pset.queryFout.
    1978                 :             :                  */
    1979         [ -  + ]:         499 :                 if (is_watch)
    1980                 :             :                 {
    1981                 :             :                     /* invoked by \watch */
    1982         [ #  # ]:           0 :                     copy_stream = printQueryFout ? printQueryFout : pset.queryFout;
    1983                 :             :                 }
    1984         [ +  + ]:         499 :                 else if (pset.copyStream)
    1985                 :             :                 {
    1986                 :             :                     /* invoked by \copy */
    1987                 :          36 :                     copy_stream = pset.copyStream;
    1988                 :             :                 }
    1989         [ +  + ]:         463 :                 else if (pset.gfname)
    1990                 :             :                 {
    1991                 :             :                     /* COPY followed by \g filename or \g |program */
    1992                 :          17 :                     success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
    1993         [ +  - ]:          17 :                     if (gfile_fout)
    1994                 :          17 :                         copy_stream = gfile_fout;
    1995                 :             :                 }
    1996                 :             :                 else
    1997                 :             :                 {
    1998                 :             :                     /* fall back to the generic query output stream */
    1999                 :         446 :                     copy_stream = pset.queryFout;
    2000                 :             :                 }
    2001                 :             :             }
    2002                 :             :             else
    2003                 :             :             {
    2004         [ -  + ]:         645 :                 if (num_copy_from_stdin <= 0)
    2005                 :             :                 {
    2006                 :             :                     /*
    2007                 :             :                      * We didn't send a COPY FROM STDIN command.  The server
    2008                 :             :                      * is broken or possibly malicious.  Report and quit.  (We
    2009                 :             :                      * could instead send an empty COPY response, but it's not
    2010                 :             :                      * clear that that's a better behavior; it would make it
    2011                 :             :                      * harder to diagnose any such problem.)
    2012                 :             :                      */
    2013                 :           0 :                     pg_log_info("unexpected COPY_IN result, aborting connection");
    2014                 :           0 :                     exit(EXIT_BADCONN);
    2015                 :             :                 }
    2016                 :             :                 /* Keep track of the number of remaining copy operations */
    2017                 :         645 :                 num_copy_from_stdin--;
    2018                 :             : 
    2019                 :             :                 /*
    2020                 :             :                  * For COPY IN, read from pset.copyStream if \copy set that,
    2021                 :             :                  * otherwise from the current command source.
    2022                 :             :                  */
    2023         [ +  + ]:         645 :                 if (pset.copyStream)
    2024                 :          47 :                     copy_stream = pset.copyStream;
    2025                 :             :                 else
    2026                 :         598 :                     copy_stream = pset.cur_cmd_source;
    2027                 :             :             }
    2028                 :             : 
    2029                 :             :             /*
    2030                 :             :              * Even if the output stream could not be opened, we call
    2031                 :             :              * HandleCopyResult() with a NULL output stream to collect and
    2032                 :             :              * discard the COPY data.
    2033                 :             :              */
    2034                 :        1144 :             success &= HandleCopyResult(&result, copy_stream);
    2035                 :             :         }
    2036                 :             : 
    2037                 :             :         /* If we have a chunked result, collect and print all chunks */
    2038         [ +  + ]:      224157 :         if (result_status == PGRES_TUPLES_CHUNK)
    2039                 :             :         {
    2040         [ +  - ]:          44 :             FILE       *tuples_fout = printQueryFout ? printQueryFout : pset.queryFout;
    2041         [ -  + ]:          44 :             printQueryOpt my_popt = opt ? *opt : pset.popt;
    2042                 :          44 :             int64       total_tuples = 0;
    2043                 :          44 :             bool        is_pager = false;
    2044                 :          44 :             int         flush_error = 0;
    2045                 :             : 
    2046                 :             :             /* initialize print options for partial table output */
    2047                 :          44 :             my_popt.topt.start_table = true;
    2048                 :          44 :             my_popt.topt.stop_table = false;
    2049                 :          44 :             my_popt.topt.prior_records = 0;
    2050                 :             : 
    2051                 :             :             /* open \g file if needed */
    2052                 :          44 :             success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
    2053         [ -  + ]:          44 :             if (gfile_fout)
    2054                 :           0 :                 tuples_fout = gfile_fout;
    2055                 :             : 
    2056                 :             :             /* force use of pager for any chunked resultset going to stdout */
    2057   [ +  -  +  - ]:          44 :             if (success && tuples_fout == stdout)
    2058                 :             :             {
    2059                 :          44 :                 tuples_fout = PageOutput(INT_MAX, &(my_popt.topt));
    2060                 :          44 :                 is_pager = true;
    2061                 :             :             }
    2062                 :             : 
    2063                 :             :             do
    2064                 :             :             {
    2065                 :             :                 /*
    2066                 :             :                  * Display the current chunk of results, unless the output
    2067                 :             :                  * stream stopped working or we got canceled.  We skip use of
    2068                 :             :                  * PrintQueryResult and go directly to printQuery, so that we
    2069                 :             :                  * can pass the correct is_pager value and because we don't
    2070                 :             :                  * want PrintQueryStatus to happen yet.  Above, we rejected
    2071                 :             :                  * use of chunking for all cases in which PrintQueryResult
    2072                 :             :                  * would send the result to someplace other than printQuery.
    2073                 :             :                  */
    2074   [ +  -  +  -  :          60 :                 if (success && !flush_error && !cancel_pressed)
                   +  - ]
    2075                 :             :                 {
    2076                 :          60 :                     printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
    2077                 :          60 :                     flush_error = fflush(tuples_fout);
    2078                 :             :                 }
    2079                 :             : 
    2080                 :             :                 /* after the first result set, disallow header decoration */
    2081                 :          60 :                 my_popt.topt.start_table = false;
    2082                 :             : 
    2083                 :             :                 /* count tuples before dropping the result */
    2084                 :          60 :                 my_popt.topt.prior_records += PQntuples(result);
    2085                 :          60 :                 total_tuples += PQntuples(result);
    2086                 :             : 
    2087                 :          60 :                 ClearOrSaveResult(result);
    2088                 :             : 
    2089                 :             :                 /* get the next result, loop if it's PGRES_TUPLES_CHUNK */
    2090                 :          60 :                 result = PQgetResult(pset.db);
    2091         [ +  + ]:          60 :             } while (PQresultStatus(result) == PGRES_TUPLES_CHUNK);
    2092                 :             : 
    2093                 :             :             /* We expect an empty PGRES_TUPLES_OK, else there's a problem */
    2094         [ +  + ]:          44 :             if (PQresultStatus(result) == PGRES_TUPLES_OK)
    2095                 :             :             {
    2096                 :             :                 char        buf[32];
    2097                 :             : 
    2098                 :             :                 Assert(PQntuples(result) == 0);
    2099                 :             : 
    2100                 :             :                 /* Display the footer using the empty result */
    2101   [ +  -  +  -  :          40 :                 if (success && !flush_error && !cancel_pressed)
                   +  - ]
    2102                 :             :                 {
    2103                 :          40 :                     my_popt.topt.stop_table = true;
    2104                 :          40 :                     printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
    2105                 :          40 :                     fflush(tuples_fout);
    2106                 :             :                 }
    2107                 :             : 
    2108         [ +  - ]:          40 :                 if (is_pager)
    2109                 :          40 :                     ClosePager(tuples_fout);
    2110                 :             : 
    2111                 :             :                 /*
    2112                 :             :                  * It's possible the data is from a RETURNING clause, in which
    2113                 :             :                  * case we need to print query status.
    2114                 :             :                  */
    2115                 :          40 :                 PrintQueryStatus(result, printQueryFout);
    2116                 :             : 
    2117                 :             :                 /*
    2118                 :             :                  * We must do a fake SetResultVariables(), since we don't have
    2119                 :             :                  * a PGresult corresponding to the whole query.
    2120                 :             :                  */
    2121                 :          40 :                 SetVariable(pset.vars, "ERROR", "false");
    2122                 :          40 :                 SetVariable(pset.vars, "SQLSTATE", "00000");
    2123                 :          40 :                 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
    2124                 :          40 :                 SetVariable(pset.vars, "ROW_COUNT", buf);
    2125                 :             :                 /* Prevent SetResultVariables call below */
    2126                 :          40 :                 is_chunked_result = true;
    2127                 :             : 
    2128                 :             :                 /* Clear the empty result so it isn't printed below */
    2129                 :          40 :                 ClearOrSaveResult(result);
    2130                 :          40 :                 result = NULL;
    2131                 :             :             }
    2132                 :             :             else
    2133                 :             :             {
    2134                 :             :                 /* Probably an error report, so close the pager and print it */
    2135         [ +  - ]:           4 :                 if (is_pager)
    2136                 :           4 :                     ClosePager(tuples_fout);
    2137                 :             : 
    2138                 :           4 :                 success &= AcceptResult(result, true);
    2139                 :             :                 /* SetResultVariables and ClearOrSaveResult happen below */
    2140                 :             :             }
    2141                 :             :         }
    2142                 :             : 
    2143         [ +  + ]:      224157 :         if (result_status == PGRES_PIPELINE_SYNC)
    2144                 :             :         {
    2145                 :             :             /*
    2146                 :             :              * Sync response, decrease the sync and requested_results
    2147                 :             :              * counters.  Guard against underflow: an error during Sync
    2148                 :             :              * processing on the server can cause the client-side counter to
    2149                 :             :              * drift.
    2150                 :             :              */
    2151         [ +  - ]:         289 :             if (pset.piped_syncs > 0)
    2152                 :         289 :                 pset.piped_syncs--;
    2153         [ +  - ]:         289 :             if (pset.requested_results > 0)
    2154                 :         289 :                 pset.requested_results--;
    2155                 :             : 
    2156                 :             :             /*
    2157                 :             :              * After a synchronisation point, reset success state to print
    2158                 :             :              * possible successful results that will be processed after this.
    2159                 :             :              */
    2160                 :         289 :             success = true;
    2161                 :             : 
    2162                 :             :             /*
    2163                 :             :              * If all syncs were processed and pipeline end was requested,
    2164                 :             :              * exit pipeline mode.
    2165                 :             :              */
    2166   [ +  +  +  + ]:         289 :             if (end_pipeline && pset.piped_syncs == 0)
    2167                 :         197 :                 success &= PQexitPipelineMode(pset.db);
    2168                 :             :         }
    2169   [ +  +  +  - ]:      223868 :         else if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF &&
    2170                 :             :                  result_status != PGRES_PIPELINE_SYNC)
    2171                 :             :         {
    2172                 :             :             /*
    2173                 :             :              * In a pipeline with a non-sync response?  Decrease the result
    2174                 :             :              * counters.
    2175                 :             :              */
    2176         [ +  + ]:         442 :             if (pset.available_results > 0)
    2177                 :         438 :                 pset.available_results--;
    2178         [ +  - ]:         442 :             if (pset.requested_results > 0)
    2179                 :         442 :                 pset.requested_results--;
    2180                 :             :         }
    2181                 :             : 
    2182                 :             :         /*
    2183                 :             :          * Check PQgetResult() again.  In the typical case of a single-command
    2184                 :             :          * string, it will return NULL.  Otherwise, we'll have other results
    2185                 :             :          * to process.  We need to do that to check whether this is the last.
    2186                 :             :          */
    2187         [ +  + ]:      224157 :         if (PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
    2188                 :      223623 :             next_result = PQgetResult(pset.db);
    2189                 :             :         else
    2190                 :             :         {
    2191                 :             :             /*
    2192                 :             :              * In pipeline mode, a NULL result indicates the end of the
    2193                 :             :              * current query being processed.  Call PQgetResult() once to
    2194                 :             :              * consume this state.
    2195                 :             :              */
    2196         [ +  + ]:         534 :             if (result_status != PGRES_PIPELINE_SYNC)
    2197                 :             :             {
    2198                 :         442 :                 next_result = PQgetResult(pset.db);
    2199                 :             :                 Assert(next_result == NULL);
    2200                 :             :             }
    2201                 :             : 
    2202                 :             :             /* Now, we can get the next result in the pipeline. */
    2203         [ +  + ]:         534 :             if (pset.requested_results > 0)
    2204                 :         462 :                 next_result = PQgetResult(pset.db);
    2205                 :             :         }
    2206                 :             : 
    2207                 :      224157 :         last = (next_result == NULL);
    2208                 :             : 
    2209                 :             :         /*
    2210                 :             :          * Update current timing measure.
    2211                 :             :          *
    2212                 :             :          * It will include the display of previous results, if any. This
    2213                 :             :          * cannot be helped because the server goes on processing further
    2214                 :             :          * queries anyway while the previous ones are being displayed. The
    2215                 :             :          * parallel execution of the client display hides the server time when
    2216                 :             :          * it is shorter.
    2217                 :             :          *
    2218                 :             :          * With combined queries, timing must be understood as an upper bound
    2219                 :             :          * of the time spent processing them.
    2220                 :             :          */
    2221         [ +  + ]:      224157 :         if (timing)
    2222                 :             :         {
    2223                 :           1 :             INSTR_TIME_SET_CURRENT(after);
    2224                 :           1 :             INSTR_TIME_SUBTRACT(after, before);
    2225                 :           1 :             *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
    2226                 :             :         }
    2227                 :             : 
    2228                 :             :         /*
    2229                 :             :          * This may or may not print something depending on settings.
    2230                 :             :          *
    2231                 :             :          * A pipeline sync will have a non-NULL result but does not have
    2232                 :             :          * anything to print, thus ignore results in this case.
    2233                 :             :          */
    2234   [ +  +  +  + ]:      224157 :         if (result != NULL && result_status != PGRES_PIPELINE_SYNC)
    2235                 :             :         {
    2236                 :             :             /*
    2237                 :             :              * If results need to be printed into the file specified by \g,
    2238                 :             :              * open it, unless we already did.  Note that when pset.gfname is
    2239                 :             :              * set, the passed-in value of printQueryFout is not used for
    2240                 :             :              * tuple output, but it's still used for status output.
    2241                 :             :              */
    2242                 :      223346 :             FILE       *tuples_fout = printQueryFout;
    2243                 :             : 
    2244         [ +  + ]:      223346 :             if (PQresultStatus(result) == PGRES_TUPLES_OK)
    2245                 :       96547 :                 success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
    2246         [ +  + ]:      223346 :             if (gfile_fout)
    2247                 :          38 :                 tuples_fout = gfile_fout;
    2248         [ +  + ]:      223346 :             if (success)
    2249                 :      223181 :                 success &= PrintQueryResult(result, last, opt,
    2250                 :             :                                             tuples_fout, printQueryFout);
    2251                 :             :         }
    2252                 :             : 
    2253                 :             :         /* set variables from last result, unless dealt with elsewhere */
    2254   [ +  +  +  +  :      224157 :         if (last && !is_watch && !is_chunked_result)
                   +  + ]
    2255                 :      222529 :             SetResultVariables(result, success);
    2256                 :             : 
    2257                 :      224157 :         ClearOrSaveResult(result);
    2258                 :      224157 :         result = next_result;
    2259                 :             : 
    2260   [ -  +  -  - ]:      224157 :         if (cancel_pressed && PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
    2261                 :             :         {
    2262                 :             :             /*
    2263                 :             :              * Outside of a pipeline, drop the next result, as well as any
    2264                 :             :              * others not yet read.
    2265                 :             :              *
    2266                 :             :              * Within a pipeline, we can let the outer loop handle this as an
    2267                 :             :              * aborted pipeline, which will discard then all the results.
    2268                 :             :              */
    2269                 :           0 :             ClearOrSaveResult(result);
    2270                 :           0 :             ClearOrSaveAllResults();
    2271                 :           0 :             break;
    2272                 :             :         }
    2273                 :             :     }
    2274                 :             : 
    2275                 :             :     /* close \g file if we opened it */
    2276                 :      252883 :     CloseGOutput(gfile_fout, gfile_is_pipe);
    2277                 :             : 
    2278         [ +  + ]:      252883 :     if (end_pipeline)
    2279                 :             :     {
    2280                 :             :         /*
    2281                 :             :          * Reset available/requested results.  Normally these are already 0,
    2282                 :             :          * but an error generated by a Sync processing itself can leave some
    2283                 :             :          * of them behind.  Consume them before exiting pipeline mode.
    2284                 :             :          */
    2285         [ +  + ]:         237 :         while (pset.piped_syncs > 0)
    2286                 :             :         {
    2287                 :             :             PGresult   *remaining;
    2288                 :             : 
    2289                 :          20 :             remaining = PQgetResult(pset.db);
    2290                 :             : 
    2291         [ -  + ]:          20 :             if (remaining == NULL)
    2292                 :             :             {
    2293         [ #  # ]:           0 :                 if (!ConnectionUp())
    2294                 :           0 :                     break;
    2295                 :           0 :                 continue;
    2296                 :             :             }
    2297         [ +  - ]:          20 :             if (PQresultStatus(remaining) == PGRES_PIPELINE_SYNC)
    2298                 :          20 :                 pset.piped_syncs--;
    2299                 :          20 :             PQclear(remaining);
    2300                 :             :         }
    2301                 :         217 :         pset.piped_syncs = 0;
    2302                 :         217 :         pset.piped_commands = 0;
    2303                 :         217 :         pset.available_results = 0;
    2304                 :         217 :         pset.requested_results = 0;
    2305                 :             : 
    2306         [ +  + ]:         217 :         if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
    2307                 :          20 :             PQexitPipelineMode(pset.db);
    2308                 :             :     }
    2309                 :             :     Assert(pset.requested_results == 0);
    2310                 :             : 
    2311                 :      252883 :     SetPipelineVariables();
    2312                 :             : 
    2313                 :             :     /* may need this to recover from conn loss during COPY */
    2314         [ -  + ]:      252883 :     if (!CheckConnection())
    2315                 :           0 :         return -1;
    2316                 :             : 
    2317                 :             :     /*
    2318                 :             :      * If we were expecting COPY ... FROM STDIN, and we didn't get
    2319                 :             :      * PGRES_COPY_IN (presumably because the COPY failed server-side), and the
    2320                 :             :      * data is supposed to come from the current command source, we must eat
    2321                 :             :      * up the data in order to stay in sync with the command file's contents.
    2322                 :             :      * Repeat for the number of unfulfilled COPY commands.
    2323                 :             :      */
    2324         [ +  + ]:      253188 :     while (num_copy_from_stdin > 0)
    2325                 :             :     {
    2326         [ +  + ]:         305 :         if (pset.copyStream == NULL ||
    2327         [ +  + ]:           5 :             pset.copyStream == pset.cur_cmd_source)
    2328                 :         304 :             (void) handleCopyIn(NULL,   /* no connection */
    2329                 :             :                                 pset.cur_cmd_source,
    2330                 :             :                                 false,  /* XXX assume not binary */
    2331                 :             :                                 NULL);  /* no result */
    2332                 :         305 :         num_copy_from_stdin--;
    2333                 :             :     }
    2334                 :             : 
    2335   [ +  +  +  + ]:      252883 :     if (cancel_pressed || return_early)
    2336                 :           2 :         return 0;
    2337                 :             : 
    2338         [ +  + ]:      252881 :     return success ? 1 : -1;
    2339                 :             : }
    2340                 :             : 
    2341                 :             : 
    2342                 :             : /*
    2343                 :             :  * Advance the given char pointer over white space and SQL comments.
    2344                 :             :  */
    2345                 :             : static const char *
    2346                 :          72 : skip_white_space(const char *query)
    2347                 :             : {
    2348                 :          72 :     int         cnestlevel = 0; /* slash-star comment nest level */
    2349                 :             : 
    2350         [ +  - ]:          88 :     while (*query)
    2351                 :             :     {
    2352                 :          88 :         int         mblen = PQmblenBounded(query, pset.encoding);
    2353                 :             : 
    2354                 :             :         /*
    2355                 :             :          * Note: we assume the encoding is a superset of ASCII, so that for
    2356                 :             :          * example "query[0] == '/'" is meaningful.  However, we do NOT assume
    2357                 :             :          * that the second and subsequent bytes of a multibyte character
    2358                 :             :          * couldn't look like ASCII characters; so it is critical to advance
    2359                 :             :          * by mblen, not 1, whenever we haven't exactly identified the
    2360                 :             :          * character we are skipping over.
    2361                 :             :          */
    2362         [ +  + ]:          88 :         if (isspace((unsigned char) *query))
    2363                 :          16 :             query += mblen;
    2364   [ -  +  -  - ]:          72 :         else if (query[0] == '/' && query[1] == '*')
    2365                 :             :         {
    2366                 :           0 :             cnestlevel++;
    2367                 :           0 :             query += 2;
    2368                 :             :         }
    2369   [ -  +  -  -  :          72 :         else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
                   -  - ]
    2370                 :             :         {
    2371                 :           0 :             cnestlevel--;
    2372                 :           0 :             query += 2;
    2373                 :             :         }
    2374   [ +  -  -  +  :          72 :         else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
                   -  - ]
    2375                 :             :         {
    2376                 :           0 :             query += 2;
    2377                 :             : 
    2378                 :             :             /*
    2379                 :             :              * We have to skip to end of line since any slash-star inside the
    2380                 :             :              * -- comment does NOT start a slash-star comment.
    2381                 :             :              */
    2382         [ #  # ]:           0 :             while (*query)
    2383                 :             :             {
    2384         [ #  # ]:           0 :                 if (*query == '\n')
    2385                 :             :                 {
    2386                 :           0 :                     query++;
    2387                 :           0 :                     break;
    2388                 :             :                 }
    2389                 :           0 :                 query += PQmblenBounded(query, pset.encoding);
    2390                 :             :             }
    2391                 :             :         }
    2392         [ -  + ]:          72 :         else if (cnestlevel > 0)
    2393                 :           0 :             query += mblen;
    2394                 :             :         else
    2395                 :          72 :             break;              /* found first token */
    2396                 :             :     }
    2397                 :             : 
    2398                 :          72 :     return query;
    2399                 :             : }
    2400                 :             : 
    2401                 :             : 
    2402                 :             : /*
    2403                 :             :  * Check whether a command is one of those for which we should NOT start
    2404                 :             :  * a new transaction block (ie, send a preceding BEGIN).
    2405                 :             :  *
    2406                 :             :  * These include the transaction control statements themselves, plus
    2407                 :             :  * certain statements that the backend disallows inside transaction blocks.
    2408                 :             :  */
    2409                 :             : static bool
    2410                 :          56 : command_no_begin(const char *query)
    2411                 :             : {
    2412                 :             :     int         wordlen;
    2413                 :             : 
    2414                 :             :     /*
    2415                 :             :      * First we must advance over any whitespace and comments.
    2416                 :             :      */
    2417                 :          56 :     query = skip_white_space(query);
    2418                 :             : 
    2419                 :             :     /*
    2420                 :             :      * Check word length (since "beginx" is not "begin").
    2421                 :             :      */
    2422                 :          56 :     wordlen = 0;
    2423         [ +  + ]:         376 :     while (isalpha((unsigned char) query[wordlen]))
    2424                 :         320 :         wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2425                 :             : 
    2426                 :             :     /*
    2427                 :             :      * Transaction control commands.  These should include every keyword that
    2428                 :             :      * gives rise to a TransactionStmt in the backend grammar, except for the
    2429                 :             :      * savepoint-related commands.
    2430                 :             :      *
    2431                 :             :      * (We assume that START must be START TRANSACTION, since there is
    2432                 :             :      * presently no other "START foo" command.)
    2433                 :             :      */
    2434   [ +  +  -  + ]:          56 :     if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
    2435                 :           0 :         return true;
    2436   [ +  +  +  - ]:          56 :     if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
    2437                 :           8 :         return true;
    2438   [ -  +  -  - ]:          48 :     if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
    2439                 :           0 :         return true;
    2440   [ +  +  -  + ]:          48 :     if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
    2441                 :           0 :         return true;
    2442   [ -  +  -  - ]:          48 :     if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
    2443                 :           0 :         return true;
    2444   [ -  +  -  - ]:          48 :     if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
    2445                 :           0 :         return true;
    2446   [ -  +  -  - ]:          48 :     if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
    2447                 :             :     {
    2448                 :             :         /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
    2449                 :           0 :         query += wordlen;
    2450                 :             : 
    2451                 :           0 :         query = skip_white_space(query);
    2452                 :             : 
    2453                 :           0 :         wordlen = 0;
    2454         [ #  # ]:           0 :         while (isalpha((unsigned char) query[wordlen]))
    2455                 :           0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2456                 :             : 
    2457   [ #  #  #  # ]:           0 :         if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
    2458                 :           0 :             return true;
    2459                 :           0 :         return false;
    2460                 :             :     }
    2461                 :             : 
    2462                 :             :     /*
    2463                 :             :      * Commands not allowed within transactions.  The statements checked for
    2464                 :             :      * here should be exactly those that call PreventInTransactionBlock() in
    2465                 :             :      * the backend.
    2466                 :             :      */
    2467   [ +  +  -  + ]:          48 :     if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
    2468                 :           0 :         return true;
    2469   [ -  +  -  - ]:          48 :     if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
    2470                 :             :     {
    2471                 :             :         /* CLUSTER with any arguments is allowed in transactions */
    2472                 :           0 :         query += wordlen;
    2473                 :             : 
    2474                 :           0 :         query = skip_white_space(query);
    2475                 :             : 
    2476         [ #  # ]:           0 :         if (isalpha((unsigned char) query[0]))
    2477                 :           0 :             return false;       /* has additional words */
    2478                 :           0 :         return true;            /* it's CLUSTER without arguments */
    2479                 :             :     }
    2480                 :             : 
    2481   [ +  +  +  + ]:          48 :     if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
    2482                 :             :     {
    2483                 :           8 :         query += wordlen;
    2484                 :             : 
    2485                 :           8 :         query = skip_white_space(query);
    2486                 :             : 
    2487                 :           8 :         wordlen = 0;
    2488         [ +  + ]:          48 :         while (isalpha((unsigned char) query[wordlen]))
    2489                 :          40 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2490                 :             : 
    2491   [ -  +  -  - ]:           8 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
    2492                 :           0 :             return true;
    2493   [ -  +  -  - ]:           8 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
    2494                 :           0 :             return true;
    2495                 :             : 
    2496                 :             :         /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
    2497   [ -  +  -  - ]:           8 :         if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
    2498                 :             :         {
    2499                 :           0 :             query += wordlen;
    2500                 :             : 
    2501                 :           0 :             query = skip_white_space(query);
    2502                 :             : 
    2503                 :           0 :             wordlen = 0;
    2504         [ #  # ]:           0 :             while (isalpha((unsigned char) query[wordlen]))
    2505                 :           0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2506                 :             :         }
    2507                 :             : 
    2508   [ +  -  -  + ]:           8 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
    2509                 :             :         {
    2510                 :           0 :             query += wordlen;
    2511                 :             : 
    2512                 :           0 :             query = skip_white_space(query);
    2513                 :             : 
    2514                 :           0 :             wordlen = 0;
    2515         [ #  # ]:           0 :             while (isalpha((unsigned char) query[wordlen]))
    2516                 :           0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2517                 :             : 
    2518   [ #  #  #  # ]:           0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2519                 :           0 :                 return true;
    2520                 :             :         }
    2521                 :             : 
    2522                 :           8 :         return false;
    2523                 :             :     }
    2524                 :             : 
    2525   [ -  +  -  - ]:          40 :     if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
    2526                 :             :     {
    2527                 :           0 :         query += wordlen;
    2528                 :             : 
    2529                 :           0 :         query = skip_white_space(query);
    2530                 :             : 
    2531                 :           0 :         wordlen = 0;
    2532         [ #  # ]:           0 :         while (isalpha((unsigned char) query[wordlen]))
    2533                 :           0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2534                 :             : 
    2535                 :             :         /* ALTER SYSTEM isn't allowed in xacts */
    2536   [ #  #  #  # ]:           0 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
    2537                 :           0 :             return true;
    2538                 :             : 
    2539                 :           0 :         return false;
    2540                 :             :     }
    2541                 :             : 
    2542                 :             :     /*
    2543                 :             :      * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
    2544                 :             :      * aren't really valid commands so we don't care much. The other four
    2545                 :             :      * possible matches are correct.
    2546                 :             :      */
    2547   [ +  +  -  +  :          40 :     if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
                   -  + ]
    2548         [ #  # ]:           0 :         (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
    2549                 :             :     {
    2550                 :           4 :         query += wordlen;
    2551                 :             : 
    2552                 :           4 :         query = skip_white_space(query);
    2553                 :             : 
    2554                 :           4 :         wordlen = 0;
    2555         [ +  + ]:          24 :         while (isalpha((unsigned char) query[wordlen]))
    2556                 :          20 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2557                 :             : 
    2558   [ -  +  -  - ]:           4 :         if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
    2559                 :           0 :             return true;
    2560   [ -  +  -  - ]:           4 :         if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
    2561                 :           0 :             return true;
    2562   [ -  +  -  - ]:           4 :         if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
    2563                 :           0 :             return true;
    2564   [ +  -  +  -  :           8 :         if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
                   +  - ]
    2565                 :           4 :                              pg_strncasecmp(query, "table", 5) == 0))
    2566                 :             :         {
    2567                 :           4 :             query += wordlen;
    2568                 :           4 :             query = skip_white_space(query);
    2569                 :           4 :             wordlen = 0;
    2570         [ +  + ]:          16 :             while (isalpha((unsigned char) query[wordlen]))
    2571                 :          12 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2572                 :             : 
    2573                 :             :             /*
    2574                 :             :              * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
    2575                 :             :              * xacts.
    2576                 :             :              */
    2577   [ -  +  -  - ]:           4 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2578                 :           0 :                 return true;
    2579                 :             :         }
    2580                 :             : 
    2581                 :             :         /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
    2582   [ -  +  -  - ]:           4 :         if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
    2583                 :             :         {
    2584                 :           0 :             query += wordlen;
    2585                 :             : 
    2586                 :           0 :             query = skip_white_space(query);
    2587                 :             : 
    2588                 :           0 :             wordlen = 0;
    2589         [ #  # ]:           0 :             while (isalpha((unsigned char) query[wordlen]))
    2590                 :           0 :                 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2591                 :             : 
    2592   [ #  #  #  # ]:           0 :             if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
    2593                 :           0 :                 return true;
    2594                 :             : 
    2595                 :           0 :             return false;
    2596                 :             :         }
    2597                 :             : 
    2598                 :           4 :         return false;
    2599                 :             :     }
    2600                 :             : 
    2601                 :             :     /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
    2602   [ -  +  -  - ]:          36 :     if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
    2603                 :             :     {
    2604                 :           0 :         query += wordlen;
    2605                 :             : 
    2606                 :           0 :         query = skip_white_space(query);
    2607                 :             : 
    2608                 :           0 :         wordlen = 0;
    2609         [ #  # ]:           0 :         while (isalpha((unsigned char) query[wordlen]))
    2610                 :           0 :             wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
    2611                 :             : 
    2612   [ #  #  #  # ]:           0 :         if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
    2613                 :           0 :             return true;
    2614                 :           0 :         return false;
    2615                 :             :     }
    2616                 :             : 
    2617                 :          36 :     return false;
    2618                 :             : }
    2619                 :             : 
    2620                 :             : 
    2621                 :             : /*
    2622                 :             :  * addQueryComment
    2623                 :             :  *
    2624                 :             :  * Reset buf and insert a comment holding label.  The comment will show up
    2625                 :             :  * in -E output and in the server log.
    2626                 :             :  *
    2627                 :             :  * If it's safe, we attempt to translate the label string.
    2628                 :             :  * (addQueryComment is marked as a gettext trigger, so this requires no
    2629                 :             :  * special effort at call sites.)
    2630                 :             :  */
    2631                 :             : void
    2632                 :       31583 : addQueryComment(PQExpBuffer buf, const char *label)
    2633                 :             : {
    2634                 :             : #if defined(ENABLE_NLS)
    2635                 :       31583 :     const char *server_enc = PQparameterStatus(pset.db, "server_encoding");
    2636                 :       31583 :     int         client_enc = PQclientEncoding(pset.db);
    2637                 :             : 
    2638                 :             :     /*
    2639                 :             :      * We must skip translation if it would cause the server to reject the
    2640                 :             :      * query due to an encoding conversion/verification failure.  For now it
    2641                 :             :      * seems sufficient to handle only the case of equal client and server
    2642                 :             :      * encodings: then the server just verifies the string in that encoding,
    2643                 :             :      * and we can run the same check here.  It's necessary to check for this
    2644                 :             :      * because we can't be 100% sure which encoding gettext() thinks it should
    2645                 :             :      * produce.  If it is indeed different from our client encoding, the
    2646                 :             :      * result may look like junk to a human, but it won't cause an error.
    2647                 :             :      */
    2648   [ +  -  +  - ]:       63166 :     if (server_enc != NULL &&
    2649                 :       31583 :         pg_char_to_encoding(server_enc) == client_enc)
    2650                 :             :     {
    2651                 :       31583 :         const char *translated = _(label);
    2652                 :       31583 :         int         len = strlen(translated);
    2653                 :             : 
    2654         [ +  - ]:       31583 :         if (pg_encoding_verifymbstr(client_enc, translated, len) == len)
    2655                 :       31583 :             label = translated;
    2656                 :             :     }
    2657                 :             : #endif
    2658                 :             : 
    2659                 :       31583 :     printfPQExpBuffer(buf, "/* %s */\n", label);
    2660                 :       31583 : }
    2661                 :             : 
    2662                 :             : 
    2663                 :             : /*
    2664                 :             :  * Test if the current user is a database superuser.
    2665                 :             :  */
    2666                 :             : bool
    2667                 :          70 : is_superuser(void)
    2668                 :             : {
    2669                 :             :     const char *val;
    2670                 :             : 
    2671         [ -  + ]:          70 :     if (!pset.db)
    2672                 :           0 :         return false;
    2673                 :             : 
    2674                 :          70 :     val = PQparameterStatus(pset.db, "is_superuser");
    2675                 :             : 
    2676   [ +  -  +  - ]:          70 :     if (val && strcmp(val, "on") == 0)
    2677                 :          70 :         return true;
    2678                 :             : 
    2679                 :           0 :     return false;
    2680                 :             : }
    2681                 :             : 
    2682                 :             : 
    2683                 :             : /*
    2684                 :             :  * Test if the current session uses standard string literals.
    2685                 :             :  */
    2686                 :             : bool
    2687                 :      524722 : standard_strings(void)
    2688                 :             : {
    2689                 :             :     const char *val;
    2690                 :             : 
    2691         [ -  + ]:      524722 :     if (!pset.db)
    2692                 :           0 :         return false;
    2693                 :             : 
    2694                 :      524722 :     val = PQparameterStatus(pset.db, "standard_conforming_strings");
    2695                 :             : 
    2696   [ +  -  +  - ]:      524722 :     if (val && strcmp(val, "on") == 0)
    2697                 :      524722 :         return true;
    2698                 :             : 
    2699                 :           0 :     return false;
    2700                 :             : }
    2701                 :             : 
    2702                 :             : 
    2703                 :             : /*
    2704                 :             :  * Return the session user of the current connection.
    2705                 :             :  */
    2706                 :             : const char *
    2707                 :           0 : session_username(void)
    2708                 :             : {
    2709                 :             :     const char *val;
    2710                 :             : 
    2711         [ #  # ]:           0 :     if (!pset.db)
    2712                 :           0 :         return NULL;
    2713                 :             : 
    2714                 :           0 :     val = PQparameterStatus(pset.db, "session_authorization");
    2715         [ #  # ]:           0 :     if (val)
    2716                 :           0 :         return val;
    2717                 :             :     else
    2718                 :           0 :         return PQuser(pset.db);
    2719                 :             : }
    2720                 :             : 
    2721                 :             : /*
    2722                 :             :  * Return the value of option for keyword in the current connection.
    2723                 :             :  *
    2724                 :             :  * The caller is responsible for freeing the result value allocated.
    2725                 :             :  */
    2726                 :             : char *
    2727                 :       11312 : get_conninfo_value(const char *keyword)
    2728                 :             : {
    2729                 :             :     PQconninfoOption *opts;
    2730                 :       11312 :     PQconninfoOption *serviceopt = NULL;
    2731                 :       11312 :     char       *res = NULL;
    2732                 :             : 
    2733         [ -  + ]:       11312 :     if (pset.db == NULL)
    2734                 :           0 :         return NULL;
    2735                 :             : 
    2736                 :       11312 :     opts = PQconninfo(pset.db);
    2737         [ -  + ]:       11312 :     if (opts == NULL)
    2738                 :           0 :         return NULL;
    2739                 :             : 
    2740         [ +  - ]:       11312 :     for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
    2741                 :             :     {
    2742         [ +  - ]:       11312 :         if (strcmp(opt->keyword, keyword) == 0)
    2743                 :             :         {
    2744                 :       11312 :             serviceopt = opt;
    2745                 :       11312 :             break;
    2746                 :             :         }
    2747                 :             :     }
    2748                 :             : 
    2749                 :             :     /* Take a copy of the value, as it is freed by PQconninfoFree(). */
    2750   [ +  -  +  + ]:       11312 :     if (serviceopt && serviceopt->val != NULL)
    2751                 :          12 :         res = pg_strdup(serviceopt->val);
    2752                 :       11312 :     PQconninfoFree(opts);
    2753                 :             : 
    2754                 :       11312 :     return res;
    2755                 :             : }
    2756                 :             : 
    2757                 :             : /*
    2758                 :             :  * expand_tilde
    2759                 :             :  *
    2760                 :             :  * substitute '~' with HOME or '~username' with username's home dir
    2761                 :             :  *
    2762                 :             :  */
    2763                 :             : void
    2764                 :         107 : expand_tilde(char **filename)
    2765                 :             : {
    2766   [ +  -  +  + ]:         107 :     if (!filename || !(*filename))
    2767                 :          12 :         return;
    2768                 :             : 
    2769                 :             :     /*
    2770                 :             :      * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
    2771                 :             :      * for short versions of long file names, though the tilde is usually
    2772                 :             :      * toward the end, not at the beginning.
    2773                 :             :      */
    2774                 :             : #ifndef WIN32
    2775                 :             : 
    2776                 :             :     /* try tilde expansion */
    2777         [ -  + ]:          95 :     if (**filename == '~')
    2778                 :             :     {
    2779                 :             :         char       *fn;
    2780                 :             :         char        oldp,
    2781                 :             :                    *p;
    2782                 :             :         struct passwd *pw;
    2783                 :             :         char        home[MAXPGPATH];
    2784                 :             : 
    2785                 :           0 :         fn = *filename;
    2786                 :           0 :         *home = '\0';
    2787                 :             : 
    2788                 :           0 :         p = fn + 1;
    2789   [ #  #  #  # ]:           0 :         while (*p != '/' && *p != '\0')
    2790                 :           0 :             p++;
    2791                 :             : 
    2792                 :           0 :         oldp = *p;
    2793                 :           0 :         *p = '\0';
    2794                 :             : 
    2795         [ #  # ]:           0 :         if (*(fn + 1) == '\0')
    2796                 :           0 :             get_home_path(home);    /* ~ or ~/ only */
    2797         [ #  # ]:           0 :         else if ((pw = getpwnam(fn + 1)) != NULL)
    2798                 :           0 :             strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
    2799                 :             : 
    2800                 :           0 :         *p = oldp;
    2801         [ #  # ]:           0 :         if (strlen(home) != 0)
    2802                 :             :         {
    2803                 :             :             char       *newfn;
    2804                 :             : 
    2805                 :           0 :             newfn = psprintf("%s%s", home, p);
    2806                 :           0 :             free(fn);
    2807                 :           0 :             *filename = newfn;
    2808                 :             :         }
    2809                 :             :     }
    2810                 :             : #endif
    2811                 :             : }
    2812                 :             : 
    2813                 :             : /*
    2814                 :             :  * Checks if connection string starts with either of the valid URI prefix
    2815                 :             :  * designators.
    2816                 :             :  *
    2817                 :             :  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
    2818                 :             :  *
    2819                 :             :  * XXX This is a duplicate of the eponymous libpq function.
    2820                 :             :  */
    2821                 :             : static int
    2822                 :          17 : uri_prefix_length(const char *connstr)
    2823                 :             : {
    2824                 :             :     /* The connection URI must start with either of the following designators: */
    2825                 :             :     static const char uri_designator[] = "postgresql://";
    2826                 :             :     static const char short_uri_designator[] = "postgres://";
    2827                 :             : 
    2828         [ -  + ]:          17 :     if (strncmp(connstr, uri_designator,
    2829                 :             :                 sizeof(uri_designator) - 1) == 0)
    2830                 :           0 :         return sizeof(uri_designator) - 1;
    2831                 :             : 
    2832         [ -  + ]:          17 :     if (strncmp(connstr, short_uri_designator,
    2833                 :             :                 sizeof(short_uri_designator) - 1) == 0)
    2834                 :           0 :         return sizeof(short_uri_designator) - 1;
    2835                 :             : 
    2836                 :          17 :     return 0;
    2837                 :             : }
    2838                 :             : 
    2839                 :             : /*
    2840                 :             :  * Reset state related to extended query protocol
    2841                 :             :  *
    2842                 :             :  * Clean up any state related to bind parameters, statement name and
    2843                 :             :  * PSQL_SEND_MODE.  This needs to be called after processing a query or when
    2844                 :             :  * running a new meta-command that uses the extended query protocol, like
    2845                 :             :  * \parse, \bind, etc.
    2846                 :             :  */
    2847                 :             : void
    2848                 :      254606 : clean_extended_state(void)
    2849                 :             : {
    2850                 :             :     int         i;
    2851                 :             : 
    2852   [ +  +  +  +  :      254606 :     switch (pset.send_mode)
                      - ]
    2853                 :             :     {
    2854                 :          25 :         case PSQL_SEND_EXTENDED_CLOSE:  /* \close_prepared */
    2855                 :          25 :             free(pset.stmtName);
    2856                 :          25 :             break;
    2857                 :          67 :         case PSQL_SEND_EXTENDED_PARSE:  /* \parse */
    2858                 :          67 :             free(pset.stmtName);
    2859                 :          67 :             break;
    2860                 :         628 :         case PSQL_SEND_EXTENDED_QUERY_PARAMS:   /* \bind */
    2861                 :             :         case PSQL_SEND_EXTENDED_QUERY_PREPARED: /* \bind_named */
    2862         [ +  + ]:        1175 :             for (i = 0; i < pset.bind_nparams; i++)
    2863                 :         547 :                 free(pset.bind_params[i]);
    2864                 :         628 :             free(pset.bind_params);
    2865                 :         628 :             free(pset.stmtName);
    2866                 :         628 :             pset.bind_params = NULL;
    2867                 :         628 :             break;
    2868                 :      253886 :         case PSQL_SEND_QUERY:
    2869                 :             :         case PSQL_SEND_START_PIPELINE_MODE: /* \startpipeline */
    2870                 :             :         case PSQL_SEND_END_PIPELINE_MODE:   /* \endpipeline */
    2871                 :             :         case PSQL_SEND_PIPELINE_SYNC:   /* \syncpipeline */
    2872                 :             :         case PSQL_SEND_FLUSH:   /* \flush */
    2873                 :             :         case PSQL_SEND_GET_RESULTS: /* \getresults */
    2874                 :             :         case PSQL_SEND_FLUSH_REQUEST:   /* \flushrequest */
    2875                 :      253886 :             break;
    2876                 :             :     }
    2877                 :             : 
    2878                 :      254606 :     pset.stmtName = NULL;
    2879                 :      254606 :     pset.send_mode = PSQL_SEND_QUERY;
    2880                 :      254606 : }
    2881                 :             : 
    2882                 :             : /*
    2883                 :             :  * Recognized connection string either starts with a valid URI prefix or
    2884                 :             :  * contains a "=" in it.
    2885                 :             :  *
    2886                 :             :  * Must be consistent with parse_connection_string: anything for which this
    2887                 :             :  * returns true should at least look like it's parseable by that routine.
    2888                 :             :  *
    2889                 :             :  * XXX This is a duplicate of the eponymous libpq function.
    2890                 :             :  */
    2891                 :             : bool
    2892                 :          17 : recognized_connection_string(const char *connstr)
    2893                 :             : {
    2894   [ +  -  +  + ]:          17 :     return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
    2895                 :             : }
        

Generated by: LCOV version 2.0-1