pg_regress.c 45.6 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * pg_regress --- regression test driver
 *
 * This is a C implementation of the previous shell script for running
6
 * the regression tests, and should be mostly compatible with it.
7 8 9 10
 * Initial author of C translation: Magnus Hagander
 *
 * This code is released under the terms of the PostgreSQL License.
 *
11
 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
12 13
 * Portions Copyright (c) 1994, Regents of the University of California
 *
14
 * $PostgreSQL: pgsql/src/test/regress/pg_regress.c,v 1.29 2007/02/07 00:52:35 petere Exp $
15 16 17 18 19 20 21 22 23
 *
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"

#include <ctype.h>
#include <sys/stat.h>
#include <sys/wait.h>
24
#include <signal.h>
25 26
#include <unistd.h>

A
 
Andrew Dunstan 已提交
27 28 29 30 31
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif

32
#include "getopt_long.h"
33
#include "pg_config_paths.h"
34 35 36 37 38 39 40 41 42 43 44 45 46

#ifndef WIN32
#define PID_TYPE pid_t
#define INVALID_PID (-1)
#else
#define PID_TYPE HANDLE
#define INVALID_PID INVALID_HANDLE_VALUE
#endif


/* simple list of strings */
typedef struct _stringlist
{
B
Bruce Momjian 已提交
47
	char	   *str;
48
	struct _stringlist *next;
B
Bruce Momjian 已提交
49
}	_stringlist;
50 51 52 53

/* for resultmap we need a list of pairs of strings */
typedef struct _resultmap
{
B
Bruce Momjian 已提交
54 55
	char	   *test;
	char	   *resultfile;
56
	struct _resultmap *next;
B
Bruce Momjian 已提交
57
}	_resultmap;
58 59

/*
60 61 62 63 64
 * Values obtained from pg_config_paths.h and Makefile.  The PG installation
 * paths are only used in temp_install mode: we use these strings to find
 * out where "make install" will put stuff under the temp_install directory.
 * In non-temp_install mode, the only thing we need is the location of psql,
 * which we expect to find in psqldir, or in the PATH if psqldir isn't given.
65 66 67 68 69 70
 */
static char *bindir = PGBINDIR;
static char *libdir = LIBDIR;
static char *datadir = PGSHAREDIR;
static char *host_platform = HOST_TUPLE;
static char *makeprog = MAKEPROG;
B
Bruce Momjian 已提交
71

72
#ifndef WIN32					/* not used in WIN32 case */
73
static char *shellprog = SHELLPROG;
74
#endif
75 76 77 78 79 80 81 82 83 84 85

/* currently we can use the same diff switches on all platforms */
static const char *basic_diff_opts = "-w";
static const char *pretty_diff_opts = "-w -C3";

/* options settable from command line */
static char *dbname = "regression";
static bool debug = false;
static char *inputdir = ".";
static char *outputdir = ".";
static _stringlist *loadlanguage = NULL;
B
Bruce Momjian 已提交
86
static int	max_connections = 0;
87 88 89 90 91
static char *encoding = NULL;
static _stringlist *schedulelist = NULL;
static _stringlist *extra_tests = NULL;
static char *temp_install = NULL;
static char *top_builddir = NULL;
B
Bruce Momjian 已提交
92
static int	temp_port = 65432;
93
static bool nolocale = false;
94
static char *psqldir = NULL;
95
static char *hostname = NULL;
B
Bruce Momjian 已提交
96
static int	port = -1;
97
static char *user = NULL;
98
static char *srcdir = NULL;
99 100 101 102 103 104 105 106 107 108 109 110

/* internal variables */
static const char *progname;
static char *logfilename;
static FILE *logfile;
static char *difffilename;

static _resultmap *resultmap = NULL;

static PID_TYPE postmaster_pid = INVALID_PID;
static bool postmaster_running = false;

B
Bruce Momjian 已提交
111 112 113
static int	success_count = 0;
static int	fail_count = 0;
static int	fail_ignore_count = 0;
114

115 116 117 118 119
static bool
directory_exists(const char *dir);
static void
make_directory(const char *dir);

120 121 122 123 124 125 126 127 128 129 130
static void
header(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 1, 2)));
static void
status(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 1, 2)));
static void
B
Bruce Momjian 已提交
131
psql_command(const char *database, const char *query,...)
132 133 134 135
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 2, 3)));

A
 
Andrew Dunstan 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
/*
 * allow core files if possible.
 */
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
static void 
unlimit_core_size(void)
{
	struct rlimit lim;
	getrlimit(RLIMIT_CORE,&lim);
	if (lim.rlim_max == 0)
	{
		fprintf(stderr,
				_("%s: cannot set core size,: disallowed by hard limit.\n"), 
				progname);
		return;
	}
	else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
	{
		lim.rlim_cur = lim.rlim_max;
		setrlimit(RLIMIT_CORE,&lim);
	}	
}
#endif

160 161 162 163 164

/*
 * Add an item at the end of a stringlist.
 */
static void
B
Bruce Momjian 已提交
165
add_stringlist_item(_stringlist ** listhead, const char *str)
166 167 168 169 170 171 172 173 174 175 176
{
	_stringlist *newentry = malloc(sizeof(_stringlist));
	_stringlist *oldentry;

	newentry->str = strdup(str);
	newentry->next = NULL;
	if (*listhead == NULL)
		*listhead = newentry;
	else
	{
		for (oldentry = *listhead; oldentry->next; oldentry = oldentry->next)
B
Bruce Momjian 已提交
177
			 /* skip */ ;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
		oldentry->next = newentry;
	}
}

/*
 * Print a progress banner on stdout.
 */
static void
header(const char *fmt,...)
{
	char		tmp[64];
	va_list		ap;

	va_start(ap, fmt);
	vsnprintf(tmp, sizeof(tmp), fmt, ap);
	va_end(ap);

	fprintf(stdout, "============== %-38s ==============\n", tmp);
	fflush(stdout);
}

/*
 * Print "doing something ..." --- supplied text should not end with newline
 */
static void
status(const char *fmt,...)
{
	va_list		ap;

	va_start(ap, fmt);
	vfprintf(stdout, fmt, ap);
	fflush(stdout);
	va_end(ap);

	if (logfile)
	{
		va_start(ap, fmt);
		vfprintf(logfile, fmt, ap);
		va_end(ap);
	}
}

/*
 * Done "doing something ..."
 */
static void
status_end(void)
{
	fprintf(stdout, "\n");
	fflush(stdout);
	if (logfile)
		fprintf(logfile, "\n");
}

/*
 * shut down temp postmaster
 */
static void
stop_postmaster(void)
{
	if (postmaster_running)
	{
		/* We use pg_ctl to issue the kill and wait for stop */
B
Bruce Momjian 已提交
241
		char		buf[MAXPGPATH * 2];
242

243 244 245 246
		/* On Windows, system() seems not to force fflush, so... */
		fflush(stdout);
		fflush(stderr);

247
		snprintf(buf, sizeof(buf),
248
				 SYSTEMQUOTE "\"%s/pg_ctl\" stop -D \"%s/data\" -s -m fast" SYSTEMQUOTE,
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 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 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
				 bindir, temp_install);
		system(buf);			/* ignore exit status */
		postmaster_running = false;
	}
}

/*
 * Always exit through here, not through plain exit(), to ensure we make
 * an effort to shut down a temp postmaster
 */
