startup.c 14.7 KB
Newer Older
P
Peter Eisentraut 已提交
1 2 3
/*
 * psql - the PostgreSQL interactive terminal
 *
P
Peter Eisentraut 已提交
4
 * Copyright 2000 by PostgreSQL Global Development Group
P
Peter Eisentraut 已提交
5
 *
P
Peter Eisentraut 已提交
6
 * $Header: /cvsroot/pgsql/src/bin/psql/startup.c,v 1.28 2000/03/18 22:48:29 petere Exp $
P
Peter Eisentraut 已提交
7
 */
8
#include "postgres.h"
9 10 11

#include <sys/types.h>

12 13 14
#ifndef WIN32
#include <unistd.h>
#else /* WIN32 */
15
#include <io.h>
B
Hi!  
Bruce Momjian 已提交
16
#include <windows.h>
17 18
#include <win32.h>
#endif /* WIN32 */
19 20 21 22 23

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

24 25
#include "libpq-fe.h"
#include "version.h"
26 27 28

#include "command.h"
#include "common.h"
29 30
#include "describe.h"
#include "help.h"
31
#include "input.h"
32
#include "mainloop.h"
33
#include "print.h"
34 35
#include "settings.h"
#include "variables.h"
36

37 38 39 40 41 42 43 44
#ifdef MULTIBYTE
#include "miscadmin.h"
#include "mb/pg_wchar.h"
#else
/* XXX Grand unified hard-coded badness; this should go into libpq */
#define pg_encoding_to_char(x) "SQL_ASCII"
#endif

45 46 47
/*
 * Global psql options
 */
48
PsqlSettings pset;
49 50


51 52
/*
 * Structures to pass information between the option parsing routine
53 54
 * and the main function
 */
B
Bruce Momjian 已提交
55 56 57 58 59 60 61
enum _actions
{
	ACT_NOTHING = 0,
	ACT_SINGLE_SLASH,
	ACT_LIST_DB,
	ACT_SINGLE_QUERY,
	ACT_FILE
62 63
};

B
Bruce Momjian 已提交
64 65 66 67 68 69 70 71 72
struct adhoc_opts
{
	char	   *dbname;
	char	   *host;
	char	   *port;
	char	   *username;
	enum _actions action;
	char	   *action_string;
	bool		no_readline;
73
    bool        no_psqlrc;
74 75 76
};

static void
77
parse_psql_options(int argc, char *argv[], struct adhoc_opts * options);
78

79 80 81 82 83 84
static void
process_psqlrc(void);

static void
showVersion(void);

85 86 87 88


/*
 *
89
 * main
90 91 92
 *
 */
