PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
command.c File Reference
#include "postgres_fe.h"
#include "command.h"
#include <ctype.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "portability/instr_time.h"
#include "libpq-fe.h"
#include "pqexpbuffer.h"
#include "fe_utils/string_utils.h"
#include "common.h"
#include "copy.h"
#include "crosstabview.h"
#include "describe.h"
#include "help.h"
#include "input.h"
#include "large_obj.h"
#include "mainloop.h"
#include "fe_utils/print.h"
#include "psqlscanslash.h"
#include "settings.h"
#include "variables.h"
Include dependency graph for command.c:

Go to the source code of this file.

Macros

#define PARAMS_ARRAY_SIZE   8
 
#define DEFAULT_SHELL   "/bin/sh"
 

Typedefs

typedef enum EditableObjectType EditableObjectType
 

Enumerations

enum  EditableObjectType { EditableFunction, EditableView }
 

Functions

static backslashResult exec_command (const char *cmd, PsqlScanState scan_state, PQExpBuffer query_buf)
 
static bool do_edit (const char *filename_arg, PQExpBuffer query_buf, int lineno, bool *edited)
 
static bool do_connect (enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
 
static bool do_shell (const char *command)
 
static bool do_watch (PQExpBuffer query_buf, double sleep)
 
static bool lookup_object_oid (EditableObjectType obj_type, const char *desc, Oid *obj_oid)
 
static bool get_create_object_cmd (EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
 
static int strip_lineno_from_objdesc (char *obj)
 
static int count_lines_in_buf (PQExpBuffer buf)
 
static void print_with_linenumbers (FILE *output, char *lines, const char *header_keyword)
 
static void minimal_error_message (PGresult *res)
 
static void printSSLInfo (void)
 
static bool printPsetInfo (const char *param, struct printQueryOpt *popt)
 
static char * pset_value_string (const char *param, struct printQueryOpt *popt)
 
backslashResult HandleSlashCmds (PsqlScanState scan_state, PQExpBuffer query_buf)
 
static char * read_connect_arg (PsqlScanState scan_state)
 
static char * prompt_for_password (const char *username)
 
static bool param_is_newly_set (const char *old_val, const char *new_val)
 
void connection_warnings (bool in_startup)
 
void SyncVariables (void)
 
void UnsyncVariables (void)
 
static bool editFile (const char *fname, int lineno)
 
int process_file (char *filename, bool use_relative_path)
 
static const char * _align2string (enum printFormat in)
 
static bool set_unicode_line_style (const char *value, size_t vallen, unicode_linestyle *linestyle)
 
static const char * _unicode_linestyle2string (int linestyle)
 
bool do_pset (const char *param, const char *value, printQueryOpt *popt, bool quiet)
 
static const char * pset_bool_string (bool val)
 
static char * pset_quoted_string (const char *str)
 
static bool echo_hidden_command (const char *query)
 

Macro Definition Documentation

#define DEFAULT_SHELL   "/bin/sh"

Definition at line 3112 of file command.c.

Referenced by do_shell().

#define PARAMS_ARRAY_SIZE   8

Referenced by do_connect().

Typedef Documentation

Enumeration Type Documentation

Enumerator
EditableFunction 
EditableView 

Definition at line 56 of file command.c.

Function Documentation

static const char* _align2string ( enum printFormat  in)
static

Definition at line 2488 of file command.c.

References PRINT_ALIGNED, PRINT_ASCIIDOC, PRINT_HTML, PRINT_LATEX, PRINT_LATEX_LONGTABLE, PRINT_NOTHING, PRINT_TROFF_MS, PRINT_UNALIGNED, and PRINT_WRAPPED.

Referenced by printPsetInfo(), and pset_value_string().

2489 {
2490  switch (in)
2491  {
2492  case PRINT_NOTHING:
2493  return "nothing";
2494  break;
2495  case PRINT_UNALIGNED:
2496  return "unaligned";
2497  break;
2498  case PRINT_ALIGNED:
2499  return "aligned";
2500  break;
2501  case PRINT_WRAPPED:
2502  return "wrapped";
2503  break;
2504  case PRINT_HTML:
2505  return "html";
2506  break;
2507  case PRINT_ASCIIDOC:
2508  return "asciidoc";
2509  break;
2510  case PRINT_LATEX:
2511  return "latex";
2512  break;
2513  case PRINT_LATEX_LONGTABLE:
2514  return "latex-longtable";
2515  break;
2516  case PRINT_TROFF_MS:
2517  return "troff-ms";
2518  break;
2519  }
2520  return "unknown";
2521 }
static const char* _unicode_linestyle2string ( int  linestyle)
static

Definition at line 2541 of file command.c.

References UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by printPsetInfo(), and pset_value_string().

2542 {
2543  switch (linestyle)
2544  {
2546  return "single";
2547  break;
2549  return "double";
2550  break;
2551  }
2552  return "unknown";
2553 }
void connection_warnings ( bool  in_startup)

Definition at line 2046 of file command.c.

References _, _psqlSettings::db, formatPGVersionNumber(), _psqlSettings::notty, PQparameterStatus(), printSSLInfo(), _psqlSettings::progname, pset, _psqlSettings::quiet, server_version, and _psqlSettings::sversion.

Referenced by do_connect(), and main().

2047 {
2048  if (!pset.quiet && !pset.notty)
2049  {
2050  int client_ver = PG_VERSION_NUM;
2051  char cverbuf[32];
2052  char sverbuf[32];
2053 
2054  if (pset.sversion != client_ver)
2055  {
2056  const char *server_version;
2057 
2058  /* Try to get full text form, might include "devel" etc */
2059  server_version = PQparameterStatus(pset.db, "server_version");
2060  /* Otherwise fall back on pset.sversion */
2061  if (!server_version)
2062  {
2064  sverbuf, sizeof(sverbuf));
2065  server_version = sverbuf;
2066  }
2067 
2068  printf(_("%s (%s, server %s)\n"),
2069  pset.progname, PG_VERSION, server_version);
2070  }
2071  /* For version match, only print psql banner on startup. */
2072  else if (in_startup)
2073  printf("%s (%s)\n", pset.progname, PG_VERSION);
2074 
2075  if (pset.sversion / 100 > client_ver / 100)
2076  printf(_("WARNING: %s major version %s, server major version %s.\n"
2077  " Some psql features might not work.\n"),
2078  pset.progname,
2079  formatPGVersionNumber(client_ver, false,
2080  cverbuf, sizeof(cverbuf)),
2082  sverbuf, sizeof(sverbuf)));
2083 
2084 #ifdef WIN32
2085  checkWin32Codepage();
2086 #endif
2087  printSSLInfo();
2088  }
2089 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:37
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:5925
const char * progname
Definition: settings.h:106
static int server_version
Definition: pg_dumpall.c:81
bool notty
Definition: settings.h:99
static void printSSLInfo(void)
Definition: command.c:2098
#define _(x)
Definition: elog.c:84
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:182
static int count_lines_in_buf ( PQExpBuffer  buf)
static

Definition at line 3595 of file command.c.

References PQExpBufferData::data.

Referenced by exec_command().

3596 {
3597  int lineno = 0;
3598  const char *lines = buf->data;
3599 
3600  while (*lines != '\0')
3601  {
3602  lineno++;
3603  /* find start of next line */
3604  lines = strchr(lines, '\n');
3605  if (!lines)
3606  break;
3607  lines++;
3608  }
3609 
3610  return lineno;
3611 }
static bool do_connect ( enum trivalue  reuse_previous_specification,
char *  dbname,
char *  user,
char *  host,
char *  port 
)
static

Definition at line 1813 of file command.c.

References _, appendConnStrVal(), appendPQExpBuffer(), CONNECTION_OK, connection_warnings(), connstr, _psqlSettings::cur_cmd_interactive, PQExpBufferData::data, _psqlSettings::db, dbname, _psqlSettings::getPassword, initPQExpBuffer(), is_absolute_path, NoticeProcessor(), _psqlSettings::notty, NULL, param_is_newly_set(), PARAMS_ARRAY_SIZE, password, pg_free(), pg_malloc(), pg_strdup(), port, PQconnectdbParams(), PQconnectionNeedsPassword(), PQdb(), PQerrorMessage(), PQfinish(), PQhost(), PQpass(), PQport(), PQsetNoticeProcessor(), PQstatus(), PQuser(), _psqlSettings::progname, prompt_for_password(), pset, psql_error(), _psqlSettings::quiet, recognized_connection_string(), SyncVariables(), termPQExpBuffer(), TRI_NO, TRI_YES, user, and values.

Referenced by exec_command().

1815 {
1816  PGconn *o_conn = pset.db,
1817  *n_conn;
1818  char *password = NULL;
1819  bool keep_password;
1820  bool has_connection_string;
1821  bool reuse_previous;
1823 
1824  if (!o_conn && (!dbname || !user || !host || !port))
1825  {
1826  /*
1827  * We don't know the supplied connection parameters and don't want to
1828  * connect to the wrong database by using defaults, so require all
1829  * parameters to be specified.
1830  */
1831  psql_error("All connection parameters must be supplied because no "
1832  "database connection exists\n");
1833  return false;
1834  }
1835 
1836  has_connection_string = dbname ?
1838  switch (reuse_previous_specification)
1839  {
1840  case TRI_YES:
1841  reuse_previous = true;
1842  break;
1843  case TRI_NO:
1844  reuse_previous = false;
1845  break;
1846  default:
1847  reuse_previous = !has_connection_string;
1848  break;
1849  }
1850  /* Silently ignore arguments subsequent to a connection string. */
1851  if (has_connection_string)
1852  {
1853  user = NULL;
1854  host = NULL;
1855  port = NULL;
1856  }
1857 
1858  /* grab missing values from the old connection */
1859  if (!user && reuse_previous)
1860  user = PQuser(o_conn);
1861  if (!host && reuse_previous)
1862  host = PQhost(o_conn);
1863  if (!port && reuse_previous)
1864  port = PQport(o_conn);
1865 
1866  /*
1867  * Any change in the parameters read above makes us discard the password.
1868  * We also discard it if we're to use a conninfo rather than the
1869  * positional syntax.
1870  */
1871  if (has_connection_string)
1872  keep_password = false;
1873  else
1874  keep_password =
1875  (user && PQuser(o_conn) && strcmp(user, PQuser(o_conn)) == 0) &&
1876  (host && PQhost(o_conn) && strcmp(host, PQhost(o_conn)) == 0) &&
1877  (port && PQport(o_conn) && strcmp(port, PQport(o_conn)) == 0);
1878 
1879  /*
1880  * Grab missing dbname from old connection. No password discard if this
1881  * changes: passwords aren't (usually) database-specific.
1882  */
1883  if (!dbname && reuse_previous)
1884  {
1885  initPQExpBuffer(&connstr);
1886  appendPQExpBuffer(&connstr, "dbname=");
1887  appendConnStrVal(&connstr, PQdb(o_conn));
1888  dbname = connstr.data;
1889  /* has_connection_string=true would be a dead store */
1890  }
1891  else
1892  connstr.data = NULL;
1893 
1894  /*
1895  * If the user asked to be prompted for a password, ask for one now. If
1896  * not, use the password from the old connection, provided the username
1897  * etc have not changed. Otherwise, try to connect without a password
1898  * first, and then ask for a password if needed.
1899  *
1900  * XXX: this behavior leads to spurious connection attempts recorded in
1901  * the postmaster's log. But libpq offers no API that would let us obtain
1902  * a password and then continue with the first connection attempt.
1903  */
1904  if (pset.getPassword == TRI_YES)
1905  {
1906  password = prompt_for_password(user);
1907  }
1908  else if (o_conn && keep_password)
1909  {
1910  password = PQpass(o_conn);
1911  if (password && *password)
1912  password = pg_strdup(password);
1913  else
1914  password = NULL;
1915  }
1916 
1917  while (true)
1918  {
1919 #define PARAMS_ARRAY_SIZE 8
1920  const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1921  const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1922  int paramnum = -1;
1923 
1924  keywords[++paramnum] = "host";
1925  values[paramnum] = host;
1926  keywords[++paramnum] = "port";
1927  values[paramnum] = port;
1928  keywords[++paramnum] = "user";
1929  values[paramnum] = user;
1930 
1931  /*
1932  * Position in the array matters when the dbname is a connection
1933  * string, because settings in a connection string override earlier
1934  * array entries only. Thus, user= in the connection string always
1935  * takes effect, but client_encoding= often will not.
1936  *
1937  * If you change this code, also change the initial-connection code in
1938  * main(). For no good reason, a connection string password= takes
1939  * precedence in main() but not here.
1940  */
1941  keywords[++paramnum] = "dbname";
1942  values[paramnum] = dbname;
1943  keywords[++paramnum] = "password";
1944  values[paramnum] = password;
1945  keywords[++paramnum] = "fallback_application_name";
1946  values[paramnum] = pset.progname;
1947  keywords[++paramnum] = "client_encoding";
1948  values[paramnum] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
1949 
1950  /* add array terminator */
1951  keywords[++paramnum] = NULL;
1952  values[paramnum] = NULL;
1953 
1954  n_conn = PQconnectdbParams(keywords, values, true);
1955 
1956  pg_free(keywords);
1957  pg_free(values);
1958 
1959  /* We can immediately discard the password -- no longer needed */
1960  if (password)
1961  pg_free(password);
1962 
1963  if (PQstatus(n_conn) == CONNECTION_OK)
1964  break;
1965 
1966  /*
1967  * Connection attempt failed; either retry the connection attempt with
1968  * a new password, or give up.
1969  */
1970  if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1971  {
1972  PQfinish(n_conn);
1973  password = prompt_for_password(user);
1974  continue;
1975  }
1976 
1977  /*
1978  * Failed to connect to the database. In interactive mode, keep the
1979  * previous connection to the DB; in scripting mode, close our
1980  * previous connection as well.
1981  */
1983  {
1984  psql_error("%s", PQerrorMessage(n_conn));
1985 
1986  /* pset.db is left unmodified */
1987  if (o_conn)
1988  psql_error("Previous connection kept\n");
1989  }
1990  else
1991  {
1992  psql_error("\\connect: %s", PQerrorMessage(n_conn));
1993  if (o_conn)
1994  {
1995  PQfinish(o_conn);
1996  pset.db = NULL;
1997  }
1998  }
1999 
2000  PQfinish(n_conn);
2001  if (connstr.data)
2002  termPQExpBuffer(&connstr);
2003  return false;
2004  }
2005  if (connstr.data)
2006  termPQExpBuffer(&connstr);
2007 
2008  /*
2009  * Replace the old connection with the new one, and update
2010  * connection-dependent variables.
2011  */
2013  pset.db = n_conn;
2014  SyncVariables();
2015  connection_warnings(false); /* Must be after SyncVariables */
2016 
2017  /* Tell the user about the new connection */
2018  if (!pset.quiet)
2019  {
2020  if (!o_conn ||
2021  param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
2022  param_is_newly_set(PQport(o_conn), PQport(pset.db)))
2023  {
2024  char *host = PQhost(pset.db);
2025 
2026  /* If the host is an absolute path, the connection is via socket */
2027  if (is_absolute_path(host))
2028  printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
2029  PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
2030  else
2031  printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
2032  PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db));
2033  }
2034  else
2035  printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
2036  PQdb(pset.db), PQuser(pset.db));
2037  }
2038 
2039  if (o_conn)
2040  PQfinish(o_conn);
2041  return true;
2042 }
static char password[100]
Definition: streamutil.c:44
static bool param_is_newly_set(const char *old_val, const char *new_val)
Definition: command.c:1789
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:5960
PsqlSettings pset
Definition: startup.c:37
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6136
void SyncVariables(void)
Definition: command.c:2153
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
bool recognized_connection_string(const char *connstr)
Definition: common.c:2140
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:536
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3517
char * PQport(const PGconn *conn)
Definition: fe-connect.c:5881
#define false
Definition: c.h:207
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:471
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5836
bool cur_cmd_interactive
Definition: settings.h:104
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
#define is_absolute_path(filename)
Definition: port.h:77
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:5844
static char * prompt_for_password(const char *username)
Definition: command.c:1771
static int port
Definition: pg_regress.c:87
#define PARAMS_ARRAY_SIZE
void psql_error(const char *fmt,...)
Definition: common.c:177
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:5861
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:198
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5828
#define NULL
Definition: c.h:226
const char * progname
Definition: settings.h:106
enum trivalue getPassword
Definition: settings.h:101
char * dbname
Definition: streamutil.c:41
void pg_free(void *ptr)
Definition: fe_memutils.c:105
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:5994
static char * user
Definition: pg_regress.c:90
void connection_warnings(bool in_startup)
Definition: command.c:2046
bool notty
Definition: settings.h:99
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:5907
#define _(x)
Definition: elog.c:84
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static char * connstr
Definition: pg_dumpall.c:67
static bool do_edit ( const char *  filename_arg,
PQExpBuffer  query_buf,
int  lineno,
bool edited 
)
static

