startup.c 12.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include <config.h>
#include <c.h>

#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

#ifdef WIN32
#include <io.h>
#include <window.h>
#else
#include <unistd.h>
#endif

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

#include <libpq-fe.h>
#include <pqsignal.h>
#include <version.h>

#include "settings.h"
#include "command.h"
#include "help.h"
#include "mainloop.h"
#include "common.h"
#include "input.h"
#include "variables.h"
#include "print.h"
#include "describe.h"



static void
B
Bruce Momjian 已提交
40
process_psqlrc(PsqlSettings *pset);
41 42

static void
B
Bruce Momjian 已提交
43
showVersion(PsqlSettings *pset);
44 45 46 47 48


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

B
Bruce Momjian 已提交
59 60 61 62 63 64 65 66 67
struct adhoc_opts
{
	char	   *dbname;
	char	   *host;
	char	   *port;
	char	   *username;
	enum _actions action;
	char	   *action_string;
	bool		no_readline;
68 69 70
};

static void
B
Bruce Momjian 已提交
71
parse_options(int argc, char *argv[], PsqlSettings *pset, struct adhoc_opts * options);
72 73 74 75 76 77 78 79 80 81 82



/*
 *
 * main()
 *
 */
int
main(int argc, char **argv)
{
B
Bruce Momjian 已提交
83 84 85
	PsqlSettings settings;
	struct adhoc_opts options;
	int			successResult;
86

B
Bruce Momjian 已提交
87 88 89
	char	   *username = NULL;
	char	   *password = NULL;
	bool		need_pass;
90

B
Bruce Momjian 已提交
91
	MemSet(&settings, 0, sizeof settings);
92

B
Bruce Momjian 已提交
93 94
	settings.cur_cmd_source = stdin;
	settings.cur_cmd_interactive = false;
95

B
Bruce Momjian 已提交
96 97 98 99 100
	settings.vars = CreateVariableSpace();
	settings.popt.topt.format = PRINT_ALIGNED;
	settings.queryFout = stdout;
	settings.popt.topt.fieldSep = strdup(DEFAULT_FIELD_SEP);
	settings.popt.topt.border = 1;
B
Bruce Momjian 已提交
101
	settings.popt.topt.pager = 1;
102

B
Bruce Momjian 已提交
103 104 105
	SetVariable(settings.vars, "prompt1", DEFAULT_PROMPT1);
	SetVariable(settings.vars, "prompt2", DEFAULT_PROMPT2);
	SetVariable(settings.vars, "prompt3", DEFAULT_PROMPT3);
106

B
Bruce Momjian 已提交
107
	settings.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
108

B
Bruce Momjian 已提交
109
	/* This is obsolete and will be removed very soon. */
110
#ifdef PSQL_ALWAYS_GET_PASSWORDS
B
Bruce Momjian 已提交
111
	settings.getPassword = true;
112
#else
B
Bruce Momjian 已提交
113
	settings.getPassword = false;
114 115 116
#endif

#ifdef MULTIBYTE
B
Bruce Momjian 已提交
117
	settings.has_client_encoding = (getenv("PGCLIENTENCODING") != NULL);
118 119
#endif

B
Bruce Momjian 已提交
120
	parse_options(argc, argv, &settings, &options);
121

B
Bruce Momjian 已提交
122 123
	if (options.action == ACT_LIST_DB || options.action == ACT_SHOW_VER)
		options.dbname = "template1";
124

B
Bruce Momjian 已提交
125 126 127 128 129 130
	if (options.username)
	{
		if (strcmp(options.username, "?") == 0)
			username = simple_prompt("Username: ", 100, true);
		else
			username = strdup(options.username);
131 132
	}

B
Bruce Momjian 已提交
133 134
	if (settings.getPassword)
		password = simple_prompt("Password: ", 100, false);
135

B
Bruce Momjian 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	/* loop until we have a password if requested by backend */
	do
	{
		need_pass = false;
		settings.db = PQsetdbLogin(options.host, options.port, NULL, NULL, options.dbname, username, password);

		if (PQstatus(settings.db) == CONNECTION_BAD &&
			strcmp(PQerrorMessage(settings.db), "fe_sendauth: no password supplied\n") == 0)
		{
			need_pass = true;
			free(password);
			password = NULL;
			password = simple_prompt("Password: ", 100, false);
		}
	} while (need_pass);
151

B
Bruce Momjian 已提交
152 153 154
	free(username);
	free(password);

B
Bruce Momjian 已提交
155
	if (PQstatus(settings.db) == CONNECTION_BAD && options.action != ACT_SHOW_VER)
B
Bruce Momjian 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
	{
		fprintf(stderr, "Connection to database '%s' failed.\n%s\n", PQdb(settings.db), PQerrorMessage(settings.db));
		PQfinish(settings.db);
		exit(EXIT_BADCONN);
	}

	if (options.action == ACT_LIST_DB)
	{
		int			success = listAllDbs(&settings);

		PQfinish(settings.db);
		exit(!success);
	}

	if (options.action == ACT_SHOW_VER)
	{
B
Bruce Momjian 已提交
172
		showVersion(&settings);
B
Bruce Momjian 已提交
173 174 175 176 177 178 179
		PQfinish(settings.db);
		exit(EXIT_SUCCESS);
	}


	if (!GetVariable(settings.vars, "quiet") && !settings.notty && !options.action)
	{
B
Bruce Momjian 已提交
180 181
		puts("Welcome to psql, the PostgreSQL interactive terminal.\n\n"
		     "Type:  \\copyright for distribution terms\n"
B
Bruce Momjian 已提交
182 183 184 185
			 "       \\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");
B
Bruce Momjian 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
	}

	process_psqlrc(&settings);

	initializeInput(options.no_readline ? 0 : 1);

	/* Now find something to do */

	/* process file given by -f */
	if (options.action == ACT_FILE)
		successResult = process_file(options.action_string, &settings) ? 0 : 1;
	/* process slash command if one was given to -c */
	else if (options.action == ACT_SINGLE_SLASH)
		successResult = HandleSlashCmds(&settings, options.action_string, NULL, NULL) != CMD_ERROR ? 0 : 1;
	/* If the query given to -c was a normal one, send it */
	else if (options.action == ACT_SINGLE_QUERY)
		successResult = SendQuery(&settings, options.action_string) ? 0 : 1;
	/* or otherwise enter interactive main loop */
	else
		successResult = MainLoop(&settings, stdin);

	/* clean up */
	finishInput();
209
	PQfinish(settings.db);
B
Bruce Momjian 已提交
210 211 212 213
	setQFout(NULL, &settings);
	DestroyVariableSpace(settings.vars);

	return successResult;
214 215 216 217 218 219 220 221 222 223
}