int
93
main(int argc, char *argv[])
94
{
B
Bruce Momjian 已提交
95 96
	struct adhoc_opts options;
	int			successResult;
97

B
Bruce Momjian 已提交
98 99 100
	char	   *username = NULL;
	char	   *password = NULL;
	bool		need_pass;
101

102
    if (!strrchr(argv[0], SEP_CHAR))
103
        pset.progname = argv[0];
104
    else
105
        pset.progname = strrchr(argv[0], SEP_CHAR) + 1;
106

107 108
	pset.cur_cmd_source = stdin;
	pset.cur_cmd_interactive = false;
P
Peter Eisentraut 已提交
109
    pset.encoding = PQenv2encoding();
110

111
	pset.vars = CreateVariableSpace();
112 113 114 115 116
    if (!pset.vars)
    {
        fprintf(stderr, "%s: out of memory\n", pset.progname);
        exit(EXIT_FAILURE);
    }
117 118 119
	pset.popt.topt.format = PRINT_ALIGNED;
	pset.queryFout = stdout;
	pset.popt.topt.border = 1;
P
Peter Eisentraut 已提交
120
	pset.popt.topt.pager = true;
121

122
    SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
123

124
	pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
125

126
	/* This is obsolete and should be removed sometime. */
127
#ifdef PSQL_ALWAYS_GET_PASSWORDS
128
	pset.getPassword = true;
129
#else
130
	pset.getPassword = false;
131 132
#endif

133
	parse_psql_options(argc, argv, &options);
134

135 136 137 138
    if (!pset.popt.topt.fieldSep)
        pset.popt.topt.fieldSep = xstrdup(DEFAULT_FIELD_SEP);
    if (!pset.popt.topt.recordSep)
        pset.popt.topt.recordSep = xstrdup(DEFAULT_RECORD_SEP);
139

B
Bruce Momjian 已提交
140 141
	if (options.username)
	{
142 143 144 145 146
        /*
         * The \001 is a hack to support the deprecated -u option which issues
         * a username prompt. The recommended option is -U followed by the name
         * on the command line.
         */
147
		if (strcmp(options.username, "\001") == 0)
B
Bruce Momjian 已提交
148 149 150
			username = simple_prompt("Username: ", 100, true);
		else
			username = strdup(options.username);
151 152
	}

153
	if (pset.getPassword)
B
Bruce Momjian 已提交
154
		password = simple_prompt("Password: ", 100, false);
155

B
Bruce Momjian 已提交
156 157 158 159
	/* loop until we have a password if requested by backend */
	do
	{
		need_pass = false;
160 161 162
		pset.db = PQsetdbLogin(options.host, options.port, NULL, NULL,
                               options.action == ACT_LIST_DB ? "template1" : options.dbname,
                               username, password);
B
Bruce Momjian 已提交
163

164 165
		if (PQstatus(pset.db) == CONNECTION_BAD &&
			strcmp(PQerrorMessage(pset.db), "fe_sendauth: no password supplied\n") == 0)
B
Bruce Momjian 已提交
166 167 168 169 170 171 172
		{
			need_pass = true;
			free(password);
			password = NULL;
			password = simple_prompt("Password: ", 100, false);
		}
	} while (need_pass);
173

B
Bruce Momjian 已提交
174 175 176
	free(username);
	free(password);

177
	if (PQstatus(pset.db) == CONNECTION_BAD)
B
Bruce Momjian 已提交
178
	{
179
        fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db));
180
		PQfinish(pset.db);
B
Bruce Momjian 已提交
181 182 183
		exit(EXIT_BADCONN);
	}

P
Peter Eisentraut 已提交
184 185 186 187 188
    PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);
    /*
     * We need to save the encoding because we want to have it
     * available even if the database connection goes bad.
     */
189
    pset.encoding = PQclientEncoding(pset.db);
P
Peter Eisentraut 已提交
190

B
Bruce Momjian 已提交
191 192
	if (options.action == ACT_LIST_DB)
	{
193
		int			success = listAllDbs(false);
B
Bruce Momjian 已提交
194

195
		PQfinish(pset.db);
196
		exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
B
Bruce Momjian 已提交
197 198
	}

199 200 201 202
    SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
    SetVariable(pset.vars, "USER", PQuser(pset.db));
    SetVariable(pset.vars, "HOST", PQhost(pset.db));
    SetVariable(pset.vars, "PORT", PQport(pset.db));
203 204 205 206 207
    SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));

#ifndef WIN32
	pqsignal(SIGINT, handle_sigint);	/* control-C => cancel */
#endif
B
Bruce Momjian 已提交
208

209 210 211
	/*
     * Now find something to do
     */
B
Bruce Momjian 已提交
212

213 214 215
	/*
     * process file given by -f
     */
B
Bruce Momjian 已提交
216
	if (options.action == ACT_FILE)
217 218 219 220
    {
        if (!options.no_psqlrc)
            process_psqlrc();

221
		successResult = process_file(options.action_string);
222
    }
223 224 225
	/*
     * process slash command if one was given to -c
     */
B
Bruce Momjian 已提交
226
	else if (options.action == ACT_SINGLE_SLASH)