static void
exit_nicely(int code)
{
	stop_postmaster();
	exit(code);
}

/*
 * Check whether string matches pattern
 *
 * In the original shell script, this function was implemented using expr(1),
 * which provides basic regular expressions restricted to match starting at
 * the string start (in conventional regex terms, there's an implicit "^"
 * at the start of the pattern --- but no implicit "$" at the end).
 *
 * For now, we only support "." and ".*" as non-literal metacharacters,
 * because that's all that anyone has found use for in resultmap.  This
 * code could be extended if more functionality is needed.
 */
static bool
string_matches_pattern(const char *str, const char *pattern)
{
	while (*str && *pattern)
	{
		if (*pattern == '.' && pattern[1] == '*')
		{
			pattern += 2;
			/* Trailing .* matches everything. */
			if (*pattern == '\0')
				return true;

			/*
			 * Otherwise, scan for a text position at which we can match the
			 * rest of the pattern.
			 */
			while (*str)
			{
				/*
				 * Optimization to prevent most recursion: don't recurse
				 * unless first pattern char might match this text char.
				 */
				if (*str == *pattern || *pattern == '.')
				{
					if (string_matches_pattern(str, pattern))
						return true;
				}

				str++;
			}

			/*
			 * End of text with no match.
			 */
			return false;
		}
		else if (*pattern != '.' && *str != *pattern)
		{
			/*
			 * Not the single-character wildcard and no explicit match? Then
			 * time to quit...
			 */
			return false;
		}

		str++;
		pattern++;
	}

	if (*pattern == '\0')
		return true;			/* end of pattern, so declare match */

	/* End of input string.  Do we have matching pattern remaining? */
	while (*pattern == '.' && pattern[1] == '*')
		pattern += 2;
	if (*pattern == '\0')
		return true;			/* end of pattern, so declare match */

	return false;
}

339 340 341 342 343 344 345 346 347 348 349 350 351
/*
 * Replace all occurances of a string in a string with a different string.
 * NOTE: Assumes there is enough room in the target buffer!
 */
static void
replace_string(char *string, char *replace, char *replacement)
{
	char *ptr;

	while ((ptr = strstr(string, replace)) != NULL) 
	{
		char *dup = strdup(string);

352
		strlcpy(string, dup, ptr - string + 1);
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 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 477 478 479
		strcat(string, replacement);
		strcat(string, dup + (ptr - string) + strlen(replace));
		free(dup);
	}
}

/*
 * Convert *.source found in the "source" directory, replacing certain tokens
 * in the file contents with their intended values, and put the resulting files
 * in the "dest" directory, replacing the ".source" prefix in their names with
 * the given suffix.
 */
static void
convert_sourcefiles_in(char *source, char *dest, char *suffix)
{
	char	abs_srcdir[MAXPGPATH];
	char	abs_builddir[MAXPGPATH];
	char	testtablespace[MAXPGPATH];
	char	indir[MAXPGPATH];
	char  **name;
	char  **names;
	int		count = 0;
#ifdef WIN32
	char *c;
#endif

	if (!getcwd(abs_builddir, sizeof(abs_builddir)))
	{
		fprintf(stderr, _("%s: could not get current directory: %s\n"),
			progname, strerror(errno));
		exit_nicely(2);
	}

	/*
	 * in a VPATH build, use the provided source directory; otherwise, use
	 * the current directory.
	 */
	if (srcdir)
		strcpy(abs_srcdir, srcdir);
	else
		strcpy(abs_srcdir, abs_builddir);

	snprintf(indir, MAXPGPATH, "%s/%s", abs_srcdir, source);
	names = pgfnames(indir);
	if (!names)
		/* Error logged in pgfnames */
		exit_nicely(2);

#ifdef WIN32
	/* in Win32, replace backslashes with forward slashes */
	for (c = abs_builddir; *c; c++)
		if (*c == '\\')
			*c = '/';
	for (c = abs_srcdir; *c; c++)
		if (*c == '\\')
			*c = '/';
#endif

	/* try to create the test tablespace dir if it doesn't exist */
	snprintf(testtablespace, MAXPGPATH, "%s/testtablespace", abs_builddir);
	if (directory_exists(testtablespace))
		rmtree(testtablespace, true);
	make_directory(testtablespace);

	/* finally loop on each file and do the replacement */
	for (name = names; *name; name++)
	{
		char	srcfile[MAXPGPATH];
		char	destfile[MAXPGPATH];
		char	prefix[MAXPGPATH];
		FILE   *infile,
			   *outfile;
		char	line[1024];

		/* reject filenames not finishing in ".source" */
		if (strlen(*name) < 8)
			continue;
		if (strcmp(*name + strlen(*name) - 7, ".source") != 0)
			continue;

		count++;

		/* build the full actual paths to open */
		snprintf(prefix, strlen(*name) - 6, "%s", *name);
		snprintf(srcfile, MAXPGPATH, "%s/%s", indir, *name);
		snprintf(destfile, MAXPGPATH, "%s/%s.%s", dest, prefix, suffix);

		infile = fopen(srcfile, "r");
		if (!infile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
					progname, srcfile, strerror(errno));
			exit_nicely(2);
		}
		outfile = fopen(destfile, "w");
		if (!outfile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, destfile, strerror(errno));
			exit_nicely(2);
		}
		while (fgets(line, sizeof(line), infile))
		{
			replace_string(line, "@abs_srcdir@", abs_srcdir);
			replace_string(line, "@abs_builddir@", abs_builddir);
			replace_string(line, "@testtablespace@", testtablespace);
			replace_string(line, "@DLSUFFIX@", DLSUFFIX);
			fputs(line, outfile);
		}
		fclose(infile);
		fclose(outfile);
	}

	/*
	 * If we didn't process any files, complain because it probably means
	 * somebody neglected to pass the needed --srcdir argument.
	 */
	if (count <= 0)
	{
		fprintf(stderr, _("%s: no *.source files found in %s\n"),
				progname, indir);
		exit_nicely(2);
	}
	
    pgfnames_cleanup(names);
}

480
/* Create the .sql and .out files from the .source files, if any */
481 482 483
static void
convert_sourcefiles(void)
{
484 485 486 487 488 489 490 491 492 493
	struct stat	st;
	int		ret;

	ret = stat("input", &st);
	if (ret == 0 && S_ISDIR(st.st_mode))
		convert_sourcefiles_in("input", "sql", "sql");

	ret = stat("output", &st);
	if (ret == 0 && S_ISDIR(st.st_mode))
		convert_sourcefiles_in("output", "expected", "out");
494 495
}

496 497 498 499
/*
 * Scan resultmap file to find which platform-specific expected files to use.
 *
 * The format of each line of the file is
B
Bruce Momjian 已提交
500
 *		   testname/hostplatformpattern=substitutefile
501 502 503 504
 * where the hostplatformpattern is evaluated per the rules of expr(1),
 * namely, it is a standard regular expression with an implicit ^ at the start.
 * (We currently support only a very limited subset of regular expressions,
 * see string_matches_pattern() above.)  What hostplatformpattern will be
B
Bruce Momjian 已提交
505
 * matched against is the config.guess output.	(In the shell-script version,
506 507 508 509 510 511
 * we also provided an indication of whether gcc or another compiler was in
 * use, but that facility isn't used anymore.)
 */
