psql.c 53.3 KB
Newer Older
Bruce Momjian's avatar
Bruce Momjian committed
1
/*-------------------------------------------------------------------------
2 3
 *
 * psql.c--
Bruce Momjian's avatar
Bruce Momjian committed
4
 *    an interactive front-end to postgreSQL
5 6 7 8 9
 *
 * Copyright (c) 1996, Regents of the University of California
 *
 *
 * IDENTIFICATION
Bruce Momjian's avatar
Bruce Momjian committed
10
 *    $Header: /cvsroot/pgsql/src/bin/psql/Attic/psql.c,v 1.77 1997/07/14 22:08:56 momjian Exp $
11 12 13 14
 *
 *-------------------------------------------------------------------------
 */
#include <stdio.h>
15
#include <stdlib.h>
16 17
#include <string.h>
#include <signal.h>
Bruce Momjian's avatar
Bruce Momjian committed
18
#include <errno.h>
19
#include <sys/types.h>
20
#include <sys/param.h>	/* for MAXPATHLEN */
21
#include <sys/stat.h>
22
#include <unistd.h>
23
#include <fcntl.h>
24
#include <ctype.h>
Bruce Momjian's avatar
Bruce Momjian committed
25
#include "postgres.h"
26
#include "libpq-fe.h"
27
#include "pqsignal.h"
28 29
#include "stringutils.h"
#include "psqlHelp.h"
30
#ifndef HAVE_STRDUP
31 32
#include "strdup.h"
#endif
33 34 35
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
36

37
#ifdef HAVE_LIBREADLINE
38 39
# ifdef HAVE_READLINE_H
#  include <readline.h>
40
#  if defined(HAVE_HISTORY) || defined(HAVE_LIBHISTORY)
41 42
#   include <history.h>
#  endif
43 44
# else
#  include <readline/readline.h>
45
#  if defined(HAVE_HISTORY) || defined(HAVE_LIBHISTORY)
46 47
#   include <readline/history.h>
#  endif
48
# endif
49 50
#endif

51 52
#define PROMPT "=> "

53 54
#define MAX_QUERY_BUFFER 20000

55
#define COPYBUFSIZ  8192
56

57
#define DEFAULT_FIELD_SEP "|"
58 59 60 61
#define DEFAULT_EDITOR  "vi"
#define DEFAULT_SHELL  "/bin/sh"

typedef struct _psqlSettings {
62 63 64 65 66 67 68 69 70 71 72 73
    PGconn         *db;		/* connection to backend */
    FILE           *queryFout;	/* where to send the query results */
    PQprintOpt      opt;	/* options to be passed to PQprint */
    char           *prompt;	/* prompt to display */
    char           *gfname;	/* one-shot file output argument for \g */
    bool            notty;	/* input or output is not a tty */
    bool            pipe;	/* queryFout is from a popen() */
    bool            echoQuery;	/* echo the query before sending it */
    bool            quiet;	/* run quietly, no messages, no promt */
    bool            singleStep;	/* prompt before for each query */
    bool            singleLineMode;	/* query terminated by newline */
    bool            useReadline;/* use libreadline routines */
74
    bool            getPassword;/* prompt the user for a username and password */
75
}               PsqlSettings;
76 77

/* declarations for functions in this file */
78 79 80 81 82 83
static void     usage(char *progname);
static void     slashUsage();
static void     handleCopyOut(PGresult * res, bool quiet, FILE * copystream);
static void
handleCopyIn(PGresult * res, const bool mustprompt,
	     FILE * copystream);
84
static int      tableList(PsqlSettings * ps, bool deep_tablelist, char info_type);
85
static int      tableDesc(PsqlSettings * ps, char *table);
86
static int	rightsList(PsqlSettings * ps);
87 88 89
static void     prompt_for_password(char *username, char *password);
static char *   make_connect_string(char *host, char *port, char *dbname,
				    char *username, char *password);
90 91 92 93 94 95 96 97 98 99 100 101 102

char           *gets_noreadline(char *prompt, FILE * source);
char           *gets_readline(char *prompt, FILE * source);
char           *gets_fromFile(char *prompt, FILE * source);
int             listAllDbs(PsqlSettings * settings);
void
SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
	  const bool copy_in, const bool copy_out, FILE * copystream);
int
HandleSlashCmds(PsqlSettings * settings,
		char *line,
		char *query);
int             MainLoop(PsqlSettings * settings, FILE * source);
103
/* probably should move this into libpq */
104 105 106 107 108
void
PQprint(FILE * fp,
	PGresult * res,
	PQprintOpt * po
);
109

110
FILE           *setFout(PsqlSettings * ps, char *fname);
111 112

/*
113
 * usage print out usage for command line arguments
114 115
 */

116
static void
117
usage(char *progname)
118
{
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    fprintf(stderr, "Usage: %s [options] [dbname]\n", progname);
    fprintf(stderr, "\t -a authsvc              set authentication service\n");
    fprintf(stderr, "\t -A                      turn off alignment when printing out attributes\n");
    fprintf(stderr, "\t -c query                run single query (slash commands too)\n");
    fprintf(stderr, "\t -d dbName               specify database name\n");
    fprintf(stderr, "\t -e                      echo the query sent to the backend\n");
    fprintf(stderr, "\t -f filename             use file as a source of queries\n");
    fprintf(stderr, "\t -F sep                  set the field separator (default is " ")\n");
    fprintf(stderr, "\t -h host                 set database server host\n");
    fprintf(stderr, "\t -H                      turn on html3.0 table output\n");
    fprintf(stderr, "\t -l                      list available databases\n");
    fprintf(stderr, "\t -n                      don't use readline library\n");
    fprintf(stderr, "\t -o filename             send output to filename or (|pipe)\n");
    fprintf(stderr, "\t -p port                 set port number\n");
    fprintf(stderr, "\t -q                      run quietly (no messages, no prompts)\n");
    fprintf(stderr, "\t -s                      single step mode (prompts for each query)\n");
    fprintf(stderr, "\t -S                      single line mode (i.e. query terminated by newline)\n");
    fprintf(stderr, "\t -t                      turn off printing of headings and row count\n");
137
    fprintf(stderr, "\t -u                      ask for a username and password for authentication\n");
138 139 140
    fprintf(stderr, "\t -T html                 set html3.0 table command options (cf. -H)\n");
    fprintf(stderr, "\t -x                      turn on expanded output (field names on left)\n");
    exit(1);
141 142 143
}

/*
144
 * slashUsage print out usage for the backslash commands
145 146
 */

147 148
static char    *
on(bool f)
149
{
150
    return f ? "on" : "off";
151 152
}

153
static void
154
slashUsage(PsqlSettings * ps)
155
{
156 157
    int ch;
    
158 159 160
    fprintf(stderr, " \\?           -- help\n");
    fprintf(stderr, " \\a           -- toggle field-alignment (currenty %s)\n", on(ps->opt.align));
    fprintf(stderr, " \\C [<captn>] -- set html3 caption (currently '%s')\n", ps->opt.caption ? ps->opt.caption : "");
161
    fprintf(stderr, " \\connect <dbname|-> <user> -- connect to new database (currently '%s')\n", PQdb(ps->db));
162
    fprintf(stderr, " \\copy table {from | to} <fname>\n");
163 164
    fprintf(stderr, " \\d [<table>] -- list tables and indicies in database or columns in <table>, * for all\n");
    fprintf(stderr, " \\di          -- list only indicies in database\n");
165
    fprintf(stderr, " \\ds          -- list only sequences in database\n");
166
    fprintf(stderr, " \\dt          -- list only tables in database\n");
167 168 169 170 171 172 173 174 175 176
    fprintf(stderr, " \\e [<fname>] -- edit the current query buffer or <fname>, \\E execute too\n");
    fprintf(stderr, " \\f [<sep>]   -- change field separater (currently '%s')\n", ps->opt.fieldSep);
    fprintf(stderr, " \\g [<fname>] [|<cmd>] -- send query to backend [and results in <fname> or pipe]\n");
    fprintf(stderr, " \\h [<cmd>]   -- help on syntax of sql commands, * for all commands\n");
    fprintf(stderr, " \\H           -- toggle html3 output (currently %s)\n", on(ps->opt.html3));
    fprintf(stderr, " \\i <fname>   -- read and execute queries from filename\n");
    fprintf(stderr, " \\l           -- list all databases\n");
    fprintf(stderr, " \\m           -- toggle monitor-like table display (currently %s)\n", on(ps->opt.standard));
    fprintf(stderr, " \\o [<fname>] [|<cmd>] -- send all query results to stdout, <fname>, or pipe\n");
    fprintf(stderr, " \\p           -- print the current query buffer\n");
177 178 179 180 181

    fprintf(stderr, "Press ENTER to continue");
    /* eat up any extra characters typed before ENTER */
    while ((ch = fgetc(stdin)) != '\r' && ch != '\n')
    	;
182 183 184 185 186 187
    fprintf(stderr, " \\q           -- quit\n");
    fprintf(stderr, " \\r           -- reset(clear) the query buffer\n");
    fprintf(stderr, " \\s [<fname>] -- print history or save it in <fname>\n");
    fprintf(stderr, " \\t           -- toggle table headings and row count (currently %s)\n", on(ps->opt.header));
    fprintf(stderr, " \\T [<html>]  -- set html3.0 <table ...> options (currently '%s')\n", ps->opt.tableOpt ? ps->opt.tableOpt : "");
    fprintf(stderr, " \\x           -- toggle expanded output (currently %s)\n", on(ps->opt.expanded));
188
    fprintf(stderr, " \\z           -- list current grant/revoke permissions\n");
189
    fprintf(stderr, " \\! [<cmd>]   -- shell escape or command\n");
190 191
}