227
    {
228 229
        const char * value;

230
        if ((value = GetVariable(pset.vars, "ECHO")) && strcmp(value, "all")==0)
231
            puts(options.action_string);
232 233
		successResult = HandleSlashCmds(options.action_string, NULL, NULL) != CMD_ERROR
            ? EXIT_SUCCESS : EXIT_FAILURE;
234
    }
235 236 237
	/*
     * If the query given to -c was a normal one, send it
     */
B
Bruce Momjian 已提交
238
	else if (options.action == ACT_SINGLE_QUERY)
239
    {
240 241
        const char * value;

242
        if ((value = GetVariable(pset.vars, "ECHO")) && strcmp(value, "all")==0)
243
            puts(options.action_string);
244 245
		successResult = SendQuery(options.action_string)
            ? EXIT_SUCCESS : EXIT_FAILURE;
246
    }
247 248 249
	/*
     * or otherwise enter interactive main loop
     */
B
Bruce Momjian 已提交
250
	else
251
    {
252 253 254 255 256 257 258 259 260 261 262 263 264 265
        pset.issuper = test_superuser(PQuser(pset.db));
        if (!QUIET() && !pset.notty)
        {
            printf("Welcome to %s, the PostgreSQL interactive terminal.\n\n"
                   "Type:  \\copyright for distribution terms\n"
                   "       \\h for help with SQL commands\n"
                   "       \\? for help on internal slash commands\n"
                   "       \\g or terminate with semicolon to execute query\n"
                   "       \\q to quit\n\n", pset.progname);
        }

        SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
        SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
        SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
266 267
        if (!options.no_psqlrc)
            process_psqlrc();
268 269
        if (!pset.notty)
            initializeInput(options.no_readline ? 0 : 1);
P
Peter Eisentraut 已提交
270
		successResult = MainLoop(stdin);
271
    }
B
Bruce Momjian 已提交
272 273

	/* clean up */
274 275
	PQfinish(pset.db);
	setQFout(NULL);
B
Bruce Momjian 已提交
276 277

	return successResult;
278 279 280 281 282 283 284 285 286 287
}



/*
 * Parse command line options
 */

#ifdef WIN32
/* getopt is not in the standard includes on Win32 */
B
Bruce Momjian 已提交
288
int			getopt(int, char *const[], const char *);
B
Hi!  
Bruce Momjian 已提交
289 290
/* And it requires progname to be set */
char        *__progname = "psql";
291 292 293
#endif