static void
load_resultmap(void)
{
B
Bruce Momjian 已提交
512 513
	char		buf[MAXPGPATH];
	FILE	   *f;
514 515 516

	/* scan the file ... */
	snprintf(buf, sizeof(buf), "%s/resultmap", inputdir);
B
Bruce Momjian 已提交
517
	f = fopen(buf, "r");
518 519 520 521 522 523 524 525 526
	if (!f)
	{
		/* OK if it doesn't exist, else complain */
		if (errno == ENOENT)
			return;
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, buf, strerror(errno));
		exit_nicely(2);
	}
527 528

	while (fgets(buf, sizeof(buf), f))
529
	{
B
Bruce Momjian 已提交
530 531 532
		char	   *platform;
		char	   *expected;
		int			i;
533 534 535

		/* strip trailing whitespace, especially the newline */
		i = strlen(buf);
B
Bruce Momjian 已提交
536
		while (i > 0 && isspace((unsigned char) buf[i - 1]))
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
			buf[--i] = '\0';

		/* parse out the line fields */
		platform = strchr(buf, '/');
		if (!platform)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
			exit_nicely(2);
		}
		*platform++ = '\0';
		expected = strchr(platform, '=');
		if (!expected)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
			exit_nicely(2);
		}
		*expected++ = '\0';

		/*
B
Bruce Momjian 已提交
558 559 560 561
		 * if it's for current platform, save it in resultmap list. Note: by
		 * adding at the front of the list, we ensure that in ambiguous cases,
		 * the last match in the resultmap file is used. This mimics the
		 * behavior of the old shell script.
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
		 */
		if (string_matches_pattern(host_platform, platform))
		{
			_resultmap *entry = malloc(sizeof(_resultmap));

			entry->test = strdup(buf);
			entry->resultfile = strdup(expected);
			entry->next = resultmap;
			resultmap = entry;
		}
	}
	fclose(f);
}

/*
 * Handy subroutine for setting an environment variable "var" to "val"
 */
static void
doputenv(const char *var, const char *val)
{
B
Bruce Momjian 已提交
582
	char	   *s = malloc(strlen(var) + strlen(val) + 2);
583 584 585 586 587 588 589 590 591 592 593 594

	sprintf(s, "%s=%s", var, val);
	putenv(s);
}

/*
 * Set the environment variable "pathname", prepending "addval" to its
 * old value (if any).
 */
static void
add_to_path(const char *pathname, char separator, const char *addval)
{
B
Bruce Momjian 已提交
595 596
	char	   *oldval = getenv(pathname);
	char	   *newval;
597 598 599 600 601 602 603 604 605 606

	if (!oldval || !oldval[0])
	{
		/* no previous value */
		newval = malloc(strlen(pathname) + strlen(addval) + 2);
		sprintf(newval, "%s=%s", pathname, addval);
	}
	else
	{
		newval = malloc(strlen(pathname) + strlen(addval) + strlen(oldval) + 3);
B
Bruce Momjian 已提交
607
		sprintf(newval, "%s=%s%c%s", pathname, addval, separator, oldval);
608 609 610 611 612 613 614 615 616 617
	}
	putenv(newval);
}

/*
 * Prepare environment variables for running regression tests
 */
static void
initialize_environment(void)
{
B
Bruce Momjian 已提交
618
	char	   *tmp;
619 620 621 622 623 624 625 626 627 628 629 630 631

	/*
	 * Clear out any non-C locale settings
	 */
	unsetenv("LC_COLLATE");
	unsetenv("LC_CTYPE");
	unsetenv("LC_MONETARY");
	unsetenv("LC_MESSAGES");
	unsetenv("LC_NUMERIC");
	unsetenv("LC_TIME");
	unsetenv("LC_ALL");
	unsetenv("LANG");
	unsetenv("LANGUAGE");
632
	/* On Windows the default locale cannot be English, so force it */
633
#if defined(WIN32) || defined(__CYGWIN__)
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
	putenv("LANG=en");
#endif

	/*
	 * Set multibyte as requested
	 */
	if (encoding)
		doputenv("PGCLIENTENCODING", encoding);
	else
		unsetenv("PGCLIENTENCODING");

	/*
	 * Set timezone and datestyle for datetime-related tests
	 */
	putenv("PGTZ=PST8PDT");
	putenv("PGDATESTYLE=Postgres, MDY");

	if (temp_install)
	{
		/*
B
Bruce Momjian 已提交
654 655 656 657 658 659
		 * Clear out any environment vars that might cause psql to connect to
		 * the wrong postmaster, or otherwise behave in nondefault ways. (Note
		 * we also use psql's -X switch consistently, so that ~/.psqlrc files
		 * won't mess things up.)  Also, set PGPORT to the temp port, and set
		 * or unset PGHOST depending on whether we are using TCP or Unix
		 * sockets.
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
		 */
		unsetenv("PGDATABASE");
		unsetenv("PGUSER");
		unsetenv("PGSERVICE");
		unsetenv("PGSSLMODE");
		unsetenv("PGREQUIRESSL");
		unsetenv("PGCONNECT_TIMEOUT");
		unsetenv("PGDATA");
		if (hostname != NULL)
			doputenv("PGHOST", hostname);
		else
			unsetenv("PGHOST");
		unsetenv("PGHOSTADDR");
		if (port != -1)
		{
B
Bruce Momjian 已提交
675
			char		s[16];
676

B
Bruce Momjian 已提交
677 678
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
		}

		/*
		 * Adjust path variables to point into the temp-install tree
		 */
		tmp = malloc(strlen(temp_install) + 32 + strlen(bindir));
		sprintf(tmp, "%s/install/%s", temp_install, bindir);
		bindir = tmp;

		tmp = malloc(strlen(temp_install) + 32 + strlen(libdir));
		sprintf(tmp, "%s/install/%s", temp_install, libdir);
		libdir = tmp;

		tmp = malloc(strlen(temp_install) + 32 + strlen(datadir));
		sprintf(tmp, "%s/install/%s", temp_install, datadir);
		datadir = tmp;

696 697 698
		/* psql will be installed into temp-install bindir */
		psqldir = bindir;

699 700 701 702
		/*
		 * Set up shared library paths to include the temp install.
		 *
		 * LD_LIBRARY_PATH covers many platforms.  DYLD_LIBRARY_PATH works on
B
Bruce Momjian 已提交
703
		 * Darwin, and maybe other Mach-based systems.	LIBPATH is for AIX.
704
		 * Windows needs shared libraries in PATH (only those linked into
B
Bruce Momjian 已提交
705 706
		 * executables, not dlopen'ed ones). Feel free to account for others
		 * as well.
707 708 709
		 */
		add_to_path("LD_LIBRARY_PATH", ':', libdir);
		add_to_path("DYLD_LIBRARY_PATH", ':', libdir);
710
		add_to_path("LIBPATH", ':', libdir);
711
#if defined(WIN32) || defined(__CYGWIN__)
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
		add_to_path("PATH", ';', libdir);
#endif
	}
	else
	{
		const char *pghost;
		const char *pgport;

		/*
		 * When testing an existing install, we honor existing environment
		 * variables, except if they're overridden by command line options.
		 */
		if (hostname != NULL)
		{
			doputenv("PGHOST", hostname);
			unsetenv("PGHOSTADDR");
		}
		if (port != -1)
		{
B
Bruce Momjian 已提交
731
			char		s[16];
732

B
Bruce Momjian 已提交
733 734
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
		}
		if (user != NULL)
			doputenv("PGUSER", user);

		/*
		 * Report what we're connecting to
		 */
		pghost = getenv("PGHOST");
		pgport = getenv("PGPORT");
#ifndef HAVE_UNIX_SOCKETS
		if (!pghost)
			pghost = "localhost";
#endif

		if (pghost && pgport)
			printf(_("(using postmaster on %s, port %s)\n"), pghost, pgport);
		if (pghost && !pgport)
			printf(_("(using postmaster on %s, default port)\n"), pghost);
		if (!pghost && pgport)
			printf(_("(using postmaster on Unix socket, port %s)\n"), pgport);
		if (!pghost && !pgport)
			printf(_("(using postmaster on Unix socket, default port)\n"));
	}

759
	convert_sourcefiles();
760 761 762 763 764 765 766 767 768
	load_resultmap();
}