Definition at line 2262 of file command.c.

References appendPQExpBufferChar(), appendPQExpBufferStr(), PQExpBufferData::data, editFile(), error(), fd(), PQExpBufferData::len, MAXPGPATH, NULL, PG_BINARY_R, psql_error(), resetPQExpBuffer(), snprintf(), and strerror().

Referenced by exec_command().

2264 {
2265  char fnametmp[MAXPGPATH];
2266  FILE *stream = NULL;
2267  const char *fname;
2268  bool error = false;
2269  int fd;
2270 
2271  struct stat before,
2272  after;
2273 
2274  if (filename_arg)
2275  fname = filename_arg;
2276  else
2277  {
2278  /* make a temp file to edit */
2279 #ifndef WIN32
2280  const char *tmpdir = getenv("TMPDIR");
2281 
2282  if (!tmpdir)
2283  tmpdir = "/tmp";
2284 #else
2285  char tmpdir[MAXPGPATH];
2286  int ret;
2287 
2288  ret = GetTempPath(MAXPGPATH, tmpdir);
2289  if (ret == 0 || ret > MAXPGPATH)
2290  {
2291  psql_error("could not locate temporary directory: %s\n",
2292  !ret ? strerror(errno) : "");
2293  return false;
2294  }
2295 
2296  /*
2297  * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
2298  * current directory to the supplied path unless we use only
2299  * backslashes, so we do that.
2300  */
2301 #endif
2302 #ifndef WIN32
2303  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
2304  "/", (int) getpid());
2305 #else
2306  snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
2307  "" /* trailing separator already present */ , (int) getpid());
2308 #endif
2309 
2310  fname = (const char *) fnametmp;
2311 
2312  fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
2313  if (fd != -1)
2314  stream = fdopen(fd, "w");
2315 
2316  if (fd == -1 || !stream)
2317  {
2318  psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
2319  error = true;
2320  }
2321  else
2322  {
2323  unsigned int ql = query_buf->len;
2324 
2325  if (ql == 0 || query_buf->data[ql - 1] != '\n')
2326  {
2327  appendPQExpBufferChar(query_buf, '\n');
2328  ql++;
2329  }
2330 
2331  if (fwrite(query_buf->data, 1, ql, stream) != ql)
2332  {
2333  psql_error("%s: %s\n", fname, strerror(errno));
2334 
2335  if (fclose(stream) != 0)
2336  psql_error("%s: %s\n", fname, strerror(errno));
2337 
2338  if (remove(fname) != 0)
2339  psql_error("%s: %s\n", fname, strerror(errno));
2340 
2341  error = true;
2342  }
2343  else if (fclose(stream) != 0)
2344  {
2345  psql_error("%s: %s\n", fname, strerror(errno));
2346  if (remove(fname) != 0)
2347  psql_error("%s: %s\n", fname, strerror(errno));
2348  error = true;
2349  }
2350  }
2351  }
2352 
2353  if (!error && stat(fname, &before) != 0)
2354  {
2355  psql_error("%s: %s\n", fname, strerror(errno));
2356  error = true;
2357  }
2358 
2359  /* call editor */
2360  if (!error)
2361  error = !editFile(fname, lineno);
2362 
2363  if (!error && stat(fname, &after) != 0)
2364  {
2365  psql_error("%s: %s\n", fname, strerror(errno));
2366  error = true;
2367  }
2368 
2369  if (!error && before.st_mtime != after.st_mtime)
2370  {
2371  stream = fopen(fname, PG_BINARY_R);
2372  if (!stream)
2373  {
2374  psql_error("%s: %s\n", fname, strerror(errno));
2375  error = true;
2376  }
2377  else
2378  {
2379  /* read file back into query_buf */
2380  char line[1024];
2381 
2382  resetPQExpBuffer(query_buf);
2383  while (fgets(line, sizeof(line), stream) != NULL)
2384  appendPQExpBufferStr(query_buf, line);
2385 
2386  if (ferror(stream))
2387  {
2388  psql_error("%s: %s\n", fname, strerror(errno));
2389  error = true;
2390  }
2391  else if (edited)
2392  {
2393  *edited = true;
2394  }
2395 
2396  fclose(stream);
2397  }
2398  }
2399 
2400  /* remove temp file */
2401  if (!filename_arg)
2402  {
2403  if (remove(fname) == -1)
2404  {
2405  psql_error("%s: %s\n", fname, strerror(errno));
2406  error = true;
2407  }
2408  }
2409 
2410  return !error;
2411 }
static void error(void)
Definition: sql-dyntest.c:147
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define PG_BINARY_R
Definition: c.h:1040
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static int before(chr x, chr y)
Definition: regc_locale.c:496
#define MAXPGPATH
static bool editFile(const char *fname, int lineno)
Definition: command.c:2194
void psql_error(const char *fmt,...)
Definition: common.c:177
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
#define NULL
Definition: c.h:226
const char * strerror(int errnum)
Definition: strerror.c:19
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
bool do_pset ( const char *  param,
const char *  value,
printQueryOpt popt,
bool  quiet 
)

Definition at line 2560 of file command.c.

References Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::fieldSep, printTableOpt::format, free, printTableOpt::line_style, NULL, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, ParseVariableBool(), pg_asciiformat, pg_asciiformat_old, pg_strcasecmp(), pg_strdup(), pg_strncasecmp(), pg_utf8format, _psqlSettings::popt, PRINT_ALIGNED, PRINT_ASCIIDOC, PRINT_HTML, PRINT_LATEX, PRINT_LATEX_LONGTABLE, PRINT_TROFF_MS, PRINT_UNALIGNED, PRINT_WRAPPED, printPsetInfo(), pset, psql_error(), PsqlVarEnumError(), printTableOpt::recordSep, refresh_utf8format(), separator::separator, separator::separator_zero, set_unicode_line_style(), printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, and printTableOpt::unicode_header_linestyle.

Referenced by exec_command(), and parse_psql_options().