static void
294
parse_psql_options(int argc, char *argv[], struct adhoc_opts * options)
295 296
{
#ifdef HAVE_GETOPT_LONG
297 298
	static struct option long_options[] =
    {
299
        {"echo-all", no_argument, NULL, 'a'},
B
Bruce Momjian 已提交
300 301 302
		{"no-align", no_argument, NULL, 'A'},
		{"command", required_argument, NULL, 'c'},
		{"dbname", required_argument, NULL, 'd'},
303
		{"echo-queries", no_argument, NULL, 'e'},
304
		{"echo-hidden", no_argument, NULL, 'E'},
B
Bruce Momjian 已提交
305
		{"file", required_argument, NULL, 'f'},
306
		{"field-separator", required_argument, NULL, 'F'},
B
Bruce Momjian 已提交
307 308 309
		{"host", required_argument, NULL, 'h'},
		{"html", no_argument, NULL, 'H'},
		{"list", no_argument, NULL, 'l'},
310
		{"output", required_argument, NULL, 'o'},
B
Bruce Momjian 已提交
311 312 313
		{"port", required_argument, NULL, 'p'},
		{"pset", required_argument, NULL, 'P'},
		{"quiet", no_argument, NULL, 'q'},
314
        {"record-separator", required_argument, NULL, 'R'},
B
Bruce Momjian 已提交
315 316 317 318 319 320 321 322 323
		{"single-step", no_argument, NULL, 's'},
		{"single-line", no_argument, NULL, 'S'},
		{"tuples-only", no_argument, NULL, 't'},
		{"table-attr", required_argument, NULL, 'T'},
		{"username", required_argument, NULL, 'U'},
		{"set", required_argument, NULL, 'v'},
		{"variable", required_argument, NULL, 'v'},
		{"version", no_argument, NULL, 'V'},
		{"password", no_argument, NULL, 'W'},
324 325
		{"expanded", no_argument, NULL, 'x'},
        {"no-psqlrc", no_argument, NULL, 'X'},
B
Bruce Momjian 已提交
326 327 328 329
		{"help", no_argument, NULL, '?'},
	};

	int			optindex;
330
#endif /* HAVE_GETOPT_LONG */
331

B
Bruce Momjian 已提交
332 333 334
	extern char *optarg;
	extern int	optind;
	int			c;
335
    bool        used_old_u_option = false;
336

337
	memset(options, 0, sizeof *options);
338 339

#ifdef HAVE_GETOPT_LONG
340
	while ((c = getopt_long(argc, argv, "aAc:d:eEf:F:lh:Hno:p:P:qRsStT:uU:v:VWxX?", long_options, &optindex)) != -1)
341
#else /* not HAVE_GETOPT_LONG */
B
Bruce Momjian 已提交
342 343 344 345
	/*
	 * Be sure to leave the '-' in here, so we can catch accidental long
	 * options.
	 */
346
	while ((c = getopt(argc, argv, "aAc:d:eEf:F:lh:Hno:p:P:qRsStT:uU:v:VWxX?-")) != -1)
347
#endif /* not HAVE_GETOPT_LONG */
348
	{
B
Bruce Momjian 已提交
349 350
		switch (c)
		{
351 352 353
			case 'a':
				SetVariable(pset.vars, "ECHO", "all");
				break;
B
Bruce Momjian 已提交
354
			case 'A':
355
				pset.popt.topt.format = PRINT_UNALIGNED;
B
Bruce Momjian 已提交
356 357 358 359
				break;
			case 'c':
				options->action_string = optarg;
				if (optarg[0] == '\\')
P
Peter Eisentraut 已提交
360
				{
B
Bruce Momjian 已提交
361
					options->action = ACT_SINGLE_SLASH;
P
Peter Eisentraut 已提交
362 363
					options->action_string++;
				}
B
Bruce Momjian 已提交
364 365 366 367 368 369 370
				else
					options->action = ACT_SINGLE_QUERY;
				break;
			case 'd':
				options->dbname = optarg;
				break;
			case 'e':
371
				SetVariable(pset.vars, "ECHO", "queries");
B
Bruce Momjian 已提交
372 373
				break;
			case 'E':
374
				SetVariableBool(pset.vars, "ECHO_HIDDEN");
B
Bruce Momjian 已提交
375 376 377 378 379 380
				break;
			case 'f':
				options->action = ACT_FILE;
				options->action_string = optarg;
				break;
			case 'F':
381
				pset.popt.topt.fieldSep = xstrdup(optarg);
B
Bruce Momjian 已提交
382 383 384 385 386
				break;
			case 'h':
				options->host = optarg;
				break;
			case 'H':
387
				pset.popt.topt.format = PRINT_HTML;
B
Bruce Momjian 已提交
388 389 390 391 392 393 394 395
				break;
			case 'l':
				options->action = ACT_LIST_DB;
				break;
			case 'n':
				options->no_readline = true;
				break;
			case 'o':
396
				setQFout(optarg);
B
Bruce Momjian 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409
				break;
			case 'p':
				options->port = optarg;
				break;
			case 'P':
				{
					char	   *value;
					char	   *equal_loc;
					bool		result;

					value = xstrdup(optarg);
					equal_loc = strchr(value, '=');
					if (!equal_loc)
410
						result = do_pset(value, NULL, &pset.popt, true);
B
Bruce Momjian 已提交
411 412 413
					else
					{
						*equal_loc = '\0';
414
						result = do_pset(value, equal_loc + 1, &pset.popt, true);
B
Bruce Momjian 已提交
415 416 417 418
					}

					if (!result)
					{
419
						fprintf(stderr, "%s: couldn't set printing parameter %s\n", pset.progname, value);
B
Bruce Momjian 已提交
420 421 422 423 424 425 426
						exit(EXIT_FAILURE);
					}

					free(value);
					break;
				}
			case 'q':
427
				SetVariableBool(pset.vars, "QUIET");
B
Bruce Momjian 已提交
428
				break;
429 430 431
            case 'R':
                pset.popt.topt.recordSep = xstrdup(optarg);
                break;
B
Bruce Momjian 已提交
432
			case 's':
433
				SetVariableBool(pset.vars, "SINGLESTEP");
B
Bruce Momjian 已提交
434 435
				break;
			case 'S':
436
				SetVariableBool(pset.vars, "SINGLELINE");
B
Bruce Momjian 已提交
437 438
				break;
			case 't':
439
				pset.popt.topt.tuples_only = true;
B
Bruce Momjian 已提交
440 441
				break;
			case 'T':
442
				pset.popt.topt.tableAttr = xstrdup(optarg);
B
Bruce Momjian 已提交
443 444
				break;
			case 'u':
445 446 447 448
				pset.getPassword = true;
				options->username = "\001"; /* hopefully nobody has that username */
                /* this option is out */
                used_old_u_option = true;
B
Bruce Momjian 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461
				break;
			case 'U':
				options->username = optarg;
				break;
			case 'v':
				{
					char	   *value;
					char	   *equal_loc;

					value = xstrdup(optarg);
					equal_loc = strchr(value, '=');
					if (!equal_loc)
					{
462
						if (!DeleteVariable(pset.vars, value))
B
Bruce Momjian 已提交
463
						{
464
							fprintf(stderr, "%s: could not delete variable %s\n",
465
                                    pset.progname, value);
B
Bruce Momjian 已提交
466 467 468 469 470 471
							exit(EXIT_FAILURE);
						}
					}
					else
					{
						*equal_loc = '\0';
472
						if (!SetVariable(pset.vars, value, equal_loc + 1))
B
Bruce Momjian 已提交
473
						{
474 475
							fprintf(stderr, "%s: could not set variable %s\n",
                                    pset.progname, value);
B
Bruce Momjian 已提交
476 477 478 479 480 481 482 483
							exit(EXIT_FAILURE);
						}
					}

					free(value);
					break;
				}
			case 'V':
484 485
				showVersion();
				exit(EXIT_SUCCESS);
B
Bruce Momjian 已提交
486
			case 'W':
487
				pset.getPassword = true;
B
Bruce Momjian 已提交
488
				break;
489 490 491 492 493 494
			case 'x':
				pset.popt.topt.expanded = true;
				break;
            case 'X':
                options->no_psqlrc = true;
                break;
B
Bruce Momjian 已提交
495
			case '?':
P
Peter Eisentraut 已提交
496 497
                /* Actual help option given */
                if (strcmp(argv[optind-1], "-?")==0 || strcmp(argv[optind-1], "--help")==0)
P
Peter Eisentraut 已提交
498 499 500 501
                {
                    usage();
                    exit(EXIT_SUCCESS);
                }
P
Peter Eisentraut 已提交
502
                /* unknown option reported by getopt */
P
Peter Eisentraut 已提交
503 504 505 506 507
                else
                {
                    fputs("Try -? for help.\n", stderr);
                    exit(EXIT_FAILURE);
                }
B
Bruce Momjian 已提交
508
				break;
509
#ifndef HAVE_GETOPT_LONG
B
Bruce Momjian 已提交
510
			case '-':
511
				fprintf(stderr, "%s was compiled without support for long options.\n"
512
						"Use -? for help on invocation options.\n", pset.progname);
B
Bruce Momjian 已提交
513 514
				exit(EXIT_FAILURE);
				break;
515
#endif
B
Bruce Momjian 已提交
516
			default:
P
Peter Eisentraut 已提交
517
				fputs("Try -? for help.\n", stderr);
B
Bruce Momjian 已提交
518 519 520
				exit(EXIT_FAILURE);
				break;
		}
521 522
	}

B
Bruce Momjian 已提交
523 524 525 526 527 528 529 530 531 532
	/*
	 * if we still have arguments, use it as the database name and
	 * username
	 */
	while (argc - optind >= 1)
	{
		if (!options->dbname)
			options->dbname = argv[optind];
		else if (!options->username)
			options->username = argv[optind];
533
		else if (!QUIET())
534
			fprintf(stderr, "%s: warning: extra option %s ignored\n",
535
                    pset.progname, argv[optind]);
B
Bruce Momjian 已提交
536 537 538

		optind++;
	}
539 540 541 542

    if (used_old_u_option && !QUIET())
        fprintf(stderr, "%s: Warning: The -u option is deprecated. Use -U.\n", pset.progname);

543 544 545 546 547
}