/*
 * Issue a command via psql, connecting to the specified database
 *
 * Since we use system(), this doesn't return until the operation finishes
 */
static void
B
Bruce Momjian 已提交
769
psql_command(const char *database, const char *query,...)
770
{
B
Bruce Momjian 已提交
771 772 773 774 775 776
	char		query_formatted[1024];
	char		query_escaped[2048];
	char		psql_cmd[MAXPGPATH + 2048];
	va_list		args;
	char	   *s;
	char	   *d;
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

	/* Generate the query with insertion of sprintf arguments */
	va_start(args, query);
	vsnprintf(query_formatted, sizeof(query_formatted), query, args);
	va_end(args);

	/* Now escape any shell double-quote metacharacters */
	d = query_escaped;
	for (s = query_formatted; *s; s++)
	{
		if (strchr("\\\"$`", *s))
			*d++ = '\\';
		*d++ = *s;
	}
	*d = '\0';

	/* And now we can build and execute the shell command */
	snprintf(psql_cmd, sizeof(psql_cmd),
795 796 797 798 799
			 SYSTEMQUOTE "\"%s%spsql\" -X -c \"%s\" \"%s\"" SYSTEMQUOTE,
			 psqldir ? psqldir : "",
			 psqldir ? "/" : "",
			 query_escaped,
			 database);
800 801 802 803 804 805 806 807 808 809 810 811

	if (system(psql_cmd) != 0)
	{
		/* psql probably already reported the error */
		fprintf(stderr, _("command failed: %s\n"), psql_cmd);
		exit_nicely(2);
	}
}

/*
 * Spawn a process to execute the given shell command; don't wait for it
 *
812
 * Returns the process ID (or HANDLE) so we can wait for it later
813 814 815 816 817
 */
static PID_TYPE
spawn_process(const char *cmdline)
{
#ifndef WIN32
B
Bruce Momjian 已提交
818
	pid_t		pid;
819 820

	/*
B
Bruce Momjian 已提交
821
	 * Must flush I/O buffers before fork.	Ideally we'd use fflush(NULL) here
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
	 * ... does anyone still care about systems where that doesn't work?
	 */
	fflush(stdout);
	fflush(stderr);
	if (logfile)
		fflush(logfile);

	pid = fork();
	if (pid == -1)
	{
		fprintf(stderr, _("%s: could not fork: %s\n"),
				progname, strerror(errno));
		exit_nicely(2);
	}
	if (pid == 0)
	{
838 839 840
		/*
		 * In child
		 *
B
Bruce Momjian 已提交
841 842 843
		 * Instead of using system(), exec the shell directly, and tell it to
		 * "exec" the command too.	This saves two useless processes per
		 * parallel test case.
844
		 */
B
Bruce Momjian 已提交
845
		char	   *cmdline2 = malloc(strlen(cmdline) + 6);
846 847 848 849 850 851

		sprintf(cmdline2, "exec %s", cmdline);
		execl(shellprog, shellprog, "-c", cmdline2, NULL);
		fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
				progname, shellprog, strerror(errno));
		exit(1);				/* not exit_nicely here... */
852 853 854 855
	}
	/* in parent */
	return pid;
#else
B
Bruce Momjian 已提交
856
	char	   *cmdline2;
857 858 859 860 861 862 863 864 865 866 867
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);

	cmdline2 = malloc(strlen(cmdline) + 8);
	sprintf(cmdline2, "cmd /c %s", cmdline);

	if (!CreateProcess(NULL, cmdline2, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
	{
868
		fprintf(stderr, _("could not start process for \"%s\": %lu\n"),
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
				cmdline2, GetLastError());
		exit_nicely(2);
	}
	free(cmdline2);

	CloseHandle(pi.hThread);
	return pi.hProcess;
#endif
}

/*
 * start a psql test process for specified file (including redirection),
 * and return process ID
 */
static PID_TYPE
psql_start_test(const char *testname)
{
B
Bruce Momjian 已提交
886 887 888 889
	PID_TYPE	pid;
	char		infile[MAXPGPATH];
	char		outfile[MAXPGPATH];
	char		psql_cmd[MAXPGPATH * 3];
890 891 892 893 894 895 896

	snprintf(infile, sizeof(infile), "%s/sql/%s.sql",
			 inputdir, testname);
	snprintf(outfile, sizeof(outfile), "%s/results/%s.out",
			 outputdir, testname);

	snprintf(psql_cmd, sizeof(psql_cmd),
897 898 899 900 901 902
			 SYSTEMQUOTE "\"%s%spsql\" -X -a -q -d \"%s\" < \"%s\" > \"%s\" 2>&1" SYSTEMQUOTE,
			 psqldir ? psqldir : "",
			 psqldir ? "/" : "",
			 dbname,
			 infile,
			 outfile);
903 904 905 906 907

	pid = spawn_process(psql_cmd);

	if (pid == INVALID_PID)
	{
908
		fprintf(stderr, _("could not start process for test %s\n"),
909 910 911 912 913 914 915 916 917 918 919 920 921
				testname);
		exit_nicely(2);
	}

	return pid;
}

/*
 * Count bytes in file
 */
static long
file_size(const char *file)
{
B
Bruce Momjian 已提交
922 923
	long		r;
	FILE	   *f = fopen(file, "r");
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

	if (!f)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, file, strerror(errno));
		return -1;
	}
	fseek(f, 0, SEEK_END);
	r = ftell(f);
	fclose(f);
	return r;
}

/*
 * Count lines in file
 */
static int
file_line_count(const char *file)
{
B
Bruce Momjian 已提交
943 944 945
	int			c;
	int			l = 0;
	FILE	   *f = fopen(file, "r");
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

	if (!f)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, file, strerror(errno));
		return -1;
	}
	while ((c = fgetc(f)) != EOF)
	{
		if (c == '\n')
			l++;
	}
	fclose(f);
	return l;
}

static bool
file_exists(const char *file)
{
B
Bruce Momjian 已提交
965
	FILE	   *f = fopen(file, "r");
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988

	if (!f)
		return false;
	fclose(f);
	return true;
}

static bool
directory_exists(const char *dir)
{
	struct stat st;

	if (stat(dir, &st) != 0)
		return false;
	if (st.st_mode & S_IFDIR)
		return true;
	return false;
}

/* Create a directory */
static void
make_directory(const char *dir)
{
989
	if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
990 991 992 993 994 995 996
	{
		fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
				progname, dir, strerror(errno));
		exit_nicely(2);
	}
}

997
/*
998
 * Run a "diff" command and also check that it didn't crash
999
 */