192
static PGresult *
193
PSQLexec(PsqlSettings * ps, char *query)
194
{
195 196
    PGresult       *res;
    res = PQexec(ps->db, query);
197
    if (!res)
198 199 200 201 202 203 204 205
	fputs(PQerrorMessage(ps->db), stderr);
    else {
	if (PQresultStatus(res) == PGRES_COMMAND_OK ||
	    PQresultStatus(res) == PGRES_TUPLES_OK)
	    return res;
	if (!ps->quiet)
	    fputs(PQerrorMessage(ps->db), stderr);
	PQclear(res);
206 207
    }
    return NULL;
208
}
209 210
/*
 * listAllDbs
211 212 213 214
 * 
 * list all the databases in the system returns 0 if all went well
 * 
 * 
215
 */
216 217

int
218
listAllDbs(PsqlSettings * ps)
219
{
220 221 222 223 224 225 226 227 228 229 230
    PGresult       *results;
    char           *query = "select * from pg_database;";

    if (!(results = PSQLexec(ps, query)))
	return 1;
    else {
	PQprint(ps->queryFout,
		results,
		&ps->opt);
	PQclear(results);
	return 0;
231 232 233 234
    }
}

/*
235 236
 * List The Database Tables returns 0 if all went well
 * 
237 238
 */