/*
P
Peter Eisentraut 已提交
548
 * Load .psqlrc file, if found.
549 550
 */
static void
551
process_psqlrc(void)
552
{
B
Bruce Momjian 已提交
553 554
	char	   *psqlrc;
	char	   *home;
555 556 557 558 559

#ifdef WIN32
#define R_OK 0
#endif

B
Bruce Momjian 已提交
560 561
	/* Look for one in the home dir */
	home = getenv("HOME");
562

B
Bruce Momjian 已提交
563 564
	if (home)
	{
565
		psqlrc = malloc(strlen(home) + 20);
B
Bruce Momjian 已提交
566 567
		if (!psqlrc)
		{
P
Peter Eisentraut 已提交
568
            fprintf(stderr, "%s: out of memory\n", pset.progname);
B
Bruce Momjian 已提交
569 570
			exit(EXIT_FAILURE);
		}
571

B
Bruce Momjian 已提交
572 573
		sprintf(psqlrc, "%s/.psqlrc-" PG_RELEASE "." PG_VERSION "." PG_SUBVERSION, home);
		if (access(psqlrc, R_OK) == 0)
P
Peter Eisentraut 已提交
574
			process_file(psqlrc);
B
Bruce Momjian 已提交
575 576 577 578
		else
		{
			sprintf(psqlrc, "%s/.psqlrc", home);
			if (access(psqlrc, R_OK) == 0)
P
Peter Eisentraut 已提交
579
				process_file(psqlrc);
B
Bruce Momjian 已提交
580 581
		}
		free(psqlrc);
582 583 584 585 586 587 588
	}
}



