LCOV - code coverage report
Current view: top level - src/bin/psql - command.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 942 1866 50.5 %
Date: 2019-06-19 16:07:09 Functions: 72 91 79.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * psql - the PostgreSQL interactive terminal
       3             :  *
       4             :  * Copyright (c) 2000-2019, PostgreSQL Global Development Group
       5             :  *
       6             :  * src/bin/psql/command.c
       7             :  */
       8             : #include "postgres_fe.h"
       9             : #include "command.h"
      10             : 
      11             : #include <ctype.h>
      12             : #include <time.h>
      13             : #include <pwd.h>
      14             : #ifndef WIN32
      15             : #include <sys/stat.h>         /* for stat() */
      16             : #include <fcntl.h>                /* open() flags */
      17             : #include <unistd.h>               /* for geteuid(), getpid(), stat() */
      18             : #else
      19             : #include <win32.h>
      20             : #include <io.h>
      21             : #include <fcntl.h>
      22             : #include <direct.h>
      23             : #include <sys/stat.h>         /* for stat() */
      24             : #endif
      25             : 
      26             : #include "catalog/pg_class_d.h"
      27             : #include "portability/instr_time.h"
      28             : 
      29             : #include "libpq-fe.h"
      30             : #include "pqexpbuffer.h"
      31             : #include "common/logging.h"
      32             : #include "fe_utils/print.h"
      33             : #include "fe_utils/string_utils.h"
      34             : 
      35             : #include "common.h"
      36             : #include "copy.h"
      37             : #include "crosstabview.h"
      38             : #include "describe.h"
      39             : #include "help.h"
      40             : #include "input.h"
      41             : #include "large_obj.h"
      42             : #include "mainloop.h"
      43             : #include "psqlscanslash.h"
      44             : #include "settings.h"
      45             : #include "variables.h"
      46             : 
      47             : /*
      48             :  * Editable database object types.
      49             :  */
      50             : typedef enum EditableObjectType
      51             : {
      52             :     EditableFunction,
      53             :     EditableView
      54             : } EditableObjectType;
      55             : 
      56             : /* local function declarations */
      57             : static backslashResult exec_command(const char *cmd,
      58             :                                     PsqlScanState scan_state,
      59             :                                     ConditionalStack cstack,
      60             :                                     PQExpBuffer query_buf,
      61             :                                     PQExpBuffer previous_buf);
      62             : static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch);
      63             : static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch);
      64             : static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch);
      65             : static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch,
      66             :                                        const char *cmd);
      67             : static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch);
      68             : static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch);
      69             : static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch);
      70             : static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch);
      71             : static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch,
      72             :                                       const char *cmd);
      73             : static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch,
      74             :                                          PQExpBuffer query_buf, PQExpBuffer previous_buf);
      75             : static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
      76             :                                           PQExpBuffer query_buf, bool is_func);
      77             : static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch,
      78             :                                          const char *cmd);
      79             : static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
      80             :                                          PQExpBuffer query_buf);
      81             : static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
      82             :                                          PQExpBuffer query_buf);
      83             : static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
      84             :                                           PQExpBuffer query_buf);
      85             : static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch);
      86             : static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch);
      87             : static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch);
      88             : static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch,
      89             :                                       const char *cmd);
      90             : static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch);
      91             : static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch);
      92             : static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch);
      93             : static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch);
      94             : static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch);
      95             : static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch,
      96             :                                             const char *cmd);
      97             : static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
      98             :                                        PQExpBuffer query_buf);
      99             : static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch,
     100             :                                          const char *cmd);
     101             : static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch,
     102             :                                        const char *cmd);
     103             : static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch);
     104             : static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch,
     105             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     106             : static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch);
     107             : static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch,
     108             :                                            const char *cmd);
     109             : static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch);
     110             : static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch);
     111             : static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch,
     112             :                                           PQExpBuffer query_buf);
     113             : static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch);
     114             : static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch);
     115             : static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch,
     116             :                                            const char *cmd);
     117             : static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
     118             :                                           const char *cmd, bool is_func);
     119             : static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch);
     120             : static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch);
     121             : static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch);
     122             : static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch,
     123             :                                           const char *cmd);
     124             : static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch,
     125             :                                           const char *cmd,
     126             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     127             : static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch,
     128             :                                           PQExpBuffer query_buf, PQExpBuffer previous_buf);
     129             : static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch);
     130             : static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch);
     131             : static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch);
     132             : static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch);
     133             : static char *read_connect_arg(PsqlScanState scan_state);
     134             : static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state);
     135             : static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name);
     136             : static void ignore_boolean_expression(PsqlScanState scan_state);
     137             : static void ignore_slash_options(PsqlScanState scan_state);
     138             : static void ignore_slash_filepipe(PsqlScanState scan_state);
     139             : static void ignore_slash_whole_line(PsqlScanState scan_state);
     140             : static bool is_branching_command(const char *cmd);
     141             : static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
     142             :                                   PQExpBuffer query_buf);
     143             : static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
     144             :                                PQExpBuffer query_buf);
     145             : static void copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf);
     146             : static bool do_connect(enum trivalue reuse_previous_specification,
     147             :                        char *dbname, char *user, char *host, char *port);
     148             : static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
     149             :                     int lineno, bool *edited);
     150             : static bool do_shell(const char *command);
     151             : static bool do_watch(PQExpBuffer query_buf, double sleep);
     152             : static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
     153             :                               Oid *obj_oid);
     154             : static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
     155             :                                   PQExpBuffer buf);
     156             : static int  strip_lineno_from_objdesc(char *obj);
     157             : static int  count_lines_in_buf(PQExpBuffer buf);
     158             : static void print_with_linenumbers(FILE *output, char *lines,
     159             :                                    const char *header_keyword);
     160             : static void minimal_error_message(PGresult *res);
     161             : 
     162             : static void printSSLInfo(void);
     163             : static void printGSSInfo(void);
     164             : static bool printPsetInfo(const char *param, struct printQueryOpt *popt);
     165             : static char *pset_value_string(const char *param, struct printQueryOpt *popt);
     166             : 
     167             : #ifdef WIN32
     168             : static void checkWin32Codepage(void);
     169             : #endif
     170             : 
     171             : 
     172             : 
     173             : /*----------
     174             :  * HandleSlashCmds:
     175             :  *
     176             :  * Handles all the different commands that start with '\'.
     177             :  * Ordinarily called by MainLoop().
     178             :  *
     179             :  * scan_state is a lexer working state that is set to continue scanning
     180             :  * just after the '\'.  The lexer is advanced past the command and all
     181             :  * arguments on return.
     182             :  *
     183             :  * cstack is the current \if stack state.  This will be examined, and
     184             :  * possibly modified by conditional commands.
     185             :  *
     186             :  * query_buf contains the query-so-far, which may be modified by
     187             :  * execution of the backslash command (for example, \r clears it).
     188             :  *
     189             :  * previous_buf contains the query most recently sent to the server
     190             :  * (empty if none yet).  This should not be modified here, but some
     191             :  * commands copy its content into query_buf.
     192             :  *
     193             :  * query_buf and previous_buf will be NULL when executing a "-c"
     194             :  * command-line option.
     195             :  *
     196             :  * Returns a status code indicating what action is desired, see command.h.
     197             :  *----------
     198             :  */
     199             : 
     200             : backslashResult
     201        4836 : HandleSlashCmds(PsqlScanState scan_state,
     202             :                 ConditionalStack cstack,
     203             :                 PQExpBuffer query_buf,
     204             :                 PQExpBuffer previous_buf)
     205             : {
     206             :     backslashResult status;
     207             :     char       *cmd;
     208             :     char       *arg;
     209             : 
     210             :     Assert(scan_state != NULL);
     211             :     Assert(cstack != NULL);
     212             : 
     213             :     /* Parse off the command name */
     214        4836 :     cmd = psql_scan_slash_command(scan_state);
     215             : 
     216             :     /* And try to execute it */
     217        4836 :     status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
     218             : 
     219        4836 :     if (status == PSQL_CMD_UNKNOWN)
     220             :     {
     221           0 :         pg_log_error("invalid command \\%s", cmd);
     222           0 :         if (pset.cur_cmd_interactive)
     223           0 :             pg_log_info("Try \\? for help.");
     224           0 :         status = PSQL_CMD_ERROR;
     225             :     }
     226             : 
     227        4836 :     if (status != PSQL_CMD_ERROR)
     228             :     {
     229             :         /*
     230             :          * Eat any remaining arguments after a valid command.  We want to
     231             :          * suppress evaluation of backticks in this situation, so transiently
     232             :          * push an inactive conditional-stack entry.
     233             :          */
     234        4756 :         bool        active_branch = conditional_active(cstack);
     235             : 
     236        4756 :         conditional_stack_push(cstack, IFSTATE_IGNORED);
     237        9528 :         while ((arg = psql_scan_slash_option(scan_state,
     238             :                                              OT_NORMAL, NULL, false)))
     239             :         {
     240          16 :             if (active_branch)
     241          16 :                 pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
     242          16 :             free(arg);
     243             :         }
     244        4756 :         conditional_stack_pop(cstack);
     245             :     }
     246             :     else
     247             :     {
     248             :         /* silently throw away rest of line after an erroneous command */
     249         160 :         while ((arg = psql_scan_slash_option(scan_state,
     250             :                                              OT_WHOLE_LINE, NULL, false)))
     251           0 :             free(arg);
     252             :     }
     253             : 
     254             :     /* if there is a trailing \\, swallow it */
     255        4836 :     psql_scan_slash_command_end(scan_state);
     256             : 
     257        4836 :     free(cmd);
     258             : 
     259             :     /* some commands write to queryFout, so make sure output is sent */
     260        4836 :     fflush(pset.queryFout);
     261             : 
     262        4836 :     return status;
     263             : }
     264             : 
     265             : 
     266             : /*
     267             :  * Subroutine to actually try to execute a backslash command.
     268             :  *
     269             :  * The typical "success" result code is PSQL_CMD_SKIP_LINE, although some
     270             :  * commands return something else.  Failure results are PSQL_CMD_ERROR,
     271             :  * unless PSQL_CMD_UNKNOWN is more appropriate.
     272             :  */
     273             : static backslashResult
     274        4836 : exec_command(const char *cmd,
     275             :              PsqlScanState scan_state,
     276             :              ConditionalStack cstack,
     277             :              PQExpBuffer query_buf,
     278             :              PQExpBuffer previous_buf)
     279             : {
     280             :     backslashResult status;
     281        4836 :     bool        active_branch = conditional_active(cstack);
     282             : 
     283             :     /*
     284             :      * In interactive mode, warn when we're ignoring a command within a false
     285             :      * \if-branch.  But we continue on, so as to parse and discard the right
     286             :      * amount of parameter text.  Each individual backslash command subroutine
     287             :      * is responsible for doing nothing after discarding appropriate
     288             :      * arguments, if !active_branch.
     289             :      */
     290        4836 :     if (pset.cur_cmd_interactive && !active_branch &&
     291           0 :         !is_branching_command(cmd))
     292             :     {
     293           0 :         pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
     294             :                        cmd);
     295             :     }
     296             : 
     297        4836 :     if (strcmp(cmd, "a") == 0)
     298          28 :         status = exec_command_a(scan_state, active_branch);
     299        4808 :     else if (strcmp(cmd, "C") == 0)
     300           4 :         status = exec_command_C(scan_state, active_branch);
     301        4804 :     else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
     302         178 :         status = exec_command_connect(scan_state, active_branch);
     303        4626 :     else if (strcmp(cmd, "cd") == 0)
     304           4 :         status = exec_command_cd(scan_state, active_branch, cmd);
     305        4622 :     else if (strcmp(cmd, "conninfo") == 0)
     306           4 :         status = exec_command_conninfo(scan_state, active_branch);
     307        4618 :     else if (pg_strcasecmp(cmd, "copy") == 0)
     308         130 :         status = exec_command_copy(scan_state, active_branch);
     309        4488 :     else if (strcmp(cmd, "copyright") == 0)
     310           4 :         status = exec_command_copyright(scan_state, active_branch);
     311        4484 :     else if (strcmp(cmd, "crosstabview") == 0)
     312          88 :         status = exec_command_crosstabview(scan_state, active_branch);
     313        4396 :     else if (cmd[0] == 'd')
     314        1974 :         status = exec_command_d(scan_state, active_branch, cmd);
     315        2422 :     else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
     316           4 :         status = exec_command_edit(scan_state, active_branch,
     317             :                                    query_buf, previous_buf);
     318        2418 :     else if (strcmp(cmd, "ef") == 0)
     319           4 :         status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
     320        2414 :     else if (strcmp(cmd, "ev") == 0)
     321           4 :         status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
     322        2410 :     else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
     323         340 :         status = exec_command_echo(scan_state, active_branch, cmd);
     324        2070 :     else if (strcmp(cmd, "elif") == 0)
     325          24 :         status = exec_command_elif(scan_state, cstack, query_buf);
     326        2046 :     else if (strcmp(cmd, "else") == 0)
     327          80 :         status = exec_command_else(scan_state, cstack, query_buf);
     328        1966 :     else if (strcmp(cmd, "endif") == 0)
     329          76 :         status = exec_command_endif(scan_state, cstack, query_buf);
     330        1890 :     else if (strcmp(cmd, "encoding") == 0)
     331           4 :         status = exec_command_encoding(scan_state, active_branch);
     332        1886 :     else if (strcmp(cmd, "errverbose") == 0)
     333           4 :         status = exec_command_errverbose(scan_state, active_branch);
     334        1882 :     else if (strcmp(cmd, "f") == 0)
     335           0 :         status = exec_command_f(scan_state, active_branch);
     336        1882 :     else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
     337          64 :         status = exec_command_g(scan_state, active_branch, cmd);
     338        1818 :     else if (strcmp(cmd, "gdesc") == 0)
     339          40 :         status = exec_command_gdesc(scan_state, active_branch);
     340        1778 :     else if (strcmp(cmd, "gexec") == 0)
     341          22 :         status = exec_command_gexec(scan_state, active_branch);
     342        1756 :     else if (strcmp(cmd, "gset") == 0)
     343          96 :         status = exec_command_gset(scan_state, active_branch);
     344        1660 :     else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
     345           4 :         status = exec_command_help(scan_state, active_branch);
     346        1656 :     else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
     347           0 :         status = exec_command_html(scan_state, active_branch);
     348        3312 :     else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
     349        3312 :              strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
     350           0 :         status = exec_command_include(scan_state, active_branch, cmd);
     351        1656 :     else if (strcmp(cmd, "if") == 0)
     352          72 :         status = exec_command_if(scan_state, cstack, query_buf);
     353        3168 :     else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
     354        3168 :              strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
     355           0 :         status = exec_command_list(scan_state, active_branch, cmd);
     356        1584 :     else if (strncmp(cmd, "lo_", 3) == 0)
     357          24 :         status = exec_command_lo(scan_state, active_branch, cmd);
     358        1560 :     else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
     359           4 :         status = exec_command_out(scan_state, active_branch);
     360        1556 :     else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
     361          28 :         status = exec_command_print(scan_state, active_branch,
     362             :                                     query_buf, previous_buf);
     363        1528 :     else if (strcmp(cmd, "password") == 0)
     364           4 :         status = exec_command_password(scan_state, active_branch);
     365        1524 :     else if (strcmp(cmd, "prompt") == 0)
     366           4 :         status = exec_command_prompt(scan_state, active_branch, cmd);
     367        1520 :     else if (strcmp(cmd, "pset") == 0)
     368        1132 :         status = exec_command_pset(scan_state, active_branch);
     369         388 :     else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
     370           4 :         status = exec_command_quit(scan_state, active_branch);
     371         384 :     else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
     372          16 :         status = exec_command_reset(scan_state, active_branch, query_buf);
     373         368 :     else if (strcmp(cmd, "s") == 0)
     374           4 :         status = exec_command_s(scan_state, active_branch);
     375         364 :     else if (strcmp(cmd, "set") == 0)
     376         228 :         status = exec_command_set(scan_state, active_branch);
     377         136 :     else if (strcmp(cmd, "setenv") == 0)
     378           4 :         status = exec_command_setenv(scan_state, active_branch, cmd);
     379         132 :     else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
     380           4 :         status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
     381         128 :     else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
     382           8 :         status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
     383         120 :     else if (strcmp(cmd, "t") == 0)
     384          44 :         status = exec_command_t(scan_state, active_branch);
     385          76 :     else if (strcmp(cmd, "T") == 0)
     386           4 :         status = exec_command_T(scan_state, active_branch);
     387          72 :     else if (strcmp(cmd, "timing") == 0)
     388           4 :         status = exec_command_timing(scan_state, active_branch);
     389          68 :     else if (strcmp(cmd, "unset") == 0)
     390          26 :         status = exec_command_unset(scan_state, active_branch, cmd);
     391          42 :     else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
     392           8 :         status = exec_command_write(scan_state, active_branch, cmd,
     393             :                                     query_buf, previous_buf);
     394          34 :     else if (strcmp(cmd, "watch") == 0)
     395           4 :         status = exec_command_watch(scan_state, active_branch,
     396             :                                     query_buf, previous_buf);
     397          30 :     else if (strcmp(cmd, "x") == 0)
     398          18 :         status = exec_command_x(scan_state, active_branch);
     399          12 :     else if (strcmp(cmd, "z") == 0)
     400           8 :         status = exec_command_z(scan_state, active_branch);
     401           4 :     else if (strcmp(cmd, "!") == 0)
     402           4 :         status = exec_command_shell_escape(scan_state, active_branch);
     403           0 :     else if (strcmp(cmd, "?") == 0)
     404           0 :         status = exec_command_slash_command_help(scan_state, active_branch);
     405             :     else
     406           0 :         status = PSQL_CMD_UNKNOWN;
     407             : 
     408             :     /*
     409             :      * All the commands that return PSQL_CMD_SEND want to execute previous_buf
     410             :      * if query_buf is empty.  For convenience we implement that here, not in
     411             :      * the individual command subroutines.
     412             :      */
     413        4836 :     if (status == PSQL_CMD_SEND)
     414         298 :         copy_previous_query(query_buf, previous_buf);
     415             : 
     416        4836 :     return status;
     417             : }
     418             : 
     419             : 
     420             : /*
     421             :  * \a -- toggle field alignment
     422             :  *
     423             :  * This makes little sense but we keep it around.
     424             :  */
     425             : static backslashResult
     426          28 : exec_command_a(PsqlScanState scan_state, bool active_branch)
     427             : {
     428          28 :     bool        success = true;
     429             : 
     430          28 :     if (active_branch)
     431             :     {
     432          24 :         if (pset.popt.topt.format != PRINT_ALIGNED)
     433          12 :             success = do_pset("format", "aligned", &pset.popt, pset.quiet);
     434             :         else
     435          12 :             success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
     436             :     }
     437             : 
     438          28 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     439             : }
     440             : 
     441             : /*
     442             :  * \C -- override table title (formerly change HTML caption)
     443             :  */
     444             : static backslashResult
     445           4 : exec_command_C(PsqlScanState scan_state, bool active_branch)
     446             : {
     447           4 :     bool        success = true;
     448             : 
     449           4 :     if (active_branch)
     450             :     {
     451           0 :         char       *opt = psql_scan_slash_option(scan_state,
     452             :                                                  OT_NORMAL, NULL, true);
     453             : 
     454           0 :         success = do_pset("title", opt, &pset.popt, pset.quiet);
     455           0 :         free(opt);
     456             :     }
     457             :     else
     458           4 :         ignore_slash_options(scan_state);
     459             : 
     460           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     461             : }
     462             : 
     463             : /*
     464             :  * \c or \connect -- connect to database using the specified parameters.
     465             :  *
     466             :  * \c [-reuse-previous=BOOL] dbname user host port
     467             :  *
     468             :  * Specifying a parameter as '-' is equivalent to omitting it.  Examples:
     469             :  *
     470             :  * \c - - hst       Connect to current database on current port of
     471             :  *                  host "hst" as current user.
     472             :  * \c - usr - prt   Connect to current database on port "prt" of current host
     473             :  *                  as user "usr".
     474             :  * \c dbs           Connect to database "dbs" on current port of current host
     475             :  *                  as current user.
     476             :  */
     477             : static backslashResult
     478         178 : exec_command_connect(PsqlScanState scan_state, bool active_branch)
     479             : {
     480         178 :     bool        success = true;
     481             : 
     482         178 :     if (active_branch)
     483             :     {
     484             :         static const char prefix[] = "-reuse-previous=";
     485             :         char       *opt1,
     486             :                    *opt2,
     487             :                    *opt3,
     488             :                    *opt4;
     489         174 :         enum trivalue reuse_previous = TRI_DEFAULT;
     490             : 
     491         174 :         opt1 = read_connect_arg(scan_state);
     492         174 :         if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
     493             :         {
     494             :             bool        on_off;
     495             : 
     496          16 :             success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
     497             :                                         "-reuse-previous",
     498             :                                         &on_off);
     499          16 :             if (success)
     500             :             {
     501          16 :                 reuse_previous = on_off ? TRI_YES : TRI_NO;
     502          16 :                 free(opt1);
     503          16 :                 opt1 = read_connect_arg(scan_state);
     504             :             }
     505             :         }
     506             : 
     507         174 :         if (success)            /* give up if reuse_previous was invalid */
     508             :         {
     509         174 :             opt2 = read_connect_arg(scan_state);
     510         174 :             opt3 = read_connect_arg(scan_state);
     511         174 :             opt4 = read_connect_arg(scan_state);
     512             : 
     513         174 :             success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
     514             : 
     515         174 :             free(opt2);
     516         174 :             free(opt3);
     517         174 :             free(opt4);
     518             :         }
     519         174 :         free(opt1);
     520             :     }
     521             :     else
     522           4 :         ignore_slash_options(scan_state);
     523             : 
     524         178 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     525             : }
     526             : 
     527             : /*
     528             :  * \cd -- change directory
     529             :  */
     530             : static backslashResult
     531           4 : exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
     532             : {
     533           4 :     bool        success = true;
     534             : 
     535           4 :     if (active_branch)
     536             :     {
     537           0 :         char       *opt = psql_scan_slash_option(scan_state,
     538             :                                                  OT_NORMAL, NULL, true);
     539             :         char       *dir;
     540             : 
     541           0 :         if (opt)
     542           0 :             dir = opt;
     543             :         else
     544             :         {
     545             : #ifndef WIN32
     546             :             struct passwd *pw;
     547           0 :             uid_t       user_id = geteuid();
     548             : 
     549           0 :             errno = 0;          /* clear errno before call */
     550           0 :             pw = getpwuid(user_id);
     551           0 :             if (!pw)
     552             :             {
     553           0 :                 pg_log_error("could not get home directory for user ID %ld: %s",
     554             :                              (long) user_id,
     555             :                              errno ? strerror(errno) : _("user does not exist"));
     556           0 :                 exit(EXIT_FAILURE);
     557             :             }
     558           0 :             dir = pw->pw_dir;
     559             : #else                           /* WIN32 */
     560             : 
     561             :             /*
     562             :              * On Windows, 'cd' without arguments prints the current
     563             :              * directory, so if someone wants to code this here instead...
     564             :              */
     565             :             dir = "/";
     566             : #endif                          /* WIN32 */
     567             :         }
     568             : 
     569           0 :         if (chdir(dir) == -1)
     570             :         {
     571           0 :             pg_log_error("\\%s: could not change directory to \"%s\": %m",
     572             :                          cmd, dir);
     573           0 :             success = false;
     574             :         }
     575             : 
     576           0 :         if (opt)
     577           0 :             free(opt);
     578             :     }
     579             :     else
     580           4 :         ignore_slash_options(scan_state);
     581             : 
     582           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     583             : }
     584             : 
     585             : /*
     586             :  * \conninfo -- display information about the current connection
     587             :  */
     588             : static backslashResult
     589           4 : exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
     590             : {
     591           4 :     if (active_branch)
     592             :     {
     593           0 :         char       *db = PQdb(pset.db);
     594             : 
     595           0 :         if (db == NULL)
     596           0 :             printf(_("You are currently not connected to a database.\n"));
     597             :         else
     598             :         {
     599           0 :             char       *host = PQhost(pset.db);
     600           0 :             char       *hostaddr = PQhostaddr(pset.db);
     601             : 
     602             :             /*
     603             :              * If the host is an absolute path, the connection is via socket
     604             :              * unless overridden by hostaddr
     605             :              */
     606           0 :             if (is_absolute_path(host))
     607             :             {
     608           0 :                 if (hostaddr && *hostaddr)
     609           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
     610             :                            db, PQuser(pset.db), hostaddr, PQport(pset.db));
     611             :                 else
     612           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
     613             :                            db, PQuser(pset.db), host, PQport(pset.db));
     614             :             }
     615             :             else
     616             :             {
     617           0 :                 if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
     618           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
     619             :                            db, PQuser(pset.db), host, hostaddr, PQport(pset.db));
     620             :                 else
     621           0 :                     printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
     622             :                            db, PQuser(pset.db), host, PQport(pset.db));
     623             :             }
     624           0 :             printSSLInfo();
     625           0 :             printGSSInfo();
     626             :         }
     627             :     }
     628             : 
     629           4 :     return PSQL_CMD_SKIP_LINE;
     630             : }
     631             : 
     632             : /*
     633             :  * \copy -- run a COPY command
     634             :  */
     635             : static backslashResult
     636         130 : exec_command_copy(PsqlScanState scan_state, bool active_branch)
     637             : {
     638         130 :     bool        success = true;
     639             : 
     640         130 :     if (active_branch)
     641             :     {
     642         126 :         char       *opt = psql_scan_slash_option(scan_state,
     643             :                                                  OT_WHOLE_LINE, NULL, false);
     644             : 
     645         126 :         success = do_copy(opt);
     646         126 :         free(opt);
     647             :     }
     648             :     else
     649           4 :         ignore_slash_whole_line(scan_state);
     650             : 
     651         130 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
     652             : }
     653             : 
     654             : /*
     655             :  * \copyright -- print copyright notice
     656             :  */
     657             : static backslashResult
     658           4 : exec_command_copyright(PsqlScanState scan_state, bool active_branch)
     659             : {
     660           4 :     if (active_branch)
     661           0 :         print_copyright();
     662             : 
     663           4 :     return PSQL_CMD_SKIP_LINE;
     664             : }
     665             : 
     666             : /*
     667             :  * \crosstabview -- execute a query and display results in crosstab
     668             :  */
     669             : static backslashResult
     670          88 : exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
     671             : {
     672          88 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     673             : 
     674          88 :     if (active_branch)
     675             :     {
     676             :         int         i;
     677             : 
     678         440 :         for (i = 0; i < lengthof(pset.ctv_args); i++)
     679         352 :             pset.ctv_args[i] = psql_scan_slash_option(scan_state,
     680             :                                                       OT_NORMAL, NULL, true);
     681          88 :         pset.crosstab_flag = true;
     682          88 :         status = PSQL_CMD_SEND;
     683             :     }
     684             :     else
     685           0 :         ignore_slash_options(scan_state);
     686             : 
     687          88 :     return status;
     688             : }
     689             : 
     690             : /*
     691             :  * \d* commands
     692             :  */
     693             : static backslashResult
     694        1974 : exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
     695             : {
     696        1974 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     697        1974 :     bool        success = true;
     698             : 
     699        1974 :     if (active_branch)
     700             :     {
     701             :         char       *pattern;
     702             :         bool        show_verbose,
     703             :                     show_system;
     704             : 
     705             :         /* We don't do SQLID reduction on the pattern yet */
     706        1970 :         pattern = psql_scan_slash_option(scan_state,
     707             :                                          OT_NORMAL, NULL, true);
     708             : 
     709        1970 :         show_verbose = strchr(cmd, '+') ? true : false;
     710        1970 :         show_system = strchr(cmd, 'S') ? true : false;
     711             : 
     712        1970 :         switch (cmd[1])
     713             :         {
     714             :             case '\0':
     715             :             case '+':
     716             :             case 'S':
     717        1544 :                 if (pattern)
     718        1544 :                     success = describeTableDetails(pattern, show_verbose, show_system);
     719             :                 else
     720             :                     /* standard listing of interesting things */
     721           0 :                     success = listTables("tvmsE", NULL, show_verbose, show_system);
     722        1544 :                 break;
     723             :             case 'A':
     724           0 :                 success = describeAccessMethods(pattern, show_verbose);
     725           0 :                 break;
     726             :             case 'a':
     727           4 :                 success = describeAggregates(pattern, show_verbose, show_system);
     728           4 :                 break;
     729             :             case 'b':
     730           0 :                 success = describeTablespaces(pattern, show_verbose);
     731           0 :                 break;
     732             :             case 'c':
     733           0 :                 success = listConversions(pattern, show_verbose, show_system);
     734           0 :                 break;
     735             :             case 'C':
     736           0 :                 success = listCasts(pattern, show_verbose);
     737           0 :                 break;
     738             :             case 'd':
     739           0 :                 if (strncmp(cmd, "ddp", 3) == 0)
     740           0 :                     success = listDefaultACLs(pattern);
     741             :                 else
     742           0 :                     success = objectDescription(pattern, show_system);
     743           0 :                 break;
     744             :             case 'D':
     745           0 :                 success = listDomains(pattern, show_verbose, show_system);
     746           0 :                 break;
     747             :             case 'f':           /* function subsystem */
     748         100 :                 switch (cmd[2])
     749             :                 {
     750             :                     case '\0':
     751             :                     case '+':
     752             :                     case 'S':
     753             :                     case 'a':
     754             :                     case 'n':
     755             :                     case 'p':
     756             :                     case 't':
     757             :                     case 'w':
     758         100 :                         success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
     759         100 :                         break;
     760             :                     default:
     761           0 :                         status = PSQL_CMD_UNKNOWN;
     762           0 :                         break;
     763             :                 }
     764         100 :                 break;
     765             :             case 'g':
     766             :                 /* no longer distinct from \du */
     767           0 :                 success = describeRoles(pattern, show_verbose, show_system);
     768           0 :                 break;
     769             :             case 'l':
     770           0 :                 success = do_lo_list();
     771           0 :                 break;
     772             :             case 'L':
     773           0 :                 success = listLanguages(pattern, show_verbose, show_system);
     774           0 :                 break;
     775             :             case 'n':
     776           0 :                 success = listSchemas(pattern, show_verbose, show_system);
     777           0 :                 break;
     778             :             case 'o':
     779           8 :                 success = describeOperators(pattern, show_verbose, show_system);
     780           8 :                 break;
     781             :             case 'O':
     782           0 :                 success = listCollations(pattern, show_verbose, show_system);
     783           0 :                 break;
     784             :             case 'p':
     785          16 :                 success = permissionsList(pattern);
     786          16 :                 break;
     787             :             case 'P':
     788             :                 {
     789          44 :                     switch (cmd[2])
     790             :                     {
     791             :                         case '\0':
     792             :                         case '+':
     793             :                         case 't':
     794             :                         case 'i':
     795             :                         case 'n':
     796          44 :                             success = listPartitionedTables(&cmd[2], pattern, show_verbose);
     797          44 :                             break;
     798             :                         default:
     799           0 :                             status = PSQL_CMD_UNKNOWN;
     800           0 :                             break;
     801             :                     }
     802             :                 }
     803          44 :                 break;
     804             :             case 'T':
     805          14 :                 success = describeTypes(pattern, show_verbose, show_system);
     806          14 :                 break;
     807             :             case 't':
     808             :             case 'v':
     809             :             case 'm':
     810             :             case 'i':
     811             :             case 's':
     812             :             case 'E':
     813           4 :                 success = listTables(&cmd[1], pattern, show_verbose, show_system);
     814           4 :                 break;
     815             :             case 'r':
     816           0 :                 if (cmd[2] == 'd' && cmd[3] == 's')
     817           0 :                 {
     818           0 :                     char       *pattern2 = NULL;
     819             : 
     820           0 :                     if (pattern)
     821           0 :                         pattern2 = psql_scan_slash_option(scan_state,
     822             :                                                           OT_NORMAL, NULL, true);
     823           0 :                     success = listDbRoleSettings(pattern, pattern2);
     824             : 
     825           0 :                     if (pattern2)
     826           0 :                         free(pattern2);
     827             :                 }
     828             :                 else
     829           0 :                     status = PSQL_CMD_UNKNOWN;
     830           0 :                 break;
     831             :             case 'R':
     832          60 :                 switch (cmd[2])
     833             :                 {
     834             :                     case 'p':
     835          40 :                         if (show_verbose)
     836          24 :                             success = describePublications(pattern);
     837             :                         else
     838          16 :                             success = listPublications(pattern);
     839          40 :                         break;
     840             :                     case 's':
     841          20 :                         success = describeSubscriptions(pattern, show_verbose);
     842          20 :                         break;
     843             :                     default:
     844           0 :                         status = PSQL_CMD_UNKNOWN;
     845             :                 }
     846          60 :                 break;
     847             :             case 'u':
     848           0 :                 success = describeRoles(pattern, show_verbose, show_system);
     849           0 :                 break;
     850             :             case 'F':           /* text search subsystem */
     851           0 :                 switch (cmd[2])
     852             :                 {
     853             :                     case '\0':
     854             :                     case '+':
     855           0 :                         success = listTSConfigs(pattern, show_verbose);
     856           0 :                         break;
     857             :                     case 'p':
     858           0 :                         success = listTSParsers(pattern, show_verbose);
     859           0 :                         break;
     860             :                     case 'd':
     861           0 :                         success = listTSDictionaries(pattern, show_verbose);
     862           0 :                         break;
     863             :                     case 't':
     864           0 :                         success = listTSTemplates(pattern, show_verbose);
     865           0 :                         break;
     866             :                     default:
     867           0 :                         status = PSQL_CMD_UNKNOWN;
     868           0 :                         break;
     869             :                 }
     870           0 :                 break;
     871             :             case 'e':           /* SQL/MED subsystem */
     872         164 :                 switch (cmd[2])
     873             :                 {
     874             :                     case 's':
     875          48 :                         success = listForeignServers(pattern, show_verbose);
     876          48 :                         break;
     877             :                     case 'u':
     878          40 :                         success = listUserMappings(pattern, show_verbose);
     879          40 :                         break;
     880             :                     case 'w':
     881          60 :                         success = listForeignDataWrappers(pattern, show_verbose);
     882          60 :                         break;
     883             :                     case 't':
     884          16 :                         success = listForeignTables(pattern, show_verbose);
     885          16 :                         break;
     886             :                     default:
     887           0 :                         status = PSQL_CMD_UNKNOWN;
     888           0 :                         break;
     889             :                 }
     890         164 :                 break;
     891             :             case 'x':           /* Extensions */
     892          12 :                 if (show_verbose)
     893          12 :                     success = listExtensionContents(pattern);
     894             :                 else
     895           0 :                     success = listExtensions(pattern);
     896          12 :                 break;
     897             :             case 'y':           /* Event Triggers */
     898           0 :                 success = listEventTriggers(pattern, show_verbose);
     899           0 :                 break;
     900             :             default:
     901           0 :                 status = PSQL_CMD_UNKNOWN;
     902             :         }
     903             : 
     904        1970 :         if (pattern)
     905        1750 :             free(pattern);
     906             :     }
     907             :     else
     908           4 :         ignore_slash_options(scan_state);
     909             : 
     910        1974 :     if (!success)
     911          10 :         status = PSQL_CMD_ERROR;
     912             : 
     913        1974 :     return status;
     914             : }
     915             : 
     916             : /*
     917             :  * \e or \edit -- edit the current query buffer, or edit a file and
     918             :  * make it the query buffer
     919             :  */
     920             : static backslashResult
     921           4 : exec_command_edit(PsqlScanState scan_state, bool active_branch,
     922             :                   PQExpBuffer query_buf, PQExpBuffer previous_buf)
     923             : {
     924           4 :     backslashResult status = PSQL_CMD_SKIP_LINE;
     925             : 
     926           4 :     if (active_branch)
     927             :     {
     928           0 :         if (!query_buf)
     929             :         {
     930           0 :             pg_log_error("no query buffer");
     931           0 :             status = PSQL_CMD_ERROR;
     932             :         }
     933             :         else
     934             :         {
     935             :             char       *fname;
     936           0 :             char       *ln = NULL;
     937           0 :             int         lineno = -1;
     938             : 
     939           0 :             fname = psql_scan_slash_option(scan_state,
     940             :                                            OT_NORMAL, NULL, true);
     941           0 :             if (fname)
     942             :             {
     943             :                 /* try to get separate lineno arg */
     944           0 :                 ln = psql_scan_slash_option(scan_state,
     945             :                                             OT_NORMAL, NULL, true);
     946           0 :                 if (ln == NULL)
     947             :                 {
     948             :                     /* only one arg; maybe it is lineno not fname */
     949           0 :                     if (fname[0] &&
     950           0 :                         strspn(fname, "0123456789") == strlen(fname))
     951             :                     {
     952             :                         /* all digits, so assume it is lineno */
     953           0 :                         ln = fname;
     954           0 :                         fname = NULL;
     955             :                     }
     956             :                 }
     957             :             }
     958           0 :             if (ln)
     959             :             {
     960           0 :                 lineno = atoi(ln);
     961           0 :                 if (lineno < 1)
     962             :                 {
     963           0 :                     pg_log_error("invalid line number: %s", ln);
     964           0 :                     status = PSQL_CMD_ERROR;
     965             :                 }
     966             :             }
     967           0 :             if (status != PSQL_CMD_ERROR)
     968             :             {
     969           0 :                 expand_tilde(&fname);
     970           0 :                 if (fname)
     971           0 :                     canonicalize_path(fname);
     972             : 
     973             :                 /* If query_buf is empty, recall previous query for editing */
     974           0 :                 copy_previous_query(query_buf, previous_buf);
     975             : 
     976           0 :                 if (do_edit(fname, query_buf, lineno, NULL))
     977           0 :                     status = PSQL_CMD_NEWEDIT;
     978             :                 else
     979           0 :                     status = PSQL_CMD_ERROR;
     980             :             }
     981           0 :             if (fname)
     982           0 :                 free(fname);
     983           0 :             if (ln)
     984           0 :                 free(ln);
     985             :         }
     986             :     }
     987             :     else
     988           4 :         ignore_slash_options(scan_state);
     989             : 
     990           4 :     return status;
     991             : }
     992             : 
     993             : /*
     994             :  * \ef/\ev -- edit the named function/view, or
     995             :  * present a blank CREATE FUNCTION/VIEW template if no argument is given
     996             :  */
     997             : static backslashResult
     998           8 : exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
     999             :                    PQExpBuffer query_buf, bool is_func)
    1000             : {
    1001           8 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1002             : 
    1003           8 :     if (active_branch)
    1004             :     {
    1005           0 :         char       *obj_desc = psql_scan_slash_option(scan_state,
    1006             :                                                       OT_WHOLE_LINE,
    1007             :                                                       NULL, true);
    1008           0 :         int         lineno = -1;
    1009             : 
    1010           0 :         if (pset.sversion < (is_func ? 80400 : 70400))
    1011             :         {
    1012             :             char        sverbuf[32];
    1013             : 
    1014           0 :             formatPGVersionNumber(pset.sversion, false,
    1015             :                                   sverbuf, sizeof(sverbuf));
    1016           0 :             if (is_func)
    1017           0 :                 pg_log_error("The server (version %s) does not support editing function source.",
    1018             :                              sverbuf);
    1019             :             else
    1020           0 :                 pg_log_error("The server (version %s) does not support editing view definitions.",
    1021             :                              sverbuf);
    1022           0 :             status = PSQL_CMD_ERROR;
    1023             :         }
    1024           0 :         else if (!query_buf)
    1025             :         {
    1026           0 :             pg_log_error("no query buffer");
    1027           0 :             status = PSQL_CMD_ERROR;
    1028             :         }
    1029             :         else
    1030             :         {
    1031           0 :             Oid         obj_oid = InvalidOid;
    1032           0 :             EditableObjectType eot = is_func ? EditableFunction : EditableView;
    1033             : 
    1034           0 :             lineno = strip_lineno_from_objdesc(obj_desc);
    1035           0 :             if (lineno == 0)
    1036             :             {
    1037             :                 /* error already reported */
    1038           0 :                 status = PSQL_CMD_ERROR;
    1039             :             }
    1040           0 :             else if (!obj_desc)
    1041             :             {
    1042             :                 /* set up an empty command to fill in */
    1043           0 :                 resetPQExpBuffer(query_buf);
    1044           0 :                 if (is_func)
    1045           0 :                     appendPQExpBufferStr(query_buf,
    1046             :                                          "CREATE FUNCTION ( )\n"
    1047             :                                          " RETURNS \n"
    1048             :                                          " LANGUAGE \n"
    1049             :                                          " -- common options:  IMMUTABLE  STABLE  STRICT  SECURITY DEFINER\n"
    1050             :                                          "AS $function$\n"
    1051             :                                          "\n$function$\n");
    1052             :                 else
    1053           0 :                     appendPQExpBufferStr(query_buf,
    1054             :                                          "CREATE VIEW  AS\n"
    1055             :                                          " SELECT \n"
    1056             :                                          "  -- something...\n");
    1057             :             }
    1058           0 :             else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
    1059             :             {
    1060             :                 /* error already reported */
    1061           0 :                 status = PSQL_CMD_ERROR;
    1062             :             }
    1063           0 :             else if (!get_create_object_cmd(eot, obj_oid, query_buf))
    1064             :             {
    1065             :                 /* error already reported */
    1066           0 :                 status = PSQL_CMD_ERROR;
    1067             :             }
    1068           0 :             else if (is_func && lineno > 0)
    1069             :             {
    1070             :                 /*
    1071             :                  * lineno "1" should correspond to the first line of the
    1072             :                  * function body.  We expect that pg_get_functiondef() will
    1073             :                  * emit that on a line beginning with "AS ", and that there
    1074             :                  * can be no such line before the real start of the function
    1075             :                  * body.  Increment lineno by the number of lines before that
    1076             :                  * line, so that it becomes relative to the first line of the
    1077             :                  * function definition.
    1078             :                  */
    1079           0 :                 const char *lines = query_buf->data;
    1080             : 
    1081           0 :                 while (*lines != '\0')
    1082             :                 {
    1083           0 :                     if (strncmp(lines, "AS ", 3) == 0)
    1084           0 :                         break;
    1085           0 :                     lineno++;
    1086             :                     /* find start of next line */
    1087           0 :                     lines = strchr(lines, '\n');
    1088           0 :                     if (!lines)
    1089           0 :                         break;
    1090           0 :                     lines++;
    1091             :                 }
    1092             :             }
    1093             :         }
    1094             : 
    1095           0 :         if (status != PSQL_CMD_ERROR)
    1096             :         {
    1097           0 :             bool        edited = false;
    1098             : 
    1099           0 :             if (!do_edit(NULL, query_buf, lineno, &edited))
    1100           0 :                 status = PSQL_CMD_ERROR;
    1101           0 :             else if (!edited)
    1102           0 :                 puts(_("No changes"));
    1103             :             else
    1104           0 :                 status = PSQL_CMD_NEWEDIT;
    1105             :         }
    1106             : 
    1107           0 :         if (obj_desc)
    1108           0 :             free(obj_desc);
    1109             :     }
    1110             :     else
    1111           8 :         ignore_slash_whole_line(scan_state);
    1112             : 
    1113           8 :     return status;
    1114             : }
    1115             : 
    1116             : /*
    1117             :  * \echo and \qecho -- echo arguments to stdout or query output
    1118             :  */
    1119             : static backslashResult
    1120         340 : exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1121             : {
    1122         340 :     if (active_branch)
    1123             :     {
    1124             :         char       *value;
    1125             :         char        quoted;
    1126         260 :         bool        no_newline = false;
    1127         260 :         bool        first = true;
    1128             :         FILE       *fout;
    1129             : 
    1130         260 :         if (strcmp(cmd, "qecho") == 0)
    1131           0 :             fout = pset.queryFout;
    1132             :         else
    1133         260 :             fout = stdout;
    1134             : 
    1135         972 :         while ((value = psql_scan_slash_option(scan_state,
    1136             :                                                OT_NORMAL, &quoted, false)))
    1137             :         {
    1138         452 :             if (!quoted && strcmp(value, "-n") == 0)
    1139           0 :                 no_newline = true;
    1140             :             else
    1141             :             {
    1142         452 :                 if (first)
    1143         260 :                     first = false;
    1144             :                 else
    1145         192 :                     fputc(' ', fout);
    1146         452 :                 fputs(value, fout);
    1147             :             }
    1148         452 :             free(value);
    1149             :         }
    1150         260 :         if (!no_newline)
    1151         260 :             fputs("\n", fout);
    1152             :     }
    1153             :     else
    1154          80 :         ignore_slash_options(scan_state);
    1155             : 
    1156         340 :     return PSQL_CMD_SKIP_LINE;
    1157             : }
    1158             : 
    1159             : /*
    1160             :  * \encoding -- set/show client side encoding
    1161             :  */
    1162             : static backslashResult
    1163           4 : exec_command_encoding(PsqlScanState scan_state, bool active_branch)
    1164             : {
    1165           4 :     if (active_branch)
    1166             :     {
    1167           0 :         char       *encoding = psql_scan_slash_option(scan_state,
    1168             :                                                       OT_NORMAL, NULL, false);
    1169             : 
    1170           0 :         if (!encoding)
    1171             :         {
    1172             :             /* show encoding */
    1173           0 :             puts(pg_encoding_to_char(pset.encoding));
    1174             :         }
    1175             :         else
    1176             :         {
    1177             :             /* set encoding */
    1178           0 :             if (PQsetClientEncoding(pset.db, encoding) == -1)
    1179           0 :                 pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
    1180             :             else
    1181             :             {
    1182             :                 /* save encoding info into psql internal data */
    1183           0 :                 pset.encoding = PQclientEncoding(pset.db);
    1184           0 :                 pset.popt.topt.encoding = pset.encoding;
    1185           0 :                 SetVariable(pset.vars, "ENCODING",
    1186             :                             pg_encoding_to_char(pset.encoding));
    1187             :             }
    1188           0 :             free(encoding);
    1189             :         }
    1190             :     }
    1191             :     else
    1192           4 :         ignore_slash_options(scan_state);
    1193             : 
    1194           4 :     return PSQL_CMD_SKIP_LINE;
    1195             : }
    1196             : 
    1197             : /*
    1198             :  * \errverbose -- display verbose message from last failed query
    1199             :  */
    1200             : static backslashResult
    1201           4 : exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
    1202             : {
    1203           4 :     if (active_branch)
    1204             :     {
    1205           0 :         if (pset.last_error_result)
    1206             :         {
    1207             :             char       *msg;
    1208             : 
    1209           0 :             msg = PQresultVerboseErrorMessage(pset.last_error_result,
    1210             :                                               PQERRORS_VERBOSE,
    1211             :                                               PQSHOW_CONTEXT_ALWAYS);
    1212           0 :             if (msg)
    1213             :             {
    1214           0 :                 pg_log_error("%s", msg);
    1215           0 :                 PQfreemem(msg);
    1216             :             }
    1217             :             else
    1218           0 :                 puts(_("out of memory"));
    1219             :         }
    1220             :         else
    1221           0 :             puts(_("There is no previous error."));
    1222             :     }
    1223             : 
    1224           4 :     return PSQL_CMD_SKIP_LINE;
    1225             : }
    1226             : 
    1227             : /*
    1228             :  * \f -- change field separator
    1229             :  */
    1230             : static backslashResult
    1231           0 : exec_command_f(PsqlScanState scan_state, bool active_branch)
    1232             : {
    1233           0 :     bool        success = true;
    1234             : 
    1235           0 :     if (active_branch)
    1236             :     {
    1237           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1238             :                                                    OT_NORMAL, NULL, false);
    1239             : 
    1240           0 :         success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
    1241           0 :         free(fname);
    1242             :     }
    1243             :     else
    1244           0 :         ignore_slash_options(scan_state);
    1245             : 
    1246           0 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1247             : }
    1248             : 
    1249             : /*
    1250             :  * \g [filename] -- send query, optionally with output to file/pipe
    1251             :  * \gx [filename] -- same as \g, with expanded mode forced
    1252             :  */
    1253             : static backslashResult
    1254          64 : exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1255             : {
    1256          64 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1257             : 
    1258          64 :     if (active_branch)
    1259             :     {
    1260          56 :         char       *fname = psql_scan_slash_option(scan_state,
    1261             :                                                    OT_FILEPIPE, NULL, false);
    1262             : 
    1263          56 :         if (!fname)
    1264          56 :             pset.gfname = NULL;
    1265             :         else
    1266             :         {
    1267           0 :             expand_tilde(&fname);
    1268           0 :             pset.gfname = pg_strdup(fname);
    1269             :         }
    1270          56 :         free(fname);
    1271          56 :         if (strcmp(cmd, "gx") == 0)
    1272          16 :             pset.g_expanded = true;
    1273          56 :         status = PSQL_CMD_SEND;
    1274             :     }
    1275             :     else
    1276           8 :         ignore_slash_filepipe(scan_state);
    1277             : 
    1278          64 :     return status;
    1279             : }
    1280             : 
    1281             : /*
    1282             :  * \gdesc -- describe query result
    1283             :  */
    1284             : static backslashResult
    1285          40 : exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
    1286             : {
    1287          40 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1288             : 
    1289          40 :     if (active_branch)
    1290             :     {
    1291          40 :         pset.gdesc_flag = true;
    1292          40 :         status = PSQL_CMD_SEND;
    1293             :     }
    1294             : 
    1295          40 :     return status;
    1296             : }
    1297             : 
    1298             : /*
    1299             :  * \gexec -- send query and execute each field of result
    1300             :  */
    1301             : static backslashResult
    1302          22 : exec_command_gexec(PsqlScanState scan_state, bool active_branch)
    1303             : {
    1304          22 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1305             : 
    1306          22 :     if (active_branch)
    1307             :     {
    1308          18 :         pset.gexec_flag = true;
    1309          18 :         status = PSQL_CMD_SEND;
    1310             :     }
    1311             : 
    1312          22 :     return status;
    1313             : }
    1314             : 
    1315             : /*
    1316             :  * \gset [prefix] -- send query and store result into variables
    1317             :  */
    1318             : static backslashResult
    1319          96 : exec_command_gset(PsqlScanState scan_state, bool active_branch)
    1320             : {
    1321          96 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1322             : 
    1323          96 :     if (active_branch)
    1324             :     {
    1325          96 :         char       *prefix = psql_scan_slash_option(scan_state,
    1326             :                                                     OT_NORMAL, NULL, false);
    1327             : 
    1328          96 :         if (prefix)
    1329          28 :             pset.gset_prefix = prefix;
    1330             :         else
    1331             :         {
    1332             :             /* we must set a non-NULL prefix to trigger storing */
    1333          68 :             pset.gset_prefix = pg_strdup("");
    1334             :         }
    1335             :         /* gset_prefix is freed later */
    1336          96 :         status = PSQL_CMD_SEND;
    1337             :     }
    1338             :     else
    1339           0 :         ignore_slash_options(scan_state);
    1340             : 
    1341          96 :     return status;
    1342             : }
    1343             : 
    1344             : /*
    1345             :  * \help [topic] -- print help about SQL commands
    1346             :  */
    1347             : static backslashResult
    1348           4 : exec_command_help(PsqlScanState scan_state, bool active_branch)
    1349             : {
    1350           4 :     if (active_branch)
    1351             :     {
    1352           0 :         char       *opt = psql_scan_slash_option(scan_state,
    1353             :                                                  OT_WHOLE_LINE, NULL, false);
    1354             :         size_t      len;
    1355             : 
    1356             :         /* strip any trailing spaces and semicolons */
    1357           0 :         if (opt)
    1358             :         {
    1359           0 :             len = strlen(opt);
    1360           0 :             while (len > 0 &&
    1361           0 :                    (isspace((unsigned char) opt[len - 1])
    1362           0 :                     || opt[len - 1] == ';'))
    1363           0 :                 opt[--len] = '\0';
    1364             :         }
    1365             : 
    1366           0 :         helpSQL(opt, pset.popt.topt.pager);
    1367           0 :         free(opt);
    1368             :     }
    1369             :     else
    1370           4 :         ignore_slash_whole_line(scan_state);
    1371             : 
    1372           4 :     return PSQL_CMD_SKIP_LINE;
    1373             : }
    1374             : 
    1375             : /*
    1376             :  * \H and \html -- toggle HTML formatting
    1377             :  */
    1378             : static backslashResult
    1379           0 : exec_command_html(PsqlScanState scan_state, bool active_branch)
    1380             : {
    1381           0 :     bool        success = true;
    1382             : 
    1383           0 :     if (active_branch)
    1384             :     {
    1385           0 :         if (pset.popt.topt.format != PRINT_HTML)
    1386           0 :             success = do_pset("format", "html", &pset.popt, pset.quiet);
    1387             :         else
    1388           0 :             success = do_pset("format", "aligned", &pset.popt, pset.quiet);
    1389             :     }
    1390             : 
    1391           0 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1392             : }
    1393             : 
    1394             : /*
    1395             :  * \i and \ir -- include a file
    1396             :  */
    1397             : static backslashResult
    1398           0 : exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1399             : {
    1400           0 :     bool        success = true;
    1401             : 
    1402           0 :     if (active_branch)
    1403             :     {
    1404           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1405             :                                                    OT_NORMAL, NULL, true);
    1406             : 
    1407           0 :         if (!fname)
    1408             :         {
    1409           0 :             pg_log_error("\\%s: missing required argument", cmd);
    1410           0 :             success = false;
    1411             :         }
    1412             :         else
    1413             :         {
    1414             :             bool        include_relative;
    1415             : 
    1416           0 :             include_relative = (strcmp(cmd, "ir") == 0
    1417           0 :                                 || strcmp(cmd, "include_relative") == 0);
    1418           0 :             expand_tilde(&fname);
    1419           0 :             success = (process_file(fname, include_relative) == EXIT_SUCCESS);
    1420           0 :             free(fname);
    1421             :         }
    1422             :     }
    1423             :     else
    1424           0 :         ignore_slash_options(scan_state);
    1425             : 
    1426           0 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1427             : }
    1428             : 
    1429             : /*
    1430             :  * \if <expr> -- beginning of an \if..\endif block
    1431             :  *
    1432             :  * <expr> is parsed as a boolean expression.  Invalid expressions will emit a
    1433             :  * warning and be treated as false.  Statements that follow a false expression
    1434             :  * will be parsed but ignored.  Note that in the case where an \if statement
    1435             :  * is itself within an inactive section of a block, then the entire inner
    1436             :  * \if..\endif block will be parsed but ignored.
    1437             :  */
    1438             : static backslashResult
    1439          72 : exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
    1440             :                 PQExpBuffer query_buf)
    1441             : {
    1442          72 :     if (conditional_active(cstack))
    1443             :     {
    1444             :         /*
    1445             :          * First, push a new active stack entry; this ensures that the lexer
    1446             :          * will perform variable substitution and backtick evaluation while
    1447             :          * scanning the expression.  (That should happen anyway, since we know
    1448             :          * we're in an active outer branch, but let's be sure.)
    1449             :          */
    1450          68 :         conditional_stack_push(cstack, IFSTATE_TRUE);
    1451             : 
    1452             :         /* Remember current query state in case we need to restore later */
    1453          68 :         save_query_text_state(scan_state, cstack, query_buf);
    1454             : 
    1455             :         /*
    1456             :          * Evaluate the expression; if it's false, change to inactive state.
    1457             :          */
    1458          68 :         if (!is_true_boolean_expression(scan_state, "\\if expression"))
    1459          32 :             conditional_stack_poke(cstack, IFSTATE_FALSE);
    1460             :     }
    1461             :     else
    1462             :     {
    1463             :         /*
    1464             :          * We're within an inactive outer branch, so this entire \if block
    1465             :          * will be ignored.  We don't want to evaluate the expression, so push
    1466             :          * the "ignored" stack state before scanning it.
    1467             :          */
    1468           4 :         conditional_stack_push(cstack, IFSTATE_IGNORED);
    1469             : 
    1470             :         /* Remember current query state in case we need to restore later */
    1471           4 :         save_query_text_state(scan_state, cstack, query_buf);
    1472             : 
    1473           4 :         ignore_boolean_expression(scan_state);
    1474             :     }
    1475             : 
    1476          72 :     return PSQL_CMD_SKIP_LINE;
    1477             : }
    1478             : 
    1479             : /*
    1480             :  * \elif <expr> -- alternative branch in an \if..\endif block
    1481             :  *
    1482             :  * <expr> is evaluated the same as in \if <expr>.
    1483             :  */
    1484             : static backslashResult
    1485          24 : exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
    1486             :                   PQExpBuffer query_buf)
    1487             : {
    1488          24 :     bool        success = true;
    1489             : 
    1490          24 :     switch (conditional_stack_peek(cstack))
    1491             :     {
    1492             :         case IFSTATE_TRUE:
    1493             : 
    1494             :             /*
    1495             :              * Just finished active branch of this \if block.  Update saved
    1496             :              * state so we will keep whatever data was put in query_buf by the
    1497             :              * active branch.
    1498             :              */
    1499           0 :             save_query_text_state(scan_state, cstack, query_buf);
    1500             : 
    1501             :             /*
    1502             :              * Discard \elif expression and ignore the rest until \endif.
    1503             :              * Switch state before reading expression to ensure proper lexer
    1504             :              * behavior.
    1505             :              */
    1506           0 :             conditional_stack_poke(cstack, IFSTATE_IGNORED);
    1507           0 :             ignore_boolean_expression(scan_state);
    1508           0 :             break;
    1509             :         case IFSTATE_FALSE:
    1510             : 
    1511             :             /*
    1512             :              * Discard any query text added by the just-skipped branch.
    1513             :              */
    1514          16 :             discard_query_text(scan_state, cstack, query_buf);
    1515             : 
    1516             :             /*
    1517             :              * Have not yet found a true expression in this \if block, so this
    1518             :              * might be the first.  We have to change state before examining
    1519             :              * the expression, or the lexer won't do the right thing.
    1520             :              */
    1521          16 :             conditional_stack_poke(cstack, IFSTATE_TRUE);
    1522          16 :             if (!is_true_boolean_expression(scan_state, "\\elif expression"))
    1523          12 :                 conditional_stack_poke(cstack, IFSTATE_FALSE);
    1524          16 :             break;
    1525             :         case IFSTATE_IGNORED:
    1526             : 
    1527             :             /*
    1528             :              * Discard any query text added by the just-skipped branch.
    1529             :              */
    1530           0 :             discard_query_text(scan_state, cstack, query_buf);
    1531             : 
    1532             :             /*
    1533             :              * Skip expression and move on.  Either the \if block already had
    1534             :              * an active section, or whole block is being skipped.
    1535             :              */
    1536           0 :             ignore_boolean_expression(scan_state);
    1537           0 :             break;
    1538             :         case IFSTATE_ELSE_TRUE:
    1539             :         case IFSTATE_ELSE_FALSE:
    1540           4 :             pg_log_error("\\elif: cannot occur after \\else");
    1541           4 :             success = false;
    1542           4 :             break;
    1543             :         case IFSTATE_NONE:
    1544             :             /* no \if to elif from */
    1545           4 :             pg_log_error("\\elif: no matching \\if");
    1546           4 :             success = false;
    1547           4 :             break;
    1548             :     }
    1549             : 
    1550          24 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1551             : }
    1552             : 
    1553             : /*
    1554             :  * \else -- final alternative in an \if..\endif block
    1555             :  *
    1556             :  * Statements within an \else branch will only be executed if
    1557             :  * all previous \if and \elif expressions evaluated to false
    1558             :  * and the block was not itself being ignored.
    1559             :  */
    1560             : static backslashResult
    1561          80 : exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
    1562             :                   PQExpBuffer query_buf)
    1563             : {
    1564          80 :     bool        success = true;
    1565             : 
    1566          80 :     switch (conditional_stack_peek(cstack))
    1567             :     {
    1568             :         case IFSTATE_TRUE:
    1569             : 
    1570             :             /*
    1571             :              * Just finished active branch of this \if block.  Update saved
    1572             :              * state so we will keep whatever data was put in query_buf by the
    1573             :              * active branch.
    1574             :              */
    1575          40 :             save_query_text_state(scan_state, cstack, query_buf);
    1576             : 
    1577             :             /* Now skip the \else branch */
    1578          40 :             conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
    1579          40 :             break;
    1580             :         case IFSTATE_FALSE:
    1581             : 
    1582             :             /*
    1583             :              * Discard any query text added by the just-skipped branch.
    1584             :              */
    1585          28 :             discard_query_text(scan_state, cstack, query_buf);
    1586             : 
    1587             :             /*
    1588             :              * We've not found any true \if or \elif expression, so execute
    1589             :              * the \else branch.
    1590             :              */
    1591          28 :             conditional_stack_poke(cstack, IFSTATE_ELSE_TRUE);
    1592          28 :             break;
    1593             :         case IFSTATE_IGNORED:
    1594             : 
    1595             :             /*
    1596             :              * Discard any query text added by the just-skipped branch.
    1597             :              */
    1598           4 :             discard_query_text(scan_state, cstack, query_buf);
    1599             : 
    1600             :             /*
    1601             :              * Either we previously processed the active branch of this \if,
    1602             :              * or the whole \if block is being skipped.  Either way, skip the
    1603             :              * \else branch.
    1604             :              */
    1605           4 :             conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
    1606           4 :             break;
    1607             :         case IFSTATE_ELSE_TRUE:
    1608             :         case IFSTATE_ELSE_FALSE:
    1609           4 :             pg_log_error("\\else: cannot occur after \\else");
    1610           4 :             success = false;
    1611           4 :             break;
    1612             :         case IFSTATE_NONE:
    1613             :             /* no \if to else from */
    1614           4 :             pg_log_error("\\else: no matching \\if");
    1615           4 :             success = false;
    1616           4 :             break;
    1617             :     }
    1618             : 
    1619          80 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1620             : }
    1621             : 
    1622             : /*
    1623             :  * \endif -- ends an \if...\endif block
    1624             :  */
    1625             : static backslashResult
    1626          76 : exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
    1627             :                    PQExpBuffer query_buf)
    1628             : {
    1629          76 :     bool        success = true;
    1630             : 
    1631          76 :     switch (conditional_stack_peek(cstack))
    1632             :     {
    1633             :         case IFSTATE_TRUE:
    1634             :         case IFSTATE_ELSE_TRUE:
    1635             :             /* Close the \if block, keeping the query text */
    1636          28 :             success = conditional_stack_pop(cstack);
    1637             :             Assert(success);
    1638          28 :             break;
    1639             :         case IFSTATE_FALSE:
    1640             :         case IFSTATE_IGNORED:
    1641             :         case IFSTATE_ELSE_FALSE:
    1642             : 
    1643             :             /*
    1644             :              * Discard any query text added by the just-skipped branch.
    1645             :              */
    1646          44 :             discard_query_text(scan_state, cstack, query_buf);
    1647             : 
    1648             :             /* Close the \if block */
    1649          44 :             success = conditional_stack_pop(cstack);
    1650             :             Assert(success);
    1651          44 :             break;
    1652             :         case IFSTATE_NONE:
    1653             :             /* no \if to end */
    1654           4 :             pg_log_error("\\endif: no matching \\if");
    1655           4 :             success = false;
    1656           4 :             break;
    1657             :     }
    1658             : 
    1659          76 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1660             : }
    1661             : 
    1662             : /*
    1663             :  * \l -- list databases
    1664             :  */
    1665             : static backslashResult
    1666           0 : exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1667             : {
    1668           0 :     bool        success = true;
    1669             : 
    1670           0 :     if (active_branch)
    1671             :     {
    1672             :         char       *pattern;
    1673             :         bool        show_verbose;
    1674             : 
    1675           0 :         pattern = psql_scan_slash_option(scan_state,
    1676             :                                          OT_NORMAL, NULL, true);
    1677             : 
    1678           0 :         show_verbose = strchr(cmd, '+') ? true : false;
    1679             : 
    1680           0 :         success = listAllDbs(pattern, show_verbose);
    1681             : 
    1682           0 :         if (pattern)
    1683           0 :             free(pattern);
    1684             :     }
    1685             :     else
    1686           0 :         ignore_slash_options(scan_state);
    1687             : 
    1688           0 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1689             : }
    1690             : 
    1691             : /*
    1692             :  * \lo_* -- large object operations
    1693             :  */
    1694             : static backslashResult
    1695          24 : exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
    1696             : {
    1697          24 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    1698          24 :     bool        success = true;
    1699             : 
    1700          24 :     if (active_branch)
    1701             :     {
    1702             :         char       *opt1,
    1703             :                    *opt2;
    1704             : 
    1705          24 :         opt1 = psql_scan_slash_option(scan_state,
    1706             :                                       OT_NORMAL, NULL, true);
    1707          24 :         opt2 = psql_scan_slash_option(scan_state,
    1708             :                                       OT_NORMAL, NULL, true);
    1709             : 
    1710          24 :         if (strcmp(cmd + 3, "export") == 0)
    1711             :         {
    1712           4 :             if (!opt2)
    1713             :             {
    1714           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1715           0 :                 success = false;
    1716             :             }
    1717             :             else
    1718             :             {
    1719           4 :                 expand_tilde(&opt2);
    1720           4 :                 success = do_lo_export(opt1, opt2);
    1721             :             }
    1722             :         }
    1723             : 
    1724          20 :         else if (strcmp(cmd + 3, "import") == 0)
    1725             :         {
    1726           8 :             if (!opt1)
    1727             :             {
    1728           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1729           0 :                 success = false;
    1730             :             }
    1731             :             else
    1732             :             {
    1733           8 :                 expand_tilde(&opt1);
    1734           8 :                 success = do_lo_import(opt1, opt2);
    1735             :             }
    1736             :         }
    1737             : 
    1738          12 :         else if (strcmp(cmd + 3, "list") == 0)
    1739           0 :             success = do_lo_list();
    1740             : 
    1741          12 :         else if (strcmp(cmd + 3, "unlink") == 0)
    1742             :         {
    1743          12 :             if (!opt1)
    1744             :             {
    1745           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    1746           0 :                 success = false;
    1747             :             }
    1748             :             else
    1749          12 :                 success = do_lo_unlink(opt1);
    1750             :         }
    1751             : 
    1752             :         else
    1753           0 :             status = PSQL_CMD_UNKNOWN;
    1754             : 
    1755          24 :         free(opt1);
    1756          24 :         free(opt2);
    1757             :     }
    1758             :     else
    1759           0 :         ignore_slash_options(scan_state);
    1760             : 
    1761          24 :     if (!success)
    1762           0 :         status = PSQL_CMD_ERROR;
    1763             : 
    1764          24 :     return status;
    1765             : }
    1766             : 
    1767             : /*
    1768             :  * \o -- set query output
    1769             :  */
    1770             : static backslashResult
    1771           4 : exec_command_out(PsqlScanState scan_state, bool active_branch)
    1772             : {
    1773           4 :     bool        success = true;
    1774             : 
    1775           4 :     if (active_branch)
    1776             :     {
    1777           0 :         char       *fname = psql_scan_slash_option(scan_state,
    1778             :                                                    OT_FILEPIPE, NULL, true);
    1779             : 
    1780           0 :         expand_tilde(&fname);
    1781           0 :         success = setQFout(fname);
    1782           0 :         free(fname);
    1783             :     }
    1784             :     else
    1785           4 :         ignore_slash_filepipe(scan_state);
    1786             : 
    1787           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1788             : }
    1789             : 
    1790             : /*
    1791             :  * \p -- print the current query buffer
    1792             :  */
    1793             : static backslashResult
    1794          28 : exec_command_print(PsqlScanState scan_state, bool active_branch,
    1795             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    1796             : {
    1797          28 :     if (active_branch)
    1798             :     {
    1799             :         /*
    1800             :          * We want to print the same thing \g would execute, but not to change
    1801             :          * the query buffer state; so we can't use copy_previous_query().
    1802             :          * Also, beware of possibility that buffer pointers are NULL.
    1803             :          */
    1804          24 :         if (query_buf && query_buf->len > 0)
    1805          12 :             puts(query_buf->data);
    1806          12 :         else if (previous_buf && previous_buf->len > 0)
    1807          12 :             puts(previous_buf->data);
    1808           0 :         else if (!pset.quiet)
    1809           0 :             puts(_("Query buffer is empty."));
    1810          24 :         fflush(stdout);
    1811             :     }
    1812             : 
    1813          28 :     return PSQL_CMD_SKIP_LINE;
    1814             : }
    1815             : 
    1816             : /*
    1817             :  * \password -- set user password
    1818             :  */
    1819             : static backslashResult
    1820           4 : exec_command_password(PsqlScanState scan_state, bool active_branch)
    1821             : {
    1822           4 :     bool        success = true;
    1823             : 
    1824           4 :     if (active_branch)
    1825             :     {
    1826           0 :         char       *opt0 = psql_scan_slash_option(scan_state,
    1827             :                                                   OT_SQLID, NULL, true);
    1828             :         char        pw1[100];
    1829             :         char        pw2[100];
    1830             : 
    1831           0 :         simple_prompt("Enter new password: ", pw1, sizeof(pw1), false);
    1832           0 :         simple_prompt("Enter it again: ", pw2, sizeof(pw2), false);
    1833             : 
    1834           0 :         if (strcmp(pw1, pw2) != 0)
    1835             :         {
    1836           0 :             pg_log_error("Passwords didn't match.");
    1837           0 :             success = false;
    1838             :         }
    1839             :         else
    1840             :         {
    1841             :             char       *user;
    1842             :             char       *encrypted_password;
    1843             : 
    1844           0 :             if (opt0)
    1845           0 :                 user = opt0;
    1846             :             else
    1847           0 :                 user = PQuser(pset.db);
    1848             : 
    1849           0 :             encrypted_password = PQencryptPasswordConn(pset.db, pw1, user, NULL);
    1850             : 
    1851           0 :             if (!encrypted_password)
    1852             :             {
    1853           0 :                 pg_log_info("%s", PQerrorMessage(pset.db));
    1854           0 :                 success = false;
    1855             :             }
    1856             :             else
    1857             :             {
    1858             :                 PQExpBufferData buf;
    1859             :                 PGresult   *res;
    1860             : 
    1861           0 :                 initPQExpBuffer(&buf);
    1862           0 :                 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
    1863             :                                   fmtId(user));
    1864           0 :                 appendStringLiteralConn(&buf, encrypted_password, pset.db);
    1865           0 :                 res = PSQLexec(buf.data);
    1866           0 :                 termPQExpBuffer(&buf);
    1867           0 :                 if (!res)
    1868           0 :                     success = false;
    1869             :                 else
    1870           0 :                     PQclear(res);
    1871           0 :                 PQfreemem(encrypted_password);
    1872             :             }
    1873             :         }
    1874             : 
    1875           0 :         if (opt0)
    1876           0 :             free(opt0);
    1877             :     }
    1878             :     else
    1879           4 :         ignore_slash_options(scan_state);
    1880             : 
    1881           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1882             : }
    1883             : 
    1884             : /*
    1885             :  * \prompt -- prompt and set variable
    1886             :  */
    1887             : static backslashResult
    1888           4 : exec_command_prompt(PsqlScanState scan_state, bool active_branch,
    1889             :                     const char *cmd)
    1890             : {
    1891           4 :     bool        success = true;
    1892             : 
    1893           4 :     if (active_branch)
    1894             :     {
    1895             :         char       *opt,
    1896           0 :                    *prompt_text = NULL;
    1897             :         char       *arg1,
    1898             :                    *arg2;
    1899             : 
    1900           0 :         arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
    1901           0 :         arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
    1902             : 
    1903           0 :         if (!arg1)
    1904             :         {
    1905           0 :             pg_log_error("\\%s: missing required argument", cmd);
    1906           0 :             success = false;
    1907             :         }
    1908             :         else
    1909             :         {
    1910             :             char       *result;
    1911             : 
    1912           0 :             if (arg2)
    1913             :             {
    1914           0 :                 prompt_text = arg1;
    1915           0 :                 opt = arg2;
    1916             :             }
    1917             :             else
    1918           0 :                 opt = arg1;
    1919             : 
    1920           0 :             if (!pset.inputfile)
    1921             :             {
    1922           0 :                 result = (char *) pg_malloc(4096);
    1923           0 :                 simple_prompt(prompt_text, result, 4096, true);
    1924             :             }
    1925             :             else
    1926             :             {
    1927           0 :                 if (prompt_text)
    1928             :                 {
    1929           0 :                     fputs(prompt_text, stdout);
    1930           0 :                     fflush(stdout);
    1931             :                 }
    1932           0 :                 result = gets_fromFile(stdin);
    1933           0 :                 if (!result)
    1934             :                 {
    1935           0 :                     pg_log_error("\\%s: could not read value for variable",
    1936             :                                  cmd);
    1937           0 :                     success = false;
    1938             :                 }
    1939             :             }
    1940             : 
    1941           0 :             if (result &&
    1942           0 :                 !SetVariable(pset.vars, opt, result))
    1943           0 :                 success = false;
    1944             : 
    1945           0 :             if (result)
    1946           0 :                 free(result);
    1947           0 :             if (prompt_text)
    1948           0 :                 free(prompt_text);
    1949           0 :             free(opt);
    1950             :         }
    1951             :     }
    1952             :     else
    1953           4 :         ignore_slash_options(scan_state);
    1954             : 
    1955           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    1956             : }
    1957             : 
    1958             : /*
    1959             :  * \pset -- set printing parameters
    1960             :  */
    1961             : static backslashResult
    1962        1132 : exec_command_pset(PsqlScanState scan_state, bool active_branch)
    1963             : {
    1964        1132 :     bool        success = true;
    1965             : 
    1966        1132 :     if (active_branch)
    1967             :     {
    1968        1124 :         char       *opt0 = psql_scan_slash_option(scan_state,
    1969             :                                                   OT_NORMAL, NULL, false);
    1970        1124 :         char       *opt1 = psql_scan_slash_option(scan_state,
    1971             :                                                   OT_NORMAL, NULL, false);
    1972             : 
    1973        1124 :         if (!opt0)
    1974             :         {
    1975             :             /* list all variables */
    1976             : 
    1977             :             int         i;
    1978             :             static const char *const my_list[] = {
    1979             :                 "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
    1980             :                 "fieldsep_zero", "footer", "format", "linestyle", "null",
    1981             :                 "numericlocale", "pager", "pager_min_lines",
    1982             :                 "recordsep", "recordsep_zero",
    1983             :                 "tableattr", "title", "tuples_only",
    1984             :                 "unicode_border_linestyle",
    1985             :                 "unicode_column_linestyle",
    1986             :                 "unicode_header_linestyle",
    1987             :                 NULL
    1988             :             };
    1989             : 
    1990          88 :             for (i = 0; my_list[i] != NULL; i++)
    1991             :             {
    1992          84 :                 char       *val = pset_value_string(my_list[i], &pset.popt);
    1993             : 
    1994          84 :                 printf("%-24s %s\n", my_list[i], val);
    1995          84 :                 free(val);
    1996             :             }
    1997             : 
    1998           4 :             success = true;
    1999             :         }
    2000             :         else
    2001        1120 :             success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
    2002             : 
    2003        1124 :         free(opt0);
    2004        1124 :         free(opt1);
    2005             :     }
    2006             :     else
    2007           8 :         ignore_slash_options(scan_state);
    2008             : 
    2009        1132 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2010             : }
    2011             : 
    2012             : /*
    2013             :  * \q or \quit -- exit psql
    2014             :  */
    2015             : static backslashResult
    2016           4 : exec_command_quit(PsqlScanState scan_state, bool active_branch)
    2017             : {
    2018           4 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2019             : 
    2020           4 :     if (active_branch)
    2021           0 :         status = PSQL_CMD_TERMINATE;
    2022             : 
    2023           4 :     return status;
    2024             : }
    2025             : 
    2026             : /*
    2027             :  * \r -- reset (clear) the query buffer
    2028             :  */
    2029             : static backslashResult
    2030          16 : exec_command_reset(PsqlScanState scan_state, bool active_branch,
    2031             :                    PQExpBuffer query_buf)
    2032             : {
    2033          16 :     if (active_branch)
    2034             :     {
    2035          12 :         resetPQExpBuffer(query_buf);
    2036          12 :         psql_scan_reset(scan_state);
    2037          12 :         if (!pset.quiet)
    2038           0 :             puts(_("Query buffer reset (cleared)."));
    2039             :     }
    2040             : 
    2041          16 :     return PSQL_CMD_SKIP_LINE;
    2042             : }
    2043             : 
    2044             : /*
    2045             :  * \s -- save history in a file or show it on the screen
    2046             :  */
    2047             : static backslashResult
    2048           4 : exec_command_s(PsqlScanState scan_state, bool active_branch)
    2049             : {
    2050           4 :     bool        success = true;
    2051             : 
    2052           4 :     if (active_branch)
    2053             :     {
    2054           0 :         char       *fname = psql_scan_slash_option(scan_state,
    2055             :                                                    OT_NORMAL, NULL, true);
    2056             : 
    2057           0 :         expand_tilde(&fname);
    2058           0 :         success = printHistory(fname, pset.popt.topt.pager);
    2059           0 :         if (success && !pset.quiet && fname)
    2060           0 :             printf(_("Wrote history to file \"%s\".\n"), fname);
    2061           0 :         if (!fname)
    2062           0 :             putchar('\n');
    2063           0 :         free(fname);
    2064             :     }
    2065             :     else
    2066           4 :         ignore_slash_options(scan_state);
    2067             : 
    2068           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2069             : }
    2070             : 
    2071             : /*
    2072             :  * \set -- set variable
    2073             :  */
    2074             : static backslashResult
    2075         228 : exec_command_set(PsqlScanState scan_state, bool active_branch)
    2076             : {
    2077         228 :     bool        success = true;
    2078             : 
    2079         228 :     if (active_branch)
    2080             :     {
    2081         224 :         char       *opt0 = psql_scan_slash_option(scan_state,
    2082             :                                                   OT_NORMAL, NULL, false);
    2083             : 
    2084         224 :         if (!opt0)
    2085             :         {
    2086             :             /* list all variables */
    2087           0 :             PrintVariables(pset.vars);
    2088           0 :             success = true;
    2089             :         }
    2090             :         else
    2091             :         {
    2092             :             /*
    2093             :              * Set variable to the concatenation of the arguments.
    2094             :              */
    2095             :             char       *newval;
    2096             :             char       *opt;
    2097             : 
    2098         224 :             opt = psql_scan_slash_option(scan_state,
    2099             :                                          OT_NORMAL, NULL, false);
    2100         224 :             newval = pg_strdup(opt ? opt : "");
    2101         224 :             free(opt);
    2102             : 
    2103         448 :             while ((opt = psql_scan_slash_option(scan_state,
    2104             :                                                  OT_NORMAL, NULL, false)))
    2105             :             {
    2106           0 :                 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
    2107           0 :                 strcat(newval, opt);
    2108           0 :                 free(opt);
    2109             :             }
    2110             : 
    2111         224 :             if (!SetVariable(pset.vars, opt0, newval))
    2112          16 :                 success = false;
    2113             : 
    2114         224 :             free(newval);
    2115             :         }
    2116         224 :         free(opt0);
    2117             :     }
    2118             :     else
    2119           4 :         ignore_slash_options(scan_state);
    2120             : 
    2121         228 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2122             : }
    2123             : 
    2124             : /*
    2125             :  * \setenv -- set environment variable
    2126             :  */
    2127             : static backslashResult
    2128           4 : exec_command_setenv(PsqlScanState scan_state, bool active_branch,
    2129             :                     const char *cmd)
    2130             : {
    2131           4 :     bool        success = true;
    2132             : 
    2133           4 :     if (active_branch)
    2134             :     {
    2135           0 :         char       *envvar = psql_scan_slash_option(scan_state,
    2136             :                                                     OT_NORMAL, NULL, false);
    2137           0 :         char       *envval = psql_scan_slash_option(scan_state,
    2138             :                                                     OT_NORMAL, NULL, false);
    2139             : 
    2140           0 :         if (!envvar)
    2141             :         {
    2142           0 :             pg_log_error("\\%s: missing required argument", cmd);
    2143           0 :             success = false;
    2144             :         }
    2145           0 :         else if (strchr(envvar, '=') != NULL)
    2146             :         {
    2147           0 :             pg_log_error("\\%s: environment variable name must not contain \"=\"",
    2148             :                          cmd);
    2149           0 :             success = false;
    2150             :         }
    2151           0 :         else if (!envval)
    2152             :         {
    2153             :             /* No argument - unset the environment variable */
    2154           0 :             unsetenv(envvar);
    2155           0 :             success = true;
    2156             :         }
    2157             :         else
    2158             :         {
    2159             :             /* Set variable to the value of the next argument */
    2160             :             char       *newval;
    2161             : 
    2162           0 :             newval = psprintf("%s=%s", envvar, envval);
    2163           0 :             putenv(newval);
    2164           0 :             success = true;
    2165             : 
    2166             :             /*
    2167             :              * Do not free newval here, it will screw up the environment if
    2168             :              * you do. See putenv man page for details. That means we leak a
    2169             :              * bit of memory here, but not enough to worry about.
    2170             :              */
    2171             :         }
    2172           0 :         free(envvar);
    2173           0 :         free(envval);
    2174             :     }
    2175             :     else
    2176           4 :         ignore_slash_options(scan_state);
    2177             : 
    2178           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2179             : }
    2180             : 
    2181             : /*
    2182             :  * \sf/\sv -- show a function/view's source code
    2183             :  */
    2184             : static backslashResult
    2185          12 : exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
    2186             :                    const char *cmd, bool is_func)
    2187             : {
    2188          12 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2189             : 
    2190          12 :     if (active_branch)
    2191             :     {
    2192           4 :         bool        show_linenumbers = (strchr(cmd, '+') != NULL);
    2193             :         PQExpBuffer buf;
    2194             :         char       *obj_desc;
    2195           4 :         Oid         obj_oid = InvalidOid;
    2196           4 :         EditableObjectType eot = is_func ? EditableFunction : EditableView;
    2197             : 
    2198           4 :         buf = createPQExpBuffer();
    2199           4 :         obj_desc = psql_scan_slash_option(scan_state,
    2200             :                                           OT_WHOLE_LINE, NULL, true);
    2201           4 :         if (pset.sversion < (is_func ? 80400 : 70400))
    2202             :         {
    2203             :             char        sverbuf[32];
    2204             : 
    2205           0 :             formatPGVersionNumber(pset.sversion, false,
    2206             :                                   sverbuf, sizeof(sverbuf));
    2207           0 :             if (is_func)
    2208           0 :                 pg_log_error("The server (version %s) does not support showing function source.",
    2209             :                              sverbuf);
    2210             :             else
    2211           0 :                 pg_log_error("The server (version %s) does not support showing view definitions.",
    2212             :                              sverbuf);
    2213           0 :             status = PSQL_CMD_ERROR;
    2214             :         }
    2215           4 :         else if (!obj_desc)
    2216             :         {
    2217           0 :             if (is_func)
    2218           0 :                 pg_log_error("function name is required");
    2219             :             else
    2220           0 :                 pg_log_error("view name is required");
    2221           0 :             status = PSQL_CMD_ERROR;
    2222             :         }
    2223           4 :         else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
    2224             :         {
    2225             :             /* error already reported */
    2226           0 :             status = PSQL_CMD_ERROR;
    2227             :         }
    2228           4 :         else if (!get_create_object_cmd(eot, obj_oid, buf))
    2229             :         {
    2230             :             /* error already reported */
    2231           0 :             status = PSQL_CMD_ERROR;
    2232             :         }
    2233             :         else
    2234             :         {
    2235             :             FILE       *output;
    2236             :             bool        is_pager;
    2237             : 
    2238             :             /* Select output stream: stdout, pager, or file */
    2239           4 :             if (pset.queryFout == stdout)
    2240             :             {
    2241             :                 /* count lines in function to see if pager is needed */
    2242           4 :                 int         lineno = count_lines_in_buf(buf);
    2243             : 
    2244           4 :                 output = PageOutput(lineno, &(pset.popt.topt));
    2245           4 :                 is_pager = true;
    2246             :             }
    2247             :             else
    2248             :             {
    2249             :                 /* use previously set output file, without pager */
    2250           0 :                 output = pset.queryFout;
    2251           0 :                 is_pager = false;
    2252             :             }
    2253             : 
    2254           4 :             if (show_linenumbers)
    2255             :             {
    2256             :                 /*
    2257             :                  * For functions, lineno "1" should correspond to the first
    2258             :                  * line of the function body.  We expect that
    2259             :                  * pg_get_functiondef() will emit that on a line beginning
    2260             :                  * with "AS ", and that there can be no such line before the
    2261             :                  * real start of the function body.
    2262             :                  */
    2263           0 :                 print_with_linenumbers(output, buf->data,
    2264             :                                        is_func ? "AS " : NULL);
    2265             :             }
    2266             :             else
    2267             :             {
    2268             :                 /* just send the definition to output */
    2269           4 :                 fputs(buf->data, output);
    2270             :             }
    2271             : 
    2272           4 :             if (is_pager)
    2273           4 :                 ClosePager(output);
    2274             :         }
    2275             : 
    2276           4 :         if (obj_desc)
    2277           4 :             free(obj_desc);
    2278           4 :         destroyPQExpBuffer(buf);
    2279             :     }
    2280             :     else
    2281           8 :         ignore_slash_whole_line(scan_state);
    2282             : 
    2283          12 :     return status;
    2284             : }
    2285             : 
    2286             : /*
    2287             :  * \t -- turn off table headers and row count
    2288             :  */
    2289             : static backslashResult
    2290          44 : exec_command_t(PsqlScanState scan_state, bool active_branch)
    2291             : {
    2292          44 :     bool        success = true;
    2293             : 
    2294          44 :     if (active_branch)
    2295             :     {
    2296          40 :         char       *opt = psql_scan_slash_option(scan_state,
    2297             :                                                  OT_NORMAL, NULL, true);
    2298             : 
    2299          40 :         success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
    2300          40 :         free(opt);
    2301             :     }
    2302             :     else
    2303           4 :         ignore_slash_options(scan_state);
    2304             : 
    2305          44 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2306             : }
    2307             : 
    2308             : /*
    2309             :  * \T -- define html <table ...> attributes
    2310             :  */
    2311             : static backslashResult
    2312           4 : exec_command_T(PsqlScanState scan_state, bool active_branch)
    2313             : {
    2314           4 :     bool        success = true;
    2315             : 
    2316           4 :     if (active_branch)
    2317             :     {
    2318           0 :         char       *value = psql_scan_slash_option(scan_state,
    2319             :                                                    OT_NORMAL, NULL, false);
    2320             : 
    2321           0 :         success = do_pset("tableattr", value, &pset.popt, pset.quiet);
    2322           0 :         free(value);
    2323             :     }
    2324             :     else
    2325           4 :         ignore_slash_options(scan_state);
    2326             : 
    2327           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2328             : }
    2329             : 
    2330             : /*
    2331             :  * \timing -- enable/disable timing of queries
    2332             :  */
    2333             : static backslashResult
    2334           4 : exec_command_timing(PsqlScanState scan_state, bool active_branch)
    2335             : {
    2336           4 :     bool        success = true;
    2337             : 
    2338           4 :     if (active_branch)
    2339             :     {
    2340           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2341             :                                                  OT_NORMAL, NULL, false);
    2342             : 
    2343           0 :         if (opt)
    2344           0 :             success = ParseVariableBool(opt, "\\timing", &pset.timing);
    2345             :         else
    2346           0 :             pset.timing = !pset.timing;
    2347           0 :         if (!pset.quiet)
    2348             :         {
    2349           0 :             if (pset.timing)
    2350           0 :                 puts(_("Timing is on."));
    2351             :             else
    2352           0 :                 puts(_("Timing is off."));
    2353             :         }
    2354           0 :         free(opt);
    2355             :     }
    2356             :     else
    2357           4 :         ignore_slash_options(scan_state);
    2358             : 
    2359           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2360             : }
    2361             : 
    2362             : /*
    2363             :  * \unset -- unset variable
    2364             :  */
    2365             : static backslashResult
    2366          26 : exec_command_unset(PsqlScanState scan_state, bool active_branch,
    2367             :                    const char *cmd)
    2368             : {
    2369          26 :     bool        success = true;
    2370             : 
    2371          26 :     if (active_branch)
    2372             :     {
    2373          22 :         char       *opt = psql_scan_slash_option(scan_state,
    2374             :                                                  OT_NORMAL, NULL, false);
    2375             : 
    2376          22 :         if (!opt)
    2377             :         {
    2378           0 :             pg_log_error("\\%s: missing required argument", cmd);
    2379           0 :             success = false;
    2380             :         }
    2381          22 :         else if (!SetVariable(pset.vars, opt, NULL))
    2382           0 :             success = false;
    2383             : 
    2384          22 :         free(opt);
    2385             :     }
    2386             :     else
    2387           4 :         ignore_slash_options(scan_state);
    2388             : 
    2389          26 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2390             : }
    2391             : 
    2392             : /*
    2393             :  * \w -- write query buffer to file
    2394             :  */
    2395             : static backslashResult
    2396           8 : exec_command_write(PsqlScanState scan_state, bool active_branch,
    2397             :                    const char *cmd,
    2398             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2399             : {
    2400           8 :     backslashResult status = PSQL_CMD_SKIP_LINE;
    2401             : 
    2402           8 :     if (active_branch)
    2403             :     {
    2404           0 :         char       *fname = psql_scan_slash_option(scan_state,
    2405             :                                                    OT_FILEPIPE, NULL, true);
    2406           0 :         FILE       *fd = NULL;
    2407           0 :         bool        is_pipe = false;
    2408             : 
    2409           0 :         if (!query_buf)
    2410             :         {
    2411           0 :             pg_log_error("no query buffer");
    2412           0 :             status = PSQL_CMD_ERROR;
    2413             :         }
    2414             :         else
    2415             :         {
    2416           0 :             if (!fname)
    2417             :             {
    2418           0 :                 pg_log_error("\\%s: missing required argument", cmd);
    2419           0 :                 status = PSQL_CMD_ERROR;
    2420             :             }
    2421             :             else
    2422             :             {
    2423           0 :                 expand_tilde(&fname);
    2424           0 :                 if (fname[0] == '|')
    2425             :                 {
    2426           0 :                     is_pipe = true;
    2427           0 :                     disable_sigpipe_trap();
    2428           0 :                     fd = popen(&fname[1], "w");
    2429             :                 }
    2430             :                 else
    2431             :                 {
    2432           0 :                     canonicalize_path(fname);
    2433           0 :                     fd = fopen(fname, "w");
    2434             :                 }
    2435           0 :                 if (!fd)
    2436             :                 {
    2437           0 :                     pg_log_error("%s: %m", fname);
    2438           0 :                     status = PSQL_CMD_ERROR;
    2439             :                 }
    2440             :             }
    2441             :         }
    2442             : 
    2443           0 :         if (fd)
    2444             :         {
    2445             :             int         result;
    2446             : 
    2447             :             /*
    2448             :              * We want to print the same thing \g would execute, but not to
    2449             :              * change the query buffer state; so we can't use
    2450             :              * copy_previous_query().  Also, beware of possibility that buffer
    2451             :              * pointers are NULL.
    2452             :              */
    2453           0 :             if (query_buf && query_buf->len > 0)
    2454           0 :                 fprintf(fd, "%s\n", query_buf->data);
    2455           0 :             else if (previous_buf && previous_buf->len > 0)
    2456           0 :                 fprintf(fd, "%s\n", previous_buf->data);
    2457             : 
    2458           0 :             if (is_pipe)
    2459           0 :                 result = pclose(fd);
    2460             :             else
    2461           0 :                 result = fclose(fd);
    2462             : 
    2463           0 :             if (result == EOF)
    2464             :             {
    2465           0 :                 pg_log_error("%s: %m", fname);
    2466           0 :                 status = PSQL_CMD_ERROR;
    2467             :             }
    2468             :         }
    2469             : 
    2470           0 :         if (is_pipe)
    2471           0 :             restore_sigpipe_trap();
    2472             : 
    2473           0 :         free(fname);
    2474             :     }
    2475             :     else
    2476           8 :         ignore_slash_filepipe(scan_state);
    2477             : 
    2478           8 :     return status;
    2479             : }
    2480             : 
    2481             : /*
    2482             :  * \watch -- execute a query every N seconds
    2483             :  */
    2484             : static backslashResult
    2485           4 : exec_command_watch(PsqlScanState scan_state, bool active_branch,
    2486             :                    PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2487             : {
    2488           4 :     bool        success = true;
    2489             : 
    2490           4 :     if (active_branch)
    2491             :     {
    2492           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2493             :                                                  OT_NORMAL, NULL, true);
    2494           0 :         double      sleep = 2;
    2495             : 
    2496             :         /* Convert optional sleep-length argument */
    2497           0 :         if (opt)
    2498             :         {
    2499           0 :             sleep = strtod(opt, NULL);
    2500           0 :             if (sleep <= 0)
    2501           0 :                 sleep = 1;
    2502           0 :             free(opt);
    2503             :         }
    2504             : 
    2505             :         /* If query_buf is empty, recall and execute previous query */
    2506           0 :         copy_previous_query(query_buf, previous_buf);
    2507             : 
    2508           0 :         success = do_watch(query_buf, sleep);
    2509             : 
    2510             :         /* Reset the query buffer as though for \r */
    2511           0 :         resetPQExpBuffer(query_buf);
    2512           0 :         psql_scan_reset(scan_state);
    2513             :     }
    2514             :     else
    2515           4 :         ignore_slash_options(scan_state);
    2516             : 
    2517           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2518             : }
    2519             : 
    2520             : /*
    2521             :  * \x -- set or toggle expanded table representation
    2522             :  */
    2523             : static backslashResult
    2524          18 : exec_command_x(PsqlScanState scan_state, bool active_branch)
    2525             : {
    2526          18 :     bool        success = true;
    2527             : 
    2528          18 :     if (active_branch)
    2529             :     {
    2530          14 :         char       *opt = psql_scan_slash_option(scan_state,
    2531             :                                                  OT_NORMAL, NULL, true);
    2532             : 
    2533          14 :         success = do_pset("expanded", opt, &pset.popt, pset.quiet);
    2534          14 :         free(opt);
    2535             :     }
    2536             :     else
    2537           4 :         ignore_slash_options(scan_state);
    2538             : 
    2539          18 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2540             : }
    2541             : 
    2542             : /*
    2543             :  * \z -- list table privileges (equivalent to \dp)
    2544             :  */
    2545             : static backslashResult
    2546           8 : exec_command_z(PsqlScanState scan_state, bool active_branch)
    2547             : {
    2548           8 :     bool        success = true;
    2549             : 
    2550           8 :     if (active_branch)
    2551             :     {
    2552           8 :         char       *pattern = psql_scan_slash_option(scan_state,
    2553             :                                                      OT_NORMAL, NULL, true);
    2554             : 
    2555           8 :         success = permissionsList(pattern);
    2556           8 :         if (pattern)
    2557           8 :             free(pattern);
    2558             :     }
    2559             :     else
    2560           0 :         ignore_slash_options(scan_state);
    2561             : 
    2562           8 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2563             : }
    2564             : 
    2565             : /*
    2566             :  * \! -- execute shell command
    2567             :  */
    2568             : static backslashResult
    2569           4 : exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
    2570             : {
    2571           4 :     bool        success = true;
    2572             : 
    2573           4 :     if (active_branch)
    2574             :     {
    2575           0 :         char       *opt = psql_scan_slash_option(scan_state,
    2576             :                                                  OT_WHOLE_LINE, NULL, false);
    2577             : 
    2578           0 :         success = do_shell(opt);
    2579           0 :         free(opt);
    2580             :     }
    2581             :     else
    2582           4 :         ignore_slash_whole_line(scan_state);
    2583             : 
    2584           4 :     return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
    2585             : }
    2586             : 
    2587             : /*
    2588             :  * \? -- print help about backslash commands
    2589             :  */
    2590             : static backslashResult
    2591           0 : exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
    2592             : {
    2593           0 :     if (active_branch)
    2594             :     {
    2595           0 :         char       *opt0 = psql_scan_slash_option(scan_state,
    2596             :                                                   OT_NORMAL, NULL, false);
    2597             : 
    2598           0 :         if (!opt0 || strcmp(opt0, "commands") == 0)
    2599           0 :             slashUsage(pset.popt.topt.pager);
    2600           0 :         else if (strcmp(opt0, "options") == 0)
    2601           0 :             usage(pset.popt.topt.pager);
    2602           0 :         else if (strcmp(opt0, "variables") == 0)
    2603           0 :             helpVariables(pset.popt.topt.pager);
    2604             :         else
    2605           0 :             slashUsage(pset.popt.topt.pager);
    2606             : 
    2607           0 :         if (opt0)
    2608           0 :             free(opt0);
    2609             :     }
    2610             :     else
    2611           0 :         ignore_slash_options(scan_state);
    2612             : 
    2613           0 :     return PSQL_CMD_SKIP_LINE;
    2614             : }
    2615             : 
    2616             : 
    2617             : /*
    2618             :  * Read and interpret an argument to the \connect slash command.
    2619             :  *
    2620             :  * Returns a malloc'd string, or NULL if no/empty argument.
    2621             :  */
    2622             : static char *
    2623         712 : read_connect_arg(PsqlScanState scan_state)
    2624             : {
    2625             :     char       *result;
    2626             :     char        quote;
    2627             : 
    2628             :     /*
    2629             :      * Ideally we should treat the arguments as SQL identifiers.  But for
    2630             :      * backwards compatibility with 7.2 and older pg_dump files, we have to
    2631             :      * take unquoted arguments verbatim (don't downcase them). For now,
    2632             :      * double-quoted arguments may be stripped of double quotes (as if SQL
    2633             :      * identifiers).  By 7.4 or so, pg_dump files can be expected to
    2634             :      * double-quote all mixed-case \connect arguments, and then we can get rid
    2635             :      * of OT_SQLIDHACK.
    2636             :      */
    2637         712 :     result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
    2638             : 
    2639         712 :     if (!result)
    2640         556 :         return NULL;
    2641             : 
    2642         156 :     if (quote)
    2643          22 :         return result;
    2644             : 
    2645         134 :     if (*result == '\0' || strcmp(result, "-") == 0)
    2646             :     {
    2647         108 :         free(result);
    2648         108 :         return NULL;
    2649             :     }
    2650             : 
    2651          26 :     return result;
    2652             : }
    2653             : 
    2654             : /*
    2655             :  * Read a boolean expression, return it as a PQExpBuffer string.
    2656             :  *
    2657             :  * Note: anything more or less than one token will certainly fail to be
    2658             :  * parsed by ParseVariableBool, so we don't worry about complaining here.
    2659             :  * This routine's return data structure will need to be rethought anyway
    2660             :  * to support likely future extensions such as "\if defined VARNAME".
    2661             :  */
    2662             : static PQExpBuffer
    2663          88 : gather_boolean_expression(PsqlScanState scan_state)
    2664             : {
    2665          88 :     PQExpBuffer exp_buf = createPQExpBuffer();
    2666          88 :     int         num_options = 0;
    2667             :     char       *value;
    2668             : 
    2669             :     /* collect all arguments for the conditional command into exp_buf */
    2670         272 :     while ((value = psql_scan_slash_option(scan_state,
    2671             :                                            OT_NORMAL, NULL, false)) != NULL)
    2672             :     {
    2673             :         /* add spaces between tokens */
    2674          96 :         if (num_options > 0)
    2675           8 :             appendPQExpBufferChar(exp_buf, ' ');
    2676          96 :         appendPQExpBufferStr(exp_buf, value);
    2677          96 :         num_options++;
    2678          96 :         free(value);
    2679             :     }
    2680             : 
    2681          88 :     return exp_buf;
    2682             : }
    2683             : 
    2684             : /*
    2685             :  * Read a boolean expression, return true if the expression
    2686             :  * was a valid boolean expression that evaluated to true.
    2687             :  * Otherwise return false.
    2688             :  *
    2689             :  * Note: conditional stack's top state must be active, else lexer will
    2690             :  * fail to expand variables and backticks.
    2691             :  */
    2692             : static bool
    2693          84 : is_true_boolean_expression(PsqlScanState scan_state, const char *name)
    2694             : {
    2695          84 :     PQExpBuffer buf = gather_boolean_expression(scan_state);
    2696          84 :     bool        value = false;
    2697          84 :     bool        success = ParseVariableBool(buf->data, name, &value);
    2698             : 
    2699          84 :     destroyPQExpBuffer(buf);
    2700          84 :     return success && value;
    2701             : }
    2702             : 
    2703             : /*
    2704             :  * Read a boolean expression, but do nothing with it.
    2705             :  *
    2706             :  * Note: conditional stack's top state must be INACTIVE, else lexer will
    2707             :  * expand variables and backticks, which we do not want here.
    2708             :  */
    2709             : static void
    2710           4 : ignore_boolean_expression(PsqlScanState scan_state)
    2711             : {
    2712           4 :     PQExpBuffer buf = gather_boolean_expression(scan_state);
    2713             : 
    2714           4 :     destroyPQExpBuffer(buf);
    2715           4 : }
    2716             : 
    2717             : /*
    2718             :  * Read and discard "normal" slash command options.
    2719             :  *
    2720             :  * This should be used for inactive-branch processing of any slash command
    2721             :  * that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
    2722             :  * We don't need to worry about exactly how many it would eat, since the
    2723             :  * cleanup logic in HandleSlashCmds would silently discard any extras anyway.
    2724             :  */
    2725             : static void
    2726         156 : ignore_slash_options(PsqlScanState scan_state)
    2727             : {
    2728             :     char       *arg;
    2729             : 
    2730         568 :     while ((arg = psql_scan_slash_option(scan_state,
    2731             :                                          OT_NORMAL, NULL, false)) != NULL)
    2732         256 :         free(arg);
    2733         156 : }
    2734             : 
    2735             : /*
    2736             :  * Read and discard FILEPIPE slash command argument.
    2737             :  *
    2738             :  * This *MUST* be used for inactive-branch processing of any slash command
    2739             :  * that takes an OT_FILEPIPE option.  Otherwise we might consume a different
    2740             :  * amount of option text in active and inactive cases.
    2741             :  */
    2742             : static void
    2743          20 : ignore_slash_filepipe(PsqlScanState scan_state)
    2744             : {
    2745          20 :     char       *arg = psql_scan_slash_option(scan_state,
    2746             :                                              OT_FILEPIPE, NULL, false);
    2747             : 
    2748          20 :     if (arg)
    2749          20 :         free(arg);
    2750          20 : }
    2751             : 
    2752             : /*
    2753             :  * Read and discard whole-line slash command argument.
    2754             :  *
    2755             :  * This *MUST* be used for inactive-branch processing of any slash command
    2756             :  * that takes an OT_WHOLE_LINE option.  Otherwise we might consume a different
    2757             :  * amount of option text in active and inactive cases.
    2758             :  */
    2759             : static void
    2760          28 : ignore_slash_whole_line(PsqlScanState scan_state)
    2761             : {
    2762          28 :     char       *arg = psql_scan_slash_option(scan_state,
    2763             :                                              OT_WHOLE_LINE, NULL, false);
    2764             : 
    2765          28 :     if (arg)
    2766          28 :         free(arg);
    2767          28 : }
    2768             : 
    2769             : /*
    2770             :  * Return true if the command given is a branching command.
    2771             :  */
    2772             : static bool
    2773           0 : is_branching_command(const char *cmd)
    2774             : {
    2775           0 :     return (strcmp(cmd, "if") == 0 ||
    2776           0 :             strcmp(cmd, "elif") == 0 ||
    2777           0 :             strcmp(cmd, "else") == 0 ||
    2778           0 :             strcmp(cmd, "endif") == 0);
    2779             : }
    2780             : 
    2781             : /*
    2782             :  * Prepare to possibly restore query buffer to its current state
    2783             :  * (cf. discard_query_text).
    2784             :  *
    2785             :  * We need to remember the length of the query buffer, and the lexer's
    2786             :  * notion of the parenthesis nesting depth.
    2787             :  */
    2788             : static void
    2789         112 : save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
    2790             :                       PQExpBuffer query_buf)
    2791             : {
    2792         112 :     if (query_buf)
    2793         112 :         conditional_stack_set_query_len(cstack, query_buf->len);
    2794         112 :     conditional_stack_set_paren_depth(cstack,
    2795             :                                       psql_scan_get_paren_depth(scan_state));
    2796         112 : }
    2797             : 
    2798             : /*
    2799             :  * Discard any query text absorbed during an inactive conditional branch.
    2800             :  *
    2801             :  * We must discard data that was appended to query_buf during an inactive
    2802             :  * \if branch.  We don't have to do anything there if there's no query_buf.
    2803             :  *
    2804             :  * Also, reset the lexer state to the same paren depth there was before.
    2805             :  * (The rest of its state doesn't need attention, since we could not be
    2806             :  * inside a comment or literal or partial token.)
    2807             :  */
    2808             : static void
    2809          92 : discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
    2810             :                    PQExpBuffer query_buf)
    2811             : {
    2812          92 :     if (query_buf)
    2813             :     {
    2814          92 :         int         new_len = conditional_stack_get_query_len(cstack);
    2815             : 
    2816             :         Assert(new_len >= 0 && new_len <= query_buf->len);
    2817          92 :         query_buf->len = new_len;
    2818          92 :         query_buf->data[new_len] = '\0';
    2819             :     }
    2820          92 :     psql_scan_set_paren_depth(scan_state,
    2821             :                               conditional_stack_get_paren_depth(cstack));
    2822          92 : }
    2823             : 
    2824             : /*
    2825             :  * If query_buf is empty, copy previous_buf into it.
    2826             :  *
    2827             :  * This is used by various slash commands for which re-execution of a
    2828             :  * previous query is a common usage.  For convenience, we allow the
    2829             :  * case of query_buf == NULL (and do nothing).
    2830             :  */
    2831             : static void
    2832         298 : copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
    2833             : {
    2834         298 :     if (query_buf && query_buf->len == 0)
    2835          40 :         appendPQExpBufferStr(query_buf, previous_buf->data);
    2836         298 : }
    2837             : 
    2838             : /*
    2839             :  * Ask the user for a password; 'username' is the username the
    2840             :  * password is for, if one has been explicitly specified. Returns a
    2841             :  * malloc'd string.
    2842             :  */
    2843             : static char *
    2844           0 : prompt_for_password(const char *username)
    2845             : {
    2846             :     char        buf[100];
    2847             : 
    2848           0 :     if (username == NULL || username[0] == '\0')
    2849           0 :         simple_prompt("Password: ", buf, sizeof(buf), false);
    2850             :     else
    2851             :     {
    2852             :         char       *prompt_text;
    2853             : 
    2854           0 :         prompt_text = psprintf(_("Password for user %s: "), username);
    2855           0 :         simple_prompt(prompt_text, buf, sizeof(buf), false);
    2856           0 :         free(prompt_text);
    2857             :     }
    2858           0 :     return pg_strdup(buf);
    2859             : }
    2860             : 
    2861             : static bool
    2862          56 : param_is_newly_set(const char *old_val, const char *new_val)
    2863             : {
    2864          56 :     if (new_val == NULL)
    2865           0 :         return false;
    2866             : 
    2867          56 :     if (old_val == NULL || strcmp(old_val, new_val) != 0)
    2868           0 :         return true;
    2869             : 
    2870          56 :     return false;
    2871             : }
    2872             : 
    2873             : /* return whether the connection has 'hostaddr' in its conninfo */
    2874             : static bool
    2875         174 : has_hostaddr(PGconn *conn)
    2876             : {
    2877         174 :     bool        used = false;
    2878         174 :     PQconninfoOption *ciopt = PQconninfo(conn);
    2879             : 
    2880        5394 :     for (PQconninfoOption *p = ciopt; p->keyword != NULL; p++)
    2881             :     {
    2882        5220 :         if (strcmp(p->keyword, "hostaddr") == 0 && p->val != NULL)
    2883             :         {
    2884           0 :             used = true;
    2885           0 :             break;
    2886             :         }
    2887             :     }
    2888             : 
    2889         174 :     PQconninfoFree(ciopt);
    2890         174 :     return used;
    2891             : }
    2892             : 
    2893             : /*
    2894             :  * do_connect -- handler for \connect
    2895             :  *
    2896             :  * Connects to a database with given parameters. Absent an established
    2897             :  * connection, all parameters are required. Given -reuse-previous=off or a
    2898             :  * connection string without -reuse-previous=on, NULL values will pass through
    2899             :  * to PQconnectdbParams(), so the libpq defaults will be used. Otherwise, NULL
    2900             :  * values will be replaced with the ones in the current connection.
    2901             :  *
    2902             :  * In interactive mode, if connection fails with the given parameters,
    2903             :  * the old connection will be kept.
    2904             :  */
    2905             : static bool
    2906         174 : do_connect(enum trivalue reuse_previous_specification,
    2907             :            char *dbname, char *user, char *host, char *port)
    2908             : {
    2909         174 :     PGconn     *o_conn = pset.db,
    2910             :                *n_conn;
    2911         174 :     char       *password = NULL;
    2912         174 :     char       *hostaddr = NULL;
    2913             :     bool        keep_password;
    2914             :     bool        has_connection_string;
    2915             :     bool        reuse_previous;
    2916             :     PQExpBufferData connstr;
    2917             : 
    2918         174 :     if (!o_conn && (!dbname || !user || !host || !port))
    2919             :     {
    2920             :         /*
    2921             :          * We don't know the supplied connection parameters and don't want to
    2922             :          * connect to the wrong database by using defaults, so require all
    2923             :          * parameters to be specified.
    2924             :          */
    2925           0 :         pg_log_error("All connection parameters must be supplied because no "
    2926             :                      "database connection exists");
    2927           0 :         return false;
    2928             :     }
    2929             : 
    2930         174 :     has_connection_string = dbname ?
    2931         174 :         recognized_connection_string(dbname) : false;
    2932         174 :     switch (reuse_previous_specification)
    2933             :     {
    2934             :         case TRI_YES:
    2935          16 :             reuse_previous = true;
    2936          16 :             break;
    2937             :         case TRI_NO:
    2938           0 :             reuse_previous = false;
    2939           0 :             break;
    2940             :         default:
    2941         158 :             reuse_previous = !has_connection_string;
    2942         158 :             break;
    2943             :     }
    2944             :     /* Silently ignore arguments subsequent to a connection string. */
    2945         174 :     if (has_connection_string)
    2946             :     {
    2947          16 :         user = NULL;
    2948          16 :         host = NULL;
    2949          16 :         port = NULL;
    2950             :     }
    2951             : 
    2952             :     /*
    2953             :      * Grab missing values from the old connection.  If we grab host (or host
    2954             :      * is the same as before) and hostaddr was set, grab that too.
    2955             :      */
    2956         174 :     if (reuse_previous)
    2957             :     {
    2958         174 :         if (!user)
    2959         174 :             user = PQuser(o_conn);
    2960         174 :         if (host && strcmp(host, PQhost(o_conn)) == 0 &&
    2961           0 :             has_hostaddr(o_conn))
    2962             :         {
    2963           0 :             hostaddr = PQhostaddr(o_conn);
    2964             :         }
    2965         174 :         if (!host)
    2966             :         {
    2967         174 :             host = PQhost(o_conn);
    2968         174 :             if (has_hostaddr(o_conn))
    2969           0 :                 hostaddr = PQhostaddr(o_conn);
    2970             :         }
    2971         174 :         if (!port)
    2972         174 :             port = PQport(o_conn);
    2973             :     }
    2974             : 
    2975             :     /*
    2976             :      * Any change in the parameters read above makes us discard the password.
    2977             :      * We also discard it if we're to use a conninfo rather than the
    2978             :      * positional syntax.
    2979             :      */
    2980         174 :     if (has_connection_string)
    2981          16 :         keep_password = false;
    2982             :     else
    2983         158 :         keep_password =
    2984         158 :             (user && PQuser(o_conn) && strcmp(user, PQuser(o_conn)) == 0) &&
    2985         474 :             (host && PQhost(o_conn) && strcmp(host, PQhost(o_conn)) == 0) &&
    2986         158 :             (port && PQport(o_conn) && strcmp(port, PQport(o_conn)) == 0);
    2987             : 
    2988             :     /*
    2989             :      * Grab missing dbname from old connection.  No password discard if this
    2990             :      * changes: passwords aren't (usually) database-specific.
    2991             :      */
    2992         174 :     if (!dbname && reuse_previous)
    2993             :     {
    2994         142 :         initPQExpBuffer(&connstr);
    2995         142 :         appendPQExpBuffer(&connstr, "dbname=");
    2996         142 :         appendConnStrVal(&connstr, PQdb(o_conn));
    2997         142 :         dbname = connstr.data;
    2998             :         /* has_connection_string=true would be a dead store */
    2999             :     }
    3000             :     else
    3001          32 :         connstr.data = NULL;
    3002             : 
    3003             :     /*
    3004             :      * If the user asked to be prompted for a password, ask for one now. If
    3005             :      * not, use the password from the old connection, provided the username
    3006             :      * etc have not changed. Otherwise, try to connect without a password
    3007             :      * first, and then ask for a password if needed.
    3008             :      *
    3009             :      * XXX: this behavior leads to spurious connection attempts recorded in
    3010             :      * the postmaster's log.  But libpq offers no API that would let us obtain
    3011             :      * a password and then continue with the first connection attempt.
    3012             :      */
    3013         174 :     if (pset.getPassword == TRI_YES)
    3014             :     {
    3015             :         /*
    3016             :          * If a connstring or URI is provided, we can't be sure we know which
    3017             :          * username will be used, since we haven't parsed that argument yet.
    3018             :          * Don't risk issuing a misleading prompt.  As in startup.c, it does
    3019             :          * not seem worth working harder, since this getPassword option is
    3020             :          * normally only used in noninteractive cases.
    3021             :          */
    3022           0 :         password = prompt_for_password(has_connection_string ? NULL : user);
    3023             :     }
    3024         174 :     else if (o_conn && keep_password)
    3025             :     {
    3026         158 :         password = PQpass(o_conn);
    3027         158 :         if (password && *password)
    3028           0 :             password = pg_strdup(password);
    3029             :         else
    3030         158 :             password = NULL;
    3031             :     }
    3032             : 
    3033             :     while (true)
    3034           0 :     {
    3035             : #define PARAMS_ARRAY_SIZE   9
    3036         174 :         const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
    3037         174 :         const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
    3038         174 :         int         paramnum = -1;
    3039             : 
    3040         174 :         keywords[++paramnum] = "host";
    3041         174 :         values[paramnum] = host;
    3042         174 :         if (hostaddr && *hostaddr)
    3043             :         {
    3044           0 :             keywords[++paramnum] = "hostaddr";
    3045           0 :             values[paramnum] = hostaddr;
    3046             :         }
    3047         174 :         keywords[++paramnum] = "port";
    3048         174 :         values[paramnum] = port;
    3049         174 :         keywords[++paramnum] = "user";
    3050         174 :         values[paramnum] = user;
    3051             : 
    3052             :         /*
    3053             :          * Position in the array matters when the dbname is a connection
    3054             :          * string, because settings in a connection string override earlier
    3055             :          * array entries only.  Thus, user= in the connection string always
    3056             :          * takes effect, but client_encoding= often will not.
    3057             :          *
    3058             :          * If you change this code, also change the initial-connection code in
    3059             :          * main().  For no good reason, a connection string password= takes
    3060             :          * precedence in main() but not here.
    3061             :          */
    3062         174 :         keywords[++paramnum] = "dbname";
    3063         174 :         values[paramnum] = dbname;
    3064         174 :         keywords[++paramnum] = "password";
    3065         174 :         values[paramnum] = password;
    3066         174 :         keywords[++paramnum] = "fallback_application_name";
    3067         174 :         values[paramnum] = pset.progname;
    3068         174 :         keywords[++paramnum] = "client_encoding";
    3069         174 :         values[paramnum] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
    3070             : 
    3071             :         /* add array terminator */
    3072         174 :         keywords[++paramnum] = NULL;
    3073         174 :         values[paramnum] = NULL;
    3074             : 
    3075         174 :         n_conn = PQconnectdbParams(keywords, values, true);
    3076             : 
    3077         174 :         pg_free(keywords);
    3078         174 :         pg_free(values);
    3079             : 
    3080             :         /* We can immediately discard the password -- no longer needed */
    3081         174 :         if (password)
    3082           0 :             pg_free(password);
    3083             : 
    3084         174 :         if (PQstatus(n_conn) == CONNECTION_OK)
    3085         174 :             break;
    3086             : 
    3087             :         /*
    3088             :          * Connection attempt failed; either retry the connection attempt with
    3089             :          * a new password, or give up.
    3090             :          */
    3091           0 :         if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
    3092             :         {
    3093             :             /*
    3094             :              * Prompt for password using the username we actually connected
    3095             :              * with --- it might've come out of "dbname" rather than "user".
    3096             :              */
    3097           0 :             password = prompt_for_password(PQuser(n_conn));
    3098           0 :             PQfinish(n_conn);
    3099           0 :             continue;
    3100             :         }
    3101             : 
    3102             :         /*
    3103             :          * Failed to connect to the database. In interactive mode, keep the
    3104             :          * previous connection to the DB; in scripting mode, close our
    3105             :          * previous connection as well.
    3106             :          */
    3107           0 :         if (pset.cur_cmd_interactive)
    3108             :         {
    3109           0 :             pg_log_info("%s", PQerrorMessage(n_conn));
    3110             : 
    3111             :             /* pset.db is left unmodified */
    3112           0 :             if (o_conn)
    3113           0 :                 pg_log_info("Previous connection kept");
    3114             :         }
    3115             :         else
    3116             :         {
    3117           0 :             pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
    3118           0 :             if (o_conn)
    3119             :             {
    3120           0 :                 PQfinish(o_conn);
    3121           0 :                 pset.db = NULL;
    3122             :             }
    3123             :         }
    3124             : 
    3125           0 :         PQfinish(n_conn);
    3126           0 :         if (connstr.data)
    3127           0 :             termPQExpBuffer(&connstr);
    3128           0 :         return false;
    3129             :     }
    3130         174 :     if (connstr.data)
    3131         142 :         termPQExpBuffer(&connstr);
    3132             : 
    3133             :     /*
    3134             :      * Replace the old connection with the new one, and update
    3135             :      * connection-dependent variables.
    3136             :      */
    3137         174 :     PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
    3138         174 :     pset.db = n_conn;
    3139         174 :     SyncVariables();
    3140         174 :     connection_warnings(false); /* Must be after SyncVariables */
    3141             : 
    3142             :     /* Tell the user about the new connection */
    3143         174 :     if (!pset.quiet)
    3144             :     {
    3145          56 :         if (!o_conn ||
    3146          56 :             param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
    3147          28 :             param_is_newly_set(PQport(o_conn), PQport(pset.db)))
    3148           0 :         {
    3149           0 :             char       *host = PQhost(pset.db);
    3150           0 :             char       *hostaddr = PQhostaddr(pset.db);
    3151             : 
    3152             :             /*
    3153             :              * If the host is an absolute path, the connection is via socket
    3154             :              * unless overridden by hostaddr
    3155             :              */
    3156           0 :             if (is_absolute_path(host))
    3157             :             {
    3158           0 :                 if (hostaddr && *hostaddr)
    3159           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
    3160             :                            PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
    3161             :                 else
    3162           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
    3163             :                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
    3164             :             }
    3165             :             else
    3166             :             {
    3167           0 :                 if (hostaddr && *hostaddr && strcmp(host, hostaddr) != 0)
    3168           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
    3169             :                            PQdb(pset.db), PQuser(pset.db), host, hostaddr, PQport(pset.db));
    3170             :                 else
    3171           0 :                     printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
    3172             :                            PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
    3173             :             }
    3174             :         }
    3175             :         else
    3176          28 :             printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
    3177             :                    PQdb(pset.db), PQuser(pset.db));
    3178             :     }
    3179             : 
    3180         174 :     if (o_conn)
    3181         174 :         PQfinish(o_conn);
    3182         174 :     return true;
    3183             : }
    3184             : 
    3185             : 
    3186             : void
    3187         174 : connection_warnings(bool in_startup)
    3188             : {
    3189         174 :     if (!pset.quiet && !pset.notty)
    3190             :     {
    3191           0 :         int         client_ver = PG_VERSION_NUM;
    3192             :         char        cverbuf[32];
    3193             :         char        sverbuf[32];
    3194             : 
    3195           0 :         if (pset.sversion != client_ver)
    3196             :         {
    3197             :             const char *server_version;
    3198             : 
    3199             :             /* Try to get full text form, might include "devel" etc */
    3200           0 :             server_version = PQparameterStatus(pset.db, "server_version");
    3201             :             /* Otherwise fall back on pset.sversion */
    3202           0 :             if (!server_version)
    3203             :             {
    3204           0 :                 formatPGVersionNumber(pset.sversion, true,
    3205             :                                       sverbuf, sizeof(sverbuf));
    3206           0 :                 server_version = sverbuf;
    3207             :             }
    3208             : 
    3209           0 :             printf(_("%s (%s, server %s)\n"),
    3210             :                    pset.progname, PG_VERSION, server_version);
    3211             :         }
    3212             :         /* For version match, only print psql banner on startup. */
    3213           0 :         else if (in_startup)
    3214           0 :             printf("%s (%s)\n", pset.progname, PG_VERSION);
    3215             : 
    3216           0 :         if (pset.sversion / 100 > client_ver / 100)
    3217           0 :             printf(_("WARNING: %s major version %s, server major version %s.\n"
    3218             :                      "         Some psql features might not work.\n"),
    3219             :                    pset.progname,
    3220             :                    formatPGVersionNumber(client_ver, false,
    3221             :                                          cverbuf, sizeof(cverbuf)),
    3222             :                    formatPGVersionNumber(pset.sversion, false,
    3223             :                                          sverbuf, sizeof(sverbuf)));
    3224             : 
    3225             : #ifdef WIN32
    3226             :         checkWin32Codepage();
    3227             : #endif
    3228           0 :         printSSLInfo();
    3229           0 :         printGSSInfo();
    3230             :     }
    3231         174 : }
    3232             : 
    3233             : 
    3234             : /*
    3235             :  * printSSLInfo
    3236             :  *
    3237             :  * Prints information about the current SSL connection, if SSL is in use
    3238             :  */
    3239             : static void
    3240           0 : printSSLInfo(void)
    3241             : {
    3242             :     const char *protocol;
    3243             :     const char *cipher;
    3244             :     const char *bits;
    3245             :     const char *compression;
    3246             : 
    3247           0 :     if (!PQsslInUse(pset.db))
    3248           0 :         return;                 /* no SSL */
    3249             : 
    3250           0 :     protocol = PQsslAttribute(pset.db, "protocol");
    3251           0 :     cipher = PQsslAttribute(pset.db, "cipher");
    3252           0 :     bits = PQsslAttribute(pset.db, "key_bits");
    3253           0 :     compression = PQsslAttribute(pset.db, "compression");
    3254             : 
    3255           0 :     printf(_("SSL connection (protocol: %s, cipher: %s, bits: %s, compression: %s)\n"),
    3256             :            protocol ? protocol : _("unknown"),
    3257             :            cipher ? cipher : _("unknown"),
    3258             :            bits ? bits : _("unknown"),
    3259             :            (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"));
    3260             : }
    3261             : 
    3262             : /*
    3263             :  * printGSSInfo
    3264             :  *
    3265             :  * Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
    3266             :  */
    3267             : static void
    3268           0 : printGSSInfo(void)
    3269             : {
    3270           0 :     if (!PQgssEncInUse(pset.db))
    3271           0 :         return;                 /* no GSSAPI encryption in use */
    3272             : 
    3273           0 :     printf(_("GSSAPI Encrypted connection\n"));
    3274             : }
    3275             : 
    3276             : 
    3277             : /*
    3278             :  * checkWin32Codepage
    3279             :  *
    3280             :  * Prints a warning when win32 console codepage differs from Windows codepage
    3281             :  */
    3282             : #ifdef WIN32
    3283             : static void
    3284             : checkWin32Codepage(void)
    3285             : {
    3286             :     unsigned int wincp,
    3287             :                 concp;
    3288             : 
    3289             :     wincp = GetACP();
    3290             :     concp = GetConsoleCP();
    3291             :     if (wincp != concp)
    3292             :     {
    3293             :         printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
    3294             :                  "         8-bit characters might not work correctly. See psql reference\n"
    3295             :                  "         page \"Notes for Windows users\" for details.\n"),
    3296             :                concp, wincp);
    3297             :     }
    3298             : }
    3299             : #endif
    3300             : 
    3301             : 
    3302             : /*
    3303             :  * SyncVariables
    3304             :  *
    3305             :  * Make psql's internal variables agree with connection state upon
    3306             :  * establishing a new connection.
    3307             :  */
    3308             : void
    3309        3850 : SyncVariables(void)
    3310             : {
    3311             :     char        vbuf[32];
    3312             :     const char *server_version;
    3313             : 
    3314             :     /* get stuff from connection */
    3315        3850 :     pset.encoding = PQclientEncoding(pset.db);
    3316        3850 :     pset.popt.topt.encoding = pset.encoding;
    3317        3850 :     pset.sversion = PQserverVersion(pset.db);
    3318             : 
    3319        3850 :     SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
    3320        3850 :     SetVariable(pset.vars, "USER", PQuser(pset.db));
    3321        3850 :     SetVariable(pset.vars, "HOST", PQhost(pset.db));
    3322        3850 :     SetVariable(pset.vars, "PORT", PQport(pset.db));
    3323        3850 :     SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
    3324             : 
    3325             :     /* this bit should match connection_warnings(): */
    3326             :     /* Try to get full text form of version, might include "devel" etc */
    3327        3850 :     server_version = PQparameterStatus(pset.db, "server_version");
    3328             :     /* Otherwise fall back on pset.sversion */
    3329        3850 :     if (!server_version)
    3330             :     {
    3331           0 :         formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
    3332           0 :         server_version = vbuf;
    3333             :     }
    3334        3850 :     SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
    3335             : 
    3336        3850 :     snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
    3337        3850 :     SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
    3338             : 
    3339             :     /* send stuff to it, too */
    3340        3850 :     PQsetErrorVerbosity(pset.db, pset.verbosity);
    3341        3850 :     PQsetErrorContextVisibility(pset.db, pset.show_context);
    3342        3850 : }
    3343             : 
    3344             : /*
    3345             :  * UnsyncVariables
    3346             :  *
    3347             :  * Clear variables that should be not be set when there is no connection.
    3348             :  */
    3349             : void
    3350           0 : UnsyncVariables(void)
    3351             : {
    3352           0 :     SetVariable(pset.vars, "DBNAME", NULL);
    3353           0 :     SetVariable(pset.vars, "USER", NULL);
    3354           0 :     SetVariable(pset.vars, "HOST", NULL);
    3355           0 :     SetVariable(pset.vars, "PORT", NULL);
    3356           0 :     SetVariable(pset.vars, "ENCODING", NULL);
    3357           0 :     SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
    3358           0 :     SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
    3359           0 : }
    3360             : 
    3361             : 
    3362             : /*
    3363             :  * do_edit -- handler for \e
    3364             :  *
    3365             :  * If you do not specify a filename, the current query buffer will be copied
    3366             :  * into a temporary one.
    3367             :  */
    3368             : static bool
    3369           0 : editFile(const char *fname, int lineno)
    3370             : {
    3371             :     const char *editorName;
    3372           0 :     const char *editor_lineno_arg = NULL;
    3373             :     char       *sys;
    3374             :     int         result;
    3375             : 
    3376             :     Assert(fname != NULL);
    3377             : 
    3378             :     /* Find an editor to use */
    3379           0 :     editorName = getenv("PSQL_EDITOR");
    3380           0 :     if (!editorName)
    3381           0 :         editorName = getenv("EDITOR");
    3382           0 :     if (!editorName)
    3383           0 :         editorName = getenv("VISUAL");
    3384           0 :     if (!editorName)
    3385           0 :         editorName = DEFAULT_EDITOR;
    3386             : 
    3387             :     /* Get line number argument, if we need it. */
    3388           0 :     if (lineno > 0)
    3389             :     {
    3390           0 :         editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
    3391             : #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
    3392           0 :         if (!editor_lineno_arg)
    3393           0 :             editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
    3394             : #endif
    3395           0 :         if (!editor_lineno_arg)
    3396             :         {
    3397           0 :             pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
    3398           0 :             return false;
    3399             :         }
    3400             :     }
    3401             : 
    3402             :     /*
    3403             :      * On Unix the EDITOR value should *not* be quoted, since it might include
    3404             :      * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
    3405             :      * if necessary.  But this policy is not very workable on Windows, due to
    3406             :      * severe brain damage in their command shell plus the fact that standard
    3407             :      * program paths include spaces.
    3408             :      */
    3409             : #ifndef WIN32
    3410           0 :     if (lineno > 0)
    3411           0 :         sys = psprintf("exec %s %s%d '%s'",
    3412             :                        editorName, editor_lineno_arg, lineno, fname);
    3413             :     else
    3414           0 :         sys = psprintf("exec %s '%s'",
    3415             :                        editorName, fname);
    3416             : #else
    3417             :     if (lineno > 0)
    3418             :         sys = psprintf("\"%s\" %s%d \"%s\"",
    3419             :                        editorName, editor_lineno_arg, lineno, fname);
    3420             :     else
    3421             :         sys = psprintf("\"%s\" \"%s\"",
    3422             :                        editorName, fname);
    3423             : #endif
    3424           0 :     result = system(sys);
    3425           0 :     if (result == -1)
    3426           0 :         pg_log_error("could not start editor \"%s\"", editorName);
    3427           0 :     else if (result == 127)
    3428           0 :         pg_log_error("could not start /bin/sh");
    3429           0 :     free(sys);
    3430             : 
    3431           0 :     return result == 0;
    3432             : }
    3433             : 
    3434             : 
    3435             : /* call this one */
    3436             : static bool
    3437           0 : do_edit(const char *filename_arg, PQExpBuffer query_buf,
    3438             :         int lineno, bool *edited)
    3439             : {
    3440             :     char        fnametmp[MAXPGPATH];
    3441           0 :     FILE       *stream = NULL;
    3442             :     const char *fname;
    3443           0 :     bool        error = false;
    3444             :     int         fd;
    3445             : 
    3446             :     struct stat before,
    3447             :                 after;
    3448             : 
    3449           0 :     if (filename_arg)
    3450           0 :         fname = filename_arg;
    3451             :     else
    3452             :     {
    3453             :         /* make a temp file to edit */
    3454             : #ifndef WIN32
    3455           0 :         const char *tmpdir = getenv("TMPDIR");
    3456             : 
    3457           0 :         if (!tmpdir)
    3458           0 :             tmpdir = "/tmp";
    3459             : #else
    3460             :         char        tmpdir[MAXPGPATH];
    3461             :         int         ret;
    3462             : 
    3463             :         ret = GetTempPath(MAXPGPATH, tmpdir);
    3464             :         if (ret == 0 || ret > MAXPGPATH)
    3465             :         {
    3466             :             pg_log_error("could not locate temporary directory: %s",
    3467             :                          !ret ? strerror(errno) : "");
    3468             :             return false;
    3469             :         }
    3470             : 
    3471             :         /*
    3472             :          * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
    3473             :          * current directory to the supplied path unless we use only
    3474             :          * backslashes, so we do that.
    3475             :          */
    3476             : #endif
    3477             : #ifndef WIN32
    3478           0 :         snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
    3479           0 :                  "/", (int) getpid());
    3480             : #else
    3481             :         snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
    3482             :                  "" /* trailing separator already present */ , (int) getpid());
    3483             : #endif
    3484             : 
    3485           0 :         fname = (const char *) fnametmp;
    3486             : 
    3487           0 :         fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
    3488           0 :         if (fd != -1)
    3489           0 :             stream = fdopen(fd, "w");
    3490             : 
    3491           0 :         if (fd == -1 || !stream)
    3492             :         {
    3493           0 :             pg_log_error("could not open temporary file \"%s\": %m", fname);
    3494           0 :             error = true;
    3495             :         }
    3496             :         else
    3497             :         {
    3498           0 :             unsigned int ql = query_buf->len;
    3499             : 
    3500           0 :             if (ql == 0 || query_buf->data[ql - 1] != '\n')
    3501             :             {
    3502           0 :                 appendPQExpBufferChar(query_buf, '\n');
    3503           0 :                 ql++;
    3504             :             }
    3505             : 
    3506           0 :             if (fwrite(query_buf->data, 1, ql, stream) != ql)
    3507             :             {
    3508           0 :                 pg_log_error("%s: %m", fname);
    3509             : 
    3510           0 :                 if (fclose(stream) != 0)
    3511           0 :                     pg_log_error("%s: %m", fname);
    3512             : 
    3513           0 :                 if (remove(fname) != 0)
    3514           0 :                     pg_log_error("%s: %m", fname);
    3515             : 
    3516           0 :                 error = true;
    3517             :             }
    3518           0 :             else if (fclose(stream) != 0)
    3519             :             {
    3520           0 :                 pg_log_error("%s: %m", fname);
    3521           0 :                 if (remove(fname) != 0)
    3522           0 :                     pg_log_error("%s: %m", fname);
    3523           0 :                 error = true;
    3524             :             }
    3525             :         }
    3526             :     }
    3527             : 
    3528           0 :     if (!error && stat(fname, &before) != 0)
    3529             :     {
    3530           0 :         pg_log_error("%s: %m", fname);
    3531           0 :         error = true;
    3532             :     }
    3533             : 
    3534             :     /* call editor */
    3535           0 :     if (!error)
    3536           0 :         error = !editFile(fname, lineno);
    3537             : 
    3538           0 :     if (!error && stat(fname, &after) != 0)
    3539             :     {
    3540           0 :         pg_log_error("%s: %m", fname);
    3541           0 :         error = true;
    3542             :     }
    3543             : 
    3544           0 :     if (!error && before.st_mtime != after.st_mtime)
    3545             :     {
    3546           0 :         stream = fopen(fname, PG_BINARY_R);
    3547           0 :         if (!stream)
    3548             :         {
    3549           0 :             pg_log_error("%s: %m", fname);
    3550           0 :             error = true;
    3551             :         }
    3552             :         else
    3553             :         {
    3554             :             /* read file back into query_buf */
    3555             :             char        line[1024];
    3556             : 
    3557           0 :             resetPQExpBuffer(query_buf);
    3558           0 :             while (fgets(line, sizeof(line), stream) != NULL)
    3559           0 :                 appendPQExpBufferStr(query_buf, line);
    3560             : 
    3561           0 :             if (ferror(stream))
    3562             :             {
    3563           0 :                 pg_log_error("%s: %m", fname);
    3564           0 :                 error = true;
    3565             :             }
    3566           0 :             else if (edited)
    3567             :             {
    3568           0 :                 *edited = true;
    3569             :             }
    3570             : 
    3571           0 :             fclose(stream);
    3572             :         }
    3573             :     }
    3574             : 
    3575             :     /* remove temp file */
    3576           0 :     if (!filename_arg)
    3577             :     {
    3578           0 :         if (remove(fname) == -1)
    3579             :         {
    3580           0 :             pg_log_error("%s: %m", fname);
    3581           0 :             error = true;
    3582             :         }
    3583             :     }
    3584             : 
    3585           0 :     return !error;
    3586             : }
    3587             : 
    3588             : 
    3589             : 
    3590             : /*
    3591             :  * process_file
    3592             :  *
    3593             :  * Reads commands from filename and passes them to the main processing loop.
    3594             :  * Handler for \i and \ir, but can be used for other things as well.  Returns
    3595             :  * MainLoop() error code.
    3596             :  *
    3597             :  * If use_relative_path is true and filename is not an absolute path, then open
    3598             :  * the file from where the currently processed file (if any) is located.
    3599             :  */
    3600             : int
    3601        2698 : process_file(char *filename, bool use_relative_path)
    3602             : {
    3603             :     FILE       *fd;
    3604             :     int         result;
    3605             :     char       *oldfilename;
    3606             :     char        relpath[MAXPGPATH];
    3607             : 
    3608        2698 :     if (!filename)
    3609             :     {
    3610        1350 :         fd = stdin;
    3611        1350 :         filename = NULL;
    3612             :     }
    3613        1348 :     else if (strcmp(filename, "-") != 0)
    3614             :     {
    3615           6 :         canonicalize_path(filename);
    3616             : 
    3617             :         /*
    3618             :          * If we were asked to resolve the pathname relative to the location
    3619             :          * of the currently executing script, and there is one, and this is a
    3620             :          * relative pathname, then prepend all but the last pathname component
    3621             :          * of the current script to this pathname.
    3622             :          */
    3623           6 :         if (use_relative_path && pset.inputfile &&
    3624           0 :             !is_absolute_path(filename) && !has_drive_prefix(filename))
    3625             :         {
    3626           0 :             strlcpy(relpath, pset.inputfile, sizeof(relpath));
    3627           0 :             get_parent_directory(relpath);
    3628           0 :             join_path_components(relpath, relpath, filename);
    3629           0 :             canonicalize_path(relpath);
    3630             : 
    3631           0 :             filename = relpath;
    3632             :         }
    3633             : 
    3634           6 :         fd = fopen(filename, PG_BINARY_R);
    3635             : 
    3636           6 :         if (!fd)
    3637             :         {
    3638           0 :             pg_log_error("%s: %m", filename);
    3639           0 :             return EXIT_FAILURE;
    3640             :         }
    3641             :     }
    3642             :     else
    3643             :     {
    3644        1342 :         fd = stdin;
    3645        1342 :         filename = "<stdin>";   /* for future error messages */
    3646             :     }
    3647             : 
    3648        2698 :     oldfilename = pset.inputfile;
    3649        2698 :     pset.inputfile = filename;
    3650             : 
    3651        2698 :     pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
    3652             : 
    3653        2698 :     result = MainLoop(fd);
    3654             : 
    3655        2692 :     if (fd != stdin)
    3656           6 :         fclose(fd);
    3657             : 
    3658        2692 :     pset.inputfile = oldfilename;
    3659             : 
    3660        2692 :     pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
    3661             : 
    3662        2692 :     return result;
    3663             : }
    3664             : 
    3665             : 
    3666             : 
    3667             : static const char *
    3668           4 : _align2string(enum printFormat in)
    3669             : {
    3670           4 :     switch (in)
    3671             :     {
    3672             :         case PRINT_NOTHING:
    3673           0 :             return "nothing";
    3674             :             break;
    3675             :         case PRINT_ALIGNED:
    3676           4 :             return "aligned";
    3677             :             break;
    3678             :         case PRINT_ASCIIDOC:
    3679           0 :             return "asciidoc";
    3680             :             break;
    3681             :         case PRINT_CSV:
    3682           0 :             return "csv";
    3683             :             break;
    3684             :         case PRINT_HTML:
    3685           0 :             return "html";
    3686             :             break;
    3687             :         case PRINT_LATEX:
    3688           0 :             return "latex";
    3689             :             break;
    3690             :         case PRINT_LATEX_LONGTABLE:
    3691           0 :             return "latex-longtable";
    3692             :             break;
    3693             :         case PRINT_TROFF_MS:
    3694           0 :             return "troff-ms";
    3695             :             break;
    3696             :         case PRINT_UNALIGNED:
    3697           0 :             return "unaligned";
    3698             :             break;
    3699             :         case PRINT_WRAPPED:
    3700           0 :             return "wrapped";
    3701             :             break;
    3702             :     }
    3703           0 :     return "unknown";
    3704             : }
    3705             : 
    3706             : /*
    3707             :  * Parse entered Unicode linestyle.  If ok, update *linestyle and return
    3708             :  * true, else return false.
    3709             :  */
    3710             : static bool
    3711           0 : set_unicode_line_style(const char *value, size_t vallen,
    3712             :                        unicode_linestyle *linestyle)
    3713             : {
    3714           0 :     if (pg_strncasecmp("single", value, vallen) == 0)
    3715           0 :         *linestyle = UNICODE_LINESTYLE_SINGLE;
    3716           0 :     else if (pg_strncasecmp("double", value, vallen) == 0)
    3717           0 :         *linestyle = UNICODE_LINESTYLE_DOUBLE;
    3718             :     else
    3719           0 :         return false;
    3720           0 :     return true;
    3721             : }
    3722             : 
    3723             : static const char *
    3724          12 : _unicode_linestyle2string(int linestyle)
    3725             : {
    3726          12 :     switch (linestyle)
    3727             :     {
    3728             :         case UNICODE_LINESTYLE_SINGLE:
    3729          12 :             return "single";
    3730             :             break;
    3731             :         case UNICODE_LINESTYLE_DOUBLE:
    3732           0 :             return "double";
    3733             :             break;
    3734             :     }
    3735           0 :     return "unknown";
    3736             : }
    3737             : 
    3738             : /*
    3739             :  * do_pset
    3740             :  *
    3741             :  */
    3742             : bool
    3743        1202 : do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
    3744             : {
    3745        1202 :     size_t      vallen = 0;
    3746             : 
    3747             :     Assert(param != NULL);
    3748             : 
    3749        1202 :     if (value)
    3750        1148 :         vallen = strlen(value);
    3751             : 
    3752             :     /* set format */
    3753        1202 :     if (strcmp(param, "format") == 0)
    3754             :     {
    3755             :         static const struct fmt
    3756             :         {
    3757             :             const char *name;
    3758             :             enum printFormat number;
    3759             :         }           formats[] =
    3760             :         {
    3761             :             /* remember to update error message below when adding more */
    3762             :             {"aligned", PRINT_ALIGNED},
    3763             :             {"asciidoc", PRINT_ASCIIDOC},
    3764             :             {"csv", PRINT_CSV},
    3765             :             {"html", PRINT_HTML},
    3766             :             {"latex", PRINT_LATEX},
    3767             :             {"troff-ms", PRINT_TROFF_MS},
    3768             :             {"unaligned", PRINT_UNALIGNED},
    3769             :             {"wrapped", PRINT_WRAPPED}
    3770             :         };
    3771             : 
    3772         400 :         if (!value)
    3773             :             ;
    3774             :         else
    3775             :         {
    3776         400 :             int         match_pos = -1;
    3777             : 
    3778        3572 :             for (int i = 0; i < lengthof(formats); i++)
    3779             :             {
    3780        3176 :                 if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
    3781             :                 {
    3782         400 :                     if (match_pos < 0)
    3783         396 :                         match_pos = i;
    3784             :                     else
    3785             :                     {
    3786           4 :                         pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
    3787             :                                      value,
    3788             :                                      formats[match_pos].name, formats[i].name);
    3789           4 :                         return false;
    3790             :                     }
    3791             :                 }
    3792             :             }
    3793         396 :             if (match_pos >= 0)
    3794         392 :                 popt->topt.format = formats[match_pos].number;
    3795           4 :             else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
    3796             :             {
    3797             :                 /*
    3798             :                  * We must treat latex-longtable specially because latex is a
    3799             :                  * prefix of it; if both were in the table above, we'd think
    3800             :                  * "latex" is ambiguous.
    3801             :                  */
    3802           4 :                 popt->topt.format = PRINT_LATEX_LONGTABLE;
    3803             :             }
    3804             :             else
    3805             :             {
    3806           0 :                 pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
    3807           0 :                 return false;
    3808             :             }
    3809             :         }
    3810             :     }
    3811             : 
    3812             :     /* set table line style */
    3813         802 :     else if (strcmp(param, "linestyle") == 0)
    3814             :     {
    3815          20 :         if (!value)
    3816             :             ;
    3817          20 :         else if (pg_strncasecmp("ascii", value, vallen) == 0)
    3818          12 :             popt->topt.line_style = &pg_asciiformat;
    3819           8 :         else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
    3820           8 :             popt->topt.line_style = &pg_asciiformat_old;
    3821           0 :         else if (pg_strncasecmp("unicode", value, vallen) == 0)
    3822           0 :             popt->topt.line_style = &pg_utf8format;
    3823             :         else
    3824             :         {
    3825           0 :             pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
    3826           0 :             return false;
    3827             :         }
    3828             :     }
    3829             : 
    3830             :     /* set unicode border line style */
    3831         782 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    3832             :     {
    3833           0 :         if (!value)
    3834             :             ;
    3835           0 :         else if (set_unicode_line_style(value, vallen,
    3836             :                                         &popt->topt.unicode_border_linestyle))
    3837           0 :             refresh_utf8format(&(popt->topt));
    3838             :         else
    3839             :         {
    3840           0 :             pg_log_error("\\pset: allowed Unicode border line styles are single, double");
    3841           0 :             return false;
    3842             :         }
    3843             :     }
    3844             : 
    3845             :     /* set unicode column line style */
    3846         782 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    3847             :     {
    3848           0 :         if (!value)
    3849             :             ;
    3850           0 :         else if (set_unicode_line_style(value, vallen,
    3851             :                                         &popt->topt.unicode_column_linestyle))
    3852           0 :             refresh_utf8format(&(popt->topt));
    3853             :         else
    3854             :         {
    3855           0 :             pg_log_error("\\pset: allowed Unicode column line styles are single, double");
    3856           0 :             return false;
    3857             :         }
    3858             :     }
    3859             : 
    3860             :     /* set unicode header line style */
    3861         782 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    3862             :     {
    3863           0 :         if (!value)
    3864             :             ;
    3865           0 :         else if (set_unicode_line_style(value, vallen,
    3866             :                                         &popt->topt.unicode_header_linestyle))
    3867           0 :             refresh_utf8format(&(popt->topt));
    3868             :         else
    3869             :         {
    3870           0 :             pg_log_error("\\pset: allowed Unicode header line styles are single, double");
    3871           0 :             return false;
    3872             :         }
    3873             :     }
    3874             : 
    3875             :     /* set border style/width */
    3876         782 :     else if (strcmp(param, "border") == 0)
    3877             :     {
    3878         268 :         if (value)
    3879         268 :             popt->topt.border = atoi(value);
    3880             :     }
    3881             : 
    3882             :     /* set expanded/vertical mode */
    3883        1028 :     else if (strcmp(param, "x") == 0 ||
    3884         844 :              strcmp(param, "expanded") == 0 ||
    3885         330 :              strcmp(param, "vertical") == 0)
    3886             :     {
    3887         368 :         if (value && pg_strcasecmp(value, "auto") == 0)
    3888           0 :             popt->topt.expanded = 2;
    3889         184 :         else if (value)
    3890             :         {
    3891             :             bool        on_off;
    3892             : 
    3893         170 :             if (ParseVariableBool(value, NULL, &on_off))
    3894         170 :                 popt->topt.expanded = on_off ? 1 : 0;
    3895             :             else
    3896             :             {
    3897           0 :                 PsqlVarEnumError(param, value, "on, off, auto");
    3898           0 :                 return false;
    3899             :             }
    3900             :         }
    3901             :         else
    3902          14 :             popt->topt.expanded = !popt->topt.expanded;
    3903             :     }
    3904             : 
    3905             :     /* field separator for CSV format */
    3906         330 :     else if (strcmp(param, "csv_fieldsep") == 0)
    3907             :     {
    3908          36 :         if (value)
    3909             :         {
    3910             :             /* CSV separator has to be a one-byte character */
    3911          36 :             if (strlen(value) != 1)
    3912             :             {
    3913          12 :                 pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
    3914          12 :                 return false;
    3915             :             }
    3916          24 :             if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
    3917             :             {
    3918          12 :                 pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
    3919          12 :                 return false;
    3920             :             }
    3921          12 :             popt->topt.csvFieldSep[0] = value[0];
    3922             :         }
    3923             :     }
    3924             : 
    3925             :     /* locale-aware numeric output */
    3926         294 :     else if (strcmp(param, "numericlocale") == 0)
    3927             :     {
    3928           8 :         if (value)
    3929           8 :             return ParseVariableBool(value, param, &popt->topt.numericLocale);
    3930             :         else
    3931           0 :             popt->topt.numericLocale = !popt->topt.numericLocale;
    3932             :     }
    3933             : 
    3934             :     /* null display */
    3935         286 :     else if (strcmp(param, "null") == 0)
    3936             :     {
    3937          34 :         if (value)
    3938             :         {
    3939          34 :             free(popt->nullPrint);
    3940          34 :             popt->nullPrint = pg_strdup(value);
    3941             :         }
    3942             :     }
    3943             : 
    3944             :     /* field separator for unaligned text */
    3945         252 :     else if (strcmp(param, "fieldsep") == 0)
    3946             :     {
    3947           4 :         if (value)
    3948             :         {
    3949           4 :             free(popt->topt.fieldSep.separator);
    3950           4 :             popt->topt.fieldSep.separator = pg_strdup(value);
    3951           4 :             popt->topt.fieldSep.separator_zero = false;
    3952             :         }
    3953             :     }
    3954             : 
    3955         248 :     else if (strcmp(param, "fieldsep_zero") == 0)
    3956             :     {
    3957           0 :         free(popt->topt.fieldSep.separator);
    3958           0 :         popt->topt.fieldSep.separator = NULL;
    3959           0 :         popt->topt.fieldSep.separator_zero = true;
    3960             :     }
    3961             : 
    3962             :     /* record separator for unaligned text */
    3963         248 :     else if (strcmp(param, "recordsep") == 0)
    3964             :     {
    3965           0 :         if (value)
    3966             :         {
    3967           0 :             free(popt->topt.recordSep.separator);
    3968           0 :             popt->topt.recordSep.separator = pg_strdup(value);
    3969           0 :             popt->topt.recordSep.separator_zero = false;
    3970             :         }
    3971             :     }
    3972             : 
    3973         248 :     else if (strcmp(param, "recordsep_zero") == 0)
    3974             :     {
    3975           0 :         free(popt->topt.recordSep.separator);
    3976           0 :         popt->topt.recordSep.separator = NULL;
    3977           0 :         popt->topt.recordSep.separator_zero = true;
    3978             :     }
    3979             : 
    3980             :     /* toggle between full and tuples-only format */
    3981         248 :     else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
    3982             :     {
    3983         208 :         if (value)
    3984         160 :             return ParseVariableBool(value, param, &popt->topt.tuples_only);
    3985             :         else
    3986          24 :             popt->topt.tuples_only = !popt->topt.tuples_only;
    3987             :     }
    3988             : 
    3989             :     /* set title override */
    3990          64 :     else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
    3991             :     {
    3992           0 :         free(popt->title);
    3993           0 :         if (!value)
    3994           0 :             popt->title = NULL;
    3995             :         else
    3996           0 :             popt->title = pg_strdup(value);
    3997             :     }
    3998             : 
    3999             :     /* set HTML table tag options */
    4000          64 :     else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
    4001             :     {
    4002          32 :         free(popt->topt.tableAttr);
    4003          64 :         if (!value)
    4004          16 :             popt->topt.tableAttr = NULL;
    4005             :         else
    4006          16 :             popt->topt.tableAttr = pg_strdup(value);
    4007             :     }
    4008             : 
    4009             :     /* toggle use of pager */
    4010          32 :     else if (strcmp(param, "pager") == 0)
    4011             :     {
    4012           0 :         if (value && pg_strcasecmp(value, "always") == 0)
    4013           0 :             popt->topt.pager = 2;
    4014           0 :         else if (value)
    4015             :         {
    4016             :             bool        on_off;
    4017             : 
    4018           0 :             if (!ParseVariableBool(value, NULL, &on_off))
    4019             :             {
    4020           0 :                 PsqlVarEnumError(param, value, "on, off, always");
    4021           0 :                 return false;
    4022             :             }
    4023           0 :             popt->topt.pager = on_off ? 1 : 0;
    4024             :         }
    4025           0 :         else if (popt->topt.pager == 1)
    4026           0 :             popt->topt.pager = 0;
    4027             :         else
    4028           0 :             popt->topt.pager = 1;
    4029             :     }
    4030             : 
    4031             :     /* set minimum lines for pager use */
    4032          32 :     else if (strcmp(param, "pager_min_lines") == 0)
    4033             :     {
    4034           0 :         if (value)
    4035           0 :             popt->topt.pager_min_lines = atoi(value);
    4036             :     }
    4037             : 
    4038             :     /* disable "(x rows)" footer */
    4039          32 :     else if (strcmp(param, "footer") == 0)
    4040             :     {
    4041           0 :         if (value)
    4042           0 :             return ParseVariableBool(value, param, &popt->topt.default_footer);
    4043             :         else
    4044           0 :             popt->topt.default_footer = !popt->topt.default_footer;
    4045             :     }
    4046             : 
    4047             :     /* set border style/width */
    4048          32 :     else if (strcmp(param, "columns") == 0)
    4049             :     {
    4050          32 :         if (value)
    4051          32 :             popt->topt.columns = atoi(value);
    4052             :     }
    4053             :     else
    4054             :     {
    4055           0 :         pg_log_error("\\pset: unknown option: %s", param);
    4056           0 :         return false;
    4057             :     }
    4058             : 
    4059        1006 :     if (!quiet)
    4060           0 :         printPsetInfo(param, &pset.popt);
    4061             : 
    4062        1006 :     return true;
    4063             : }
    4064             : 
    4065             : 
    4066             : static bool
    4067           0 : printPsetInfo(const char *param, struct printQueryOpt *popt)
    4068             : {
    4069             :     Assert(param != NULL);
    4070             : 
    4071             :     /* show border style/width */
    4072           0 :     if (strcmp(param, "border") == 0)
    4073           0 :         printf(_("Border style is %d.\n"), popt->topt.border);
    4074             : 
    4075             :     /* show the target width for the wrapped format */
    4076           0 :     else if (strcmp(param, "columns") == 0)
    4077             :     {
    4078           0 :         if (!popt->topt.columns)
    4079           0 :             printf(_("Target width is unset.\n"));
    4080             :         else
    4081           0 :             printf(_("Target width is %d.\n"), popt->topt.columns);
    4082             :     }
    4083             : 
    4084             :     /* show expanded/vertical mode */
    4085           0 :     else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
    4086             :     {
    4087           0 :         if (popt->topt.expanded == 1)
    4088           0 :             printf(_("Expanded display is on.\n"));
    4089           0 :         else if (popt->topt.expanded == 2)
    4090           0 :             printf(_("Expanded display is used automatically.\n"));
    4091             :         else
    4092           0 :             printf(_("Expanded display is off.\n"));
    4093             :     }
    4094             : 
    4095             :     /* show field separator for CSV format */
    4096           0 :     else if (strcmp(param, "csv_fieldsep") == 0)
    4097             :     {
    4098           0 :         printf(_("Field separator for CSV is \"%s\".\n"),
    4099             :                popt->topt.csvFieldSep);
    4100             :     }
    4101             : 
    4102             :     /* show field separator for unaligned text */
    4103           0 :     else if (strcmp(param, "fieldsep") == 0)
    4104             :     {
    4105           0 :         if (popt->topt.fieldSep.separator_zero)
    4106           0 :             printf(_("Field separator is zero byte.\n"));
    4107             :         else
    4108           0 :             printf(_("Field separator is \"%s\".\n"),
    4109             :                    popt->topt.fieldSep.separator);
    4110             :     }
    4111             : 
    4112           0 :     else if (strcmp(param, "fieldsep_zero") == 0)
    4113             :     {
    4114           0 :         printf(_("Field separator is zero byte.\n"));
    4115             :     }
    4116             : 
    4117             :     /* show disable "(x rows)" footer */
    4118           0 :     else if (strcmp(param, "footer") == 0)
    4119             :     {
    4120           0 :         if (popt->topt.default_footer)
    4121           0 :             printf(_("Default footer is on.\n"));
    4122             :         else
    4123           0 :             printf(_("Default footer is off.\n"));
    4124             :     }
    4125             : 
    4126             :     /* show format */
    4127           0 :     else if (strcmp(param, "format") == 0)
    4128             :     {
    4129           0 :         printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
    4130             :     }
    4131             : 
    4132             :     /* show table line style */
    4133           0 :     else if (strcmp(param, "linestyle") == 0)
    4134             :     {
    4135           0 :         printf(_("Line style is %s.\n"),
    4136             :                get_line_style(&popt->topt)->name);
    4137             :     }
    4138             : 
    4139             :     /* show null display */
    4140           0 :     else if (strcmp(param, "null") == 0)
    4141             :     {
    4142           0 :         printf(_("Null display is \"%s\".\n"),
    4143             :                popt->nullPrint ? popt->nullPrint : "");
    4144             :     }
    4145             : 
    4146             :     /* show locale-aware numeric output */
    4147           0 :     else if (strcmp(param, "numericlocale") == 0)
    4148             :     {
    4149           0 :         if (popt->topt.numericLocale)
    4150           0 :             printf(_("Locale-adjusted numeric output is on.\n"));
    4151             :         else
    4152           0 :             printf(_("Locale-adjusted numeric output is off.\n"));
    4153             :     }
    4154             : 
    4155             :     /* show toggle use of pager */
    4156           0 :     else if (strcmp(param, "pager") == 0)
    4157             :     {
    4158           0 :         if (popt->topt.pager == 1)
    4159           0 :             printf(_("Pager is used for long output.\n"));
    4160           0 :         else if (popt->topt.pager == 2)
    4161           0 :             printf(_("Pager is always used.\n"));
    4162             :         else
    4163           0 :             printf(_("Pager usage is off.\n"));
    4164             :     }
    4165             : 
    4166             :     /* show minimum lines for pager use */
    4167           0 :     else if (strcmp(param, "pager_min_lines") == 0)
    4168             :     {
    4169           0 :         printf(ngettext("Pager won't be used for less than %d line.\n",
    4170             :                         "Pager won't be used for less than %d lines.\n",
    4171             :                         popt->topt.pager_min_lines),
    4172             :                popt->topt.pager_min_lines);
    4173             :     }
    4174             : 
    4175             :     /* show record separator for unaligned text */
    4176           0 :     else if (strcmp(param, "recordsep") == 0)
    4177             :     {
    4178           0 :         if (popt->topt.recordSep.separator_zero)
    4179           0 :             printf(_("Record separator is zero byte.\n"));
    4180           0 :         else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
    4181           0 :             printf(_("Record separator is <newline>.\n"));
    4182             :         else
    4183           0 :             printf(_("Record separator is \"%s\".\n"),
    4184             :                    popt->topt.recordSep.separator);
    4185             :     }
    4186             : 
    4187           0 :     else if (strcmp(param, "recordsep_zero") == 0)
    4188             :     {
    4189           0 :         printf(_("Record separator is zero byte.\n"));
    4190             :     }
    4191             : 
    4192             :     /* show HTML table tag options */
    4193           0 :     else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
    4194             :     {
    4195           0 :         if (popt->topt.tableAttr)
    4196           0 :             printf(_("Table attributes are \"%s\".\n"),
    4197             :                    popt->topt.tableAttr);
    4198             :         else
    4199           0 :             printf(_("Table attributes unset.\n"));
    4200             :     }
    4201             : 
    4202             :     /* show title override */
    4203           0 :     else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
    4204             :     {
    4205           0 :         if (popt->title)
    4206           0 :             printf(_("Title is \"%s\".\n"), popt->title);
    4207             :         else
    4208           0 :             printf(_("Title is unset.\n"));
    4209             :     }
    4210             : 
    4211             :     /* show toggle between full and tuples-only format */
    4212           0 :     else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
    4213             :     {
    4214           0 :         if (popt->topt.tuples_only)
    4215           0 :             printf(_("Tuples only is on.\n"));
    4216             :         else
    4217           0 :             printf(_("Tuples only is off.\n"));
    4218             :     }
    4219             : 
    4220             :     /* Unicode style formatting */
    4221           0 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    4222             :     {
    4223           0 :         printf(_("Unicode border line style is \"%s\".\n"),
    4224             :                _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
    4225             :     }
    4226             : 
    4227           0 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    4228             :     {
    4229           0 :         printf(_("Unicode column line style is \"%s\".\n"),
    4230             :                _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
    4231             :     }
    4232             : 
    4233           0 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    4234             :     {
    4235           0 :         printf(_("Unicode header line style is \"%s\".\n"),
    4236             :                _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
    4237             :     }
    4238             : 
    4239             :     else
    4240             :     {
    4241           0 :         pg_log_error("\\pset: unknown option: %s", param);
    4242           0 :         return false;
    4243             :     }
    4244             : 
    4245           0 :     return true;
    4246             : }
    4247             : 
    4248             : 
    4249             : static const char *
    4250          24 : pset_bool_string(bool val)
    4251             : {
    4252          24 :     return val ? "on" : "off";
    4253             : }
    4254             : 
    4255             : 
    4256             : static char *
    4257          16 : pset_quoted_string(const char *str)
    4258             : {
    4259          16 :     char       *ret = pg_malloc(strlen(str) * 2 + 3);
    4260          16 :     char       *r = ret;
    4261             : 
    4262          16 :     *r++ = '\'';
    4263             : 
    4264          28 :     for (; *str; str++)
    4265             :     {
    4266          12 :         if (*str == '\n')
    4267             :         {
    4268           4 :             *r++ = '\\';
    4269           4 :             *r++ = 'n';
    4270             :         }
    4271           8 :         else if (*str == '\'')
    4272             :         {
    4273           0 :             *r++ = '\\';
    4274           0 :             *r++ = '\'';
    4275             :         }
    4276             :         else
    4277           8 :             *r++ = *str;
    4278             :     }
    4279             : 
    4280          16 :     *r++ = '\'';
    4281          16 :     *r = '\0';
    4282             : 
    4283          16 :     return ret;
    4284             : }
    4285             : 
    4286             : 
    4287             : /*
    4288             :  * Return a malloc'ed string for the \pset value.
    4289             :  *
    4290             :  * Note that for some string parameters, print.c distinguishes between unset
    4291             :  * and empty string, but for others it doesn't.  This function should produce
    4292             :  * output that produces the correct setting when fed back into \pset.
    4293             :  */
    4294             : static char *
    4295          84 : pset_value_string(const char *param, struct printQueryOpt *popt)
    4296             : {
    4297             :     Assert(param != NULL);
    4298             : 
    4299          84 :     if (strcmp(param, "border") == 0)
    4300           4 :         return psprintf("%d", popt->topt.border);
    4301          80 :     else if (strcmp(param, "columns") == 0)
    4302           4 :         return psprintf("%d", popt->topt.columns);
    4303          76 :     else if (strcmp(param, "csv_fieldsep") == 0)
    4304           4 :         return pset_quoted_string(popt->topt.csvFieldSep);
    4305          72 :     else if (strcmp(param, "expanded") == 0)
    4306           8 :         return pstrdup(popt->topt.expanded == 2
    4307             :                        ? "auto"
    4308           4 :                        : pset_bool_string(popt->topt.expanded));
    4309          68 :     else if (strcmp(param, "fieldsep") == 0)
    4310           4 :         return pset_quoted_string(popt->topt.fieldSep.separator
    4311             :                                   ? popt->topt.fieldSep.separator
    4312             :                                   : "");
    4313          64 :     else if (strcmp(param, "fieldsep_zero") == 0)
    4314           4 :         return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
    4315          60 :     else if (strcmp(param, "footer") == 0)
    4316           4 :         return pstrdup(pset_bool_string(popt->topt.default_footer));
    4317          56 :     else if (strcmp(param, "format") == 0)
    4318           4 :         return psprintf("%s", _align2string(popt->topt.format));
    4319          52 :     else if (strcmp(param, "linestyle") == 0)
    4320           4 :         return psprintf("%s", get_line_style(&popt->topt)->name);
    4321          48 :     else if (strcmp(param, "null") == 0)
    4322           4 :         return pset_quoted_string(popt->nullPrint
    4323             :                                   ? popt->nullPrint
    4324             :                                   : "");
    4325          44 :     else if (strcmp(param, "numericlocale") == 0)
    4326           4 :         return pstrdup(pset_bool_string(popt->topt.numericLocale));
    4327          40 :     else if (strcmp(param, "pager") == 0)
    4328           4 :         return psprintf("%d", popt->topt.pager);
    4329          36 :     else if (strcmp(param, "pager_min_lines") == 0)
    4330           4 :         return psprintf("%d", popt->topt.pager_min_lines);
    4331          32 :     else if (strcmp(param, "recordsep") == 0)
    4332           4 :         return pset_quoted_string(popt->topt.recordSep.separator
    4333             :                                   ? popt->topt.recordSep.separator
    4334             :                                   : "");
    4335          28 :     else if (strcmp(param, "recordsep_zero") == 0)
    4336           4 :         return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
    4337          24 :     else if (strcmp(param, "tableattr") == 0)
    4338           4 :         return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
    4339          20 :     else if (strcmp(param, "title") == 0)
    4340           4 :         return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
    4341          16 :     else if (strcmp(param, "tuples_only") == 0)
    4342           4 :         return pstrdup(pset_bool_string(popt->topt.tuples_only));
    4343          12 :     else if (strcmp(param, "unicode_border_linestyle") == 0)
    4344           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
    4345           8 :     else if (strcmp(param, "unicode_column_linestyle") == 0)
    4346           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
    4347           4 :     else if (strcmp(param, "unicode_header_linestyle") == 0)
    4348           4 :         return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
    4349             :     else
    4350           0 :         return pstrdup("ERROR");
    4351             : }
    4352             : 
    4353             : 
    4354             : 
    4355             : #ifndef WIN32
    4356             : #define DEFAULT_SHELL "/bin/sh"
    4357             : #else
    4358             : /*
    4359             :  *  CMD.EXE is in different places in different Win32 releases so we
    4360             :  *  have to rely on the path to find it.
    4361             :  */
    4362             : #define DEFAULT_SHELL "cmd.exe"
    4363             : #endif
    4364             : 
    4365             : static bool
    4366           0 : do_shell(const char *command)
    4367             : {
    4368             :     int         result;
    4369             : 
    4370           0 :     if (!command)
    4371             :     {
    4372             :         char       *sys;
    4373             :         const char *shellName;
    4374             : 
    4375           0 :         shellName = getenv("SHELL");
    4376             : #ifdef WIN32
    4377             :         if (shellName == NULL)
    4378             :             shellName = getenv("COMSPEC");
    4379             : #endif
    4380           0 :         if (shellName == NULL)
    4381           0 :             shellName = DEFAULT_SHELL;
    4382             : 
    4383             :         /* See EDITOR handling comment for an explanation */
    4384             : #ifndef WIN32
    4385           0 :         sys = psprintf("exec %s", shellName);
    4386             : #else
    4387             :         sys = psprintf("\"%s\"", shellName);
    4388             : #endif
    4389           0 :         result = system(sys);
    4390           0 :         free(sys);
    4391             :     }
    4392             :     else
    4393           0 :         result = system(command);
    4394             : 
    4395           0 :     if (result == 127 || result == -1)
    4396             :     {
    4397           0 :         pg_log_error("\\!: failed");
    4398           0 :         return false;
    4399             :     }
    4400           0 :     return true;
    4401             : }
    4402             : 
    4403             : /*
    4404             :  * do_watch -- handler for \watch
    4405             :  *
    4406             :  * We break this out of exec_command to avoid having to plaster "volatile"
    4407             :  * onto a bunch of exec_command's variables to silence stupider compilers.
    4408             :  */
    4409             : static bool
    4410           0 : do_watch(PQExpBuffer query_buf, double sleep)
    4411             : {
    4412           0 :     long        sleep_ms = (long) (sleep * 1000);
    4413           0 :     printQueryOpt myopt = pset.popt;
    4414             :     const char *strftime_fmt;
    4415             :     const char *user_title;
    4416             :     char       *title;
    4417             :     int         title_len;
    4418           0 :     int         res = 0;
    4419             : 
    4420           0 :     if (!query_buf || query_buf->len <= 0)
    4421             :     {
    4422           0 :         pg_log_error("\\watch cannot be used with an empty query");
    4423           0 :         return false;
    4424             :     }
    4425             : 
    4426             :     /*
    4427             :      * Choose format for timestamps.  We might eventually make this a \pset
    4428             :      * option.  In the meantime, using a variable for the format suppresses
    4429             :      * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
    4430             :      */
    4431           0 :     strftime_fmt = "%c";
    4432             : 
    4433             :     /*
    4434             :      * Set up rendering options, in particular, disable the pager, because
    4435             :      * nobody wants to be prompted while watching the output of 'watch'.
    4436             :      */
    4437           0 :     myopt.topt.pager = 0;
    4438             : 
    4439             :     /*
    4440             :      * If there's a title in the user configuration, make sure we have room
    4441             :      * for it in the title buffer.  Allow 128 bytes for the timestamp plus 128
    4442             :      * bytes for the rest.
    4443             :      */
    4444           0 :     user_title = myopt.title;
    4445           0 :     title_len = (user_title ? strlen(user_title) : 0) + 256;
    4446           0 :     title = pg_malloc(title_len);
    4447             : 
    4448             :     for (;;)
    4449           0 :     {
    4450             :         time_t      timer;
    4451             :         char        timebuf[128];
    4452             :         long        i;
    4453             : 
    4454             :         /*
    4455             :          * Prepare title for output.  Note that we intentionally include a
    4456             :          * newline at the end of the title; this is somewhat historical but it
    4457             :          * makes for reasonably nicely formatted output in simple cases.
    4458             :          */
    4459           0 :         timer = time(NULL);
    4460           0 :         strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
    4461             : 
    4462           0 :         if (user_title)
    4463           0 :             snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
    4464             :                      user_title, timebuf, sleep);
    4465             :         else
    4466           0 :             snprintf(title, title_len, _("%s (every %gs)\n"),
    4467             :                      timebuf, sleep);
    4468           0 :         myopt.title = title;
    4469             : 
    4470             :         /* Run the query and print out the results */
    4471           0 :         res = PSQLexecWatch(query_buf->data, &myopt);
    4472             : 
    4473             :         /*
    4474             :          * PSQLexecWatch handles the case where we can no longer repeat the
    4475             :          * query, and returns 0 or -1.
    4476             :          */
    4477           0 :         if (res <= 0)
    4478           0 :             break;
    4479             : 
    4480             :         /*
    4481             :          * Set up cancellation of 'watch' via SIGINT.  We redo this each time
    4482             :          * through the loop since it's conceivable something inside
    4483             :          * PSQLexecWatch could change sigint_interrupt_jmp.
    4484             :          */
    4485           0 :         if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
    4486           0 :             break;
    4487             : 
    4488             :         /*
    4489             :          * Enable 'watch' cancellations and wait a while before running the
    4490             :          * query again.  Break the sleep into short intervals (at most 1s)
    4491             :          * since pg_usleep isn't interruptible on some platforms.
    4492             :          */
    4493           0 :         sigint_interrupt_enabled = true;
    4494           0 :         i = sleep_ms;
    4495           0 :         while (i > 0)
    4496             :         {
    4497           0 :             long        s = Min(i, 1000L);
    4498             : 
    4499           0 :             pg_usleep(s * 1000L);
    4500           0 :             if (cancel_pressed)
    4501           0 :                 break;
    4502           0 :             i -= s;
    4503             :         }
    4504           0 :         sigint_interrupt_enabled = false;
    4505             :     }
    4506             : 
    4507           0 :     pg_free(title);
    4508           0 :     return (res >= 0);
    4509             : }
    4510             : 
    4511             : /*
    4512             :  * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
    4513             :  * returns true unless we have ECHO_HIDDEN_NOEXEC.
    4514             :  */
    4515             : static bool
    4516           8 : echo_hidden_command(const char *query)
    4517             : {
    4518           8 :     if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
    4519             :     {
    4520           0 :         printf(_("********* QUERY **********\n"
    4521             :                  "%s\n"
    4522             :                  "**************************\n\n"), query);
    4523           0 :         fflush(stdout);
    4524           0 :         if (pset.logfile)
    4525             :         {
    4526           0 :             fprintf(pset.logfile,
    4527           0 :                     _("********* QUERY **********\n"
    4528             :                       "%s\n"
    4529             :                       "**************************\n\n"), query);
    4530           0 :             fflush(pset.logfile);
    4531             :         }
    4532             : 
    4533           0 :         if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
    4534           0 :             return false;
    4535             :     }
    4536           8 :     return true;
    4537             : }
    4538             : 
    4539             : /*
    4540             :  * Look up the object identified by obj_type and desc.  If successful,
    4541             :  * store its OID in *obj_oid and return true, else return false.
    4542             :  *
    4543             :  * Note that we'll fail if the object doesn't exist OR if there are multiple
    4544             :  * matching candidates OR if there's something syntactically wrong with the
    4545             :  * object description; unfortunately it can be hard to tell the difference.
    4546             :  */
    4547             : static bool
    4548           4 : lookup_object_oid(EditableObjectType obj_type, const char *desc,
    4549             :                   Oid *obj_oid)
    4550             : {
    4551           4 :     bool        result = true;
    4552           4 :     PQExpBuffer query = createPQExpBuffer();
    4553             :     PGresult   *res;
    4554             : 
    4555           4 :     switch (obj_type)
    4556             :     {
    4557             :         case EditableFunction:
    4558             : 
    4559             :             /*
    4560             :              * We have a function description, e.g. "x" or "x(int)".  Issue a
    4561             :              * query to retrieve the function's OID using a cast to regproc or
    4562             :              * regprocedure (as appropriate).
    4563             :              */
    4564           0 :             appendPQExpBufferStr(query, "SELECT ");
    4565           0 :             appendStringLiteralConn(query, desc, pset.db);
    4566           0 :             appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
    4567           0 :                               strchr(desc, '(') ? "regprocedure" : "regproc");
    4568           0 :             break;
    4569             : 
    4570             :         case EditableView:
    4571             : 
    4572             :             /*
    4573             :              * Convert view name (possibly schema-qualified) to OID.  Note:
    4574             :              * this code doesn't check if the relation is actually a view.
    4575             :              * We'll detect that in get_create_object_cmd().
    4576             :              */
    4577           4 :             appendPQExpBufferStr(query, "SELECT ");
    4578           4 :             appendStringLiteralConn(query, desc, pset.db);
    4579           4 :             appendPQExpBuffer(query, "::pg_catalog.regclass::pg_catalog.oid");
    4580           4 :             break;
    4581             :     }
    4582             : 
    4583           4 :     if (!echo_hidden_command(query->data))
    4584             :     {
    4585           0 :         destroyPQExpBuffer(query);
    4586           0 :         return false;
    4587             :     }
    4588           4 :     res = PQexec(pset.db, query->data);
    4589           4 :     if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
    4590           4 :         *obj_oid = atooid(PQgetvalue(res, 0, 0));
    4591             :     else
    4592             :     {
    4593           0 :         minimal_error_message(res);
    4594           0 :         result = false;
    4595             :     }
    4596             : 
    4597           4 :     PQclear(res);
    4598           4 :     destroyPQExpBuffer(query);
    4599             : 
    4600           4 :     return result;
    4601             : }
    4602             : 
    4603             : /*
    4604             :  * Construct a "CREATE OR REPLACE ..." command that describes the specified
    4605             :  * database object.  If successful, the result is stored in buf.
    4606             :  */
    4607             : static bool
    4608           4 : get_create_object_cmd(EditableObjectType obj_type, Oid oid,
    4609             :                       PQExpBuffer buf)
    4610             : {
    4611           4 :     bool        result = true;
    4612           4 :     PQExpBuffer query = createPQExpBuffer();
    4613             :     PGresult   *res;
    4614             : 
    4615           4 :     switch (obj_type)
    4616             :     {
    4617             :         case EditableFunction:
    4618           0 :             printfPQExpBuffer(query,
    4619             :                               "SELECT pg_catalog.pg_get_functiondef(%u)",
    4620             :                               oid);
    4621           0 :             break;
    4622             : 
    4623             :         case EditableView:
    4624             : 
    4625             :             /*
    4626             :              * pg_get_viewdef() just prints the query, so we must prepend
    4627             :              * CREATE for ourselves.  We must fully qualify the view name to
    4628             :              * ensure the right view gets replaced.  Also, check relation kind
    4629             :              * to be sure it's a view.
    4630             :              *
    4631             :              * Starting with 9.2, views may have reloptions (security_barrier)
    4632             :              * and from 9.4 onwards they may also have WITH [LOCAL|CASCADED]
    4633             :              * CHECK OPTION.  These are not part of the view definition
    4634             :              * returned by pg_get_viewdef() and so need to be retrieved
    4635             :              * separately.  Materialized views (introduced in 9.3) may have
    4636             :              * arbitrary storage parameter reloptions.
    4637             :              */
    4638           4 :             if (pset.sversion >= 90400)
    4639             :             {
    4640           4 :                 printfPQExpBuffer(query,
    4641             :                                   "SELECT nspname, relname, relkind, "
    4642             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4643             :                                   "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
    4644             :                                   "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
    4645             :                                   "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
    4646             :                                   "FROM pg_catalog.pg_class c "
    4647             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4648             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4649             :                                   oid);
    4650             :             }
    4651           0 :             else if (pset.sversion >= 90200)
    4652             :             {
    4653           0 :                 printfPQExpBuffer(query,
    4654             :                                   "SELECT nspname, relname, relkind, "
    4655             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4656             :                                   "c.reloptions AS reloptions, "
    4657             :                                   "NULL AS checkoption "
    4658             :                                   "FROM pg_catalog.pg_class c "
    4659             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4660             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4661             :                                   oid);
    4662             :             }
    4663             :             else
    4664             :             {
    4665           0 :                 printfPQExpBuffer(query,
    4666             :                                   "SELECT nspname, relname, relkind, "
    4667             :                                   "pg_catalog.pg_get_viewdef(c.oid, true), "
    4668             :                                   "NULL AS reloptions, "
    4669             :                                   "NULL AS checkoption "
    4670             :                                   "FROM pg_catalog.pg_class c "
    4671             :                                   "LEFT JOIN pg_catalog.pg_namespace n "
    4672             :                                   "ON c.relnamespace = n.oid WHERE c.oid = %u",
    4673             :                                   oid);
    4674             :             }
    4675           4 :             break;
    4676             :     }
    4677             : 
    4678           4 :     if (!echo_hidden_command(query->data))
    4679             :     {
    4680           0 :         destroyPQExpBuffer(query);
    4681           0 :         return false;
    4682             :     }
    4683           4 :     res = PQexec(pset.db, query->data);
    4684           4 :     if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
    4685             :     {
    4686           4 :         resetPQExpBuffer(buf);
    4687           4 :         switch (obj_type)
    4688             :         {
    4689             :             case EditableFunction:
    4690           0 :                 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
    4691           0 :                 break;
    4692             : 
    4693             :             case EditableView:
    4694             :                 {
    4695           4 :                     char       *nspname = PQgetvalue(res, 0, 0);
    4696           4 :                     char       *relname = PQgetvalue(res, 0, 1);
    4697           4 :                     char       *relkind = PQgetvalue(res, 0, 2);
    4698           4 :                     char       *viewdef = PQgetvalue(res, 0, 3);
    4699           4 :                     char       *reloptions = PQgetvalue(res, 0, 4);
    4700           4 :                     char       *checkoption = PQgetvalue(res, 0, 5);
    4701             : 
    4702             :                     /*
    4703             :                      * If the backend ever supports CREATE OR REPLACE
    4704             :                      * MATERIALIZED VIEW, allow that here; but as of today it
    4705             :                      * does not, so editing a matview definition in this way
    4706             :                      * is impossible.
    4707             :                      */
    4708           4 :                     switch (relkind[0])
    4709             :                     {
    4710             : #ifdef NOT_USED
    4711             :                         case RELKIND_MATVIEW:
    4712             :                             appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
    4713             :                             break;
    4714             : #endif
    4715             :                         case RELKIND_VIEW:
    4716           4 :                             appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
    4717           4 :                             break;
    4718             :                         default:
    4719           0 :                             pg_log_error("\"%s.%s\" is not a view",
    4720             :                                          nspname, relname);
    4721           0 :                             result = false;
    4722           0 :                             break;
    4723             :                     }
    4724           4 :                     appendPQExpBuffer(buf, "%s.", fmtId(nspname));
    4725           4 :                     appendPQExpBufferStr(buf, fmtId(relname));
    4726             : 
    4727             :                     /* reloptions, if not an empty array "{}" */
    4728           4 :                     if (reloptions != NULL && strlen(reloptions) > 2)
    4729             :                     {
    4730           0 :                         appendPQExpBufferStr(buf, "\n WITH (");
    4731           0 :                         if (!appendReloptionsArray(buf, reloptions, "",
    4732             :                                                    pset.encoding,
    4733           0 :                                                    standard_strings()))
    4734             :                         {
    4735           0 :                             pg_log_error("could not parse reloptions array");
    4736           0 :                             result = false;
    4737             :                         }
    4738           0 :                         appendPQExpBufferChar(buf, ')');
    4739             :                     }
    4740             : 
    4741             :                     /* View definition from pg_get_viewdef (a SELECT query) */
    4742           4 :                     appendPQExpBuffer(buf, " AS\n%s", viewdef);
    4743             : 
    4744             :                     /* Get rid of the semicolon that pg_get_viewdef appends */
    4745           4 :                     if (buf->len > 0 && buf->data[buf->len - 1] == ';')
    4746           4 :                         buf->data[--(buf->len)] = '\0';
    4747             : 
    4748             :                     /* WITH [LOCAL|CASCADED] CHECK OPTION */
    4749           4 :                     if (checkoption && checkoption[0] != '\0')
    4750           0 :                         appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
    4751             :                                           checkoption);
    4752             :                 }
    4753           4 :                 break;
    4754             :         }
    4755             :         /* Make sure result ends with a newline */
    4756           8 :         if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
    4757           4 :             appendPQExpBufferChar(buf, '\n');
    4758             :     }
    4759             :     else
    4760             :     {
    4761           0 :         minimal_error_message(res);
    4762           0 :         result = false;
    4763             :     }
    4764             : 
    4765           4 :     PQclear(res);
    4766           4 :     destroyPQExpBuffer(query);
    4767             : 
    4768           4 :     return result;
    4769             : }
    4770             : 
    4771             : /*
    4772             :  * If the given argument of \ef or \ev ends with a line number, delete the line
    4773             :  * number from the argument string and return it as an integer.  (We need
    4774             :  * this kluge because we're too lazy to parse \ef's function or \ev's view
    4775             :  * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
    4776             :  *
    4777             :  * Returns -1 if no line number is present, 0 on error, or a positive value
    4778             :  * on success.
    4779             :  */
    4780             : static int
    4781           0 : strip_lineno_from_objdesc(char *obj)
    4782             : {
    4783             :     char       *c;
    4784             :     int         lineno;
    4785             : 
    4786           0 :     if (!obj || obj[0] == '\0')
    4787           0 :         return -1;
    4788             : 
    4789           0 :     c = obj + strlen(obj) - 1;
    4790             : 
    4791             :     /*
    4792             :      * This business of parsing backwards is dangerous as can be in a
    4793             :      * multibyte environment: there is no reason to believe that we are
    4794             :      * looking at the first byte of a character, nor are we necessarily
    4795             :      * working in a "safe" encoding.  Fortunately the bitpatterns we are
    4796             :      * looking for are unlikely to occur as non-first bytes, but beware of
    4797             :      * trying to expand the set of cases that can be recognized.  We must
    4798             :      * guard the <ctype.h> macros by using isascii() first, too.
    4799             :      */
    4800             : 
    4801             :     /* skip trailing whitespace */
    4802           0 :     while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
    4803           0 :         c--;
    4804             : 
    4805             :     /* must have a digit as last non-space char */
    4806           0 :     if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
    4807           0 :         return -1;
    4808             : 
    4809             :     /* find start of digit string */
    4810           0 :     while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
    4811           0 :         c--;
    4812             : 
    4813             :     /* digits must be separated from object name by space or closing paren */
    4814             :     /* notice also that we are not allowing an empty object name ... */
    4815           0 :     if (c == obj || !isascii((unsigned char) *c) ||
    4816           0 :         !(isspace((unsigned char) *c) || *c == ')'))
    4817           0 :         return -1;
    4818             : 
    4819             :     /* parse digit string */
    4820           0 :     c++;
    4821           0 :     lineno = atoi(c);
    4822           0 :     if (lineno < 1)
    4823             :     {
    4824           0 :         pg_log_error("invalid line number: %s", c);
    4825           0 :         return 0;
    4826             :     }
    4827             : 
    4828             :     /* strip digit string from object name */
    4829           0 :     *c = '\0';
    4830             : 
    4831           0 :     return lineno;
    4832             : }
    4833             : 
    4834             : /*
    4835             :  * Count number of lines in the buffer.
    4836             :  * This is used to test if pager is needed or not.
    4837             :  */
    4838             : static int
    4839           4 : count_lines_in_buf(PQExpBuffer buf)
    4840             : {
    4841           4 :     int         lineno = 0;
    4842           4 :     const char *lines = buf->data;
    4843             : 
    4844          56 :     while (*lines != '\0')
    4845             :     {
    4846          48 :         lineno++;
    4847             :         /* find start of next line */
    4848          48 :         lines = strchr(lines, '\n');
    4849          48 :         if (!lines)
    4850           0 :             break;
    4851          48 :         lines++;
    4852             :     }
    4853             : 
    4854           4 :     return lineno;
    4855             : }
    4856             : 
    4857             : /*
    4858             :  * Write text at *lines to output with line numbers.
    4859             :  *
    4860             :  * If header_keyword isn't NULL, then line 1 should be the first line beginning
    4861             :  * with header_keyword; lines before that are unnumbered.
    4862             :  *
    4863             :  * Caution: this scribbles on *lines.
    4864             :  */
    4865             : static void
    4866           0 : print_with_linenumbers(FILE *output, char *lines,
    4867             :                        const char *header_keyword)
    4868             : {
    4869           0 :     bool        in_header = (header_keyword != NULL);
    4870           0 :     size_t      header_sz = in_header ? strlen(header_keyword) : 0;
    4871           0 :     int         lineno = 0;
    4872             : 
    4873           0 :     while (*lines != '\0')
    4874             :     {
    4875             :         char       *eol;
    4876             : 
    4877           0 :         if (in_header && strncmp(lines, header_keyword, header_sz) == 0)
    4878           0 :             in_header = false;
    4879             : 
    4880             :         /* increment lineno only for body's lines */
    4881           0 :         if (!in_header)
    4882           0 :             lineno++;
    4883             : 
    4884             :         /* find and mark end of current line */
    4885           0 :         eol = strchr(lines, '\n');
    4886           0 :         if (eol != NULL)
    4887           0 :             *eol = '\0';
    4888             : 
    4889             :         /* show current line as appropriate */
    4890           0 :         if (in_header)
    4891           0 :             fprintf(output, "        %s\n", lines);
    4892             :         else
    4893           0 :             fprintf(output, "%-7d %s\n", lineno, lines);
    4894             : 
    4895             :         /* advance to next line, if any */
    4896           0 :         if (eol == NULL)
    4897           0 :             break;
    4898           0 :         lines = ++eol;
    4899             :     }
    4900           0 : }
    4901             : 
    4902             : /*
    4903             :  * Report just the primary error; this is to avoid cluttering the output
    4904             :  * with, for instance, a redisplay of the internally generated query
    4905             :  */
    4906             : static void
    4907           0 : minimal_error_message(PGresult *res)
    4908             : {
    4909             :     PQExpBuffer msg;
    4910             :     const char *fld;
    4911             : 
    4912           0 :     msg = createPQExpBuffer();
    4913             : 
    4914           0 :     fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
    4915           0 :     if (fld)
    4916           0 :         printfPQExpBuffer(msg, "%s:  ", fld);
    4917             :     else
    4918           0 :         printfPQExpBuffer(msg, "ERROR:  ");
    4919           0 :     fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
    4920           0 :     if (fld)
    4921           0 :         appendPQExpBufferStr(msg, fld);
    4922             :     else
    4923           0 :         appendPQExpBufferStr(msg, "(not available)");
    4924           0 :     appendPQExpBufferChar(msg, '\n');
    4925             : 
    4926           0 :     pg_log_error("%s", msg->data);
    4927             : 
    4928           0 :     destroyPQExpBuffer(msg);
    4929           0 : }

Generated by: LCOV version 1.13