/*
 * Parse command line options
 */

#ifdef WIN32
/* getopt is not in the standard includes on Win32 */
B
Bruce Momjian 已提交
224 225
int			getopt(int, char *const[], const char *);

226 227 228
#endif

static void
B
Bruce Momjian 已提交
229
parse_options(int argc, char *argv[], PsqlSettings *pset, struct adhoc_opts * options)
230 231
{
#ifdef HAVE_GETOPT_LONG
B
Bruce Momjian 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	static struct option long_options[] = {
		{"no-align", no_argument, NULL, 'A'},
		{"command", required_argument, NULL, 'c'},
		{"database", required_argument, NULL, 'd'},
		{"dbname", required_argument, NULL, 'd'},
		{"echo", no_argument, NULL, 'e'},
		{"echo-queries", no_argument, NULL, 'e'},
		{"echo-all", no_argument, NULL, 'E'},
		{"echo-all-queries", no_argument, NULL, 'E'},
		{"file", required_argument, NULL, 'f'},
		{"field-sep", required_argument, NULL, 'F'},
		{"host", required_argument, NULL, 'h'},
		{"html", no_argument, NULL, 'H'},
		{"list", no_argument, NULL, 'l'},
		{"no-readline", no_argument, NULL, 'n'},
		{"out", required_argument, NULL, 'o'},
		{"to-file", required_argument, NULL, 'o'},
		{"port", required_argument, NULL, 'p'},
		{"pset", required_argument, NULL, 'P'},
		{"quiet", no_argument, NULL, 'q'},
		{"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'},
		{"expanded", no_argument, NULL, 'x'},
		{"set", required_argument, NULL, 'v'},
		{"variable", required_argument, NULL, 'v'},
		{"version", no_argument, NULL, 'V'},
		{"password", no_argument, NULL, 'W'},
		{"help", no_argument, NULL, '?'},
	};

	int			optindex;

267 268
#endif

B
Bruce Momjian 已提交
269 270 271
	extern char *optarg;
	extern int	optind;
	int			c;
272

B
Bruce Momjian 已提交
273
	MemSet(options, 0, sizeof *options);
274 275

#ifdef HAVE_GETOPT_LONG
B
Bruce Momjian 已提交
276
	while ((c = getopt_long(argc, argv, "Ac:d:eEf:F:lh:Hno:p:P:qsStT:uU:v:VWx?", long_options, &optindex)) != -1)
277
#else
B
Bruce Momjian 已提交
278 279 280 281 282 283

	/*
	 * Be sure to leave the '-' in here, so we can catch accidental long
	 * options.
	 */
	while ((c = getopt(argc, argv, "Ac:d:eEf:F:lh:Hno:p:P:qsStT:uU:v:VWx?-")) != -1)
284 285
#endif
	{
B
Bruce Momjian 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
		switch (c)
		{
			case 'A':
				pset->popt.topt.format = PRINT_UNALIGNED;
				break;
			case 'c':
				options->action_string = optarg;
				if (optarg[0] == '\\')
					options->action = ACT_SINGLE_SLASH;
				else
					options->action = ACT_SINGLE_QUERY;
				break;
			case 'd':
				options->dbname = optarg;
				break;
			case 'e':
				SetVariable(pset->vars, "echo", "");
				break;
			case 'E':
				SetVariable(pset->vars, "echo_secret", "");
				break;
			case 'f':
				options->action = ACT_FILE;
				options->action_string = optarg;
				break;
			case 'F':
				pset->popt.topt.fieldSep = strdup(optarg);
				break;
			case 'h':
				options->host = optarg;
				break;
			case 'H':
				pset->popt.topt.format = PRINT_HTML;
				break;
			case 'l':
				options->action = ACT_LIST_DB;
				break;
			case 'n':
				options->no_readline = true;
				break;
			case 'o':
				setQFout(optarg, pset);
				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)
						result = do_pset(value, NULL, &pset->popt, true);
					else
					{
						*equal_loc = '\0';
						result = do_pset(value, equal_loc + 1, &pset->popt, true);
					}

					if (!result)
					{
						fprintf(stderr, "Couldn't set printing paramter %s.\n", value);
						exit(EXIT_FAILURE);
					}

					free(value);
					break;
				}
			case 'q':
				SetVariable(pset->vars, "quiet", "");
				break;
			case 's':
				SetVariable(pset->vars, "singlestep", "");
				break;
			case 'S':
				SetVariable(pset->vars, "singleline", "");
				break;
			case 't':
				pset->popt.topt.tuples_only = true;
				break;
			case 'T':
				pset->popt.topt.tableAttr = xstrdup(optarg);
				break;
			case 'u':
				pset->getPassword = true;
				options->username = "?";
				break;
			case 'U':
				options->username = optarg;
				break;
			case 'x':
				pset->popt.topt.expanded = true;
				break;
			case 'v':
				{
					char	   *value;
					char	   *equal_loc;

					value = xstrdup(optarg);
					equal_loc = strchr(value, '=');
					if (!equal_loc)
					{
						if (!DeleteVariable(pset->vars, value))
						{
							fprintf(stderr, "Couldn't delete variable %s.\n", value);
							exit(EXIT_FAILURE);
						}
					}
					else
					{
						*equal_loc = '\0';
						if (!SetVariable(pset->vars, value, equal_loc + 1))
						{
							fprintf(stderr, "Couldn't set variable %s to %s.\n", value, equal_loc);
							exit(EXIT_FAILURE);
						}
					}

					free(value);
					break;
				}
			case 'V':
				options->action = ACT_SHOW_VER;
				break;
			case 'W':
				pset->getPassword = true;
				break;
			case '?':
				usage();
				exit(EXIT_SUCCESS);
				break;
420
#ifndef HAVE_GETOPT_LONG
B
Bruce Momjian 已提交
421 422 423 424 425
			case '-':
				fprintf(stderr, "This version of psql was compiled without support for long options.\n"
						"Use -? for help on invocation options.\n");
				exit(EXIT_FAILURE);
				break;
426
#endif
B
Bruce Momjian 已提交
427 428 429 430 431
			default:
				usage();
				exit(EXIT_FAILURE);
				break;
		}
432 433
	}