/* showVersion
 *
589
 * This output format is intended to match GNU standards.
590 591
 */
static void
592
showVersion(void)
593
{
594
    puts("psql (PostgreSQL) " PG_RELEASE "." PG_VERSION "." PG_SUBVERSION);
595

596 597
#if defined(USE_READLINE) || defined (USE_HISTORY) || defined(MULTIBYTE)
    fputs("contains ", stdout);
598 599

#ifdef USE_READLINE
600 601
    fputs("readline", stdout);
#define _Feature
602
#endif
603

604
#ifdef USE_HISTORY
605 606 607 608
#ifdef _Feature
    fputs(", ", stdout);
#else
#define _Feature
609
#endif
610
    fputs("history", stdout);
611
#endif
612 613 614 615 616 617

#ifdef MULTIBYTE
#ifdef _Feature
    fputs(", ", stdout);
#else
#define _Feature
618
#endif
619
    fputs("multibyte", stdout);
620
#endif
621 622
    
#undef _Feature
623

624 625
    puts(" support");
#endif
626

B
Bruce Momjian 已提交
627
    puts("Portions Copyright (c) 1996-2000, PostgreSQL, Inc");
628
    puts("Portions Copyright (c) 1996 Regents of the University of California");
P
Peter Eisentraut 已提交
629
    puts("Read the file COPYRIGHT or use the command \\copyright to see the");
630
    puts("usage and distribution terms.");
631
}