1000 1001
static int
run_diff(const char *cmd, const char *filename)
1002
{
B
Bruce Momjian 已提交
1003
	int			r;
1004 1005 1006 1007 1008 1009 1010

	r = system(cmd);
	if (!WIFEXITED(r) || WEXITSTATUS(r) > 1)
	{
		fprintf(stderr, _("diff command failed with status %d: %s\n"), r, cmd);
		exit_nicely(2);
	}
1011
#ifdef WIN32
B
Bruce Momjian 已提交
1012

1013
	/*
B
Bruce Momjian 已提交
1014 1015
	 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
	 * but produces nothing to stdout, so we check for that here.
1016 1017 1018 1019 1020 1021 1022
	 */
	if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
	{
		fprintf(stderr, _("diff command not found: %s\n"), cmd);
		exit_nicely(2);
	}
#endif
B
Bruce Momjian 已提交
1023

1024
	return WEXITSTATUS(r);
1025 1026
}

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/*
 * Check the actual result file for the given test against expected results
 *
 * Returns true if different (failure), false if correct match found.
 * In the true case, the diff is appended to the diffs file.
 */
static bool
results_differ(const char *testname)
{
	const char *expectname;
B
Bruce Momjian 已提交
1037 1038 1039 1040 1041
	char		resultsfile[MAXPGPATH];
	char		expectfile[MAXPGPATH];
	char		diff[MAXPGPATH];
	char		cmd[MAXPGPATH * 3];
	char		best_expect_file[MAXPGPATH];
1042
	_resultmap *rm;
B
Bruce Momjian 已提交
1043 1044 1045 1046 1047
	FILE	   *difffile;
	int			best_line_count;
	int			i;
	int			l;

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	/* Check in resultmap if we should be looking at a different file */
	expectname = testname;
	for (rm = resultmap; rm != NULL; rm = rm->next)
	{
		if (strcmp(testname, rm->test) == 0)
		{
			expectname = rm->resultfile;
			break;
		}
	}

	/* Name of test results file */
	snprintf(resultsfile, sizeof(resultsfile), "%s/results/%s.out",
			 outputdir, testname);

	/* Name of expected-results file */
	snprintf(expectfile, sizeof(expectfile), "%s/expected/%s.out",
			 inputdir, expectname);

	/* Name to use for temporary diff file */
	snprintf(diff, sizeof(diff), "%s/results/%s.diff",
			 outputdir, testname);

	/* OK, run the diff */
	snprintf(cmd, sizeof(cmd),
1073
			 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
1074 1075 1076
			 basic_diff_opts, expectfile, resultsfile, diff);

	/* Is the diff file empty? */
1077
	if (run_diff(cmd, diff) == 0)
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	{
		unlink(diff);
		return false;
	}

	/* There may be secondary comparison files that match better */
	best_line_count = file_line_count(diff);
	strcpy(best_expect_file, expectfile);

	for (i = 0; i <= 9; i++)
	{
		snprintf(expectfile, sizeof(expectfile), "%s/expected/%s_%d.out",
				 inputdir, expectname, i);
		if (!file_exists(expectfile))
			continue;

		snprintf(cmd, sizeof(cmd),
1095
				 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
1096 1097
				 basic_diff_opts, expectfile, resultsfile, diff);

1098
		if (run_diff(cmd, diff) == 0)
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
		{
			unlink(diff);
			return false;
		}

		l = file_line_count(diff);
		if (l < best_line_count)
		{
			/* This diff was a better match than the last one */
			best_line_count = l;
			strcpy(best_expect_file, expectfile);
		}
	}

B
Bruce Momjian 已提交
1113 1114 1115
	/*
	 * fall back on the canonical results file if we haven't tried it yet and
	 * haven't found a complete match yet.
A
 
Andrew Dunstan 已提交
1116 1117 1118 1119 1120
	 */

	if (strcmp(expectname, testname) != 0)
	{
		snprintf(expectfile, sizeof(expectfile), "%s/expected/%s.out",
1121
				 inputdir, testname);
A
 
Andrew Dunstan 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

		snprintf(cmd, sizeof(cmd),
				 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
				 basic_diff_opts, expectfile, resultsfile, diff);

		if (run_diff(cmd, diff) == 0)
		{
			/* No diff = no changes = good */
			unlink(diff);
			return false;
		}

		l = file_line_count(diff);
		if (l < best_line_count)
		{
			/* This diff was a better match than the last one */
			best_line_count = l;
			strcpy(best_expect_file, expectfile);
		}
	}

1143
	/*
B
Bruce Momjian 已提交
1144 1145
	 * Use the best comparison file to generate the "pretty" diff, which we
	 * append to the diffs summary file.
1146 1147
	 */
	snprintf(cmd, sizeof(cmd),
1148
			 SYSTEMQUOTE "diff %s \"%s\" \"%s\" >> \"%s\"" SYSTEMQUOTE,
1149
			 pretty_diff_opts, best_expect_file, resultsfile, difffilename);
1150
	run_diff(cmd, difffilename);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

	/* And append a separator */
	difffile = fopen(difffilename, "a");
	if (difffile)
	{
		fprintf(difffile,
				"\n======================================================================\n\n");
		fclose(difffile);
	}

	unlink(diff);
	return true;
}

/*
 * Wait for specified subprocesses to finish
1167 1168 1169 1170
 *
 * If names isn't NULL, report each subprocess as it finishes
 *
 * Note: it's OK to scribble on the pids array, but not on the names array
1171 1172
 */
static void
B
Bruce Momjian 已提交
1173
wait_for_tests(PID_TYPE * pids, char **names, int num_tests)
1174
{
B
Bruce Momjian 已提交
1175 1176
	int			tests_left;
	int			i;
1177

1178
#ifdef WIN32
B
Bruce Momjian 已提交
1179
	PID_TYPE   *active_pids = malloc(num_tests * sizeof(PID_TYPE));
1180 1181 1182 1183

	memcpy(active_pids, pids, num_tests * sizeof(PID_TYPE));
#endif

1184 1185 1186
	tests_left = num_tests;
	while (tests_left > 0)
	{
B
Bruce Momjian 已提交
1187
		PID_TYPE	p;
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

#ifndef WIN32
		p = wait(NULL);

		if (p == INVALID_PID)
		{
			fprintf(stderr, _("failed to wait for subprocesses: %s\n"),
					strerror(errno));
			exit_nicely(2);
		}
#else
B
Bruce Momjian 已提交
1199
		int			r;
1200

1201 1202
		r = WaitForMultipleObjects(tests_left, active_pids, FALSE, INFINITE);
		if (r < WAIT_OBJECT_0 || r >= WAIT_OBJECT_0 + tests_left)
1203
		{
1204 1205
			fprintf(stderr, _("failed to wait for subprocesses: %lu\n"),
					GetLastError());
1206 1207
			exit_nicely(2);
		}
1208 1209 1210
		p = active_pids[r - WAIT_OBJECT_0];
		/* compact the active_pids array */
		active_pids[r - WAIT_OBJECT_0] = active_pids[tests_left - 1];
B
Bruce Momjian 已提交
1211
#endif   /* WIN32 */
1212

B
Bruce Momjian 已提交
1213
		for (i = 0; i < num_tests; i++)
1214 1215 1216
		{
			if (p == pids[i])
			{
1217 1218 1219 1220 1221 1222
#ifdef WIN32
				CloseHandle(pids[i]);
#endif
				pids[i] = INVALID_PID;
				if (names)
					status(" %s", names[i]);
1223
				tests_left--;
1224
				break;
1225 1226 1227 1228
			}
		}
	}

1229 1230
#ifdef WIN32
	free(active_pids);
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
#endif
}