int
239
tableList(PsqlSettings * ps, bool deep_tablelist, char info_type)
240
{
241 242 243 244 245 246 247 248 249 250 251
    char            listbuf[256];
    int             nColumns;
    int             i;
    char           *rk;
    char           *rr;

    PGresult       *res;

    listbuf[0] = '\0';
    strcat(listbuf, "SELECT usename, relname, relkind, relhasrules");
    strcat(listbuf, "  FROM pg_class, pg_user ");
252
 	switch (info_type) {
253 254 255 256
 		case 't':	strcat(listbuf, "WHERE ( relkind = 'r') ");
 		 		break;
 		case 'i':	strcat(listbuf, "WHERE ( relkind = 'i') ");
 		  		break;
257 258
 		case 'S':	strcat(listbuf, "WHERE ( relkind = 'S') ");
 		  		break;
259
 		case 'b':
260
 		default:	strcat(listbuf, "WHERE ( relkind = 'r' OR relkind = 'i' OR relkind = 'S') ");
261 262
 		 		break;
 	}
263 264
	strcat(listbuf, "  and relname !~ '^pg_'");
	strcat(listbuf, "  and relname !~ '^xin[vx][0-9]+'");
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /*
     * the usesysid = relowner won't work on stock 1.0 dbs, need to add in
     * the int4oideq function
     */
    strcat(listbuf, "  and usesysid = relowner");
    strcat(listbuf, "  ORDER BY relname ");
    if (!(res = PSQLexec(ps, listbuf)))
	return -1;
    /* first, print out the attribute names */
    nColumns = PQntuples(res);
    if (nColumns > 0) {
	if (deep_tablelist) {
	    /* describe everything here */
	    char          **table;
	    table = (char **) malloc(nColumns * sizeof(char *));
	    if (table == NULL)
		perror("malloc");

	    /* load table table */
	    for (i = 0; i < nColumns; i++) {
		table[i] = (char *) malloc(PQgetlength(res, i, 1) * sizeof(char) + 1);
		if (table[i] == NULL)
		    perror("malloc");
		strcpy(table[i], PQgetvalue(res, i, 1));
	    }

291
	    PQclear(res);  /* PURIFY */
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
	    for (i = 0; i < nColumns; i++) {
		tableDesc(ps, table[i]);
	    }
	    free(table);
	} else {
	    /* Display the information */

	    printf("\nDatabase    = %s\n", PQdb(ps->db));
	    printf(" +------------------+----------------------------------+----------+\n");
	    printf(" |  Owner           |             Relation             |   Type   |\n");
	    printf(" +------------------+----------------------------------+----------+\n");

	    /* next, print out the instances */
	    for (i = 0; i < PQntuples(res); i++) {
		printf(" | %-16.16s", PQgetvalue(res, i, 0));
		printf(" | %-32.32s | ", PQgetvalue(res, i, 1));
		rk = PQgetvalue(res, i, 2);
		rr = PQgetvalue(res, i, 3);
		if (strcmp(rk, "r") == 0)
		    printf("%-8.8s |", (rr[0] == 't') ? "view?" : "table");
		else
313
		if (strcmp(rk, "i") == 0)
314
		    printf("%-8.8s |", "index");
315 316
		else 
		    printf("%-8.8s |", "sequence");
317 318 319 320 321 322 323 324
		printf("\n");
	    }
	    printf(" +------------------+----------------------------------+----------+\n");
	    PQclear(res);
	}
	return (0);

    } else {
325
        PQclear(res);  /* PURIFY */
326
 	switch (info_type) {
327 328 329 330
 		case 't':	fprintf(stderr, "Couldn't find any tables!\n");
 		 		break;
 		case 'i':	fprintf(stderr, "Couldn't find any indicies!\n");
 		  		break;
331 332
		case 'S':	fprintf(stderr, "Couldn't find any sequences!\n");
				break;
333
 		case 'b':
334
 		default:	fprintf(stderr, "Couldn't find any tables, sequences or indicies!\n");
335 336
 		 		break;
 	}
337
	return (-1);
338
    }
339 340
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
/*
 * List Tables Grant/Revoke Permissions returns 0 if all went well
 * 
 */
int
rightsList(PsqlSettings * ps)
{
    char            listbuf[256];
    int             nColumns;
    int             i;

    PGresult       *res;

    listbuf[0] = '\0';
    strcat(listbuf, "SELECT relname, relacl");
    strcat(listbuf, "  FROM pg_class, pg_user ");
    strcat(listbuf, "WHERE ( relkind = 'r' OR relkind = 'i') "); 
    strcat(listbuf, "  and relname !~ '^pg_'");
359
    strcat(listbuf, "  and relname !~ '^xin[vx][0-9]+'");
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    strcat(listbuf, "  and usesysid = relowner");
    strcat(listbuf, "  ORDER BY relname ");
    if (!(res = PSQLexec(ps, listbuf)))
	return -1;
    
    nColumns = PQntuples(res);
    if(nColumns > 0) {
      /* Display the information */
    
      printf("\nDatabase    = %s\n", PQdb(ps->db));
      printf(" +------------------+----------------------------------------------------+\n");
      printf(" |  Relation        |             Grant/Revoke Permissions               |\n");
      printf(" +------------------+----------------------------------------------------+\n");
      
      /* next, print out the instances */
      for (i = 0; i < PQntuples(res); i++) {
         printf(" | %-16.16s", PQgetvalue(res, i, 0));
         printf(" | %-50.50s | ", PQgetvalue(res, i, 1));
         printf("\n");
       }
       printf(" +------------------+----------------------------------------------------+\n");
       PQclear(res);
       return (0);
    } else {
	fprintf(stderr, "Couldn't find any tables!\n");
	return (-1);
    }
}
388
/*
389
 * Describe a table
390 391 392 393
 * 
 * Describe the columns in a database table. returns 0 if all went well
 * 
 * 
394 395
 */
int
396
tableDesc(PsqlSettings * ps, char *table)
397
{
398 399 400 401 402 403 404 405 406 407
    char            descbuf[256];
    int             nColumns;
    char           *rtype;
    int             i;
    int             rsize;

    PGresult       *res;

    /* Build the query */

408 409 410 411
    for(i = strlen(table); i >= 0; i--)
	if (isupper(table[i]))
	    table[i] = tolower(table[i]);

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    descbuf[0] = '\0';
    strcat(descbuf, "SELECT a.attnum, a.attname, t.typname, a.attlen");
    strcat(descbuf, "  FROM pg_class c, pg_attribute a, pg_type t ");
    strcat(descbuf, "    WHERE c.relname = '");
    strcat(descbuf, table);
    strcat(descbuf, "'");
    strcat(descbuf, "    and a.attnum > 0 ");
    strcat(descbuf, "    and a.attrelid = c.oid ");
    strcat(descbuf, "    and a.atttypid = t.oid ");
    strcat(descbuf, "  ORDER BY attnum ");
    if (!(res = PSQLexec(ps, descbuf)))
	return -1;
    /* first, print out the attribute names */
    nColumns = PQntuples(res);
    if (nColumns > 0) {
	/*
	 * * Display the information
	 */

	printf("\nTable    = %s\n", table);
	printf("+----------------------------------+----------------------------------+-------+\n");
	printf("|              Field               |              Type                | Length|\n");
	printf("+----------------------------------+----------------------------------+-------+\n");

	/* next, print out the instances */
	for (i = 0; i < PQntuples(res); i++) {
	    printf("| %-32.32s | ", PQgetvalue(res, i, 1));
	    rtype = PQgetvalue(res, i, 2);
	    rsize = atoi(PQgetvalue(res, i, 3));
	    if (strcmp(rtype, "text") == 0) {
		printf("%-32.32s |", rtype);
		printf("%6s |", "var");
	    } else if (strcmp(rtype, "bpchar") == 0) {
		printf("%-32.32s |", "(bp)char");
		printf("%6i |", rsize > 0 ? rsize - 4 : 0);
	    } else if (strcmp(rtype, "varchar") == 0) {
		printf("%-32.32s |", rtype);
		printf("%6i |", rsize > 0 ? rsize - 4 : 0);
	    } else {
		/* array types start with an underscore */
		if (rtype[0] != '_')
		    printf("%-32.32s |", rtype);
		else {
		    char           *newname;
		    newname = malloc(strlen(rtype) + 2);
		    strcpy(newname, rtype + 1);
		    strcat(newname, "[]");
		    printf("%-32.32s |", newname);
		    free(newname);
		}
		if (rsize > 0)
		    printf("%6i |", rsize);
		else
		    printf("%6s |", "var");
	    }
	    printf("\n");
	}
	printf("+----------------------------------+----------------------------------+-------+\n");

	PQclear(res);
	return (0);

    } else {
	fprintf(stderr, "Couldn't find table %s!\n", table);
	return (-1);
477 478 479
    }
}

480
typedef char   *(*READ_ROUTINE) (char *prompt, FILE * source);
481

482 483 484 485 486 487
/*
 * gets_noreadline  prompt source gets a line of input without calling
 * readline, the source is ignored
 */
char           *
gets_noreadline(char *prompt, FILE * source)
488 489 490
{
    fputs(prompt, stdout);
    fflush(stdout);
491
    return (gets_fromFile(prompt, stdin));
492 493 494
}

/*
495 496
 * gets_readline  prompt source the routine to get input from GNU readline(),
 * the source is ignored the prompt argument is used as the prompting string
497
 */
498 499
char           *
gets_readline(char *prompt, FILE * source)
500
{
501 502 503 504 505 506 507 508
    char *s;
#ifdef HAVE_LIBREADLINE
    s = readline(prompt);
#else
    char buf[500];
    printf("%s", prompt);
    s = fgets(buf, 500, stdin);
#endif
Marc G. Fournier's avatar
Marc G. Fournier committed
509 510 511
    fputc('\r', stdout);
    fflush(stdout);
    return s;
512 513 514 515
}

/*
 * gets_fromFile  prompt source
516 517 518
 * 
 * the routine to read from a file, the prompt argument is ignored the source
 * argument is a FILE *
519
 */
520 521
char           *
gets_fromFile(char *prompt, FILE * source)
522
{
523 524
    char           *line;
    int             len;
525

526
    line = malloc(MAX_QUERY_BUFFER + 1);
527

528 529
    /* read up to MAX_QUERY_BUFFER characters */
    if (fgets(line, MAX_QUERY_BUFFER, source) == NULL)
530 531
	{
	free(line);
532
	return NULL;
533
	}
534

535 536 537 538 539
    line[MAX_QUERY_BUFFER - 1] = '\0';
    len = strlen(line);
    if (len == MAX_QUERY_BUFFER) {
	fprintf(stderr, "line read exceeds maximum length.  Truncating at %d\n",
		MAX_QUERY_BUFFER);
540
    }
541
    return line;
542 543 544
}

/*
545 546
 * SendQuery: send the query string to the backend return *success_p = 1 if
 * the query executed successfully returns *success_p = 0 otherwise
547
 */
548
void
549 550 551
SendQuery(bool * success_p, PsqlSettings * settings, const char *query,
	  const bool copy_in, const bool copy_out, FILE * copystream)
{
552

553 554
    PGresult       *results;
    PGnotify       *notify;
555

556 557 558
    if (settings->singleStep)
	fprintf(stdout, "\n**************************************"
		"*****************************************\n");
559

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    if (settings->echoQuery || settings->singleStep) {
	fprintf(stderr, "QUERY: %s\n", query);
	fflush(stderr);
    }
    if (settings->singleStep) {
	fprintf(stdout, "\n**************************************"
		"*****************************************\n");
	fflush(stdout);
	printf("\npress return to continue ..\n");
	gets_fromFile("", stdin);
    }
    results = PQexec(settings->db, query);
    if (results == NULL) {
	fprintf(stderr, "%s", PQerrorMessage(settings->db));
	*success_p = false;
    } else {
	switch (PQresultStatus(results)) {
	case PGRES_TUPLES_OK:
	    if (settings->gfname) {
		PsqlSettings    ps = *settings;
		FILE           *fp;
		ps.queryFout = stdout;
		fp = setFout(&ps, settings->gfname);
		if (!fp || fp == stdout) {
		    *success_p = false;
		    break;
		} else
		    *success_p = true;
		PQprint(fp,
			results,
			&(settings->opt));
		if (ps.pipe)
		    pclose(fp);
		else
		    fclose(fp);
595
		free(settings->gfname);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
		settings->gfname = NULL;
		break;
	    } else {
		*success_p = true;
		PQprint(settings->queryFout,
			results,
			&(settings->opt));
		fflush(settings->queryFout);
	    }
	    break;
	case PGRES_EMPTY_QUERY:
	    *success_p = true;
	    break;
	case PGRES_COMMAND_OK:
	    *success_p = true;
	    if (!settings->quiet)
		fprintf(stdout, "%s\n", PQcmdStatus(results));
	    break;
	case PGRES_COPY_OUT:
	    *success_p = true;
	    if (copy_out) {
		handleCopyOut(results, settings->quiet, copystream);
	    } else {
		if (!settings->quiet)
		    fprintf(stdout, "Copy command returns...\n");

		handleCopyOut(results, settings->quiet, stdout);
	    }
	    break;
	case PGRES_COPY_IN:
	    *success_p = true;
627
	    if (copy_in)
628
		handleCopyIn(results, false, copystream);
629
	    else
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
		handleCopyIn(results, !settings->quiet, stdin);
	    break;
	case PGRES_NONFATAL_ERROR:
	case PGRES_FATAL_ERROR:
	case PGRES_BAD_RESPONSE:
	    *success_p = false;
	    fprintf(stderr, "%s", PQerrorMessage(settings->db));
	    break;
	}

	if (PQstatus(settings->db) == CONNECTION_BAD) {
	    fprintf(stderr,
		    "We have lost the connection to the backend, so "
		    "further processing is impossible.  "
		    "Terminating.\n");
	    exit(2);		/* we are out'ta here */
	}
	/* check for asynchronous returns */
	notify = PQnotifies(settings->db);
	if (notify) {
	    fprintf(stderr,
		    "ASYNC NOTIFY of '%s' from backend pid '%d' received\n",
		    notify->relname, notify->be_pid);
	    free(notify);
	}
655
 	if(results) PQclear(results);
656
    }
657
}
658 659 660



661
static void
662 663
editFile(char *fname)
{
664 665
    char           *editorName;
    char           *sys;
666 667
    editorName = getenv("EDITOR");
    if (!editorName)
668 669 670 671 672
	editorName = DEFAULT_EDITOR;
    sys = malloc(strlen(editorName) + strlen(fname) + 32 + 1);
    if (!sys) {
	perror("malloc");
	exit(1);
673 674 675 676 677 678
    }
    sprintf(sys, "exec '%s' '%s'", editorName, fname);
    system(sys);
    free(sys);
}

679 680
static          bool
toggle(PsqlSettings * settings, bool * sw, char *msg)
681
{
682
    *sw = !*sw;
683
    if (!settings->quiet)
684
	fprintf(stderr, "turned %s %s\n", on(*sw), msg);
685
    return *sw;
686 687
}

688 689


690
static void
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
unescape(char *dest, const char *source)
{
    /*-----------------------------------------------------------------------------
      Return as the string <dest> the value of string <source> with escape
      sequences turned into the bytes they represent.
    -----------------------------------------------------------------------------*/
    char           *p;
    bool            esc;	/* Last character we saw was the escape
				 * character (/) */

    esc = false;		/* Haven't seen escape character yet */
    for (p = (char *) source; *p; p++) {
	char            c;	/* Our output character */

	if (esc) {
	    switch (*p) {
	    case 'n':
		c = '\n';
		break;
	    case 'r':
		c = '\r';
		break;
	    case 't':
		c = '\t';
		break;
	    case 'f':
		c = '\f';
		break;
	    case '\\':
		c = '\\';
		break;
	    default:
		c = *p;
	    }
	    esc = false;
	} else if (*p == '\\') {
	    esc = true;
	    c = ' ';		/* meaningless, but compiler doesn't know
				 * that */
	} else {
	    c = *p;
	    esc = false;
	}
	if (!esc)
	    *dest++ = c;
736
    }
737
    *dest = '\0';		/* Terminating null character */
738 739
}

740 741


742
static void
743
parse_slash_copy(const char *args, char *table, const int table_len,
744 745 746 747 748 749 750 751 752 753
		 char *file, const int file_len,
		 bool * from_p, bool * error_p)
{

    char            work_args[200];
    /*
     * A copy of the \copy command arguments, except that we modify it as we
     * parse to suit our parsing needs.
     */
    char           *table_tok, *fromto_tok;
754 755

    strncpy(work_args, args, sizeof(work_args));
756
    work_args[sizeof(work_args) - 1] = '\0';
757

758
    *error_p = false;		/* initial assumption */
759 760 761

    table_tok = strtok(work_args, " ");
    if (table_tok == NULL) {
762 763
	fprintf(stderr, "\\copy needs arguments.\n");
	*error_p = true;
764
    } else {
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
	strncpy(table, table_tok, table_len);
	file[table_len - 1] = '\0';

	fromto_tok = strtok(NULL, "  ");
	if (fromto_tok == NULL) {
	    fprintf(stderr, "'FROM' or 'TO' must follow table name.\n");
	    *error_p = true;
	} else {
	    if (strcasecmp(fromto_tok, "from") == 0)
		*from_p = true;
	    else if (strcasecmp(fromto_tok, "to") == 0)
		*from_p = false;
	    else {
		fprintf(stderr,
			"Unrecognized token found where "
			"'FROM' or 'TO' expected: '%s'.\n",
			fromto_tok);
		*error_p = true;
	    }
	    if (!*error_p) {
		char           *file_tok;

		file_tok = strtok(NULL, " ");
		if (file_tok == NULL) {
		    fprintf(stderr, "A file pathname must follow '%s'.\n",
			    fromto_tok);
		    *error_p = true;
		} else {
		    strncpy(file, file_tok, file_len);
		    file[file_len - 1] = '\0';
		    if (strtok(NULL, " ") != NULL) {
			fprintf(stderr,
			     "You have extra tokens after the filename.\n");
			*error_p = true;
		    }
		}
	    }
	}
803 804 805 806 807
    }
}



808
static void
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
do_copy(const char *args, PsqlSettings * settings)
{
    /*---------------------------------------------------------------------------
      Execute a \copy command (frontend copy).  We have to open a file, then
      submit a COPY query to the backend and either feed it data from the
      file or route its response into the file.

      We do a text copy with default (tab) column delimiters.  Some day, we
      should do all the things a backend copy can do.

    ----------------------------------------------------------------------------*/
    char            query[200];
    /* The COPY command we send to the back end */
    bool            from;
    /* The direction of the copy is from a file to a table. */
    char            file[MAXPATHLEN + 1];
    /* The pathname of the file from/to which we copy */
    char            table[NAMEDATALEN + 1];
    /* The name of the table from/to which we copy */
    bool            syntax_error;
    /* The \c command has invalid syntax */
    FILE           *copystream;
831 832

    parse_slash_copy(args, table, sizeof(table), file, sizeof(file),
833
		     &from, &syntax_error);
834 835

    if (!syntax_error) {
836 837 838 839 840 841 842 843 844 845 846 847 848
	strcpy(query, "COPY ");
	strcat(query, table);

	if (from)
	    strcat(query, " FROM stdin");
	else
	    strcat(query, " TO stdout");

	if (from) {
	    copystream = fopen(file, "r");
	} else {
	    copystream = fopen(file, "w");
	}
849
	if (copystream == NULL)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	    fprintf(stderr,
		    "Unable to open file %s which to copy, errno = %s (%d).",
		    from ? "from" : "to", strerror(errno), errno);
	else {
	    bool            success;	/* The query succeeded at the backend */

	    SendQuery(&success, settings, query, from, !from, copystream);
	    fclose(copystream);
	    if (!settings->quiet) {
		if (success)
		    fprintf(stdout, "Successfully copied.\n");
		else
		    fprintf(stdout, "Copy failed.\n");
	    }
	}
865 866 867 868
    }
}


869
static void
870 871
do_connect(const char *new_dbname,
		const char *new_user,
872
		PsqlSettings *settings)
873 874 875
{
    if (!new_dbname)
	fprintf(stderr, "\\connect must be followed by a database name\n");
876
    else {
877
	PGconn          *olddb =  settings->db;
878
	static char	*userenv = NULL;
879
	char		*old_userenv = NULL;
880
	const char	*dbparam;
881

882 883 884 885 886
	if (new_user != NULL) {
		/*
		   PQsetdb() does not allow us to specify the user,
		   so we have to do it via PGUSER
		*/
887
	    if (userenv != NULL)
888
	    	old_userenv = userenv;
889 890
	    userenv = malloc(strlen("PGUSER=") + strlen(new_user) + 1);
	    sprintf(userenv,"PGUSER=%s",new_user);
891 892 893 894 895
	    /* putenv() may continue to use memory as part of environment */
	    putenv(userenv);
	    /* can delete old memory if we malloc'ed it */
	    if (old_userenv != NULL)
	    	free(old_userenv);
896
	}
897 898 899 900 901

	if (strcmp(new_dbname,"-") != 0)
		dbparam = new_dbname;
	else	dbparam = PQdb(olddb);

902
	settings->db = PQsetdb(PQhost(olddb), PQport(olddb),
903 904 905 906 907 908 909 910 911 912 913
			       NULL, NULL, dbparam);
	if (!settings->quiet) {
	    if (!new_user)
	    	printf("connecting to new database: %s\n", dbparam);
	    else if (dbparam != new_dbname)
	    	printf("connecting as new user: %s\n", new_user);
	    else
	    	printf("connecting to new database: %s as user: %s\n",
						dbparam,new_user);
	}

914 915
	if (PQstatus(settings->db) == CONNECTION_BAD) {
	    fprintf(stderr, "%s\n", PQerrorMessage(settings->db));
916 917
	    fprintf(stderr,"Could not connect to new database. exiting\n");
	    exit(2);
918 919 920 921
	} else {
	    PQfinish(olddb);
	    free(settings->prompt);
	    settings->prompt = malloc(strlen(PQdb(settings->db)) + 10);
922
	    sprintf(settings->prompt, "%s%s", PQdb(settings->db), PROMPT);
923
	}
924 925 926 927
    }
}


928
static void
929 930
do_edit(const char *filename_arg, char *query, int *status_p)
{
931

932 933 934 935 936 937
    int             fd;
    char            tmp[64];
    char           *fname;
    int             cc;
    const int       ql = strlen(query);
    bool            error;
938 939

    if (filename_arg) {
940 941
	fname = (char *) filename_arg;
	error = false;
942
    } else {
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
	sprintf(tmp, "/tmp/psql.%ld.%ld", (long) geteuid(), (long) getpid());
	fname = tmp;
	unlink(tmp);
	if (ql > 0) {
	    if ((fd = open(tmp, O_EXCL | O_CREAT | O_WRONLY, 0600)) == -1) {
		perror(tmp);
		error = true;
	    } else {
		if (query[ql - 1] != '\n')
		    strcat(query, "\n");
		if (write(fd, query, ql) != ql) {
		    perror(tmp);
		    close(fd);
		    unlink(tmp);
		    error = true;
		} else
		    error = false;
		close(fd);
	    }
	} else
	    error = false;
964 965
    }

966 967
    if (error)
	*status_p = 1;
968
    else {
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
	editFile(fname);
	if ((fd = open(fname, O_RDONLY)) == -1) {
	    perror(fname);
	    if (!filename_arg)
		unlink(fname);
	    *status_p = 1;
	} else {
	    if ((cc = read(fd, query, MAX_QUERY_BUFFER)) == -1) {
		perror(fname);
		close(fd);
		if (!filename_arg)
		    unlink(fname);
		*status_p = 1;
	    } else {
		query[cc] = '\0';
		close(fd);
		if (!filename_arg)
		    unlink(fname);
		rightTrim(query);
		*status_p = 3;
	    }
	}
991 992 993 994 995
    }
}



996
static void
997 998
do_help(const char *topic)
{
999 1000

    if (!topic) {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	char            left_center_right;	/* Which column we're
						 * displaying */
	int             i;	/* Index into QL_HELP[] */

	printf("type \\h <cmd> where <cmd> is one of the following:\n");

	left_center_right = 'L';/* Start with left column */
	i = 0;
	while (QL_HELP[i].cmd != NULL) {
	    switch (left_center_right) {
	    case 'L':
		printf("    %-25s", QL_HELP[i].cmd);
		left_center_right = 'C';
		break;
	    case 'C':
		printf("%-25s", QL_HELP[i].cmd);
		left_center_right = 'R';
		break;
	    case 'R':
		printf("%-25s\n", QL_HELP[i].cmd);
		left_center_right = 'L';
		break;
	    };
	    i++;
	}
	if (left_center_right != 'L')
	    puts("\n");
	printf("type \\h * for a complete description of all commands\n");
1029
    } else {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	int             i;	/* Index into QL_HELP[] */
	bool            help_found;	/* We found the help he asked for */

	help_found = false;	/* Haven't found it yet */
	for (i = 0; QL_HELP[i].cmd; i++) {
	    if (strcmp(QL_HELP[i].cmd, topic) == 0 ||
		strcmp(topic, "*") == 0) {
		help_found = true;
		printf("Command: %s\n", QL_HELP[i].cmd);
		printf("Description: %s\n", QL_HELP[i].help);
		printf("Syntax:\n");
		printf("%s\n", QL_HELP[i].syntax);
		printf("\n");
	    }
	}
	if (!help_found)
	    printf("command not found, "
		   "try \\h with no arguments to see available help\n");
1048 1049 1050 1051 1052
    }
}



1053
static void
1054 1055
do_shell(const char *command)
{
1056 1057

    if (!command) {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
	char           *sys;
	char           *shellName;

	shellName = getenv("SHELL");
	if (shellName == NULL)
	    shellName = DEFAULT_SHELL;
	sys = malloc(strlen(shellName) + 16);
	if (!sys) {
	    perror("malloc");
	    exit(1);
	}
	sprintf(sys, "exec %s", shellName);
	system(sys);
	free(sys);
    } else
	system(command);
1074 1075 1076 1077
}



1078
/*
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
 * HandleSlashCmds:
 * 
 * Handles all the different commands that start with \ db_ptr is a pointer to
 * the TgDb* structure line is the current input line prompt_ptr is a pointer
 * to the prompt string, a pointer is used because the prompt can be used
 * with a connection to a new database returns a status: 0 - send currently
 * constructed query to backend (i.e. we got a \g) 1 - skip processing of
 * this line, continue building up query 2 - terminate processing of this
 * query entirely, 3 - new query supplied by edit
 */
1089
int
1090 1091 1092
HandleSlashCmds(PsqlSettings * settings,
		char *line,
		char *query)
1093
{
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    int             status = 1;
    char           *optarg;
    /*
     * Pointer inside the <cmd> string to the argument of the slash command,
     * assuming it is a one-character slash command.  If it's not a
     * one-character command, this is meaningless.
     */
    char           *optarg2;
    /*
     * Pointer inside the <cmd> string to the argument of the slash command
     * assuming it's not a one-character command.  If it's a one-character
     * command, this is meaningless.
     */
    char           *cmd;
    /*
     * String: value of the slash command, less the slash and with escape
     * sequences decoded.
     */
    int             blank_loc;
1113 1114
    /* Offset within <cmd> of first blank */

1115
    cmd = malloc(strlen(line));	/* unescaping better not make string grow. */
1116

1117
    unescape(cmd, line + 1);	/* sets cmd string */
1118

1119 1120 1121
    if (strlen(cmd) >= 1 && cmd[strlen(cmd)-1] == ';') /* strip trailing ; */
    	cmd[strlen(cmd)-1] = '\0';

1122 1123 1124 1125 1126 1127 1128
    /*
     * Originally, there were just single character commands.  Now, we define
     * some longer, friendly commands, but we have to keep the old single
     * character commands too.  \c used to be what \connect is now.
     * Complicating matters is the fact that with the single-character
     * commands, you can start the argument right after the single character,
     * so "\copy" would mean "connect to database named 'opy'".
1129
     */
1130

1131 1132
    if (strlen(cmd) > 1)
	optarg = cmd + 1 + strspn(cmd + 1, " \t");
1133
    else
1134 1135 1136
	optarg = NULL;

    blank_loc = strcspn(cmd, " \t");
Bruce Momjian's avatar
Bruce Momjian committed
1137
    if (blank_loc == 0 || !cmd[blank_loc])
1138
	optarg2 = NULL;
1139
    else
1140
	optarg2 = cmd + blank_loc + strspn(cmd + blank_loc, " \t");
1141
		
1142 1143 1144 1145 1146 1147 1148 1149
    switch (cmd[0]) {
    case 'a':			/* toggles to align fields on output */
	toggle(settings, &settings->opt.align, "field alignment");
	break;
    case 'C':			/* define new caption */
	if (settings->opt.caption)
	    free(settings->opt.caption);
	if (!optarg)
1150 1151 1152
	{
	    if (settings->opt.caption)
	    	free(settings->opt.caption);
1153
	    settings->opt.caption = NULL;
1154
	}
1155 1156 1157 1158 1159 1160 1161 1162
	else if (!(settings->opt.caption = strdup(optarg))) {
	    perror("malloc");
	    exit(1);
	}
	break;
    case 'c':{
	    if (strncmp(cmd, "copy ", strlen("copy ")) == 0)
		do_copy(optarg2, settings);
Bruce Momjian's avatar
Bruce Momjian committed
1163 1164
	    else if (strncmp(cmd, "connect ", strlen("connect ")) == 0 ||
		     strcmp(cmd, "connect") == 0 /* issue error message */) {
1165
		char           *optarg3 = NULL;
1166 1167
		int            blank_loc2;

Bruce Momjian's avatar
Bruce Momjian committed
1168 1169 1170 1171 1172 1173
		if (optarg2) {
		    blank_loc2 = strcspn(optarg2, " \t");
		    if (blank_loc2 == 0 || *(optarg2 + blank_loc2) == '\0')
		    	optarg3 = NULL;
		    else {
	    	    	optarg3 = optarg2 + blank_loc2 +
1174
					strspn(optarg2 + blank_loc2, " \t");
Bruce Momjian's avatar
Bruce Momjian committed
1175 1176
			*(optarg2 + blank_loc2) = '\0';
		    }
1177
		}
1178
		do_connect(optarg2, optarg3, settings);
1179
	    }
1180
	    else {
1181
		char           *optarg3 = NULL;
1182 1183
		int            blank_loc2;

Bruce Momjian's avatar
Bruce Momjian committed
1184 1185 1186 1187 1188 1189
		if (optarg) {
		    blank_loc2 = strcspn(optarg, " \t");
		    if (blank_loc2 == 0 || *(optarg + blank_loc2) == '\0')
		    	optarg3 = NULL;
		    else {
	    	    	optarg3 = optarg + blank_loc2 +
1190
					strspn(optarg + blank_loc2, " \t");
Bruce Momjian's avatar
Bruce Momjian committed
1191 1192
			*(optarg + blank_loc2) = '\0';
		    }
1193 1194 1195
		}
		do_connect(optarg, optarg3,  settings);
	    }
1196 1197 1198
	}
	break;
    case 'd':			/* \d describe tables or columns in a table */
1199 1200
 	if (strncmp(cmd, "dt", 2) == 0) {		/* only tables */
 		tableList(settings, 0, 't');
1201
 	} else if (strncmp(cmd, "di", 2) == 0) {	/* only indicies */
1202
 		tableList(settings, 0, 'i');
1203 1204 1205
	} else if (strncmp(cmd, "ds", 2) == 0) {	/* only sequences */
		tableList(settings, 0, 'S');
 	} else if (!optarg) {				/* show tables, sequences and indicies */
1206 1207 1208 1209 1210
 	    tableList(settings, 0, 'b');
 	} else if (strcmp(optarg, "*") == 0) {		/* show everything */
 	    tableList(settings, 0, 'b');
 	    tableList(settings, 1, 'b');
 	} else {					/* describe the specified table */
1211 1212 1213 1214 1215 1216 1217 1218
	    tableDesc(settings, optarg);
	}
	break;
    case 'e':			/* edit */
	{
	    do_edit(optarg, query, &status);
	    break;
	}
Marc G. Fournier's avatar
Marc G. Fournier committed
1219
    case 'E':
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	{
	    FILE           *fd;
	    static char    *lastfile;
	    struct stat     st, st2;
	    if (optarg) {
		if (lastfile)
		    free(lastfile);
		lastfile = malloc(strlen(optarg + 1));
		if (!lastfile) {
		    perror("malloc");
		    exit(1);
		}
		strcpy(lastfile, optarg);
	    } else if (!lastfile) {
		fprintf(stderr, "\\r must be followed by a file name initially\n");
		break;
	    }
	    stat(lastfile, &st);
	    editFile(lastfile);
	    if ((stat(lastfile, &st2) == -1) || ((fd = fopen(lastfile, "r")) == NULL)) {
		perror(lastfile);
		break;
	    }
	    if (st2.st_mtime == st.st_mtime) {
		if (!settings->quiet)
		    fprintf(stderr, "warning: %s not modified. query not executed\n", lastfile);
		fclose(fd);
		break;
	    }
	    MainLoop(settings, fd);
	    fclose(fd);
	    break;
	}
1253
    case 'f':
1254 1255 1256 1257
	{
	    char           *fs = DEFAULT_FIELD_SEP;
	    if (optarg)
		fs = optarg;
1258
	    if (settings->opt.fieldSep)
1259
	    	free(settings->opt.fieldSep);
1260 1261 1262 1263 1264 1265 1266 1267 1268
	    if (!(settings->opt.fieldSep = strdup(fs))) {
		perror("malloc");
		exit(1);
	    }
	    if (!settings->quiet)
		fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
	    break;
	}
    case 'g':			/* \g means send query */
Bruce Momjian's avatar
Bruce Momjian committed
1269 1270 1271 1272 1273 1274
	if (!optarg)
	    settings->gfname = NULL;
	else if (!(settings->gfname = strdup(optarg))) {
	    perror("malloc");
	    exit(1);
	}
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
	status = 0;
	break;
    case 'h':			/* help */
	{
	    do_help(optarg);
	    break;
	}
    case 'i':			/* \i is include file */
	{
	    FILE           *fd;

	    if (!optarg) {
		fprintf(stderr, "\\i must be followed by a file name\n");
		break;
	    }
	    if ((fd = fopen(optarg, "r")) == NULL) {
		fprintf(stderr, "file named %s could not be opened\n", optarg);
		break;
	    }
	    MainLoop(settings, fd);
	    fclose(fd);
	    break;
	}
    case 'l':			/* \l is list database */
	listAllDbs(settings);
	break;
1301
    case 'H':
1302 1303 1304
	if (toggle(settings, &settings->opt.html3, "HTML3.0 tabular output"))
	    settings->opt.standard = 0;
	break;
1305
    case 'o':
1306 1307
	setFout(settings, optarg);
	break;
1308
    case 'p':
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	if (query) {
	    fputs(query, stdout);
	    fputc('\n', stdout);
	}
	break;
    case 'q':			/* \q is quit */
	status = 2;
	break;
    case 'r':			/* reset(clear) the buffer */
	query[0] = '\0';
	if (!settings->quiet)
	    fprintf(stderr, "buffer reset(cleared)\n");
	break;
    case 's':			/* \s is save history to a file */
	if (!optarg)
	    optarg = "/dev/tty";
1325
#ifdef HAVE_HISTORY
1326 1327
	if (write_history(optarg) != 0)
	    fprintf(stderr, "cannot write history to %s\n", optarg);
1328
#endif
1329 1330 1331 1332 1333
	break;
    case 'm':			/* monitor like type-setting */
	if (toggle(settings, &settings->opt.standard, "standard SQL separaters and padding")) {
	    settings->opt.html3 = settings->opt.expanded = 0;
	    settings->opt.align = settings->opt.header = 1;
1334 1335
	    if (settings->opt.fieldSep)
		free(settings->opt.fieldSep);
1336 1337 1338 1339
	    settings->opt.fieldSep = strdup("|");
	    if (!settings->quiet)
		fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
	} else {
1340 1341
	    if (settings->opt.fieldSep)
	    	free(settings->opt.fieldSep);
1342 1343 1344 1345 1346
	    settings->opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
	    if (!settings->quiet)
		fprintf(stderr, "field separater changed to '%s'\n", settings->opt.fieldSep);
	}
	break;
1347 1348 1349
    case 'z': 			/* list table rights (grant/revoke) */
	rightsList(settings);
	break;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    case 't':			/* toggle headers */
	toggle(settings, &settings->opt.header, "output headings and row count");
	break;
    case 'T':			/* define html <table ...> option */
	if (settings->opt.tableOpt)
	    free(settings->opt.tableOpt);
	if (!optarg)
	    settings->opt.tableOpt = NULL;
	else if (!(settings->opt.tableOpt = strdup(optarg))) {
	    perror("malloc");
	    exit(1);
	}
	break;
1363
    case 'x':
1364 1365
	toggle(settings, &settings->opt.expanded, "expanded table representation");
	break;
1366
    case '!':
1367 1368
	do_shell(optarg);
	break;
1369
    default:
1370 1371 1372
    case '?':			/* \? is help */
	slashUsage(settings);
	break;
1373
    }
1374 1375
    free(cmd);
    return status;
1376 1377
}

1378 1379 1380 1381 1382 1383 1384 1385 1386
/*
 * MainLoop: main processing loop for reading lines of input and sending them
 * to the backend
 * 
 * this loop is re-entrant.  May be called by \i command which reads input from
 * a file
 * 
 * db_ptr must be initialized and set
 */
1387

1388
int
1389
MainLoop(PsqlSettings * settings, FILE * source)
1390
{
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    char           *line;	/* line of input */
    int             len;	/* length of the line */
    char            query[MAX_QUERY_BUFFER];	/* multi-line query storage */
    int             successResult = 1;
    int             slashCmdStatus = 0;
    /*
     * slashCmdStatus can be: 0 - send currently constructed query to backend
     * (i.e. we got a \g) 1 - skip processing of this line, continue building
     * up query 2 - terminate processing of this query entirely 3 - new query
     * supplied by edit
     */

    bool            querySent = false;
    bool            interactive;
    READ_ROUTINE    GetNextLine;
    bool            eof = 0;
    /* We've reached the end of our command input. */
    bool            success;
    bool            in_quote;
    bool            was_bslash;	/* backslash */
    bool            was_dash;
    int             paren_level;
    char           *query_start;
1414 1415 1416

    interactive = ((source == stdin) && !settings->notty);
    if (interactive) {
1417 1418 1419 1420 1421 1422 1423 1424 1425
	if (settings->prompt)
	    free(settings->prompt);
	settings->prompt =
	    malloc(strlen(PQdb(settings->db)) + strlen(PROMPT) + 1);
	if (settings->quiet)
	    settings->prompt[0] = '\0';
	else
	    sprintf(settings->prompt, "%s%s", PQdb(settings->db), PROMPT);
	if (settings->useReadline) {
1426
#ifdef HAVE_HISTORY
1427
	    using_history();
1428
#endif
1429 1430 1431 1432 1433
	    GetNextLine = gets_readline;
	} else
	    GetNextLine = gets_noreadline;
    } else
	GetNextLine = gets_fromFile;
1434 1435

    query[0] = '\0';
1436 1437 1438
    in_quote = false;
    paren_level = 0;
    slashCmdStatus = -1;	/* set default */
1439

1440 1441 1442
    /* main loop for getting queries and executing them */
    while (!eof) {
	if (slashCmdStatus == 3) {
Bruce Momjian's avatar
Bruce Momjian committed
1443
	    paren_level = 0;
1444 1445 1446
	    line = strdup(query);
	    query[0] = '\0';
	} else {
1447 1448 1449 1450 1451 1452 1453 1454
	    if (interactive && !settings->quiet) {
	    	if (in_quote)
	    	    settings->prompt[strlen(settings->prompt)-3] = '\'';
	    	else if (query[0] != '\0' && !querySent)
	    	    settings->prompt[strlen(settings->prompt)-3] = '-';
	    	else
	    	    settings->prompt[strlen(settings->prompt)-3] = '=';
	    }
1455
	    line = GetNextLine(settings->prompt, source);
1456
#ifdef HAVE_HISTORY
1457 1458
	    if (interactive && settings->useReadline && line != NULL)
		add_history(line);	/* save non-empty lines in history */
1459
#endif
1460 1461 1462
	}

	query_start = line;
1463 1464 1465
	if (line == NULL) {	/* No more input.  Time to quit */
	    if (!settings->quiet)
		printf("EOF\n");	/* Goes on prompt line */
1466 1467 1468 1469 1470
	    eof = true;
	} else {
	    /* remove whitespaces on the right, incl. \n's */
	    line = rightTrim(line);

1471 1472 1473
	    if (!interactive && !settings->singleStep && !settings->quiet)
		fprintf(stderr, "%s\n", line);

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
	    if (line[0] == '\0') {
		free(line);
		continue;
	    }

	    len = strlen(line);

	    if (settings->singleLineMode) {
		SendQuery(&success, settings, line, false, false, 0);
		successResult &= success;
		querySent = true;
	    } else {
		int             i;
		was_bslash = false;
		was_dash = false;

		for (i = 0; i < len; i++) {
		    if (!in_quote && line[i] == '\\') {
			char            hold_char = line[i];

			line[i] = '\0';
			if (query_start[0] != '\0') {
			    if (query[0] != '\0') {
				strcat(query, "\n");
				strcat(query, query_start);
			    } else
				strcpy(query, query_start);
			}
			line[i] = hold_char;
			query_start = line + i;
			break;	/* handle command */
		    }
		    if (querySent && !isspace(line[i])) {
			query[0] = '\0';
			querySent = false;
		    }
		    if (!in_quote && was_dash && line[i] == '-') {
			/* print comment at top of query */
			if (settings->singleStep)
			    fprintf(stdout, "%s\n", line + i - 1);
			line[i - 1] = '\0';	/* remove comment */
			break;
		    }
		    was_dash = false;

		    if (!in_quote && !paren_level &&
			line[i] == ';') {
			char            hold_char = line[i + 1];

			line[i + 1] = '\0';
			if (query_start[0] != '\0') {
			    if (query[0] != '\0') {
				strcat(query, "\n");
				strcat(query, query_start);
			    } else
				strcpy(query, query_start);
			}
			SendQuery(&success, settings, query, false, false, 0);
			successResult &= success;
			line[i + 1] = hold_char;
			query_start = line + i + 1;
			querySent = true;
		    }
		    if (was_bslash)
			was_bslash = false;
		    else if (line[i] == '\\')
			was_bslash = true;
		    else if (line[i] == '\'')
			in_quote ^= 1;
		    else if (!in_quote && line[i] == '(')
			paren_level++;
		    else if (!in_quote && paren_level && line[i] == ')')
			paren_level--;
		    else if (!in_quote && line[i] == '-')
			was_dash = true;
		}
	    }

	    slashCmdStatus = -1;
	    if (!in_quote && query_start[0] == '\\') {
		slashCmdStatus = HandleSlashCmds(settings,
						 query_start,
						 query);
		if (slashCmdStatus == 1) {
Bruce Momjian's avatar
Bruce Momjian committed
1558 1559
		    if (query[0] == '\0')
			paren_level = 0;
Bruce Momjian's avatar
Bruce Momjian committed
1560 1561
		    free(line);
		    continue;
1562 1563 1564 1565 1566
		}
		if (slashCmdStatus == 2) {
		    free(line);
		    break;
		}
Bruce Momjian's avatar
Bruce Momjian committed
1567
		free(line);
1568 1569 1570 1571
	    } else if (strlen(query) + strlen(query_start) > MAX_QUERY_BUFFER) {
		fprintf(stderr, "query buffer max length of %d exceeded\n",
			MAX_QUERY_BUFFER);
		fprintf(stderr, "query line ignored\n");
1572
	        free (line);
1573 1574
	    } else {
		if (query_start[0] != '\0') {
1575

1576 1577 1578 1579 1580 1581 1582
		    querySent = false;
		    if (query[0] != '\0') {
			strcat(query, "\n");
			strcat(query, query_start);
		    } else
			strcpy(query, query_start);
		}
Bruce Momjian's avatar
Bruce Momjian committed
1583
		free(line); /* PURIFY */
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
	    }

	    if (slashCmdStatus == 0) {
		SendQuery(&success, settings, query, false, false, 0);
		successResult &= success;
		querySent = true;
	    }
	}
    }				/* while */
    return successResult;
}
1595

1596
int
1597
main(int argc, char **argv)
1598
{
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
    extern char    *optarg;
    extern int      optind;

    char           *dbname = NULL;
    char           *host = NULL;
    char           *port = NULL;
    char           *qfilename = NULL;
    char            errbuf[ERROR_MSG_LENGTH];

    PsqlSettings    settings;

    char           *singleQuery = NULL;

    bool            listDatabases = 0;
    int             successResult = 1;
    bool            singleSlashCmd = 0;
    int             c;

    memset(&settings, 0, sizeof settings);
    settings.opt.align = 1;
    settings.opt.header = 1;
    settings.queryFout = stdout;
    settings.opt.fieldSep = strdup(DEFAULT_FIELD_SEP);
    settings.opt.pager = 1;
    if (!isatty(0) || !isatty(1))
	settings.quiet = settings.notty = 1;
1625
#ifdef HAVE_LIBREADLINE
1626 1627
    else
	settings.useReadline = 1;
1628
#endif
1629 1630 1631 1632 1633
#ifdef PSQL_ALWAYS_GET_PASSWORDS
    settings.getPassword = 1;
#else
    settings.getPassword = 0;
#endif
Marc G. Fournier's avatar
Marc G. Fournier committed
1634

1635
    while ((c = getopt(argc, argv, "Aa:c:d:ef:F:lh:Hnso:p:qStT:ux")) != EOF) {
1636 1637 1638 1639 1640 1641 1642 1643
	switch (c) {
	case 'A':
	    settings.opt.align = 0;
	    break;
	case 'a':
	    fe_setauthsvc(optarg, errbuf);
	    break;
	case 'c':
Bruce Momjian's avatar
Bruce Momjian committed
1644
	    singleQuery = strdup(optarg);
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
	    if (singleQuery[0] == '\\') {
		singleSlashCmd = 1;
	    }
	    break;
	case 'd':
	    dbname = optarg;
	    break;
	case 'e':
	    settings.echoQuery = 1;
	    break;
	case 'f':
	    qfilename = optarg;
	    break;
	case 'F':
Bruce Momjian's avatar
Bruce Momjian committed
1659
	    settings.opt.fieldSep = strdup(optarg);
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
	    break;
	case 'l':
	    listDatabases = 1;
	    break;
	case 'h':
	    host = optarg;
	    break;
	case 'H':
	    settings.opt.html3 = 1;
	    break;
	case 'n':
	    settings.useReadline = 0;
	    break;
	case 'o':
	    setFout(&settings, optarg);
	    break;
	case 'p':
	    port = optarg;
	    break;
	case 'q':
	    settings.quiet = 1;
	    break;
	case 's':
	    settings.singleStep = 1;
	    break;
	case 'S':
	    settings.singleLineMode = 1;
	    break;
	case 't':
	    settings.opt.header = 0;
	    break;
	case 'T':
Bruce Momjian's avatar
Bruce Momjian committed
1692
	    settings.opt.tableOpt = strdup(optarg);
1693
	    break;
1694 1695 1696
	case 'u':
	    settings.getPassword = 1;
	    break;
1697 1698 1699 1700 1701 1702 1703
	case 'x':
	    settings.opt.expanded = 1;
	    break;
	default:
	    usage(argv[0]);
	    break;
	}
1704
    }
1705 1706 1707 1708 1709 1710 1711
    /* if we still have an argument, use it as the database name */
    if (argc - optind == 1)
	dbname = argv[optind];

    if (listDatabases)
	dbname = "template1";

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
    if(settings.getPassword) {
	char username[9];
	char password[9];
	char *connect_string;

	prompt_for_password(username, password);

	/* now use PQconnectdb so we can pass these options */
	connect_string = make_connect_string(host, port, dbname, username, password);
	settings.db = PQconnectdb(connect_string);
	free(connect_string);
    } else {
	settings.db = PQsetdb(host, port, NULL, NULL, dbname);
    }

1727 1728 1729 1730 1731
    dbname = PQdb(settings.db);

    if (PQstatus(settings.db) == CONNECTION_BAD) {
	fprintf(stderr, "Connection to database '%s' failed.\n", dbname);
	fprintf(stderr, "%s", PQerrorMessage(settings.db));
1732
	PQfinish(settings.db);
1733 1734 1735 1736 1737 1738
	exit(1);
    }
    if (listDatabases) {
	exit(listAllDbs(&settings));
    }
    if (!settings.quiet && !singleQuery && !qfilename) {
Bruce Momjian's avatar
Bruce Momjian committed
1739
	printf("Welcome to the POSTGRESQL interactive sql monitor:\n");
1740
	printf("  Please read the file COPYRIGHT for copyright terms "
Bruce Momjian's avatar
Bruce Momjian committed
1741
	       "of POSTGRESQL\n\n");
1742 1743 1744 1745
	printf("   type \\? for help on slash commands\n");
	printf("   type \\q to quit\n");
	printf("   type \\g or terminate with semicolon to execute query\n");
	printf(" You are currently connected to the database: %s\n\n", dbname);
1746
    }
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
    if (qfilename || singleSlashCmd) {
	/*
	 * read in a file full of queries instead of reading in queries
	 * interactively
	 */
	char           *line;

	if (singleSlashCmd) {
	    /* Not really a query, but "Do what I mean, not what I say." */
	    line = singleQuery;
	} else {
	    line = malloc(strlen(qfilename) + 5);
	    sprintf(line, "\\i %s", qfilename);
	}
	HandleSlashCmds(&settings, line, "");
Bruce Momjian's avatar
Bruce Momjian committed
1762
        free (line);	/* PURIFY */
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
    } else {
	if (singleQuery) {
	    bool            success;	/* The query succeeded at the backend */
	    SendQuery(&success, &settings, singleQuery, false, false, 0);
	    successResult = success;
	} else
	    successResult = MainLoop(&settings, stdin);
    }

    PQfinish(settings.db);
1773 1774
    free(settings.opt.fieldSep);	        /* PURIFY */
    if(settings.prompt) free(settings.prompt);	/* PURIFY */
1775 1776

    return !successResult;
1777 1778
}

1779
#define COPYBUFSIZ  8192
1780 1781

static void
1782 1783 1784 1785 1786
handleCopyOut(PGresult * res, bool quiet, FILE * copystream)
{
    bool            copydone;
    char            copybuf[COPYBUFSIZ];
    int             ret;
1787

1788
    copydone = false;		/* Can't be done; haven't started. */
1789

1790
    while (!copydone) {
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
	ret = PQgetline(res->conn, copybuf, COPYBUFSIZ);

	if (copybuf[0] == '\\' &&
	    copybuf[1] == '.' &&
	    copybuf[2] == '\0') {
	    copydone = true;	/* don't print this... */
	} else {
	    fputs(copybuf, copystream);
	    switch (ret) {
	    case EOF:
		copydone = true;
		/* FALLTHROUGH */
	    case 0:
		fputc('\n', copystream);
		break;
	    case 1:
		break;
	    }
	}
1810
    }
1811
    fflush(copystream);
1812 1813 1814 1815
    PQendcopy(res->conn);
}


1816

1817
static void
1818 1819 1820 1821 1822 1823 1824 1825 1826
handleCopyIn(PGresult * res, const bool mustprompt, FILE * copystream)
{
    bool            copydone = false;
    bool            firstload;
    bool            linedone;
    char            copybuf[COPYBUFSIZ];
    char           *s;
    int             buflen;
    int             c;
1827 1828

    if (mustprompt) {
1829 1830 1831
	fputs("Enter info followed by a newline\n", stdout);
	fputs("End with a backslash and a "
	      "period on a line by itself.\n", stdout);
1832
    }
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    while (!copydone) {		/* for each input line ... */
	if (mustprompt) {
	    fputs(">> ", stdout);
	    fflush(stdout);
	}
	firstload = true;
	linedone = false;
	while (!linedone) {	/* for each buffer ... */
	    s = copybuf;
	    buflen = COPYBUFSIZ;
	    for (; buflen > 1 &&
		 !(linedone = (c = getc(copystream)) == '\n' || c == EOF);
		 --buflen) {
		*s++ = c;
	    }
	    if (c == EOF) {
		PQputline(res->conn, "\\.");
		copydone = true;
		break;
	    }
	    *s = '\0';
	    PQputline(res->conn, copybuf);
	    if (firstload) {
		if (!strcmp(copybuf, "\\.")) {
		    copydone = true;
		}
		firstload = false;
	    }
	}
	PQputline(res->conn, "\n");
1863 1864 1865 1866
    }
    PQendcopy(res->conn);
}

1867 1868


1869 1870 1871
/*
 * try to open fname and return a FILE *, if it fails, use stdout, instead
 */
1872

1873 1874
FILE           *
setFout(PsqlSettings * ps, char *fname)
1875
{
1876 1877 1878 1879 1880
    if (ps->queryFout && ps->queryFout != stdout) {
	if (ps->pipe)
	    pclose(ps->queryFout);
	else
	    fclose(ps->queryFout);
1881
    }
1882
    if (!fname) {
1883
	ps->queryFout = stdout;
1884 1885
	pqsignal(SIGPIPE, SIG_DFL);
    }
1886 1887
    else {
	if (*fname == '|') {
1888
	    pqsignal(SIGPIPE, SIG_IGN);
1889 1890 1891 1892
	    ps->queryFout = popen(fname + 1, "w");
	    ps->pipe = 1;
	} else {
	    ps->queryFout = fopen(fname, "w");
1893
	    pqsignal(SIGPIPE, SIG_DFL);
1894 1895 1896 1897 1898 1899
	    ps->pipe = 0;
	}
	if (!ps->queryFout) {
	    perror(fname);
	    ps->queryFout = stdout;
	}
1900
    }
1901
    return ps->queryFout;
1902
}
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

static void prompt_for_password(char *username, char *password)
{
    int length;
#ifdef HAVE_TERMIOS_H
    struct termios t_orig, t;
#endif

    printf("Username: ");
    fgets(username, 9, stdin);
    length = strlen(username);
    if(length > 0 && username[length-1] == '\n') username[length-1] = '\0';

    printf("Password: ");
#ifdef HAVE_TERMIOS_H
    tcgetattr(0, &t);
    t_orig = t;
    t.c_lflag &= ~ECHO;
    tcsetattr(0, TCSADRAIN, &t);
#endif
    fgets(password, 9, stdin);
#ifdef HAVE_TERMIOS_H
    tcsetattr(0, TCSADRAIN, &t_orig);
#endif

    length = strlen(password);
    if(length > 0 && password[length-1] == '\n') password[length-1] = '\0';

    printf("\n\n");
}

static char *make_connect_string(char *host, char *port, char *dbname,
				 char *username, char *password)
{
    int connect_string_len = 0;
    char *connect_string;
    
    if(host)
	connect_string_len += 6 + strlen(host);       /* 6 == "host=" + " " */
    if(username) 
	connect_string_len += 6 + strlen(username);   /* 6 == "user=" + " " */
    if(password)
	connect_string_len += 10 + strlen(password);  /* 10 == "password=" + " " */
    if(port)
	connect_string_len += 6 + strlen(port);       /* 6 == "port=" + " " */
    if(dbname)
	connect_string_len += 8 + strlen(dbname);     /* 8 == "dbname=" + " " */
    connect_string_len += 18;   /* "authtype=password" + null */
    
    connect_string = (char *)malloc(connect_string_len);
    if(!connect_string) {
	return 0;
    }
    connect_string[0] = '\0';
    if(host) {
	strcat(connect_string, "host=");
	strcat(connect_string, host);
	strcat(connect_string, " ");
    }
    if(username) {
	strcat(connect_string, "user=");
	strcat(connect_string, username);
	strcat(connect_string, " ");
    }
    if(password) {
	strcat(connect_string, "password=");
	strcat(connect_string, password);
	strcat(connect_string, " ");
    }
    if(port) {
	strcat(connect_string, "port=");
	strcat(connect_string, port);
	strcat(connect_string, " ");
    }
    if(dbname) {
	strcat(connect_string, "dbname=");
	strcat(connect_string, dbname);
	strcat(connect_string, " ");
    }
    strcat(connect_string, "authtype=password");

    return connect_string;
}