B
Bruce Momjian 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
	/*
	 * 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];
		else
			fprintf(stderr, "Warning: extra option %s ignored.\n", argv[optind]);

		optind++;
	}
449 450 451 452 453 454 455 456
}



/*
 * Load /etc/psqlrc or .psqlrc file, if found.
 */
static void
B
Bruce Momjian 已提交
457
process_psqlrc(PsqlSettings *pset)
458
{
B
Bruce Momjian 已提交
459 460
	char	   *psqlrc;
	char	   *home;
461 462 463 464 465

#ifdef WIN32
#define R_OK 0
#endif

B
Bruce Momjian 已提交
466 467 468 469 470
	/* System-wide startup file */
	if (access("/etc/psqlrc-" PG_RELEASE "." PG_VERSION "." PG_SUBVERSION, R_OK) == 0)
		process_file("/etc/psqlrc-" PG_RELEASE "." PG_VERSION "." PG_SUBVERSION, pset);
	else if (access("/etc/psqlrc", R_OK) == 0)
		process_file("/etc/psqlrc", pset);
471

B
Bruce Momjian 已提交
472 473
	/* Look for one in the home dir */
	home = getenv("HOME");
474

B
Bruce Momjian 已提交
475 476 477 478 479 480 481 482
	if (home)
	{
		psqlrc = (char *) malloc(strlen(home) + 20);
		if (!psqlrc)
		{
			perror("malloc");
			exit(EXIT_FAILURE);
		}
483

B
Bruce Momjian 已提交
484 485 486 487 488 489 490 491 492 493
		sprintf(psqlrc, "%s/.psqlrc-" PG_RELEASE "." PG_VERSION "." PG_SUBVERSION, home);
		if (access(psqlrc, R_OK) == 0)
			process_file(psqlrc, pset);
		else
		{
			sprintf(psqlrc, "%s/.psqlrc", home);
			if (access(psqlrc, R_OK) == 0)
				process_file(psqlrc, pset);
		}
		free(psqlrc);
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
	}
}