/*
 * Run all the tests specified in one schedule file
 */
static void
run_schedule(const char *schedule)
{
#define MAX_PARALLEL_TESTS 100
B
Bruce Momjian 已提交
1241 1242
	char	   *tests[MAX_PARALLEL_TESTS];
	PID_TYPE	pids[MAX_PARALLEL_TESTS];
1243
	_stringlist *ignorelist = NULL;
B
Bruce Momjian 已提交
1244 1245 1246
	char		scbuf[1024];
	FILE	   *scf;
	int			line_num = 0;
1247 1248 1249 1250 1251 1252 1253 1254 1255

	scf = fopen(schedule, "r");
	if (!scf)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, schedule, strerror(errno));
		exit_nicely(2);
	}

1256
	while (fgets(scbuf, sizeof(scbuf), scf))
1257
	{
B
Bruce Momjian 已提交
1258 1259 1260 1261 1262
		char	   *test = NULL;
		char	   *c;
		int			num_tests;
		bool		inword;
		int			i;
1263 1264 1265 1266 1267

		line_num++;

		/* strip trailing whitespace, especially the newline */
		i = strlen(scbuf);
B
Bruce Momjian 已提交
1268
		while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
			scbuf[--i] = '\0';

		if (scbuf[0] == '\0' || scbuf[0] == '#')
			continue;
		if (strncmp(scbuf, "test: ", 6) == 0)
			test = scbuf + 6;
		else if (strncmp(scbuf, "ignore: ", 8) == 0)
		{
			c = scbuf + 8;
			while (*c && isspace((unsigned char) *c))
				c++;
			add_stringlist_item(&ignorelist, c);
B
Bruce Momjian 已提交
1281

1282 1283
			/*
			 * Note: ignore: lines do not run the test, they just say that
B
Bruce Momjian 已提交
1284 1285
			 * failure of this test when run later on is to be ignored. A bit
			 * odd but that's how the shell-script version did it.
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
			 */
			continue;
		}
		else
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
			exit_nicely(2);
		}

		num_tests = 0;
		inword = false;
		for (c = test; *c; c++)
		{
			if (isspace((unsigned char) *c))
			{
				*c = '\0';
				inword = false;
			}
			else if (!inword)
			{
				if (num_tests >= MAX_PARALLEL_TESTS)
				{
					/* can't print scbuf here, it's already been trashed */
					fprintf(stderr, _("too many parallel tests in schedule file \"%s\", line %d\n"),
							schedule, line_num);
					exit_nicely(2);
				}
				tests[num_tests] = c;
				num_tests++;
				inword = true;
			}
		}

		if (num_tests == 0)
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
			exit_nicely(2);
		}

		if (num_tests == 1)
		{
			status(_("test %-20s ... "), tests[0]);
			pids[0] = psql_start_test(tests[0]);
1331
			wait_for_tests(pids, NULL, 1);
1332 1333 1334 1335
			/* status line is finished below */
		}
		else if (max_connections > 0 && max_connections < num_tests)
		{
B
Bruce Momjian 已提交
1336
			int			oldest = 0;
1337 1338 1339 1340 1341 1342 1343

			status(_("parallel group (%d tests, in groups of %d): "),
				   num_tests, max_connections);
			for (i = 0; i < num_tests; i++)
			{
				if (i - oldest >= max_connections)
				{
1344
					wait_for_tests(pids + oldest, tests + oldest, i - oldest);
1345 1346 1347 1348
					oldest = i;
				}
				pids[i] = psql_start_test(tests[i]);
			}
1349
			wait_for_tests(pids + oldest, tests + oldest, i - oldest);
1350 1351 1352 1353 1354 1355 1356 1357 1358
			status_end();
		}
		else
		{
			status(_("parallel group (%d tests): "), num_tests);
			for (i = 0; i < num_tests; i++)
			{
				pids[i] = psql_start_test(tests[i]);
			}
1359
			wait_for_tests(pids, tests, num_tests);
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
			status_end();
		}

		/* Check results for all tests */
		for (i = 0; i < num_tests; i++)
		{
			if (num_tests > 1)
				status(_("     %-20s ... "), tests[i]);

			if (results_differ(tests[i]))
			{
B
Bruce Momjian 已提交
1371
				bool		ignore = false;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
				_stringlist *sl;

				for (sl = ignorelist; sl != NULL; sl = sl->next)
				{
					if (strcmp(tests[i], sl->str) == 0)
					{
						ignore = true;
						break;
					}
				}
				if (ignore)
				{
					status(_("failed (ignored)"));
					fail_ignore_count++;
				}
				else
				{
					status(_("FAILED"));
					fail_count++;
				}
			}
			else
			{
				status(_("ok"));
				success_count++;
			}

			status_end();
		}
	}

	fclose(scf);
}

/*
 * Run a single test
 */
static void
run_single_test(const char *test)
{
B
Bruce Momjian 已提交
1412
	PID_TYPE	pid;
1413 1414 1415

	status(_("test %-20s ... "), test);
	pid = psql_start_test(test);
1416
	wait_for_tests(&pid, NULL, 1);
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

	if (results_differ(test))
	{
		status(_("FAILED"));
		fail_count++;
	}
	else
	{
		status(_("ok"));
		success_count++;
	}
	status_end();
}

/*
 * Create the summary-output files (making them empty if already existing)
 */
static void
open_result_files(void)
{
B
Bruce Momjian 已提交
1437 1438
	char		file[MAXPGPATH];
	FILE	   *difffile;
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

	/* create the log file (copy of running status output) */
	snprintf(file, sizeof(file), "%s/regression.out", outputdir);
	logfilename = strdup(file);
	logfile = fopen(logfilename, "w");
	if (!logfile)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, logfilename, strerror(errno));
		exit_nicely(2);
	}

	/* create the diffs file as empty */
	snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
	difffilename = strdup(file);
	difffile = fopen(difffilename, "w");
	if (!difffile)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, difffilename, strerror(errno));
		exit_nicely(2);
	}
	/* we don't keep the diffs file open continuously */
	fclose(difffile);

	/* also create the output directory if not present */
	snprintf(file, sizeof(file), "%s/results", outputdir);
	if (!directory_exists(file))
		make_directory(file);
}