2561 {
2562  size_t vallen = 0;
2563 
2564  Assert(param != NULL);
2565 
2566  if (value)
2567  vallen = strlen(value);
2568 
2569  /* set format */
2570  if (strcmp(param, "format") == 0)
2571  {
2572  if (!value)
2573  ;
2574  else if (pg_strncasecmp("unaligned", value, vallen) == 0)
2575  popt->topt.format = PRINT_UNALIGNED;
2576  else if (pg_strncasecmp("aligned", value, vallen) == 0)
2577  popt->topt.format = PRINT_ALIGNED;
2578  else if (pg_strncasecmp("wrapped", value, vallen) == 0)
2579  popt->topt.format = PRINT_WRAPPED;
2580  else if (pg_strncasecmp("html", value, vallen) == 0)
2581  popt->topt.format = PRINT_HTML;
2582  else if (pg_strncasecmp("asciidoc", value, vallen) == 0)
2583  popt->topt.format = PRINT_ASCIIDOC;
2584  else if (pg_strncasecmp("latex", value, vallen) == 0)
2585  popt->topt.format = PRINT_LATEX;
2586  else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
2588  else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
2589  popt->topt.format = PRINT_TROFF_MS;
2590  else
2591  {
2592  psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, asciidoc, latex, latex-longtable, troff-ms\n");
2593  return false;
2594  }
2595  }
2596 
2597  /* set table line style */
2598  else if (strcmp(param, "linestyle") == 0)
2599  {
2600  if (!value)
2601  ;
2602  else if (pg_strncasecmp("ascii", value, vallen) == 0)
2603  popt->topt.line_style = &pg_asciiformat;
2604  else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
2606  else if (pg_strncasecmp("unicode", value, vallen) == 0)
2607  popt->topt.line_style = &pg_utf8format;
2608  else
2609  {
2610  psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
2611  return false;
2612  }
2613  }
2614 
2615  /* set unicode border line style */
2616  else if (strcmp(param, "unicode_border_linestyle") == 0)
2617  {
2618  if (!value)
2619  ;
2620  else if (set_unicode_line_style(value, vallen,
2622  refresh_utf8format(&(popt->topt));
2623  else
2624  {
2625  psql_error("\\pset: allowed Unicode border line styles are single, double\n");
2626  return false;
2627  }
2628  }
2629 
2630  /* set unicode column line style */
2631  else if (strcmp(param, "unicode_column_linestyle") == 0)
2632  {
2633  if (!value)
2634  ;
2635  else if (set_unicode_line_style(value, vallen,
2637  refresh_utf8format(&(popt->topt));
2638  else
2639  {
2640  psql_error("\\pset: allowed Unicode column line styles are single, double\n");
2641  return false;
2642  }
2643  }
2644 
2645  /* set unicode header line style */
2646  else if (strcmp(param, "unicode_header_linestyle") == 0)
2647  {
2648  if (!value)
2649  ;
2650  else if (set_unicode_line_style(value, vallen,
2652  refresh_utf8format(&(popt->topt));
2653  else
2654  {
2655  psql_error("\\pset: allowed Unicode header line styles are single, double\n");
2656  return false;
2657  }
2658  }
2659 
2660  /* set border style/width */
2661  else if (strcmp(param, "border") == 0)
2662  {
2663  if (value)
2664  popt->topt.border = atoi(value);
2665  }
2666 
2667  /* set expanded/vertical mode */
2668  else if (strcmp(param, "x") == 0 ||
2669  strcmp(param, "expanded") == 0 ||
2670  strcmp(param, "vertical") == 0)
2671  {
2672  if (value && pg_strcasecmp(value, "auto") == 0)
2673  popt->topt.expanded = 2;
2674  else if (value)
2675  {
2676  bool on_off;
2677 
2678  if (ParseVariableBool(value, NULL, &on_off))
2679  popt->topt.expanded = on_off ? 1 : 0;
2680  else
2681  {
2682  PsqlVarEnumError(param, value, "on, off, auto");
2683  return false;
2684  }
2685  }
2686  else
2687  popt->topt.expanded = !popt->topt.expanded;
2688  }
2689 
2690  /* locale-aware numeric output */
2691  else if (strcmp(param, "numericlocale") == 0)
2692  {
2693  if (value)
2694  return ParseVariableBool(value, param, &popt->topt.numericLocale);
2695  else
2696  popt->topt.numericLocale = !popt->topt.numericLocale;
2697  }
2698 
2699  /* null display */
2700  else if (strcmp(param, "null") == 0)
2701  {
2702  if (value)
2703  {
2704  free(popt->nullPrint);
2705  popt->nullPrint = pg_strdup(value);
2706  }
2707  }
2708 
2709  /* field separator for unaligned text */
2710  else if (strcmp(param, "fieldsep") == 0)
2711  {
2712  if (value)
2713  {
2714  free(popt->topt.fieldSep.separator);
2716  popt->topt.fieldSep.separator_zero = false;
2717  }
2718  }
2719 
2720  else if (strcmp(param, "fieldsep_zero") == 0)
2721  {
2722  free(popt->topt.fieldSep.separator);
2723  popt->topt.fieldSep.separator = NULL;
2724  popt->topt.fieldSep.separator_zero = true;
2725  }
2726 
2727  /* record separator for unaligned text */
2728  else if (strcmp(param, "recordsep") == 0)
2729  {
2730  if (value)
2731  {
2732  free(popt->topt.recordSep.separator);
2734  popt->topt.recordSep.separator_zero = false;
2735  }
2736  }
2737 
2738  else if (strcmp(param, "recordsep_zero") == 0)
2739  {
2740  free(popt->topt.recordSep.separator);
2741  popt->topt.recordSep.separator = NULL;
2742  popt->topt.recordSep.separator_zero = true;
2743  }
2744 
2745  /* toggle between full and tuples-only format */
2746  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2747  {
2748  if (value)
2749  return ParseVariableBool(value, param, &popt->topt.tuples_only);
2750  else
2751  popt->topt.tuples_only = !popt->topt.tuples_only;
2752  }
2753 
2754  /* set title override */
2755  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
2756  {
2757  free(popt->title);
2758  if (!value)
2759  popt->title = NULL;
2760  else
2761  popt->title = pg_strdup(value);
2762  }
2763 
2764  /* set HTML table tag options */
2765  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2766  {
2767  free(popt->topt.tableAttr);
2768  if (!value)
2769  popt->topt.tableAttr = NULL;
2770  else
2771  popt->topt.tableAttr = pg_strdup(value);
2772  }
2773 
2774  /* toggle use of pager */
2775  else if (strcmp(param, "pager") == 0)
2776  {
2777  if (value && pg_strcasecmp(value, "always") == 0)
2778  popt->topt.pager = 2;
2779  else if (value)
2780  {
2781  bool on_off;
2782 
2783  if (!ParseVariableBool(value, NULL, &on_off))
2784  {
2785  PsqlVarEnumError(param, value, "on, off, always");
2786  return false;
2787  }
2788  popt->topt.pager = on_off ? 1 : 0;
2789  }
2790  else if (popt->topt.pager == 1)
2791  popt->topt.pager = 0;
2792  else
2793  popt->topt.pager = 1;
2794  }
2795 
2796  /* set minimum lines for pager use */
2797  else if (strcmp(param, "pager_min_lines") == 0)
2798  {
2799  if (value)
2800  popt->topt.pager_min_lines = atoi(value);
2801  }
2802 
2803  /* disable "(x rows)" footer */
2804  else if (strcmp(param, "footer") == 0)
2805  {
2806  if (value)
2807  return ParseVariableBool(value, param, &popt->topt.default_footer);
2808  else
2809  popt->topt.default_footer = !popt->topt.default_footer;
2810  }
2811 
2812  /* set border style/width */
2813  else if (strcmp(param, "columns") == 0)
2814  {
2815  if (value)
2816  popt->topt.columns = atoi(value);
2817  }
2818  else
2819  {
2820  psql_error("\\pset: unknown option: %s\n", param);
2821  return false;
2822  }
2823 
2824  if (!quiet)
2825  printPsetInfo(param, &pset.popt);
2826 
2827  return true;
2828 }
static struct @76 value
char * nullPrint
Definition: print.h:166
PsqlSettings pset
Definition: startup.c:37
const printTextFormat * line_style
Definition: print.h:112
printTextFormat pg_utf8format
Definition: print.c:103
const printTextFormat pg_asciiformat_old
Definition: print.c:81
enum printFormat format
Definition: print.h:98
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:391
printTableOpt topt
Definition: print.h:165
unicode_linestyle unicode_header_linestyle
Definition: print.h:123
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
bool separator_zero
Definition: print.h:93
unicode_linestyle unicode_border_linestyle
Definition: print.h:121
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
unsigned short int border
Definition: print.h:101
unsigned short int expanded
Definition: print.h:99
static bool printPsetInfo(const char *param, struct printQueryOpt *popt)
Definition: command.c:2832
unicode_linestyle unicode_column_linestyle
Definition: print.h:122
bool tuples_only
Definition: print.h:107
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
char * tableAttr
Definition: print.h:117
void psql_error(const char *fmt,...)
Definition: common.c:177
unsigned short int pager
Definition: print.h:103
#define free(a)
Definition: header.h:60
struct separator fieldSep
Definition: print.h:113
char * title
Definition: print.h:167
int pager_min_lines
Definition: print.h:105
bool default_footer
Definition: print.h:110
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
printQueryOpt popt
Definition: settings.h:91
static bool set_unicode_line_style(const char *value, size_t vallen, unicode_linestyle *linestyle)
Definition: command.c:2528
bool numericLocale
Definition: print.h:115
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3427
const printTextFormat pg_asciiformat
Definition: print.c:60
char * separator
Definition: print.h:92
struct separator recordSep
Definition: print.h:114
int columns
Definition: print.h:120
static bool do_shell ( const char *  command)
static

Definition at line 3122 of file command.c.

References DEFAULT_SHELL, free, NULL, psprintf(), and psql_error().

Referenced by exec_command().

3123 {
3124  int result;
3125 
3126  if (!command)
3127  {
3128  char *sys;
3129  const char *shellName;
3130 
3131  shellName = getenv("SHELL");
3132 #ifdef WIN32
3133  if (shellName == NULL)
3134  shellName = getenv("COMSPEC");
3135 #endif
3136  if (shellName == NULL)
3137  shellName = DEFAULT_SHELL;
3138 
3139  /* See EDITOR handling comment for an explanation */
3140 #ifndef WIN32
3141  sys = psprintf("exec %s", shellName);
3142 #else
3143  sys = psprintf("\"%s\"", shellName);
3144 #endif
3145  result = system(sys);
3146  free(sys);
3147  }
3148  else
3149  result = system(command);
3150 
3151  if (result == 127 || result == -1)
3152  {
3153  psql_error("\\!: failed\n");
3154  return false;
3155  }
3156  return true;
3157 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void psql_error(const char *fmt,...)
Definition: common.c:177
#define free(a)
Definition: header.h:60
#define NULL
Definition: c.h:226
#define DEFAULT_SHELL
Definition: command.c:3112
static bool do_watch ( PQExpBuffer  query_buf,
double  sleep 
)
static

Definition at line 3166 of file command.c.

References _, cancel_pressed, PQExpBufferData::data, i, PQExpBufferData::len, Min, NULL, printTableOpt::pager, pg_free(), pg_malloc(), pg_usleep(), _psqlSettings::popt, pset, psql_error(), PSQLexecWatch(), sigint_interrupt_enabled, sigint_interrupt_jmp, snprintf(), printQueryOpt::title, and printQueryOpt::topt.

Referenced by exec_command().

3167 {
3168  long sleep_ms = (long) (sleep * 1000);
3169  printQueryOpt myopt = pset.popt;
3170  const char *strftime_fmt;
3171  const char *user_title;
3172  char *title;
3173  int title_len;
3174  int res = 0;
3175 
3176  if (!query_buf || query_buf->len <= 0)
3177  {
3178  psql_error(_("\\watch cannot be used with an empty query\n"));
3179  return false;
3180  }
3181 
3182  /*
3183  * Choose format for timestamps. We might eventually make this a \pset
3184  * option. In the meantime, using a variable for the format suppresses
3185  * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
3186  */
3187  strftime_fmt = "%c";
3188 
3189  /*
3190  * Set up rendering options, in particular, disable the pager, because
3191  * nobody wants to be prompted while watching the output of 'watch'.
3192  */
3193  myopt.topt.pager = 0;
3194 
3195  /*
3196  * If there's a title in the user configuration, make sure we have room
3197  * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
3198  * bytes for the rest.
3199  */
3200  user_title = myopt.title;
3201  title_len = (user_title ? strlen(user_title) : 0) + 256;
3202  title = pg_malloc(title_len);
3203 
3204  for (;;)
3205  {
3206  time_t timer;
3207  char timebuf[128];
3208  long i;
3209 
3210  /*
3211  * Prepare title for output. Note that we intentionally include a
3212  * newline at the end of the title; this is somewhat historical but it
3213  * makes for reasonably nicely formatted output in simple cases.
3214  */
3215  timer = time(NULL);
3216  strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
3217 
3218  if (user_title)
3219  snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
3220  user_title, timebuf, sleep);
3221  else
3222  snprintf(title, title_len, _("%s (every %gs)\n"),
3223  timebuf, sleep);
3224  myopt.title = title;
3225 
3226  /* Run the query and print out the results */
3227  res = PSQLexecWatch(query_buf->data, &myopt);
3228 
3229  /*
3230  * PSQLexecWatch handles the case where we can no longer repeat the
3231  * query, and returns 0 or -1.
3232  */
3233  if (res <= 0)
3234  break;
3235 
3236  /*
3237  * Set up cancellation of 'watch' via SIGINT. We redo this each time
3238  * through the loop since it's conceivable something inside
3239  * PSQLexecWatch could change sigint_interrupt_jmp.
3240  */
3241  if (sigsetjmp(sigint_interrupt_jmp, 1) != 0)
3242  break;
3243 
3244  /*
3245  * Enable 'watch' cancellations and wait a while before running the
3246  * query again. Break the sleep into short intervals (at most 1s)
3247  * since pg_usleep isn't interruptible on some platforms.
3248  */
3249  sigint_interrupt_enabled = true;
3250  i = sleep_ms;
3251  while (i > 0)
3252  {
3253  long s = Min(i, 1000L);
3254 
3255  pg_usleep(s * 1000L);
3256  if (cancel_pressed)
3257  break;
3258  i -= s;
3259  }
3260  sigint_interrupt_enabled = false;
3261  }
3262 
3263  pg_free(title);
3264  return (res >= 0);
3265 }
volatile bool sigint_interrupt_enabled
Definition: common.c:230
PsqlSettings pset
Definition: startup.c:37
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
int PSQLexecWatch(const char *query, const printQueryOpt *opt)
Definition: common.c:654
#define Min(x, y)
Definition: c.h:802
printTableOpt topt
Definition: print.h:165
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:232
volatile bool cancel_pressed
Definition: print.c:47
void pg_usleep(long microsec)
Definition: signal.c:53
void psql_error(const char *fmt,...)
Definition: common.c:177
unsigned short int pager
Definition: print.h:103
char * title
Definition: print.h:167
#define NULL
Definition: c.h:226
printQueryOpt popt
Definition: settings.h:91
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int i
#define _(x)
Definition: elog.c:84
static bool echo_hidden_command ( const char *  query)
static

Definition at line 3272 of file command.c.

References _, _psqlSettings::echo_hidden, _psqlSettings::logfile, pset, PSQL_ECHO_HIDDEN_NOEXEC, and PSQL_ECHO_HIDDEN_OFF.

Referenced by get_create_object_cmd(), and lookup_object_oid().

3273 {
3275  {
3276  printf(_("********* QUERY **********\n"
3277  "%s\n"
3278  "**************************\n\n"), query);
3279  fflush(stdout);
3280  if (pset.logfile)
3281  {
3282  fprintf(pset.logfile,
3283  _("********* QUERY **********\n"
3284  "%s\n"
3285  "**************************\n\n"), query);
3286  fflush(pset.logfile);
3287  }
3288 
3290  return false;
3291  }
3292  return true;
3293 }
PsqlSettings pset
Definition: startup.c:37
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:131
FILE * logfile
Definition: settings.h:113
#define _(x)
Definition: elog.c:84
static bool editFile ( const char *  fname,
int  lineno 
)
static

Definition at line 2194 of file command.c.

References Assert, DEFAULT_EDITOR, DEFAULT_EDITOR_LINENUMBER_ARG, free, NULL, psprintf(), and psql_error().

Referenced by do_edit().

2195 {
2196  const char *editorName;
2197  const char *editor_lineno_arg = NULL;
2198  char *sys;
2199  int result;
2200 
2201  Assert(fname != NULL);
2202 
2203  /* Find an editor to use */
2204  editorName = getenv("PSQL_EDITOR");
2205  if (!editorName)
2206  editorName = getenv("EDITOR");
2207  if (!editorName)
2208  editorName = getenv("VISUAL");
2209  if (!editorName)
2210  editorName = DEFAULT_EDITOR;
2211 
2212  /* Get line number argument, if we need it. */
2213  if (lineno > 0)
2214  {
2215  editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
2216 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
2217  if (!editor_lineno_arg)
2218  editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
2219 #endif
2220  if (!editor_lineno_arg)
2221  {
2222  psql_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number\n");
2223  return false;
2224  }
2225  }
2226 
2227  /*
2228  * On Unix the EDITOR value should *not* be quoted, since it might include
2229  * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
2230  * if necessary. But this policy is not very workable on Windows, due to
2231  * severe brain damage in their command shell plus the fact that standard
2232  * program paths include spaces.
2233  */
2234 #ifndef WIN32
2235  if (lineno > 0)
2236  sys = psprintf("exec %s %s%d '%s'",
2237  editorName, editor_lineno_arg, lineno, fname);
2238  else
2239  sys = psprintf("exec %s '%s'",
2240  editorName, fname);
2241 #else
2242  if (lineno > 0)
2243  sys = psprintf("\"%s\" %s%d \"%s\"",
2244  editorName, editor_lineno_arg, lineno, fname);
2245  else
2246  sys = psprintf("\"%s\" \"%s\"",
2247  editorName, fname);
2248 #endif
2249  result = system(sys);
2250  if (result == -1)
2251  psql_error("could not start editor \"%s\"\n", editorName);
2252  else if (result == 127)
2253  psql_error("could not start /bin/sh\n");
2254  free(sys);
2255 
2256  return result == 0;
2257 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define DEFAULT_EDITOR
Definition: settings.h:22
void psql_error(const char *fmt,...)
Definition: common.c:177
#define free(a)
Definition: header.h:60
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define DEFAULT_EDITOR_LINENUMBER_ARG
Definition: settings.h:23
static backslashResult exec_command ( const char *  cmd,
PsqlScanState  scan_state,
PQExpBuffer  query_buf 
)
static

Definition at line 202 of file command.c.

References _, appendStringLiteralConn(), buf, canonicalize_path(), ClosePager(), count_lines_in_buf(), createPQExpBuffer(), _psqlSettings::crosstab_flag, _psqlSettings::ctv_args, PQExpBufferData::data, _psqlSettings::db, describeAccessMethods(), describeAggregates(), describeFunctions(), describeOperators(), describePublications(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), destroyPQExpBuffer(), disable_sigpipe_trap(), do_connect(), do_copy(), do_edit(), do_lo_export(), do_lo_import(), do_lo_list(), do_lo_unlink(), do_pset(), do_shell(), do_watch(), EditableFunction, EditableView, _psqlSettings::encoding, printTableOpt::encoding, encoding, EXIT_FAILURE, EXIT_SUCCESS, expand_tilde(), fd(), fmtId(), printTableOpt::format, formatPGVersionNumber(), free, get_create_object_cmd(), gets_fromFile(), _psqlSettings::gexec_flag, _psqlSettings::gfname, _psqlSettings::gset_prefix, helpSQL(), helpVariables(), i, initPQExpBuffer(), _psqlSettings::inputfile, InvalidOid, is_absolute_path, _PQconninfoOption::keyword, _psqlSettings::last_error_result, PQExpBufferData::len, lengthof, listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSDictionaries(), listTSParsers(), listTSTemplates(), listUserMappings(), lookup_object_oid(), newval, NULL, objectDescription(), OT_FILEPIPE, OT_NORMAL, OT_SQLID, OT_WHOLE_LINE, output(), PageOutput(), printTableOpt::pager, ParseVariableBool(), permissionsList(), pg_encoding_to_char(), pg_malloc(), pg_realloc(), pg_strcasecmp(), pg_strdup(), _psqlSettings::popt, PQclear(), PQclientEncoding(), PQconninfo(), PQconninfoFree(), PQdb(), PQencryptPassword(), PQERRORS_VERBOSE, PQfreemem(), PQhost(), PQport(), PQresultVerboseErrorMessage(), PQsetClientEncoding(), PQSHOW_CONTEXT_ALWAYS, PQuser(), PRINT_ALIGNED, print_copyright(), PRINT_HTML, print_with_linenumbers(), printfPQExpBuffer(), printHistory(), printSSLInfo(), PrintVariables(), process_file(), pset, pset_value_string(), psprintf(), PSQL_CMD_ERROR, PSQL_CMD_NEWEDIT, PSQL_CMD_SEND, PSQL_CMD_SKIP_LINE, PSQL_CMD_TERMINATE, PSQL_CMD_UNKNOWN, psql_error(), psql_scan_reset(), psql_scan_slash_option(), PSQLexec(), putenv, _psqlSettings::queryFout, _psqlSettings::quiet, read_connect_arg(), resetPQExpBuffer(), restore_sigpipe_trap(), setQFout(), SetVariable(), simple_prompt(), slashUsage(), status(), strerror(), strip_lineno_from_objdesc(), success, _psqlSettings::sversion, termPQExpBuffer(), _psqlSettings::timing, printQueryOpt::topt, TRI_DEFAULT, TRI_NO, TRI_YES, unsetenv, usage(), user, _PQconninfoOption::val, val, value, and _psqlSettings::vars.

Referenced by HandleSlashCmds().

205 {
206  bool success = true; /* indicate here if the command ran ok or
207  * failed */
209 
210  /*
211  * \a -- toggle field alignment This makes little sense but we keep it
212  * around.
213  */
214  if (strcmp(cmd, "a") == 0)
215  {
217  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
218  else
219  success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
220  }
221 
222  /* \C -- override table title (formerly change HTML caption) */
223  else if (strcmp(cmd, "C") == 0)
224  {
225  char *opt = psql_scan_slash_option(scan_state,
226  OT_NORMAL, NULL, true);
227 
228  success = do_pset("title", opt, &pset.popt, pset.quiet);
229  free(opt);
230  }
231 
232  /*
233  * \c or \connect -- connect to database using the specified parameters.
234  *
235  * \c [-reuse-previous=BOOL] dbname user host port
236  *
237  * Specifying a parameter as '-' is equivalent to omitting it. Examples:
238  *
239  * \c - - hst Connect to current database on current port of host
240  * "hst" as current user. \c - usr - prt Connect to current database on
241  * "prt" port of current host as user "usr". \c dbs Connect to
242  * "dbs" database on current port of current host as current user.
243  */
244  else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
245  {
246  static const char prefix[] = "-reuse-previous=";
247  char *opt1,
248  *opt2,
249  *opt3,
250  *opt4;
251  enum trivalue reuse_previous = TRI_DEFAULT;
252 
253  opt1 = read_connect_arg(scan_state);
254  if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
255  {
256  bool on_off;
257 
258  success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
259  "-reuse-previous",
260  &on_off);
261  if (success)
262  {
263  reuse_previous = on_off ? TRI_YES : TRI_NO;
264  free(opt1);
265  opt1 = read_connect_arg(scan_state);
266  }
267  }
268 
269  if (success) /* give up if reuse_previous was invalid */
270  {
271  opt2 = read_connect_arg(scan_state);
272  opt3 = read_connect_arg(scan_state);
273  opt4 = read_connect_arg(scan_state);
274 
275  success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
276 
277  free(opt2);
278  free(opt3);
279  free(opt4);
280  }
281  free(opt1);
282  }
283 
284  /* \cd */
285  else if (strcmp(cmd, "cd") == 0)
286  {
287  char *opt = psql_scan_slash_option(scan_state,
288  OT_NORMAL, NULL, true);
289  char *dir;
290 
291  if (opt)
292  dir = opt;
293  else
294  {
295 #ifndef WIN32
296  struct passwd *pw;
297  uid_t user_id = geteuid();
298 
299  errno = 0; /* clear errno before call */
300  pw = getpwuid(user_id);
301  if (!pw)
302  {
303  psql_error("could not get home directory for user ID %ld: %s\n",
304  (long) user_id,
305  errno ? strerror(errno) : _("user does not exist"));
306  exit(EXIT_FAILURE);
307  }
308  dir = pw->pw_dir;
309 #else /* WIN32 */
310 
311  /*
312  * On Windows, 'cd' without arguments prints the current
313  * directory, so if someone wants to code this here instead...
314  */
315  dir = "/";
316 #endif /* WIN32 */
317  }
318 
319  if (chdir(dir) == -1)
320  {
321  psql_error("\\%s: could not change directory to \"%s\": %s\n",
322  cmd, dir, strerror(errno));
323  success = false;
324  }
325 
326  if (opt)
327  free(opt);
328  }
329 
330  /* \conninfo -- display information about the current connection */
331  else if (strcmp(cmd, "conninfo") == 0)
332  {
333  char *db = PQdb(pset.db);
334 
335  if (db == NULL)
336  printf(_("You are currently not connected to a database.\n"));
337  else
338  {
339  char *host;
340  PQconninfoOption *connOptions;
342 
343  host = PQhost(pset.db);
344  /* A usable "hostaddr" overrides the basic sense of host. */
345  connOptions = PQconninfo(pset.db);
346  if (connOptions == NULL)
347  {
348  psql_error("out of memory\n");
349  exit(EXIT_FAILURE);
350  }
351  for (option = connOptions; option && option->keyword; option++)
352  if (strcmp(option->keyword, "hostaddr") == 0)
353  {
354  if (option->val != NULL && option->val[0] != '\0')
355  host = option->val;
356  break;
357  }
358 
359  /* If the host is an absolute path, the connection is via socket */
360  if (is_absolute_path(host))
361  printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
362  db, PQuser(pset.db), host, PQport(pset.db));
363  else
364  printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
365  db, PQuser(pset.db), host, PQport(pset.db));
366  printSSLInfo();
367 
368  PQconninfoFree(connOptions);
369  }
370  }
371 
372  /* \copy */
373  else if (pg_strcasecmp(cmd, "copy") == 0)
374  {
375  char *opt = psql_scan_slash_option(scan_state,
376  OT_WHOLE_LINE, NULL, false);
377 
378  success = do_copy(opt);
379  free(opt);
380  }
381 
382  /* \copyright */
383  else if (strcmp(cmd, "copyright") == 0)
384  print_copyright();
385 
386  /* \crosstabview -- execute a query and display results in crosstab */
387  else if (strcmp(cmd, "crosstabview") == 0)
388  {
389  int i;
390 
391  for (i = 0; i < lengthof(pset.ctv_args); i++)
392  pset.ctv_args[i] = psql_scan_slash_option(scan_state,
393  OT_NORMAL, NULL, true);
394  pset.crosstab_flag = true;
395  status = PSQL_CMD_SEND;
396  }
397 
398  /* \d* commands */
399  else if (cmd[0] == 'd')
400  {
401  char *pattern;
402  bool show_verbose,
403  show_system;
404 
405  /* We don't do SQLID reduction on the pattern yet */
406  pattern = psql_scan_slash_option(scan_state,
407  OT_NORMAL, NULL, true);
408 
409  show_verbose = strchr(cmd, '+') ? true : false;
410  show_system = strchr(cmd, 'S') ? true : false;
411 
412  switch (cmd[1])
413  {
414  case '\0':
415  case '+':
416  case 'S':
417  if (pattern)
418  success = describeTableDetails(pattern, show_verbose, show_system);
419  else
420  /* standard listing of interesting things */
421  success = listTables("tvmsE", NULL, show_verbose, show_system);
422  break;
423  case 'A':
424  success = describeAccessMethods(pattern, show_verbose);
425  break;
426  case 'a':
427  success = describeAggregates(pattern, show_verbose, show_system);
428  break;
429  case 'b':
430  success = describeTablespaces(pattern, show_verbose);
431  break;
432  case 'c':
433  success = listConversions(pattern, show_verbose, show_system);
434  break;
435  case 'C':
436  success = listCasts(pattern, show_verbose);
437  break;
438  case 'd':
439  if (strncmp(cmd, "ddp", 3) == 0)
440  success = listDefaultACLs(pattern);
441  else
442  success = objectDescription(pattern, show_system);
443  break;
444  case 'D':
445  success = listDomains(pattern, show_verbose, show_system);
446  break;
447  case 'f': /* function subsystem */
448  switch (cmd[2])
449  {
450  case '\0':
451  case '+':
452  case 'S':
453  case 'a':
454  case 'n':
455  case 't':
456  case 'w':
457  success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
458  break;
459  default:
460  status = PSQL_CMD_UNKNOWN;
461  break;
462  }
463  break;
464  case 'g':
465  /* no longer distinct from \du */
466  success = describeRoles(pattern, show_verbose, show_system);
467  break;
468  case 'l':
469  success = do_lo_list();
470  break;
471  case 'L':
472  success = listLanguages(pattern, show_verbose, show_system);
473  break;
474  case 'n':
475  success = listSchemas(pattern, show_verbose, show_system);
476  break;
477  case 'o':
478  success = describeOperators(pattern, show_verbose, show_system);
479  break;
480  case 'O':
481  success = listCollations(pattern, show_verbose, show_system);
482  break;
483  case 'p':
484  success = permissionsList(pattern);
485  break;
486  case 'T':
487  success = describeTypes(pattern, show_verbose, show_system);
488  break;
489  case 't':
490  case 'v':
491  case 'm':
492  case 'i':
493  case 's':
494  case 'E':
495  success = listTables(&cmd[1], pattern, show_verbose, show_system);
496  break;
497  case 'r':
498  if (cmd[2] == 'd' && cmd[3] == 's')
499  {
500  char *pattern2 = NULL;
501 
502  if (pattern)
503  pattern2 = psql_scan_slash_option(scan_state,
504  OT_NORMAL, NULL, true);
505  success = listDbRoleSettings(pattern, pattern2);
506  }
507  else
508  success = PSQL_CMD_UNKNOWN;
509  break;
510  case 'R':
511  switch (cmd[2])
512  {
513  case 'p':
514  if (show_verbose)
515  success = describePublications(pattern);
516  else
517  success = listPublications(pattern);
518  break;
519  case 's':
520  success = describeSubscriptions(pattern, show_verbose);
521  break;
522  default:
523  status = PSQL_CMD_UNKNOWN;
524  }
525  break;
526  case 'u':
527  success = describeRoles(pattern, show_verbose, show_system);
528  break;
529  case 'F': /* text search subsystem */
530  switch (cmd[2])
531  {
532  case '\0':
533  case '+':
534  success = listTSConfigs(pattern, show_verbose);
535  break;
536  case 'p':
537  success = listTSParsers(pattern, show_verbose);
538  break;
539  case 'd':
540  success = listTSDictionaries(pattern, show_verbose);
541  break;
542  case 't':
543  success = listTSTemplates(pattern, show_verbose);
544  break;
545  default:
546  status = PSQL_CMD_UNKNOWN;
547  break;
548  }
549  break;
550  case 'e': /* SQL/MED subsystem */
551  switch (cmd[2])
552  {
553  case 's':
554  success = listForeignServers(pattern, show_verbose);
555  break;
556  case 'u':
557  success = listUserMappings(pattern, show_verbose);
558  break;
559  case 'w':
560  success = listForeignDataWrappers(pattern, show_verbose);
561  break;
562  case 't':
563  success = listForeignTables(pattern, show_verbose);
564  break;
565  default:
566  status = PSQL_CMD_UNKNOWN;
567  break;
568  }
569  break;
570  case 'x': /* Extensions */
571  if (show_verbose)
572  success = listExtensionContents(pattern);
573  else
574  success = listExtensions(pattern);
575  break;
576  case 'y': /* Event Triggers */
577  success = listEventTriggers(pattern, show_verbose);
578  break;
579  default:
580  status = PSQL_CMD_UNKNOWN;
581  }
582 
583  if (pattern)
584  free(pattern);
585  }
586 
587 
588  /*
589  * \e or \edit -- edit the current query buffer, or edit a file and make
590  * it the query buffer
591  */
592  else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
593  {
594  if (!query_buf)
595  {
596  psql_error("no query buffer\n");
597  status = PSQL_CMD_ERROR;
598  }
599  else
600  {
601  char *fname;
602  char *ln = NULL;
603  int lineno = -1;
604 
605  fname = psql_scan_slash_option(scan_state,
606  OT_NORMAL, NULL, true);
607  if (fname)
608  {
609  /* try to get separate lineno arg */
610  ln = psql_scan_slash_option(scan_state,
611  OT_NORMAL, NULL, true);
612  if (ln == NULL)
613  {
614  /* only one arg; maybe it is lineno not fname */
615  if (fname[0] &&
616  strspn(fname, "0123456789") == strlen(fname))
617  {
618  /* all digits, so assume it is lineno */
619  ln = fname;
620  fname = NULL;
621  }
622  }
623  }
624  if (ln)
625  {
626  lineno = atoi(ln);
627  if (lineno < 1)
628  {
629  psql_error("invalid line number: %s\n", ln);
630  status = PSQL_CMD_ERROR;
631  }
632  }
633  if (status != PSQL_CMD_ERROR)
634  {
635  expand_tilde(&fname);
636  if (fname)
637  canonicalize_path(fname);
638  if (do_edit(fname, query_buf, lineno, NULL))
639  status = PSQL_CMD_NEWEDIT;
640  else
641  status = PSQL_CMD_ERROR;
642  }
643  if (fname)
644  free(fname);
645  if (ln)
646  free(ln);
647  }
648  }
649 
650  /*
651  * \ef -- edit the named function, or present a blank CREATE FUNCTION
652  * template if no argument is given
653  */
654  else if (strcmp(cmd, "ef") == 0)
655  {
656  int lineno = -1;
657 
658  if (pset.sversion < 80400)
659  {
660  char sverbuf[32];
661 
662  psql_error("The server (version %s) does not support editing function source.\n",
664  sverbuf, sizeof(sverbuf)));
665  status = PSQL_CMD_ERROR;
666  }
667  else if (!query_buf)
668  {
669  psql_error("no query buffer\n");
670  status = PSQL_CMD_ERROR;
671  }
672  else
673  {
674  char *func;
675  Oid foid = InvalidOid;
676 
677  func = psql_scan_slash_option(scan_state,
678  OT_WHOLE_LINE, NULL, true);
679  lineno = strip_lineno_from_objdesc(func);
680  if (lineno == 0)
681  {
682  /* error already reported */
683  status = PSQL_CMD_ERROR;
684  }
685  else if (!func)
686  {
687  /* set up an empty command to fill in */
688  printfPQExpBuffer(query_buf,
689  "CREATE FUNCTION ( )\n"
690  " RETURNS \n"
691  " LANGUAGE \n"
692  " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
693  "AS $function$\n"
694  "\n$function$\n");
695  }
696  else if (!lookup_object_oid(EditableFunction, func, &foid))
697  {
698  /* error already reported */
699  status = PSQL_CMD_ERROR;
700  }
701  else if (!get_create_object_cmd(EditableFunction, foid, query_buf))
702  {
703  /* error already reported */
704  status = PSQL_CMD_ERROR;
705  }
706  else if (lineno > 0)
707  {
708  /*
709  * lineno "1" should correspond to the first line of the
710  * function body. We expect that pg_get_functiondef() will
711  * emit that on a line beginning with "AS ", and that there
712  * can be no such line before the real start of the function
713  * body. Increment lineno by the number of lines before that
714  * line, so that it becomes relative to the first line of the
715  * function definition.
716  */
717  const char *lines = query_buf->data;
718 
719  while (*lines != '\0')
720  {
721  if (strncmp(lines, "AS ", 3) == 0)
722  break;
723  lineno++;
724  /* find start of next line */
725  lines = strchr(lines, '\n');
726  if (!lines)
727  break;
728  lines++;
729  }
730  }
731 
732  if (func)
733  free(func);
734  }
735 
736  if (status != PSQL_CMD_ERROR)
737  {
738  bool edited = false;
739 
740  if (!do_edit(NULL, query_buf, lineno, &edited))
741  status = PSQL_CMD_ERROR;
742  else if (!edited)
743  puts(_("No changes"));
744  else
745  status = PSQL_CMD_NEWEDIT;
746  }
747  }
748 
749  /*
750  * \ev -- edit the named view, or present a blank CREATE VIEW template if
751  * no argument is given
752  */
753  else if (strcmp(cmd, "ev") == 0)
754  {
755  int lineno = -1;
756 
757  if (pset.sversion < 70400)
758  {
759  char sverbuf[32];
760 
761  psql_error("The server (version %s) does not support editing view definitions.\n",
763  sverbuf, sizeof(sverbuf)));
764  status = PSQL_CMD_ERROR;
765  }
766  else if (!query_buf)
767  {
768  psql_error("no query buffer\n");
769  status = PSQL_CMD_ERROR;
770  }
771  else
772  {
773  char *view;
774  Oid view_oid = InvalidOid;
775 
776  view = psql_scan_slash_option(scan_state,
777  OT_WHOLE_LINE, NULL, true);
778  lineno = strip_lineno_from_objdesc(view);
779  if (lineno == 0)
780  {
781  /* error already reported */
782  status = PSQL_CMD_ERROR;
783  }
784  else if (!view)
785  {
786  /* set up an empty command to fill in */
787  printfPQExpBuffer(query_buf,
788  "CREATE VIEW AS\n"
789  " SELECT \n"
790  " -- something...\n");
791  }
792  else if (!lookup_object_oid(EditableView, view, &view_oid))
793  {
794  /* error already reported */
795  status = PSQL_CMD_ERROR;
796  }
797  else if (!get_create_object_cmd(EditableView, view_oid, query_buf))
798  {
799  /* error already reported */
800  status = PSQL_CMD_ERROR;
801  }
802 
803  if (view)
804  free(view);
805  }
806 
807  if (status != PSQL_CMD_ERROR)
808  {
809  bool edited = false;
810 
811  if (!do_edit(NULL, query_buf, lineno, &edited))
812  status = PSQL_CMD_ERROR;
813  else if (!edited)
814  puts(_("No changes"));
815  else
816  status = PSQL_CMD_NEWEDIT;
817  }
818  }
819 
820  /* \echo and \qecho */
821  else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
822  {
823  char *value;
824  char quoted;
825  bool no_newline = false;
826  bool first = true;
827  FILE *fout;
828 
829  if (strcmp(cmd, "qecho") == 0)
830  fout = pset.queryFout;
831  else
832  fout = stdout;
833 
834  while ((value = psql_scan_slash_option(scan_state,
835  OT_NORMAL, &quoted, false)))
836  {
837  if (!quoted && strcmp(value, "-n") == 0)
838  no_newline = true;
839  else
840  {
841  if (first)
842  first = false;
843  else
844  fputc(' ', fout);
845  fputs(value, fout);
846  }
847  free(value);
848  }
849  if (!no_newline)
850  fputs("\n", fout);
851  }
852 
853  /* \encoding -- set/show client side encoding */
854  else if (strcmp(cmd, "encoding") == 0)
855  {
856  char *encoding = psql_scan_slash_option(scan_state,
857  OT_NORMAL, NULL, false);
858 
859  if (!encoding)
860  {
861  /* show encoding */
863  }
864  else
865  {
866  /* set encoding */
867  if (PQsetClientEncoding(pset.db, encoding) == -1)
868  psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
869  else
870  {
871  /* save encoding info into psql internal data */
874  SetVariable(pset.vars, "ENCODING",
876  }
877  free(encoding);
878  }
879  }
880 
881  /* \errverbose -- display verbose message from last failed query */
882  else if (strcmp(cmd, "errverbose") == 0)
883  {
885  {
886  char *msg;
887 
891  if (msg)
892  {
893  psql_error("%s", msg);
894  PQfreemem(msg);
895  }
896  else
897  puts(_("out of memory"));
898  }
899  else
900  puts(_("There is no previous error."));
901  }
902 
903  /* \f -- change field separator */
904  else if (strcmp(cmd, "f") == 0)
905  {
906  char *fname = psql_scan_slash_option(scan_state,
907  OT_NORMAL, NULL, false);
908 
909  success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
910  free(fname);
911  }
912 
913  /* \g [filename] -- send query, optionally with output to file/pipe */
914  else if (strcmp(cmd, "g") == 0)
915  {
916  char *fname = psql_scan_slash_option(scan_state,
917  OT_FILEPIPE, NULL, false);
918 
919  if (!fname)
920  pset.gfname = NULL;
921  else
922  {
923  expand_tilde(&fname);
924  pset.gfname = pg_strdup(fname);
925  }
926  free(fname);
927  status = PSQL_CMD_SEND;
928  }
929 
930  /* \gexec -- send query and execute each field of result */
931  else if (strcmp(cmd, "gexec") == 0)
932  {
933  pset.gexec_flag = true;
934  status = PSQL_CMD_SEND;
935  }
936 
937  /* \gset [prefix] -- send query and store result into variables */
938  else if (strcmp(cmd, "gset") == 0)
939  {
940  char *prefix = psql_scan_slash_option(scan_state,
941  OT_NORMAL, NULL, false);
942 
943  if (prefix)
944  pset.gset_prefix = prefix;
945  else
946  {
947  /* we must set a non-NULL prefix to trigger storing */
948  pset.gset_prefix = pg_strdup("");
949  }
950  /* gset_prefix is freed later */
951  status = PSQL_CMD_SEND;
952  }
953 
954  /* help */
955  else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
956  {
957  char *opt = psql_scan_slash_option(scan_state,
958  OT_WHOLE_LINE, NULL, false);
959  size_t len;
960 
961  /* strip any trailing spaces and semicolons */
962  if (opt)
963  {
964  len = strlen(opt);
965  while (len > 0 &&
966  (isspace((unsigned char) opt[len - 1])
967  || opt[len - 1] == ';'))
968  opt[--len] = '\0';
969  }
970 
971  helpSQL(opt, pset.popt.topt.pager);
972  free(opt);
973  }
974 
975  /* HTML mode */
976  else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
977  {
978  if (pset.popt.topt.format != PRINT_HTML)
979  success = do_pset("format", "html", &pset.popt, pset.quiet);
980  else
981  success = do_pset("format", "aligned", &pset.popt, pset.quiet);
982  }
983 
984 
985  /* \i and \ir include files */
986  else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0
987  || strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
988  {
989  char *fname = psql_scan_slash_option(scan_state,
990  OT_NORMAL, NULL, true);
991 
992  if (!fname)
993  {
994  psql_error("\\%s: missing required argument\n", cmd);
995  success = false;
996  }
997  else
998  {
999  bool include_relative;
1000 
1001  include_relative = (strcmp(cmd, "ir") == 0
1002  || strcmp(cmd, "include_relative") == 0);
1003  expand_tilde(&fname);
1004  success = (process_file(fname, include_relative) == EXIT_SUCCESS);
1005  free(fname);
1006  }
1007  }
1008 
1009  /* \l is list databases */
1010  else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
1011  strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
1012  {
1013  char *pattern;
1014  bool show_verbose;
1015 
1016  pattern = psql_scan_slash_option(scan_state,
1017  OT_NORMAL, NULL, true);
1018 
1019  show_verbose = strchr(cmd, '+') ? true : false;
1020 
1021  success = listAllDbs(pattern, show_verbose);
1022 
1023  if (pattern)
1024  free(pattern);
1025  }
1026 
1027  /*
1028  * large object things
1029  */
1030  else if (strncmp(cmd, "lo_", 3) == 0)
1031  {
1032  char *opt1,
1033  *opt2;
1034 
1035  opt1 = psql_scan_slash_option(scan_state,
1036  OT_NORMAL, NULL, true);
1037  opt2 = psql_scan_slash_option(scan_state,
1038  OT_NORMAL, NULL, true);
1039 
1040  if (strcmp(cmd + 3, "export") == 0)
1041  {
1042  if (!opt2)
1043  {
1044  psql_error("\\%s: missing required argument\n", cmd);
1045  success = false;
1046  }
1047  else
1048  {
1049  expand_tilde(&opt2);
1050  success = do_lo_export(opt1, opt2);
1051  }
1052  }
1053 
1054  else if (strcmp(cmd + 3, "import") == 0)
1055  {
1056  if (!opt1)
1057  {
1058  psql_error("\\%s: missing required argument\n", cmd);
1059  success = false;
1060  }
1061  else
1062  {
1063  expand_tilde(&opt1);
1064  success = do_lo_import(opt1, opt2);
1065  }
1066  }
1067 
1068  else if (strcmp(cmd + 3, "list") == 0)
1069  success = do_lo_list();
1070 
1071  else if (strcmp(cmd + 3, "unlink") == 0)
1072  {
1073  if (!opt1)
1074  {
1075  psql_error("\\%s: missing required argument\n", cmd);
1076  success = false;
1077  }
1078  else
1079  success = do_lo_unlink(opt1);
1080  }
1081 
1082  else
1083  status = PSQL_CMD_UNKNOWN;
1084 
1085  free(opt1);
1086  free(opt2);
1087  }
1088 
1089 
1090  /* \o -- set query output */
1091  else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
1092  {
1093  char *fname = psql_scan_slash_option(scan_state,
1094  OT_FILEPIPE, NULL, true);
1095 
1096  expand_tilde(&fname);
1097  success = setQFout(fname);
1098  free(fname);
1099  }
1100 
1101  /* \p prints the current query buffer */
1102  else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
1103  {
1104  if (query_buf && query_buf->len > 0)
1105  puts(query_buf->data);
1106  else if (!pset.quiet)
1107  puts(_("Query buffer is empty."));
1108  fflush(stdout);
1109  }
1110 
1111  /* \password -- set user password */
1112  else if (strcmp(cmd, "password") == 0)
1113  {
1114  char pw1[100];
1115  char pw2[100];
1116 
1117  simple_prompt("Enter new password: ", pw1, sizeof(pw1), false);
1118  simple_prompt("Enter it again: ", pw2, sizeof(pw2), false);
1119 
1120  if (strcmp(pw1, pw2) != 0)
1121  {
1122  psql_error("Passwords didn't match.\n");
1123  success = false;
1124  }
1125  else
1126  {
1127  char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
1128  char *user;
1129  char *encrypted_password;
1130 
1131  if (opt0)
1132  user = opt0;
1133  else
1134  user = PQuser(pset.db);
1135 
1136  encrypted_password = PQencryptPassword(pw1, user);
1137 
1138  if (!encrypted_password)
1139  {
1140  psql_error("Password encryption failed.\n");
1141  success = false;
1142  }
1143  else
1144  {
1146  PGresult *res;
1147 
1148  initPQExpBuffer(&buf);
1149  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
1150  fmtId(user));
1151  appendStringLiteralConn(&buf, encrypted_password, pset.db);
1152  res = PSQLexec(buf.data);
1153  termPQExpBuffer(&buf);
1154  if (!res)
1155  success = false;
1156  else
1157  PQclear(res);
1158  PQfreemem(encrypted_password);
1159  }
1160 
1161  if (opt0)
1162  free(opt0);
1163  }
1164  }
1165 
1166  /* \prompt -- prompt and set variable */
1167  else if (strcmp(cmd, "prompt") == 0)
1168  {
1169  char *opt,
1170  *prompt_text = NULL;
1171  char *arg1,
1172  *arg2;
1173 
1174  arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1175  arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1176 
1177  if (!arg1)
1178  {
1179  psql_error("\\%s: missing required argument\n", cmd);
1180  success = false;
1181  }
1182  else
1183  {
1184  char *result;
1185 
1186  if (arg2)
1187  {
1188  prompt_text = arg1;
1189  opt = arg2;
1190  }
1191  else
1192  opt = arg1;
1193 
1194  if (!pset.inputfile)
1195  {
1196  result = (char *) pg_malloc(4096);
1197  simple_prompt(prompt_text, result, 4096, true);
1198  }
1199  else
1200  {
1201  if (prompt_text)
1202  {
1203  fputs(prompt_text, stdout);
1204  fflush(stdout);
1205  }
1206  result = gets_fromFile(stdin);
1207  if (!result)
1208  {
1209  psql_error("\\%s: could not read value for variable\n",
1210  cmd);
1211  success = false;
1212  }
1213  }
1214 
1215  if (result &&
1216  !SetVariable(pset.vars, opt, result))
1217  success = false;
1218 
1219  if (result)
1220  free(result);
1221  if (prompt_text)
1222  free(prompt_text);
1223  free(opt);
1224  }
1225  }
1226 
1227  /* \pset -- set printing parameters */
1228  else if (strcmp(cmd, "pset") == 0)
1229  {
1230  char *opt0 = psql_scan_slash_option(scan_state,
1231  OT_NORMAL, NULL, false);
1232  char *opt1 = psql_scan_slash_option(scan_state,
1233  OT_NORMAL, NULL, false);
1234 
1235  if (!opt0)
1236  {
1237  /* list all variables */
1238 
1239  int i;
1240  static const char *const my_list[] = {
1241  "border", "columns", "expanded", "fieldsep", "fieldsep_zero",
1242  "footer", "format", "linestyle", "null",
1243  "numericlocale", "pager", "pager_min_lines",
1244  "recordsep", "recordsep_zero",
1245  "tableattr", "title", "tuples_only",
1246  "unicode_border_linestyle",
1247  "unicode_column_linestyle",
1248  "unicode_header_linestyle",
1249  NULL
1250  };
1251 
1252  for (i = 0; my_list[i] != NULL; i++)
1253  {
1254  char *val = pset_value_string(my_list[i], &pset.popt);
1255 
1256  printf("%-24s %s\n", my_list[i], val);
1257  free(val);
1258  }
1259 
1260  success = true;
1261  }
1262  else
1263  success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
1264 
1265  free(opt0);
1266  free(opt1);
1267  }
1268 
1269  /* \q or \quit */
1270  else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
1271  status = PSQL_CMD_TERMINATE;
1272 
1273  /* reset(clear) the buffer */
1274  else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
1275  {
1276  resetPQExpBuffer(query_buf);
1277  psql_scan_reset(scan_state);
1278  if (!pset.quiet)
1279  puts(_("Query buffer reset (cleared)."));
1280  }
1281 
1282  /* \s save history in a file or show it on the screen */
1283  else if (strcmp(cmd, "s") == 0)
1284  {
1285  char *fname = psql_scan_slash_option(scan_state,
1286  OT_NORMAL, NULL, true);
1287 
1288  expand_tilde(&fname);
1289  success = printHistory(fname, pset.popt.topt.pager);
1290  if (success && !pset.quiet && fname)
1291  printf(_("Wrote history to file \"%s\".\n"), fname);
1292  if (!fname)
1293  putchar('\n');
1294  free(fname);
1295  }
1296 
1297  /* \set -- generalized set variable/option command */
1298  else if (strcmp(cmd, "set") == 0)
1299  {
1300  char *opt0 = psql_scan_slash_option(scan_state,
1301  OT_NORMAL, NULL, false);
1302 
1303  if (!opt0)
1304  {
1305  /* list all variables */
1307  success = true;
1308  }
1309  else
1310  {
1311  /*
1312  * Set variable to the concatenation of the arguments.
1313  */
1314  char *newval;
1315  char *opt;
1316 
1317  opt = psql_scan_slash_option(scan_state,
1318  OT_NORMAL, NULL, false);
1319  newval = pg_strdup(opt ? opt : "");
1320  free(opt);
1321 
1322  while ((opt = psql_scan_slash_option(scan_state,
1323  OT_NORMAL, NULL, false)))
1324  {
1325  newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
1326  strcat(newval, opt);
1327  free(opt);
1328  }
1329 
1330  if (!SetVariable(pset.vars, opt0, newval))
1331  success = false;
1332 
1333  free(newval);
1334  }
1335  free(opt0);
1336  }
1337 
1338 
1339  /* \setenv -- set environment command */
1340  else if (strcmp(cmd, "setenv") == 0)
1341  {
1342  char *envvar = psql_scan_slash_option(scan_state,
1343  OT_NORMAL, NULL, false);
1344  char *envval = psql_scan_slash_option(scan_state,
1345  OT_NORMAL, NULL, false);
1346 
1347  if (!envvar)
1348  {
1349  psql_error("\\%s: missing required argument\n", cmd);
1350  success = false;
1351  }
1352  else if (strchr(envvar, '=') != NULL)
1353  {
1354  psql_error("\\%s: environment variable name must not contain \"=\"\n",
1355  cmd);
1356  success = false;
1357  }
1358  else if (!envval)
1359  {
1360  /* No argument - unset the environment variable */
1361  unsetenv(envvar);
1362  success = true;
1363  }
1364  else
1365  {
1366  /* Set variable to the value of the next argument */
1367  char *newval;
1368 
1369  newval = psprintf("%s=%s", envvar, envval);
1370  putenv(newval);
1371  success = true;
1372 
1373  /*
1374  * Do not free newval here, it will screw up the environment if
1375  * you do. See putenv man page for details. That means we leak a
1376  * bit of memory here, but not enough to worry about.
1377  */
1378  }
1379  free(envvar);
1380  free(envval);
1381  }
1382 
1383  /* \sf -- show a function's source code */
1384  else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
1385  {
1386  bool show_linenumbers = (strcmp(cmd, "sf+") == 0);
1387  PQExpBuffer func_buf;
1388  char *func;
1389  Oid foid = InvalidOid;
1390 
1391  func_buf = createPQExpBuffer();
1392  func = psql_scan_slash_option(scan_state,
1393  OT_WHOLE_LINE, NULL, true);
1394  if (pset.sversion < 80400)
1395  {
1396  char sverbuf[32];
1397 
1398  psql_error("The server (version %s) does not support showing function source.\n",
1400  sverbuf, sizeof(sverbuf)));
1401  status = PSQL_CMD_ERROR;
1402  }
1403  else if (!func)
1404  {
1405  psql_error("function name is required\n");
1406  status = PSQL_CMD_ERROR;
1407  }
1408  else if (!lookup_object_oid(EditableFunction, func, &foid))
1409  {
1410  /* error already reported */
1411  status = PSQL_CMD_ERROR;
1412  }
1413  else if (!get_create_object_cmd(EditableFunction, foid, func_buf))
1414  {
1415  /* error already reported */
1416  status = PSQL_CMD_ERROR;
1417  }
1418  else
1419  {
1420  FILE *output;
1421  bool is_pager;
1422 
1423  /* Select output stream: stdout, pager, or file */
1424  if (pset.queryFout == stdout)
1425  {
1426  /* count lines in function to see if pager is needed */
1427  int lineno = count_lines_in_buf(func_buf);
1428 
1429  output = PageOutput(lineno, &(pset.popt.topt));
1430  is_pager = true;
1431  }
1432  else
1433  {
1434  /* use previously set output file, without pager */
1435  output = pset.queryFout;
1436  is_pager = false;
1437  }
1438 
1439  if (show_linenumbers)
1440  {
1441  /*
1442  * lineno "1" should correspond to the first line of the
1443  * function body. We expect that pg_get_functiondef() will
1444  * emit that on a line beginning with "AS ", and that there
1445  * can be no such line before the real start of the function
1446  * body.
1447  */
1448  print_with_linenumbers(output, func_buf->data, "AS ");
1449  }
1450  else
1451  {
1452  /* just send the function definition to output */
1453  fputs(func_buf->data, output);
1454  }
1455 
1456  if (is_pager)
1457  ClosePager(output);
1458  }
1459 
1460  if (func)
1461  free(func);
1462  destroyPQExpBuffer(func_buf);
1463  }
1464 
1465  /* \sv -- show a view's source code */
1466  else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
1467  {
1468  bool show_linenumbers = (strcmp(cmd, "sv+") == 0);
1469  PQExpBuffer view_buf;
1470  char *view;
1471  Oid view_oid = InvalidOid;
1472 
1473  view_buf = createPQExpBuffer();
1474  view = psql_scan_slash_option(scan_state,
1475  OT_WHOLE_LINE, NULL, true);
1476  if (pset.sversion < 70400)
1477  {
1478  char sverbuf[32];
1479 
1480  psql_error("The server (version %s) does not support showing view definitions.\n",
1482  sverbuf, sizeof(sverbuf)));
1483  status = PSQL_CMD_ERROR;
1484  }
1485  else if (!view)
1486  {
1487  psql_error("view name is required\n");
1488  status = PSQL_CMD_ERROR;
1489  }
1490  else if (!lookup_object_oid(EditableView, view, &view_oid))
1491  {
1492  /* error already reported */
1493  status = PSQL_CMD_ERROR;
1494  }
1495  else if (!get_create_object_cmd(EditableView, view_oid, view_buf))
1496  {
1497  /* error already reported */
1498  status = PSQL_CMD_ERROR;
1499  }
1500  else
1501  {
1502  FILE *output;
1503  bool is_pager;
1504 
1505  /* Select output stream: stdout, pager, or file */
1506  if (pset.queryFout == stdout)
1507  {
1508  /* count lines in view to see if pager is needed */
1509  int lineno = count_lines_in_buf(view_buf);
1510 
1511  output = PageOutput(lineno, &(pset.popt.topt));
1512  is_pager = true;
1513  }
1514  else
1515  {
1516  /* use previously set output file, without pager */
1517  output = pset.queryFout;
1518  is_pager = false;
1519  }
1520 
1521  if (show_linenumbers)
1522  {
1523  /* add line numbers, numbering all lines */
1524  print_with_linenumbers(output, view_buf->data, NULL);
1525  }
1526  else
1527  {
1528  /* just send the view definition to output */
1529  fputs(view_buf->data, output);
1530  }
1531 
1532  if (is_pager)
1533  ClosePager(output);
1534  }
1535 
1536  if (view)
1537  free(view);
1538  destroyPQExpBuffer(view_buf);
1539  }
1540 
1541  /* \t -- turn off headers and row count */
1542  else if (strcmp(cmd, "t") == 0)
1543  {
1544  char *opt = psql_scan_slash_option(scan_state,
1545  OT_NORMAL, NULL, true);
1546 
1547  success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1548  free(opt);
1549  }
1550 
1551  /* \T -- define html <table ...> attributes */
1552  else if (strcmp(cmd, "T") == 0)
1553  {
1554  char *value = psql_scan_slash_option(scan_state,
1555  OT_NORMAL, NULL, false);
1556 
1557  success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1558  free(value);
1559  }
1560 
1561  /* \timing -- toggle timing of queries */
1562  else if (strcmp(cmd, "timing") == 0)
1563  {
1564  char *opt = psql_scan_slash_option(scan_state,
1565  OT_NORMAL, NULL, false);
1566 
1567  if (opt)
1568  success = ParseVariableBool(opt, "\\timing", &pset.timing);
1569  else
1570  pset.timing = !pset.timing;
1571  if (!pset.quiet)
1572  {
1573  if (pset.timing)
1574  puts(_("Timing is on."));
1575  else
1576  puts(_("Timing is off."));
1577  }
1578  free(opt);
1579  }
1580 
1581  /* \unset */
1582  else if (strcmp(cmd, "unset") == 0)
1583  {
1584  char *opt = psql_scan_slash_option(scan_state,
1585  OT_NORMAL, NULL, false);
1586 
1587  if (!opt)
1588  {
1589  psql_error("\\%s: missing required argument\n", cmd);
1590  success = false;
1591  }
1592  else if (!SetVariable(pset.vars, opt, NULL))
1593  success = false;
1594 
1595  free(opt);
1596  }
1597 
1598  /* \w -- write query buffer to file */
1599  else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1600  {
1601  FILE *fd = NULL;
1602  bool is_pipe = false;
1603  char *fname = NULL;
1604 
1605  if (!query_buf)
1606  {
1607  psql_error("no query buffer\n");
1608  status = PSQL_CMD_ERROR;
1609  }
1610  else
1611  {
1612  fname = psql_scan_slash_option(scan_state,
1613  OT_FILEPIPE, NULL, true);
1614  expand_tilde(&fname);
1615 
1616  if (!fname)
1617  {
1618  psql_error("\\%s: missing required argument\n", cmd);
1619  success = false;
1620  }
1621  else
1622  {
1623  if (fname[0] == '|')
1624  {
1625  is_pipe = true;
1627  fd = popen(&fname[1], "w");
1628  }
1629  else
1630  {
1631  canonicalize_path(fname);
1632  fd = fopen(fname, "w");
1633  }
1634  if (!fd)
1635  {
1636  psql_error("%s: %s\n", fname, strerror(errno));
1637  success = false;
1638  }
1639  }
1640  }
1641 
1642  if (fd)
1643  {
1644  int result;
1645 
1646  if (query_buf && query_buf->len > 0)
1647  fprintf(fd, "%s\n", query_buf->data);
1648 
1649  if (is_pipe)
1650  result = pclose(fd);
1651  else
1652  result = fclose(fd);
1653 
1654  if (result == EOF)
1655  {
1656  psql_error("%s: %s\n", fname, strerror(errno));
1657  success = false;
1658  }
1659  }
1660 
1661  if (is_pipe)
1663 
1664  free(fname);
1665  }
1666 
1667  /* \watch -- execute a query every N seconds */
1668  else if (strcmp(cmd, "watch") == 0)
1669  {
1670  char *opt = psql_scan_slash_option(scan_state,
1671  OT_NORMAL, NULL, true);
1672  double sleep = 2;
1673 
1674  /* Convert optional sleep-length argument */
1675  if (opt)
1676  {
1677  sleep = strtod(opt, NULL);
1678  if (sleep <= 0)
1679  sleep = 1;
1680  free(opt);
1681  }
1682 
1683  success = do_watch(query_buf, sleep);
1684 
1685  /* Reset the query buffer as though for \r */
1686  resetPQExpBuffer(query_buf);
1687  psql_scan_reset(scan_state);
1688  }
1689 
1690  /* \x -- set or toggle expanded table representation */
1691  else if (strcmp(cmd, "x") == 0)
1692  {
1693  char *opt = psql_scan_slash_option(scan_state,
1694  OT_NORMAL, NULL, true);
1695 
1696  success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1697  free(opt);
1698  }
1699 
1700  /* \z -- list table rights (equivalent to \dp) */
1701  else if (strcmp(cmd, "z") == 0)
1702  {
1703  char *pattern = psql_scan_slash_option(scan_state,
1704  OT_NORMAL, NULL, true);
1705 
1706  success = permissionsList(pattern);
1707  if (pattern)
1708  free(pattern);
1709  }
1710 
1711  /* \! -- shell escape */
1712  else if (strcmp(cmd, "!") == 0)
1713  {
1714  char *opt = psql_scan_slash_option(scan_state,
1715  OT_WHOLE_LINE, NULL, false);
1716 
1717  success = do_shell(opt);
1718  free(opt);
1719  }
1720 
1721  /* \? -- slash command help */
1722  else if (strcmp(cmd, "?") == 0)
1723  {
1724  char *opt0 = psql_scan_slash_option(scan_state,
1725  OT_NORMAL, NULL, false);
1726 
1727  if (!opt0 || strcmp(opt0, "commands") == 0)
1729  else if (strcmp(opt0, "options") == 0)
1731  else if (strcmp(opt0, "variables") == 0)
1733  else
1735  }
1736 
1737 #if 0
1738 
1739  /*
1740  * These commands don't do anything. I just use them to test the parser.
1741  */
1742  else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1743  {
1744  int i = 0;
1745  char *value;
1746 
1747  while ((value = psql_scan_slash_option(scan_state,
1748  OT_NORMAL, NULL, true)))
1749  {
1750  psql_error("+ opt(%d) = |%s|\n", i++, value);
1751  free(value);
1752  }
1753  }
1754 #endif
1755 
1756  else
1757  status = PSQL_CMD_UNKNOWN;
1758 
1759  if (!success)
1760  status = PSQL_CMD_ERROR;
1761 
1762  return status;
1763 }
char * gset_prefix
Definition: settings.h:94
static void usage(void)
Definition: pg_standby.c:503
static struct @76 value
bool do_lo_export(const char *loid_arg, const char *filename_arg)
Definition: large_obj.c:141
PGconn * db
Definition: settings.h:82
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
void print_copyright(void)
Definition: help.c:572
int encoding
Definition: print.h:118
#define EXIT_SUCCESS
Definition: settings.h:146
PsqlSettings pset
Definition: startup.c:37
bool listTSConfigs(const char *pattern, bool verbose)
Definition: describe.c:4215
bool objectDescription(const char *pattern, bool showSystem)
Definition: describe.c:1084
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
bool listExtensionContents(const char *pattern)
Definition: describe.c:4777
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
int uid_t
Definition: win32.h:260
void disable_sigpipe_trap(void)
Definition: print.c:2802
static void output(uint64 loop_count)
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void ClosePager(FILE *pagerpipe)
Definition: print.c:2901
bool do_lo_unlink(const char *loid_arg)
Definition: large_obj.c:238
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool gexec_flag
Definition: settings.h:95
enum printFormat format
Definition: print.h:98
printTableOpt topt
Definition: print.h:165
bool listEventTriggers(const char *pattern, bool verbose)
Definition: describe.c:3534
bool listCollations(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3699
bool listLanguages(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3297
static bool lookup_object_oid(EditableObjectType obj_type, const char *desc, Oid *obj_oid)
Definition: command.c:3304
static void print_with_linenumbers(FILE *output, char *lines, const char *header_keyword)
Definition: command.c:3622
FILE * queryFout
Definition: settings.h:84
void canonicalize_path(char *path)
Definition: path.c:254
char * PQport(const PGconn *conn)
Definition: fe-connect.c:5881
char * inputfile
Definition: settings.h:107
bool do_copy(const char *args)
Definition: copy.c:269
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define lengthof(array)
Definition: c.h:558
unsigned int Oid
Definition: postgres_ext.h:31
bool listDomains(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3372
void PrintVariables(VariableSpace space)
Definition: variables.c:186
#define putenv(x)
Definition: win32.h:421
bool listSchemas(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3778
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static char * read_connect_arg(PsqlScanState scan_state)
Definition: command.c:169
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6020
bool describeTablespaces(const char *pattern, bool verbose)
Definition: describe.c:203
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5836
bool describeSubscriptions(const char *pattern, bool verbose)
Definition: describe.c:5076
static int count_lines_in_buf(PQExpBuffer buf)
Definition: command.c:3595
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
char * ctv_args[4]
Definition: settings.h:97
bool describeAggregates(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:59
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:2852
void expand_tilde(char **filename)
Definition: common.c:2053
static bool do_watch(PQExpBuffer query_buf, double sleep)
Definition: command.c:3166
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3142
bool describeTableDetails(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:1276
static bool success
Definition: pg_basebackup.c:99
char * PQresultVerboseErrorMessage(const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-exec.c:2620
static char * buf
Definition: pg_test_fsync.c:65
bool listConversions(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:3458
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
void psql_scan_reset(PsqlScanState state)
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5810
#define is_absolute_path(filename)
Definition: port.h:77
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:5769
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:2560
static char * pset_value_string(const char *param, struct printQueryOpt *popt)
Definition: command.c:3053
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
bool do_lo_import(const char *filename_arg, const char *comment_arg)
Definition: large_obj.c:175
void restore_sigpipe_trap(void)
Definition: print.c:2825
bool listForeignTables(const char *pattern, bool verbose)
Definition: describe.c:4642
bool describePublications(const char *pattern)
Definition: describe.c:4950
trivalue
Definition: vacuumlo.c:31
void psql_error(const char *fmt,...)
Definition: common.c:177
char * gfname
Definition: settings.h:93
void helpVariables(unsigned short int pager)
Definition: help.c:320
bool listTSDictionaries(const char *pattern, bool verbose)
Definition: describe.c:4073
bool setQFout(const char *fname)
Definition: common.c:84
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
int PQsetClientEncoding(PGconn *conn, const char *encoding)
Definition: fe-connect.c:6028
PGresult * last_error_result
Definition: settings.h:89
static bool do_edit(const char *filename_arg, PQExpBuffer query_buf, int lineno, bool *edited)
Definition: command.c:2262
bool listPublications(const char *pattern)
Definition: describe.c:4887
bool listForeignServers(const char *pattern, bool verbose)
Definition: describe.c:4499
unsigned short int pager
Definition: print.h:103
#define InvalidOid
Definition: postgres_ext.h:36
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:5861
int process_file(char *filename, bool use_relative_path)
Definition: command.c:2426
void PQclear(PGresult *res)
Definition: fe-exec.c:650
static char * encoding
Definition: initdb.c:121
#define free(a)
Definition: header.h:60
bool describeTypes(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:586
enum _backslashResult backslashResult
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:531
bool describeAccessMethods(const char *pattern, bool verbose)
Definition: describe.c:136
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5828
#define NULL
Definition: c.h:226
static int strip_lineno_from_objdesc(char *obj)
Definition: command.c:3537
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
bool listForeignDataWrappers(const char *pattern, bool verbose)
Definition: describe.c:4416
printQueryOpt popt
Definition: settings.h:91
bool listUserMappings(const char *pattern, bool verbose)
Definition: describe.c:4581
char * gets_fromFile(FILE *source)
Definition: input.c:187
#define newval
#define unsetenv(x)
Definition: win32.h:422
bool describeFunctions(const char *functypes, const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:297
static bool do_shell(const char *command)
Definition: command.c:3122
bool do_lo_list(void)
Definition: large_obj.c:273
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
bool listExtensions(const char *pattern)
Definition: describe.c:4720
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:298
static char * user
Definition: pg_regress.c:90
bool describeOperators(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:700
static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid, PQExpBuffer buf)
Definition: command.c:3364
bool listCasts(const char *pattern, bool verbose)
Definition: describe.c:3600
void helpSQL(const char *topic, unsigned short int pager)
Definition: help.c:432
int i
const char * strerror(int errnum)
Definition: strerror.c:19
bool crosstab_flag
Definition: settings.h:96
#define EXIT_FAILURE
Definition: settings.h:150
bool listDefaultACLs(const char *pattern)
Definition: describe.c:1001
bool permissionsList(const char *pattern)
Definition: describe.c:847
static void printSSLInfo(void)
Definition: command.c:2098
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int encoding
Definition: settings.h:83
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
bool listDbRoleSettings(const char *pattern, const char *pattern2)
Definition: describe.c:3067
bool listTSTemplates(const char *pattern, bool verbose)
Definition: describe.c:4144
bool describeRoles(const char *pattern, bool verbose, bool showSystem)
Definition: describe.c:2896
#define _(x)
Definition: elog.c:84
bool listTSParsers(const char *pattern, bool verbose)
Definition: describe.c:3835
void PQfreemem(void *ptr)
Definition: fe-exec.c:3200
long val
Definition: informix.c:689
void slashUsage(unsigned short int pager)
Definition: help.c:159
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:777
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
char * PQencryptPassword(const char *passwd, const char *user)
Definition: fe-auth.c:817
static bool do_connect(enum trivalue reuse_previous_specification, char *dbname, char *user, char *host, char *port)
Definition: command.c:1813
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:182
bool printHistory(const char *fname, unsigned short int pager)
Definition: input.c:490
PGresult * PSQLexec(const char *query)
Definition: common.c:599
VariableSpace vars
Definition: settings.h:115
static bool get_create_object_cmd ( EditableObjectType  obj_type,
Oid  oid,
PQExpBuffer  buf 
)
static

Definition at line 3364 of file command.c.

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendReloptionsArray(), createPQExpBuffer(), PQExpBufferData::data, _psqlSettings::db, destroyPQExpBuffer(), echo_hidden_command(), EditableFunction, EditableView, _psqlSettings::encoding, fmtId(), PQExpBufferData::len, minimal_error_message(), NULL, PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQntuples(), PQresultStatus(), printfPQExpBuffer(), pset, psql_error(), resetPQExpBuffer(), standard_strings(), and _psqlSettings::sversion.

Referenced by exec_command().

3366 {
3367  bool result = true;
3368  PQExpBuffer query = createPQExpBuffer();
3369  PGresult *res;
3370 
3371  switch (obj_type)
3372  {
3373  case EditableFunction:
3374  printfPQExpBuffer(query,
3375  "SELECT pg_catalog.pg_get_functiondef(%u)",
3376  oid);
3377  break;
3378 
3379  case EditableView:
3380 
3381  /*
3382  * pg_get_viewdef() just prints the query, so we must prepend
3383  * CREATE for ourselves. We must fully qualify the view name to
3384  * ensure the right view gets replaced. Also, check relation kind
3385  * to be sure it's a view.
3386  *
3387  * Starting with 9.2, views may have reloptions (security_barrier)
3388  * and from 9.4 onwards they may also have WITH [LOCAL|CASCADED]
3389  * CHECK OPTION. These are not part of the view definition
3390  * returned by pg_get_viewdef() and so need to be retrieved
3391  * separately. Materialized views (introduced in 9.3) may have
3392  * arbitrary storage parameter reloptions.
3393  */
3394  if (pset.sversion >= 90400)
3395  {
3396  printfPQExpBuffer(query,
3397  "SELECT nspname, relname, relkind, "
3398  "pg_catalog.pg_get_viewdef(c.oid, true), "
3399  "array_remove(array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
3400  "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
3401  "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
3402  "FROM pg_catalog.pg_class c "
3403  "LEFT JOIN pg_catalog.pg_namespace n "
3404  "ON c.relnamespace = n.oid WHERE c.oid = %u",
3405  oid);
3406  }
3407  else if (pset.sversion >= 90200)
3408  {
3409  printfPQExpBuffer(query,
3410  "SELECT nspname, relname, relkind, "
3411  "pg_catalog.pg_get_viewdef(c.oid, true), "
3412  "c.reloptions AS reloptions, "
3413  "NULL AS checkoption "
3414  "FROM pg_catalog.pg_class c "
3415  "LEFT JOIN pg_catalog.pg_namespace n "
3416  "ON c.relnamespace = n.oid WHERE c.oid = %u",
3417  oid);
3418  }
3419  else
3420  {
3421  printfPQExpBuffer(query,
3422  "SELECT nspname, relname, relkind, "
3423  "pg_catalog.pg_get_viewdef(c.oid, true), "
3424  "NULL AS reloptions, "
3425  "NULL AS checkoption "
3426  "FROM pg_catalog.pg_class c "
3427  "LEFT JOIN pg_catalog.pg_namespace n "
3428  "ON c.relnamespace = n.oid WHERE c.oid = %u",
3429  oid);
3430  }
3431  break;
3432  }
3433 
3434  if (!echo_hidden_command(query->data))
3435  {
3436  destroyPQExpBuffer(query);
3437  return false;
3438  }
3439  res = PQexec(pset.db, query->data);
3440  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
3441  {
3442  resetPQExpBuffer(buf);
3443  switch (obj_type)
3444  {
3445  case EditableFunction:
3446  appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
3447  break;
3448 
3449  case EditableView:
3450  {
3451  char *nspname = PQgetvalue(res, 0, 0);
3452  char *relname = PQgetvalue(res, 0, 1);
3453  char *relkind = PQgetvalue(res, 0, 2);
3454  char *viewdef = PQgetvalue(res, 0, 3);
3455  char *reloptions = PQgetvalue(res, 0, 4);
3456  char *checkoption = PQgetvalue(res, 0, 5);
3457 
3458  /*
3459  * If the backend ever supports CREATE OR REPLACE
3460  * MATERIALIZED VIEW, allow that here; but as of today it
3461  * does not, so editing a matview definition in this way
3462  * is impossible.
3463  */
3464  switch (relkind[0])
3465  {
3466 #ifdef NOT_USED
3467  case 'm':
3468  appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
3469  break;
3470 #endif
3471  case 'v':
3472  appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
3473  break;
3474  default:
3475  psql_error("\"%s.%s\" is not a view\n",
3476  nspname, relname);
3477  result = false;
3478  break;
3479  }
3480  appendPQExpBuffer(buf, "%s.", fmtId(nspname));
3481  appendPQExpBufferStr(buf, fmtId(relname));
3482 
3483  /* reloptions, if not an empty array "{}" */
3484  if (reloptions != NULL && strlen(reloptions) > 2)
3485  {
3486  appendPQExpBufferStr(buf, "\n WITH (");
3487  if (!appendReloptionsArray(buf, reloptions, "",
3488  pset.encoding,
3489  standard_strings()))
3490  {
3491  psql_error("could not parse reloptions array\n");
3492  result = false;
3493  }
3494  appendPQExpBufferStr(buf, ")");
3495  }
3496 
3497  /* View definition from pg_get_viewdef (a SELECT query) */
3498  appendPQExpBuffer(buf, " AS\n%s", viewdef);
3499 
3500  /* Get rid of the semicolon that pg_get_viewdef appends */
3501  if (buf->len > 0 && buf->data[buf->len - 1] == ';')
3502  buf->data[--(buf->len)] = '\0';
3503 
3504  /* WITH [LOCAL|CASCADED] CHECK OPTION */
3505  if (checkoption && checkoption[0] != '\0')
3506  appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
3507  checkoption);
3508  }
3509  break;
3510  }
3511  /* Make sure result ends with a newline */
3512  if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
3513  appendPQExpBufferChar(buf, '\n');
3514  }
3515  else
3516  {
3517  minimal_error_message(res);
3518  result = false;
3519  }
3520 
3521  PQclear(res);
3522  destroyPQExpBuffer(query);
3523 
3524  return result;
3525 }
PGconn * db
Definition: settings.h:82
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
PsqlSettings pset
Definition: startup.c:37
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
const char * fmtId(const char *rawid)
Definition: string_utils.c:66
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
static void minimal_error_message(PGresult *res)
Definition: command.c:3663
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
bool appendReloptionsArray(PQExpBuffer buffer, const char *reloptions, const char *prefix, int encoding, bool std_strings)
Definition: string_utils.c:731
void psql_error(const char *fmt,...)
Definition: common.c:177
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
void PQclear(PGresult *res)
Definition: fe-exec.c:650
bool standard_strings(void)
Definition: common.c:2008
#define NULL
Definition: c.h:226
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
int encoding
Definition: settings.h:83
static bool echo_hidden_command(const char *query)
Definition: command.c:3272
backslashResult HandleSlashCmds ( PsqlScanState  scan_state,
PQExpBuffer  query_buf 
)

Definition at line 111 of file command.c.

References arg, Assert, _psqlSettings::cur_cmd_interactive, exec_command(), free, NULL, OT_NO_EVAL, OT_WHOLE_LINE, pset, PSQL_CMD_ERROR, PSQL_CMD_SKIP_LINE, PSQL_CMD_UNKNOWN, psql_error(), psql_scan_slash_command(), psql_scan_slash_command_end(), psql_scan_slash_option(), _psqlSettings::queryFout, and status().

Referenced by main(), and MainLoop().

113 {
115  char *cmd;
116  char *arg;
117 
118  Assert(scan_state != NULL);
119 
120  /* Parse off the command name */
121  cmd = psql_scan_slash_command(scan_state);
122 
123  /* And try to execute it */
124  status = exec_command(cmd, scan_state, query_buf);
125 
126  if (status == PSQL_CMD_UNKNOWN)
127  {
129  psql_error("Invalid command \\%s. Try \\? for help.\n", cmd);
130  else
131  psql_error("invalid command \\%s\n", cmd);
132  status = PSQL_CMD_ERROR;
133  }
134 
135  if (status != PSQL_CMD_ERROR)
136  {
137  /* eat any remaining arguments after a valid command */
138  /* note we suppress evaluation of backticks here */
139  while ((arg = psql_scan_slash_option(scan_state,
140  OT_NO_EVAL, NULL, false)))
141  {
142  psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
143  free(arg);
144  }
145  }
146  else
147  {
148  /* silently throw away rest of line after an erroneous command */
149  while ((arg = psql_scan_slash_option(scan_state,
150  OT_WHOLE_LINE, NULL, false)))
151  free(arg);
152  }
153 
154  /* if there is a trailing \\, swallow it */
155  psql_scan_slash_command_end(scan_state);
156 
157  free(cmd);
158 
159  /* some commands write to queryFout, so make sure output is sent */
160  fflush(pset.queryFout);
161 
162  return status;
163 }
void psql_scan_slash_command_end(PsqlScanState state)
PsqlSettings pset
Definition: startup.c:37
char * psql_scan_slash_command(PsqlScanState state)
static backslashResult exec_command(const char *cmd, PsqlScanState scan_state, PQExpBuffer query_buf)
Definition: command.c:202
FILE * queryFout
Definition: settings.h:84
bool cur_cmd_interactive
Definition: settings.h:104
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
void psql_error(const char *fmt,...)
Definition: common.c:177
#define free(a)
Definition: header.h:60
enum _backslashResult backslashResult
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void * arg
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222
static bool lookup_object_oid ( EditableObjectType  obj_type,
const char *  desc,
Oid obj_oid 
)
static

Definition at line 3304 of file command.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), appendStringLiteralConn(), atooid, createPQExpBuffer(), PQExpBufferData::data, _psqlSettings::db, destroyPQExpBuffer(), echo_hidden_command(), EditableFunction, EditableView, minimal_error_message(), PGRES_TUPLES_OK, PQclear(), PQexec(), PQgetvalue(), PQntuples(), PQresultStatus(), and pset.

Referenced by exec_command().

3306 {
3307  bool result = true;
3308  PQExpBuffer query = createPQExpBuffer();
3309  PGresult *res;
3310 
3311  switch (obj_type)
3312  {
3313  case EditableFunction:
3314 
3315  /*
3316  * We have a function description, e.g. "x" or "x(int)". Issue a
3317  * query to retrieve the function's OID using a cast to regproc or
3318  * regprocedure (as appropriate).
3319  */
3320  appendPQExpBufferStr(query, "SELECT ");
3321  appendStringLiteralConn(query, desc, pset.db);
3322  appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
3323  strchr(desc, '(') ? "regprocedure" : "regproc");
3324  break;
3325 
3326  case EditableView:
3327 
3328  /*
3329  * Convert view name (possibly schema-qualified) to OID. Note:
3330  * this code doesn't check if the relation is actually a view.
3331  * We'll detect that in get_create_object_cmd().
3332  */
3333  appendPQExpBufferStr(query, "SELECT ");
3334  appendStringLiteralConn(query, desc, pset.db);
3335  appendPQExpBuffer(query, "::pg_catalog.regclass::pg_catalog.oid");
3336  break;
3337  }
3338 
3339  if (!echo_hidden_command(query->data))
3340  {
3341  destroyPQExpBuffer(query);
3342  return false;
3343  }
3344  res = PQexec(pset.db, query->data);
3345  if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
3346  *obj_oid = atooid(PQgetvalue(res, 0, 0));
3347  else
3348  {
3349  minimal_error_message(res);
3350  result = false;
3351  }
3352 
3353  PQclear(res);
3354  destroyPQExpBuffer(query);
3355 
3356  return result;
3357 }
PGconn * db
Definition: settings.h:82
PsqlSettings pset
Definition: startup.c:37
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
static void minimal_error_message(PGresult *res)
Definition: command.c:3663
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
void PQclear(PGresult *res)
Definition: fe-exec.c:650
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:298
#define atooid(x)
Definition: lo.c:17
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1846
static bool echo_hidden_command(const char *query)
Definition: command.c:3272
static void minimal_error_message ( PGresult res)
static

Definition at line 3663 of file command.c.

References appendPQExpBufferStr(), createPQExpBuffer(), PQExpBufferData::data, destroyPQExpBuffer(), PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SEVERITY, PQresultErrorField(), printfPQExpBuffer(), and psql_error().

Referenced by get_create_object_cmd(), and lookup_object_oid().

3664 {
3665  PQExpBuffer msg;
3666  const char *fld;
3667 
3668  msg = createPQExpBuffer();
3669 
3671  if (fld)
3672  printfPQExpBuffer(msg, "%s: ", fld);
3673  else
3674  printfPQExpBuffer(msg, "ERROR: ");
3676  if (fld)
3677  appendPQExpBufferStr(msg, fld);
3678  else
3679  appendPQExpBufferStr(msg, "(not available)");
3680  appendPQExpBufferStr(msg, "\n");
3681 
3682  psql_error("%s", msg->data);
3683 
3684  destroyPQExpBuffer(msg);
3685 }
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:234
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:54
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:51
void psql_error(const char *fmt,...)
Definition: common.c:177
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2658
static bool param_is_newly_set ( const char *  old_val,
const char *  new_val 
)
static

Definition at line 1789 of file command.c.

References NULL.

Referenced by do_connect().

1790 {
1791  if (new_val == NULL)
1792  return false;
1793 
1794  if (old_val == NULL || strcmp(old_val, new_val) != 0)
1795  return true;
1796 
1797  return false;
1798 }
#define NULL
Definition: c.h:226
static void print_with_linenumbers ( FILE *  output,
char *  lines,
const char *  header_keyword 
)
static

Definition at line 3622 of file command.c.

References NULL.

Referenced by exec_command().

3624 {
3625  bool in_header = (header_keyword != NULL);
3626  size_t header_sz = in_header ? strlen(header_keyword) : 0;
3627  int lineno = 0;
3628 
3629  while (*lines != '\0')
3630  {
3631  char *eol;
3632 
3633  if (in_header && strncmp(lines, header_keyword, header_sz) == 0)
3634  in_header = false;
3635 
3636  /* increment lineno only for body's lines */
3637  if (!in_header)
3638  lineno++;
3639 
3640  /* find and mark end of current line */
3641  eol = strchr(lines, '\n');
3642  if (eol != NULL)
3643  *eol = '\0';
3644 
3645  /* show current line as appropriate */
3646  if (in_header)
3647  fprintf(output, " %s\n", lines);
3648  else
3649  fprintf(output, "%-7d %s\n", lineno, lines);
3650 
3651  /* advance to next line, if any */
3652  if (eol == NULL)
3653  break;
3654  lines = ++eol;
3655  }
3656 }
static void output(uint64 loop_count)
#define NULL
Definition: c.h:226
static bool printPsetInfo ( const char *  param,
struct printQueryOpt popt 
)
static

Definition at line 2832 of file command.c.

References _, _align2string(), _unicode_linestyle2string(), Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::fieldSep, printTableOpt::format, get_line_style(), printTextFormat::name, ngettext, NULL, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, psql_error(), printTableOpt::recordSep, separator::separator, separator::separator_zero, printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, and printTableOpt::unicode_header_linestyle.

Referenced by do_pset().

2833 {
2834  Assert(param != NULL);
2835 
2836  /* show border style/width */
2837  if (strcmp(param, "border") == 0)
2838  printf(_("Border style is %d.\n"), popt->topt.border);
2839 
2840  /* show the target width for the wrapped format */
2841  else if (strcmp(param, "columns") == 0)
2842  {
2843  if (!popt->topt.columns)
2844  printf(_("Target width is unset.\n"));
2845  else
2846  printf(_("Target width is %d.\n"), popt->topt.columns);
2847  }
2848 
2849  /* show expanded/vertical mode */
2850  else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
2851  {
2852  if (popt->topt.expanded == 1)
2853  printf(_("Expanded display is on.\n"));
2854  else if (popt->topt.expanded == 2)
2855  printf(_("Expanded display is used automatically.\n"));
2856  else
2857  printf(_("Expanded display is off.\n"));
2858  }
2859 
2860  /* show field separator for unaligned text */
2861  else if (strcmp(param, "fieldsep") == 0)
2862  {
2863  if (popt->topt.fieldSep.separator_zero)
2864  printf(_("Field separator is zero byte.\n"));
2865  else
2866  printf(_("Field separator is \"%s\".\n"),
2867  popt->topt.fieldSep.separator);
2868  }
2869 
2870  else if (strcmp(param, "fieldsep_zero") == 0)
2871  {
2872  printf(_("Field separator is zero byte.\n"));
2873  }
2874 
2875  /* show disable "(x rows)" footer */
2876  else if (strcmp(param, "footer") == 0)
2877  {
2878  if (popt->topt.default_footer)
2879  printf(_("Default footer is on.\n"));
2880  else
2881  printf(_("Default footer is off.\n"));
2882  }
2883 
2884  /* show format */
2885  else if (strcmp(param, "format") == 0)
2886  {
2887  printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
2888  }
2889 
2890  /* show table line style */
2891  else if (strcmp(param, "linestyle") == 0)
2892  {
2893  printf(_("Line style is %s.\n"),
2894  get_line_style(&popt->topt)->name);
2895  }
2896 
2897  /* show null display */
2898  else if (strcmp(param, "null") == 0)
2899  {
2900  printf(_("Null display is \"%s\".\n"),
2901  popt->nullPrint ? popt->nullPrint : "");
2902  }
2903 
2904  /* show locale-aware numeric output */
2905  else if (strcmp(param, "numericlocale") == 0)
2906  {
2907  if (popt->topt.numericLocale)
2908  printf(_("Locale-adjusted numeric output is on.\n"));
2909  else
2910  printf(_("Locale-adjusted numeric output is off.\n"));
2911  }
2912 
2913  /* show toggle use of pager */
2914  else if (strcmp(param, "pager") == 0)
2915  {
2916  if (popt->topt.pager == 1)
2917  printf(_("Pager is used for long output.\n"));
2918  else if (popt->topt.pager == 2)
2919  printf(_("Pager is always used.\n"));
2920  else
2921  printf(_("Pager usage is off.\n"));
2922  }
2923 
2924  /* show minimum lines for pager use */
2925  else if (strcmp(param, "pager_min_lines") == 0)
2926  {
2927  printf(ngettext("Pager won't be used for less than %d line.\n",
2928  "Pager won't be used for less than %d lines.\n",
2929  popt->topt.pager_min_lines),
2930  popt->topt.pager_min_lines);
2931  }
2932 
2933  /* show record separator for unaligned text */
2934  else if (strcmp(param, "recordsep") == 0)
2935  {
2936  if (popt->topt.recordSep.separator_zero)
2937  printf(_("Record separator is zero byte.\n"));
2938  else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
2939  printf(_("Record separator is <newline>.\n"));
2940  else
2941  printf(_("Record separator is \"%s\".\n"),
2942  popt->topt.recordSep.separator);
2943  }
2944 
2945  else if (strcmp(param, "recordsep_zero") == 0)
2946  {
2947  printf(_("Record separator is zero byte.\n"));
2948  }
2949 
2950  /* show HTML table tag options */
2951  else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2952  {
2953  if (popt->topt.tableAttr)
2954  printf(_("Table attributes are \"%s\".\n"),
2955  popt->topt.tableAttr);
2956  else
2957  printf(_("Table attributes unset.\n"));
2958  }
2959 
2960  /* show title override */
2961  else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
2962  {
2963  if (popt->title)
2964  printf(_("Title is \"%s\".\n"), popt->title);
2965  else
2966  printf(_("Title is unset.\n"));
2967  }
2968 
2969  /* show toggle between full and tuples-only format */
2970  else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
2971  {
2972  if (popt->topt.tuples_only)
2973  printf(_("Tuples only is on.\n"));
2974  else
2975  printf(_("Tuples only is off.\n"));
2976  }
2977 
2978  /* Unicode style formatting */
2979  else if (strcmp(param, "unicode_border_linestyle") == 0)
2980  {
2981  printf(_("Unicode border line style is \"%s\".\n"),
2983  }
2984 
2985  else if (strcmp(param, "unicode_column_linestyle") == 0)
2986  {
2987  printf(_("Unicode column line style is \"%s\".\n"),
2989  }
2990 
2991  else if (strcmp(param, "unicode_header_linestyle") == 0)
2992  {
2993  printf(_("Unicode header line style is \"%s\".\n"),
2995  }
2996 
2997  else
2998  {
2999  psql_error("\\pset: unknown option: %s\n", param);
3000  return false;
3001  }
3002 
3003  return true;
3004 }
char * nullPrint
Definition: print.h:166
enum printFormat format
Definition: print.h:98
printTableOpt topt
Definition: print.h:165
unicode_linestyle unicode_header_linestyle
Definition: print.h:123
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:2541
const char * name
Definition: print.h:69
bool separator_zero
Definition: print.h:93
unicode_linestyle unicode_border_linestyle
Definition: print.h:121
unsigned short int border
Definition: print.h:101
unsigned short int expanded
Definition: print.h:99
unicode_linestyle unicode_column_linestyle
Definition: print.h:122
bool tuples_only
Definition: print.h:107
char * tableAttr
Definition: print.h:117
#define ngettext(s, p, n)
Definition: c.h:127
void psql_error(const char *fmt,...)
Definition: common.c:177
unsigned short int pager
Definition: print.h:103
struct separator fieldSep
Definition: print.h:113
const printTextFormat * get_line_style(const printTableOpt *opt)
Definition: print.c:3413
char * title
Definition: print.h:167
int pager_min_lines
Definition: print.h:105
bool default_footer
Definition: print.h:110
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
bool numericLocale
Definition: print.h:115
static const char * _align2string(enum printFormat in)
Definition: command.c:2488
char * separator
Definition: print.h:92
struct separator recordSep
Definition: print.h:114
int columns
Definition: print.h:120
#define _(x)
Definition: elog.c:84
static void printSSLInfo ( void  )
static

Definition at line 2098 of file command.c.

References _, _psqlSettings::db, PQsslAttribute(), PQsslInUse(), and pset.

Referenced by connection_warnings(), and exec_command().

2099 {
2100  const char *protocol;
2101  const char *cipher;
2102  const char *bits;
2103  const char *compression;
2104 
2105  if (!PQsslInUse(pset.db))
2106  return; /* no SSL */
2107 
2108  protocol = PQsslAttribute(pset.db, "protocol");
2109  cipher = PQsslAttribute(pset.db, "cipher");
2110  bits = PQsslAttribute(pset.db, "key_bits");
2111  compression = PQsslAttribute(pset.db, "compression");
2112 
2113  printf(_("SSL connection (protocol: %s, cipher: %s, bits: %s, compression: %s)\n"),
2114  protocol ? protocol : _("unknown"),
2115  cipher ? cipher : _("unknown"),
2116  bits ? bits : _("unknown"),
2117  (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"));
2118 }
PGconn * db
Definition: settings.h:82
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
PsqlSettings pset
Definition: startup.c:37
int PQsslInUse(PGconn *conn)
#define _(x)
Definition: elog.c:84
int process_file ( char *  filename,
bool  use_relative_path 
)

Definition at line 2426 of file command.c.

References canonicalize_path(), EXIT_FAILURE, fd(), filename, get_parent_directory(), has_drive_prefix(), _psqlSettings::inputfile, is_absolute_path, join_path_components(), MainLoop(), MAXPGPATH, NULL, PG_BINARY_R, pset, psql_error(), relpath, strerror(), and strlcpy().

Referenced by exec_command().

2427 {
2428  FILE *fd;
2429  int result;
2430  char *oldfilename;
2431  char relpath[MAXPGPATH];
2432 
2433  if (!filename)
2434  {
2435  fd = stdin;
2436  filename = NULL;
2437  }
2438  else if (strcmp(filename, "-") != 0)
2439  {
2441 
2442  /*
2443  * If we were asked to resolve the pathname relative to the location
2444  * of the currently executing script, and there is one, and this is a
2445  * relative pathname, then prepend all but the last pathname component
2446  * of the current script to this pathname.
2447  */
2448  if (use_relative_path && pset.inputfile &&
2450  {
2451  strlcpy(relpath, pset.inputfile, sizeof(relpath));
2452  get_parent_directory(relpath);
2453  join_path_components(relpath, relpath, filename);
2454  canonicalize_path(relpath);
2455 
2456  filename = relpath;
2457  }
2458 
2459  fd = fopen(filename, PG_BINARY_R);
2460 
2461  if (!fd)
2462  {
2463  psql_error("%s: %s\n", filename, strerror(errno));
2464  return EXIT_FAILURE;
2465  }
2466  }
2467  else
2468  {
2469  fd = stdin;
2470  filename = "<stdin>"; /* for future error messages */
2471  }
2472 
2473  oldfilename = pset.inputfile;
2475 
2476  result = MainLoop(fd);
2477 
2478  if (fd != stdin)
2479  fclose(fd);
2480 
2481  pset.inputfile = oldfilename;
2482  return result;
2483 }
PsqlSettings pset
Definition: startup.c:37
void canonicalize_path(char *path)
Definition: path.c:254
char * inputfile
Definition: settings.h:107
#define PG_BINARY_R
Definition: c.h:1040
static int fd(const char *x, int i)
Definition: preproc-init.c:105
bool has_drive_prefix(const char *filename)
Definition: path.c:87
#define MAXPGPATH
#define is_absolute_path(filename)
Definition: port.h:77
void get_parent_directory(char *path)
Definition: path.c:854
void psql_error(const char *fmt,...)
Definition: common.c:177
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:226
int MainLoop(FILE *source)
Definition: mainloop.c:35
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:218
static char * filename
Definition: pg_dumpall.c:84
const char * strerror(int errnum)
Definition: strerror.c:19
#define relpath(rnode, forknum)
Definition: relpath.h:71
#define EXIT_FAILURE
Definition: settings.h:150
static char* prompt_for_password ( const char *  username)
static

Definition at line 1771 of file command.c.

References _, buf, free, NULL, pg_strdup(), psprintf(), and simple_prompt().

Referenced by do_connect().

1772 {
1773  char buf[100];
1774 
1775  if (username == NULL)
1776  simple_prompt("Password: ", buf, sizeof(buf), false);
1777  else
1778  {
1779  char *prompt_text;
1780 
1781  prompt_text = psprintf(_("Password for user %s: "), username);
1782  simple_prompt(prompt_text, buf, sizeof(buf), false);
1783  free(prompt_text);
1784  }
1785  return pg_strdup(buf);
1786 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static char * buf
Definition: pg_test_fsync.c:65
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * username
Definition: initdb.c:130
#define free(a)
Definition: header.h:60
#define NULL
Definition: c.h:226
#define _(x)
Definition: elog.c:84
static const char* pset_bool_string ( bool  val)
static

Definition at line 3008 of file command.c.

Referenced by pset_value_string().

3009 {
3010  return val ? "on" : "off";
3011 }
long val
Definition: informix.c:689
static char* pset_quoted_string ( const char *  str)
static

Definition at line 3015 of file command.c.

References pg_malloc().

Referenced by pset_value_string().

3016 {
3017  char *ret = pg_malloc(strlen(str) * 2 + 3);
3018  char *r = ret;
3019 
3020  *r++ = '\'';
3021 
3022  for (; *str; str++)
3023  {
3024  if (*str == '\n')
3025  {
3026  *r++ = '\\';
3027  *r++ = 'n';
3028  }
3029  else if (*str == '\'')
3030  {
3031  *r++ = '\\';
3032  *r++ = '\'';
3033  }
3034  else
3035  *r++ = *str;
3036  }
3037 
3038  *r++ = '\'';
3039  *r = '\0';
3040 
3041  return ret;
3042 }
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
static char * pset_value_string ( const char *  param,
struct printQueryOpt popt 
)
static

Definition at line 3053 of file command.c.

References _align2string(), _unicode_linestyle2string(), Assert, printTableOpt::border, printTableOpt::columns, printTableOpt::default_footer, printTableOpt::expanded, printTableOpt::fieldSep, printTableOpt::format, get_line_style(), printTextFormat::name, NULL, printQueryOpt::nullPrint, printTableOpt::numericLocale, printTableOpt::pager, printTableOpt::pager_min_lines, pset_bool_string(), pset_quoted_string(), psprintf(), pstrdup(), printTableOpt::recordSep, separator::separator, separator::separator_zero, printTableOpt::tableAttr, printQueryOpt::title, printQueryOpt::topt, printTableOpt::tuples_only, printTableOpt::unicode_border_linestyle, printTableOpt::unicode_column_linestyle, and printTableOpt::unicode_header_linestyle.

Referenced by exec_command().

3054 {
3055  Assert(param != NULL);
3056 
3057  if (strcmp(param, "border") == 0)
3058  return psprintf("%d", popt->topt.border);
3059  else if (strcmp(param, "columns") == 0)
3060  return psprintf("%d", popt->topt.columns);
3061  else if (strcmp(param, "expanded") == 0)
3062  return pstrdup(popt->topt.expanded == 2
3063  ? "auto"
3064  : pset_bool_string(popt->topt.expanded));
3065  else if (strcmp(param, "fieldsep") == 0)
3067  ? popt->topt.fieldSep.separator
3068  : "");
3069  else if (strcmp(param, "fieldsep_zero") == 0)
3071  else if (strcmp(param, "footer") == 0)
3073  else if (strcmp(param, "format") == 0)
3074  return psprintf("%s", _align2string(popt->topt.format));
3075  else if (strcmp(param, "linestyle") == 0)
3076  return psprintf("%s", get_line_style(&popt->topt)->name);
3077  else if (strcmp(param, "null") == 0)
3078  return pset_quoted_string(popt->nullPrint
3079  ? popt->nullPrint
3080  : "");
3081  else if (strcmp(param, "numericlocale") == 0)
3082  return pstrdup(pset_bool_string(popt->topt.numericLocale));
3083  else if (strcmp(param, "pager") == 0)
3084  return psprintf("%d", popt->topt.pager);
3085  else if (strcmp(param, "pager_min_lines") == 0)
3086  return psprintf("%d", popt->topt.pager_min_lines);
3087  else if (strcmp(param, "recordsep") == 0)
3089  ? popt->topt.recordSep.separator
3090  : "");
3091  else if (strcmp(param, "recordsep_zero") == 0)
3093  else if (strcmp(param, "tableattr") == 0)
3094  return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
3095  else if (strcmp(param, "title") == 0)
3096  return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
3097  else if (strcmp(param, "tuples_only") == 0)
3098  return pstrdup(pset_bool_string(popt->topt.tuples_only));
3099  else if (strcmp(param, "unicode_border_linestyle") == 0)
3101  else if (strcmp(param, "unicode_column_linestyle") == 0)
3103  else if (strcmp(param, "unicode_header_linestyle") == 0)
3105  else
3106  return pstrdup("ERROR");
3107 }
char * nullPrint
Definition: print.h:166
char * pstrdup(const char *in)
Definition: mcxt.c:1165
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
enum printFormat format
Definition: print.h:98
printTableOpt topt
Definition: print.h:165
unicode_linestyle unicode_header_linestyle
Definition: print.h:123
static const char * _unicode_linestyle2string(int linestyle)
Definition: command.c:2541
const char * name
Definition: print.h:69
bool separator_zero
Definition: print.h:93
unicode_linestyle unicode_border_linestyle
Definition: print.h:121
unsigned short int border
Definition: print.h:101
unsigned short int expanded
Definition: print.h:99
static const char * pset_bool_string(bool val)
Definition: command.c:3008
unicode_linestyle unicode_column_linestyle
Definition: print.h:122
bool tuples_only
Definition: print.h:107
char * tableAttr
Definition: print.h:117
unsigned short int pager
Definition: print.h:103
struct separator fieldSep
Definition: print.h:113
const printTextFormat * get_line_style(const printTableOpt *opt)
Definition: print.c:3413
char * title
Definition: print.h:167
int pager_min_lines
Definition: print.h:105
bool default_footer
Definition: print.h:110
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
bool numericLocale
Definition: print.h:115
static const char * _align2string(enum printFormat in)
Definition: command.c:2488
char * separator
Definition: print.h:92
struct separator recordSep
Definition: print.h:114
int columns
Definition: print.h:120
static char * pset_quoted_string(const char *str)
Definition: command.c:3015
static char* read_connect_arg ( PsqlScanState  scan_state)
static

Definition at line 169 of file command.c.

References NULL, OT_SQLIDHACK, and psql_scan_slash_option().

Referenced by exec_command().

170 {
171  char *result;
172  char quote;
173 
174  /*
175  * Ideally we should treat the arguments as SQL identifiers. But for
176  * backwards compatibility with 7.2 and older pg_dump files, we have to
177  * take unquoted arguments verbatim (don't downcase them). For now,
178  * double-quoted arguments may be stripped of double quotes (as if SQL
179  * identifiers). By 7.4 or so, pg_dump files can be expected to
180  * double-quote all mixed-case \connect arguments, and then we can get rid
181  * of OT_SQLIDHACK.
182  */
183  result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
184 
185  if (!result)
186  return NULL;
187 
188  if (quote)
189  return result;
190 
191  if (*result == '\0' || strcmp(result, "-") == 0)
192  return NULL;
193 
194  return result;
195 }
char * psql_scan_slash_option(PsqlScanState state, enum slash_option_type type, char *quote, bool semicolon)
#define NULL
Definition: c.h:226
static bool set_unicode_line_style ( const char *  value,
size_t  vallen,
unicode_linestyle linestyle 
)
static

Definition at line 2528 of file command.c.

References pg_strncasecmp(), UNICODE_LINESTYLE_DOUBLE, and UNICODE_LINESTYLE_SINGLE.

Referenced by do_pset().

2530 {
2531  if (pg_strncasecmp("single", value, vallen) == 0)
2532  *linestyle = UNICODE_LINESTYLE_SINGLE;
2533  else if (pg_strncasecmp("double", value, vallen) == 0)
2534  *linestyle = UNICODE_LINESTYLE_DOUBLE;
2535  else
2536  return false;
2537  return true;
2538 }
static struct @76 value
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
static int strip_lineno_from_objdesc ( char *  obj)
static

Definition at line 3537 of file command.c.

References psql_error().

Referenced by exec_command().

3538 {
3539  char *c;
3540  int lineno;
3541 
3542  if (!obj || obj[0] == '\0')
3543  return -1;
3544 
3545  c = obj + strlen(obj) - 1;
3546 
3547  /*
3548  * This business of parsing backwards is dangerous as can be in a
3549  * multibyte environment: there is no reason to believe that we are
3550  * looking at the first byte of a character, nor are we necessarily
3551  * working in a "safe" encoding. Fortunately the bitpatterns we are
3552  * looking for are unlikely to occur as non-first bytes, but beware of
3553  * trying to expand the set of cases that can be recognized. We must
3554  * guard the <ctype.h> macros by using isascii() first, too.
3555  */
3556 
3557  /* skip trailing whitespace */
3558  while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
3559  c--;
3560 
3561  /* must have a digit as last non-space char */
3562  if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
3563  return -1;
3564 
3565  /* find start of digit string */
3566  while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
3567  c--;
3568 
3569  /* digits must be separated from object name by space or closing paren */
3570  /* notice also that we are not allowing an empty object name ... */
3571  if (c == obj || !isascii((unsigned char) *c) ||
3572  !(isspace((unsigned char) *c) || *c == ')'))
3573  return -1;
3574 
3575  /* parse digit string */
3576  c++;
3577  lineno = atoi(c);
3578  if (lineno < 1)
3579  {
3580  psql_error("invalid line number: %s\n", c);
3581  return 0;
3582  }
3583 
3584  /* strip digit string from object name */
3585  *c = '\0';
3586 
3587  return lineno;
3588 }
char * c
void psql_error(const char *fmt,...)
Definition: common.c:177
void SyncVariables ( void  )

Definition at line 2153 of file command.c.

References _psqlSettings::db, _psqlSettings::encoding, printTableOpt::encoding, pg_encoding_to_char(), _psqlSettings::popt, PQclientEncoding(), PQdb(), PQhost(), PQport(), PQserverVersion(), PQsetErrorContextVisibility(), PQsetErrorVerbosity(), PQuser(), pset, SetVariable(), _psqlSettings::show_context, _psqlSettings::sversion, printQueryOpt::topt, _psqlSettings::vars, and _psqlSettings::verbosity.

Referenced by do_connect(), and main().

2154 {
2155  /* get stuff from connection */
2159 
2160  SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
2161  SetVariable(pset.vars, "USER", PQuser(pset.db));
2162  SetVariable(pset.vars, "HOST", PQhost(pset.db));
2163  SetVariable(pset.vars, "PORT", PQport(pset.db));
2165 
2166  /* send stuff to it, too */
2169 }
PGconn * db
Definition: settings.h:82
int encoding
Definition: print.h:118
PsqlSettings pset
Definition: startup.c:37
printTableOpt topt
Definition: print.h:165
char * PQport(const PGconn *conn)
Definition: fe-connect.c:5881
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:5950
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6020
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:5836
PGContextVisibility show_context
Definition: settings.h:139
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:6086
PGVerbosity verbosity
Definition: settings.h:138
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:5861
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:531
char * PQdb(const PGconn *conn)
Definition: fe-connect.c:5828
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
printQueryOpt popt
Definition: settings.h:91
int encoding
Definition: settings.h:83
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:6074
VariableSpace vars
Definition: settings.h:115
void UnsyncVariables ( void  )

Definition at line 2177 of file command.c.

References NULL, pset, SetVariable(), and _psqlSettings::vars.

Referenced by CheckConnection().

2178 {
2179  SetVariable(pset.vars, "DBNAME", NULL);
2180  SetVariable(pset.vars, "USER", NULL);
2181  SetVariable(pset.vars, "HOST", NULL);
2182  SetVariable(pset.vars, "PORT", NULL);
2183  SetVariable(pset.vars, "ENCODING", NULL);
2184 }
PsqlSettings pset
Definition: startup.c:37
#define NULL
Definition: c.h:226
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
VariableSpace vars
Definition: settings.h:115