/* showVersion
 *
 * Displays the database backend version.
 * Also checks against the version psql was compiled for and makes
 * sure that there are no problems.
 *
 * Returns false if there was a problem retrieving the information
 * or a mismatch was detected.
 */
static void
B
Bruce Momjian 已提交
509
showVersion(PsqlSettings *pset)
510
{
B
Bruce Momjian 已提交
511 512
	PGresult   *res = NULL;
	const char *versionstr = NULL;
B
Bruce Momjian 已提交
513 514 515 516 517
	long int	release = 0,
				version = 0,
				subversion = 0;

	/* get backend version */
B
Bruce Momjian 已提交
518
	if (pset->db && PQstatus(pset->db) == CONNECTION_OK) {
B
Bruce Momjian 已提交
519 520 521 522 523
	res = PSQLexec(pset, "SELECT version()");
	if (PQresultStatus(res) == PGRES_TUPLES_OK)
		versionstr = PQgetvalue(res, 0, 0);
	}

B
Bruce Momjian 已提交
524
	if (versionstr && strncmp(versionstr, "PostgreSQL ", 11) == 0)
B
Bruce Momjian 已提交
525 526
	{
		char	   *tmp;
527

B
Bruce Momjian 已提交
528 529 530 531
		release = strtol(&versionstr[11], &tmp, 10);
		version = strtol(tmp + 1, &tmp, 10);
		subversion = strtol(tmp + 1, &tmp, 10);
	}
532

B
Bruce Momjian 已提交
533
	printf("Server: %s\npsql", versionstr ? versionstr : "(could not connect)");
534

B
Bruce Momjian 已提交
535
	if (!versionstr || strcmp(versionstr, PG_VERSION_STR) != 0)
B
Bruce Momjian 已提交
536 537
		printf(&PG_VERSION_STR[strcspn(PG_VERSION_STR, " ")]);
	printf(" (" __DATE__ " " __TIME__ ")");
538 539

#ifdef MULTIBYTE
B
Bruce Momjian 已提交
540
	printf(", multibyte");
541 542
#endif
#ifdef HAVE_GETOPT_LONG
B
Bruce Momjian 已提交
543
	printf(", long options");
544 545
#endif
#ifdef USE_READLINE
B
Bruce Momjian 已提交
546
	printf(", readline");
547 548
#endif
#ifdef USE_HISTORY
B
Bruce Momjian 已提交
549
	printf(", history");
550 551
#endif
#ifdef USE_LOCALE
B
Bruce Momjian 已提交
552
	printf(", locale");
553 554
#endif
#ifdef PSQL_ALWAYS_GET_PASSWORDS
B
Bruce Momjian 已提交
555
	printf(", always password");
556 557
#endif
#ifdef USE_ASSERT_CHECKING
B
Bruce Momjian 已提交
558
	printf(", assert checks");
559 560
#endif

B
Bruce Momjian 已提交
561
	puts("");
562

B
Bruce Momjian 已提交
563
	if (versionstr && (release < 6 || (release == 6 && version < 5)))
B
Bruce Momjian 已提交
564 565 566
		puts("\nWarning: The server you are connected to is potentially too old for this client\n"
			 "version. You should ideally be using clients and servers from the same\n"
			 "distribution.");
567

B
Bruce Momjian 已提交
568
	if (res)
B
Bruce Momjian 已提交
569
	PQclear(res);
570
}