static void
help(void)
{
	printf(_("PostgreSQL regression test driver\n"));
	printf(_("\n"));
	printf(_("Usage: %s [options...] [extra tests...]\n"), progname);
	printf(_("\n"));
	printf(_("Options:\n"));
	printf(_("  --dbname=DB               use database DB (default \"regression\")\n"));
	printf(_("  --debug                   turn on debug mode in programs that are run\n"));
	printf(_("  --inputdir=DIR            take input files from DIR (default \".\")\n"));
	printf(_("  --load-language=lang      load the named language before running the\n"));
	printf(_("                            tests; can appear multiple times\n"));
	printf(_("  --max-connections=N       maximum number of concurrent connections\n"));
	printf(_("                            (default is 0 meaning unlimited)\n"));
	printf(_("  --multibyte=ENCODING      use ENCODING as the multibyte encoding\n"));
	printf(_("  --outputdir=DIR           place output files in DIR (default \".\")\n"));
	printf(_("  --schedule=FILE           use test ordering schedule from FILE\n"));
1488
	printf(_("                            (can be used multiple times to concatenate)\n"));
1489
	printf(_("  --srcdir=DIR              absolute path to source directory (for VPATH builds)\n"));
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
	printf(_("  --temp-install=DIR        create a temporary installation in DIR\n"));
	printf(_("  --no-locale               use C locale\n"));
	printf(_("\n"));
	printf(_("Options for \"temp-install\" mode:\n"));
	printf(_("  --top-builddir=DIR        (relative) path to top level build directory\n"));
	printf(_("  --temp-port=PORT          port number to start temp postmaster on\n"));
	printf(_("\n"));
	printf(_("Options for using an existing installation:\n"));
	printf(_("  --host=HOST               use postmaster running on HOST\n"));
	printf(_("  --port=PORT               use postmaster running at PORT\n"));
	printf(_("  --user=USER               connect as USER\n"));
1501
	printf(_("  --psqldir=DIR             use psql in DIR (default: find in PATH)\n"));
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
	printf(_("\n"));
	printf(_("The exit status is 0 if all tests passed, 1 if some tests failed, and 2\n"));
	printf(_("if the tests could not be run for some reason.\n"));
	printf(_("\n"));
	printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
}

