LCOV - code coverage report
Current view: top level - src/bin/psql - common.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 75.7 % 1034 783
Test Date: 2026-08-10 16:15:55 Functions: 92.7 % 41 38
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 65.1 % 790 514

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

Generated by: LCOV version 2.0-1