int
main(int argc, char *argv[])
{
	_stringlist *sl;
B
Bruce Momjian 已提交
1513 1514 1515 1516
	int			c;
	int			i;
	int			option_index;
	char		buf[MAXPGPATH * 4];
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

	static struct option long_options[] = {
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{"dbname", required_argument, NULL, 1},
		{"debug", no_argument, NULL, 2},
		{"inputdir", required_argument, NULL, 3},
		{"load-language", required_argument, NULL, 4},
		{"max-connections", required_argument, NULL, 5},
		{"multibyte", required_argument, NULL, 6},
		{"outputdir", required_argument, NULL, 7},
		{"schedule", required_argument, NULL, 8},
		{"temp-install", required_argument, NULL, 9},
		{"no-locale", no_argument, NULL, 10},
		{"top-builddir", required_argument, NULL, 11},
		{"temp-port", required_argument, NULL, 12},
		{"host", required_argument, NULL, 13},
		{"port", required_argument, NULL, 14},
		{"user", required_argument, NULL, 15},
1536
		{"psqldir", required_argument, NULL, 16},
1537
		{"srcdir", required_argument, NULL, 17},
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
		{NULL, 0, NULL, 0}
	};

	progname = get_progname(argv[0]);
	set_pglocale_pgservice(argv[0], "pg_regress");

#ifndef HAVE_UNIX_SOCKETS
	/* no unix domain sockets available, so change default */
	hostname = "localhost";
#endif

	while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
	{
		switch (c)
		{
			case 'h':
				help();
				exit_nicely(0);
			case 'V':
				printf("pg_regress (PostgreSQL %s)\n", PG_VERSION);
				exit_nicely(0);
			case 1:
				dbname = strdup(optarg);
				break;
			case 2:
				debug = true;
				break;
			case 3:
				inputdir = strdup(optarg);
				break;
			case 4:
				add_stringlist_item(&loadlanguage, optarg);
				break;
			case 5:
				max_connections = atoi(optarg);
				break;
			case 6:
				encoding = strdup(optarg);
				break;
			case 7:
				outputdir = strdup(optarg);
				break;
			case 8:
				add_stringlist_item(&schedulelist, optarg);
				break;
			case 9:
				/* temp_install must be absolute path */
				if (is_absolute_path(optarg))
					temp_install = strdup(optarg);
				else
				{
B
Bruce Momjian 已提交
1589
					char		cwdbuf[MAXPGPATH];
1590 1591 1592 1593 1594 1595 1596

					if (!getcwd(cwdbuf, sizeof(cwdbuf)))
					{
						fprintf(stderr, _("could not get current working directory: %s\n"), strerror(errno));
						exit_nicely(2);
					}
					temp_install = malloc(strlen(cwdbuf) + strlen(optarg) + 2);
B
Bruce Momjian 已提交
1597
					sprintf(temp_install, "%s/%s", cwdbuf, optarg);
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
				}
				canonicalize_path(temp_install);
				break;
			case 10:
				nolocale = true;
				break;
			case 11:
				top_builddir = strdup(optarg);
				break;
			case 12:
				{
B
Bruce Momjian 已提交
1609
					int			p = atoi(optarg);
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624

					/* Since Makefile isn't very bright, check port range */
					if (p >= 1024 && p <= 65535)
						temp_port = p;
				}
				break;
			case 13:
				hostname = strdup(optarg);
				break;
			case 14:
				port = atoi(optarg);
				break;
			case 15:
				user = strdup(optarg);
				break;
1625 1626 1627 1628 1629
			case 16:
				/* "--psqldir=" should mean to use PATH */
				if (strlen(optarg))
					psqldir = strdup(optarg);
				break;
1630 1631 1632
			case 17:
				srcdir = strdup(optarg);
				break;
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
			default:
				/* getopt_long already emitted a complaint */
				fprintf(stderr, _("\nTry \"%s -h\" for more information.\n"),
						progname);
				exit_nicely(2);
		}
	}

	/*
	 * if we still have arguments, they are extra tests to run
	 */
	while (argc - optind >= 1)
	{
		add_stringlist_item(&extra_tests, argv[optind]);
		optind++;
	}

	if (temp_install)
		port = temp_port;

	/*
	 * Initialization
	 */
	open_result_files();

	initialize_environment();

A
 
Andrew Dunstan 已提交
1660 1661 1662 1663
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
	unlimit_core_size();
#endif

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
	if (temp_install)
	{
		/*
		 * Prepare the temp installation
		 */
		if (!top_builddir)
		{
			fprintf(stderr, _("--top-builddir must be specified when using --temp-install\n"));
			exit_nicely(2);
		}

		if (directory_exists(temp_install))
		{
			header(_("removing existing temp installation"));
B
Bruce Momjian 已提交
1678
			rmtree(temp_install, true);
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
		}

		header(_("creating temporary installation"));

		/* make the temp install top directory */
		make_directory(temp_install);

		/* and a directory for log files */
		snprintf(buf, sizeof(buf), "%s/log", outputdir);
		if (!directory_exists(buf))
			make_directory(buf);

		/* "make install" */
		snprintf(buf, sizeof(buf),
1693
				 SYSTEMQUOTE "\"%s\" -C \"%s\" DESTDIR=\"%s/install\" install with_perl=no with_python=no > \"%s/log/install.log\" 2>&1" SYSTEMQUOTE,
1694
				 makeprog, top_builddir, temp_install, outputdir);
1695 1696
		if (system(buf))
		{
1697
			fprintf(stderr, _("\n%s: installation failed\nExamine %s/log/install.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
1698 1699 1700 1701 1702 1703
			exit_nicely(2);
		}

		/* initdb */
		header(_("initializing database system"));
		snprintf(buf, sizeof(buf),
1704
				 SYSTEMQUOTE "\"%s/initdb\" -D \"%s/data\" -L \"%s\" --noclean%s%s > \"%s/log/initdb.log\" 2>&1" SYSTEMQUOTE,
1705
				 bindir, temp_install, datadir,
1706 1707
				 debug ? " --debug" : "",
				 nolocale ? " --no-locale" : "",
1708 1709 1710
				 outputdir);
		if (system(buf))
		{
1711
			fprintf(stderr, _("\n%s: initdb failed\nExamine %s/log/initdb.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
1712 1713 1714 1715 1716 1717 1718 1719
			exit_nicely(2);
		}

		/*
		 * Start the temp postmaster
		 */
		header(_("starting postmaster"));
		snprintf(buf, sizeof(buf),
1720
				 SYSTEMQUOTE "\"%s/postgres\" -D \"%s/data\" -F%s -c \"listen_addresses=%s\" > \"%s/log/postmaster.log\" 2>&1" SYSTEMQUOTE,
1721
				 bindir, temp_install,
1722
				 debug ? " -d 5" : "",
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
				 hostname ? hostname : "",
				 outputdir);
		postmaster_pid = spawn_process(buf);
		if (postmaster_pid == INVALID_PID)
		{
			fprintf(stderr, _("\n%s: could not spawn postmaster: %s\n"),
					progname, strerror(errno));
			exit_nicely(2);
		}

		/*
B
Bruce Momjian 已提交
1734 1735 1736
		 * Wait till postmaster is able to accept connections (normally only a
		 * second or so, but Cygwin is reportedly *much* slower).  Don't wait
		 * forever, however.
1737 1738
		 */
		snprintf(buf, sizeof(buf),
1739
				 SYSTEMQUOTE "\"%s/psql\" -X postgres <%s 2>%s" SYSTEMQUOTE,
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
				 bindir, DEVNULL, DEVNULL);
		for (i = 0; i < 60; i++)
		{
			/* Done if psql succeeds */
			if (system(buf) == 0)
				break;

			/*
			 * Fail immediately if postmaster has exited
			 */
#ifndef WIN32
			if (kill(postmaster_pid, 0) != 0)
1752 1753 1754
#else
			if (WaitForSingleObject(postmaster_pid, 0) == WAIT_OBJECT_0)
#endif
1755 1756 1757 1758 1759 1760 1761
			{
				fprintf(stderr, _("\n%s: postmaster failed\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
				exit_nicely(2);
			}

			pg_usleep(1000000L);
		}
1762
		if (i >= 60)
1763
		{
1764 1765 1766
			fprintf(stderr, _("\n%s: postmaster did not respond within 60 seconds\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);

			/*
B
Bruce Momjian 已提交
1767 1768 1769
			 * If we get here, the postmaster is probably wedged somewhere in
			 * startup.  Try to kill it ungracefully rather than leaving a
			 * stuck postmaster that might interfere with subsequent test
1770 1771 1772 1773 1774 1775 1776
			 * attempts.
			 */
#ifndef WIN32
			if (kill(postmaster_pid, SIGKILL) != 0 &&
				errno != ESRCH)
				fprintf(stderr, _("\n%s: could not kill failed postmaster: %s\n"),
						progname, strerror(errno));
1777 1778 1779 1780
#else
			if (TerminateProcess(postmaster_pid, 255) == 0)
				fprintf(stderr, _("\n%s: could not kill failed postmaster: %lu\n"),
						progname, GetLastError());
1781 1782
#endif

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
			exit_nicely(2);
		}

		postmaster_running = true;

		printf(_("running on port %d with pid %lu\n"),
			   temp_port, (unsigned long) postmaster_pid);
	}
	else
	{
		/*
		 * Using an existing installation, so may need to get rid of
		 * pre-existing database.
		 */
		header(_("dropping database \"%s\""), dbname);
B
Bruce Momjian 已提交
1798
		psql_command("postgres", "DROP DATABASE IF EXISTS \"%s\"", dbname);
1799 1800 1801 1802 1803
	}

	/*
	 * Create the test database
	 *
B
Bruce Momjian 已提交
1804 1805
	 * We use template0 so that any installation-local cruft in template1 will
	 * not mess up the tests.
1806 1807 1808 1809
	 */
	header(_("creating database \"%s\""), dbname);
	if (encoding)
		psql_command("postgres",
B
Bruce Momjian 已提交
1810
				   "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'",
1811
					 dbname, encoding);
B
Bruce Momjian 已提交
1812 1813
	else
		/* use installation default */
1814 1815 1816 1817 1818 1819 1820 1821
		psql_command("postgres",
					 "CREATE DATABASE \"%s\" TEMPLATE=template0",
					 dbname);

	psql_command(dbname,
				 "ALTER DATABASE \"%s\" SET lc_messages TO 'C';"
				 "ALTER DATABASE \"%s\" SET lc_monetary TO 'C';"
				 "ALTER DATABASE \"%s\" SET lc_numeric TO 'C';"
1822
				 "ALTER DATABASE \"%s\" SET lc_time TO 'C';"
B
Bruce Momjian 已提交
1823
			"ALTER DATABASE \"%s\" SET timezone_abbreviations TO 'Default';",
1824
				 dbname, dbname, dbname, dbname, dbname);
1825 1826 1827 1828 1829 1830 1831 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 1863 1864 1865 1866 1867

	/*
	 * Install any requested PL languages
	 */
	for (sl = loadlanguage; sl != NULL; sl = sl->next)
	{
		header(_("installing %s"), sl->str);
		psql_command(dbname, "CREATE LANGUAGE \"%s\"", sl->str);
	}

	/*
	 * Ready to run the tests
	 */
	header(_("running regression test queries"));

	for (sl = schedulelist; sl != NULL; sl = sl->next)
	{
		run_schedule(sl->str);
	}

	for (sl = extra_tests; sl != NULL; sl = sl->next)
	{
		run_single_test(sl->str);
	}

	/*
	 * Shut down temp installation's postmaster
	 */
	if (temp_install)
	{
		header(_("shutting down postmaster"));
		stop_postmaster();
	}

	fclose(logfile);

	/*
	 * Emit nice-looking summary message
	 */
	if (fail_count == 0 && fail_ignore_count == 0)
		snprintf(buf, sizeof(buf),
				 _(" All %d tests passed. "),
				 success_count);
B
Bruce Momjian 已提交
1868
	else if (fail_count == 0)	/* fail_count=0, fail_ignore_count>0 */
1869 1870 1871 1872 1873
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests passed, %d failed test(s) ignored. "),
				 success_count,
				 success_count + fail_ignore_count,
				 fail_ignore_count);
B
Bruce Momjian 已提交
1874
	else if (fail_ignore_count == 0)	/* fail_count>0 && fail_ignore_count=0 */
1875 1876 1877
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed. "),
				 fail_count,
B
Bruce Momjian 已提交
1878 1879 1880
				 success_count + fail_count);
	else
		/* fail_count>0 && fail_ignore_count>0 */
1881 1882
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed, %d of these failures ignored. "),
B
Bruce Momjian 已提交
1883 1884
				 fail_count + fail_ignore_count,
				 success_count + fail_count + fail_ignore_count,
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
				 fail_ignore_count);

	putchar('\n');
	for (i = strlen(buf); i > 0; i--)
		putchar('=');
	printf("\n%s\n", buf);
	for (i = strlen(buf); i > 0; i--)
		putchar('=');
	putchar('\n');
	putchar('\n');

	if (file_size(difffilename) > 0)
	{
		printf(_("The differences that caused some tests to fail can be viewed in the\n"
				 "file \"%s\".  A copy of the test summary that you see\n"
				 "above is saved in the file \"%s\".\n\n"),
			   difffilename, logfilename);
	}
	else
	{
		unlink(difffilename);
		unlink(logfilename);
	}

	if (fail_count != 0)
		exit_nicely(1);

	return 0;
}