1 /*-------------------------------------------------------------------------
3 * pg_regress --- regression test driver
5 * This is a C implementation of the previous shell script for running
6 * the regression tests, and should be mostly compatible with it.
7 * Initial author of C translation: Magnus Hagander
9 * This code is released under the terms of the PostgreSQL License.
11 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
14 * src/test/regress/pg_regress.c
16 *-------------------------------------------------------------------------
19 #include "pg_regress.h"
27 #ifdef HAVE_SYS_RESOURCE_H
29 #include <sys/resource.h>
32 #include "common/restricted_token.h"
33 #include "common/username.h"
34 #include "getopt_long.h"
35 #include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */
36 #include "pg_config_paths.h"
38 /* for resultmap we need a list of pairs of strings */
39 typedef struct _resultmap
44 struct _resultmap *next;
48 * Values obtained from Makefile.
50 char *host_platform = HOST_TUPLE;
52 #ifndef WIN32 /* not used in WIN32 case */
53 static char *shellprog = SHELLPROG;
57 * On Windows we use -w in diff switches to avoid problems with inconsistent
58 * newline representation. The actual result files will generally have
59 * Windows-style newlines, but the comparison files might or might not.
62 const char *basic_diff_opts = "";
63 const char *pretty_diff_opts = "-C3";
65 const char *basic_diff_opts = "-w";
66 const char *pretty_diff_opts = "-w -C3";
69 /* options settable from command line */
70 _stringlist *dblist = NULL;
73 char *outputdir = ".";
74 char *bindir = PGBINDIR;
75 char *launcher = NULL;
76 static _stringlist *loadlanguage = NULL;
77 static _stringlist *loadextension = NULL;
78 static int max_connections = 0;
79 static char *encoding = NULL;
80 static _stringlist *schedulelist = NULL;
81 static _stringlist *extra_tests = NULL;
82 static char *temp_instance = NULL;
83 static _stringlist *temp_configs = NULL;
84 static bool nolocale = false;
85 static bool use_existing = false;
86 static char *hostname = NULL;
88 static bool port_specified_by_user = false;
89 static char *dlpath = PKGLIBDIR;
90 static char *user = NULL;
91 static _stringlist *extraroles = NULL;
92 static char *config_auth_datadir = NULL;
94 /* internal variables */
95 static const char *progname;
96 static char *logfilename;
98 static char *difffilename;
99 static const char *sockdir;
100 #ifdef HAVE_UNIX_SOCKETS
101 static const char *temp_sockdir;
102 static char sockself[MAXPGPATH];
103 static char socklock[MAXPGPATH];
106 static _resultmap *resultmap = NULL;
108 static PID_TYPE postmaster_pid = INVALID_PID;
109 static bool postmaster_running = false;
111 static int success_count = 0;
112 static int fail_count = 0;
113 static int fail_ignore_count = 0;
115 static bool directory_exists(const char *dir);
116 static void make_directory(const char *dir);
118 static void header(const char *fmt,...) pg_attribute_printf(1, 2);
119 static void status(const char *fmt,...) pg_attribute_printf(1, 2);
120 static void psql_command(const char *database, const char *query,...) pg_attribute_printf(2, 3);
123 * allow core files if possible.
125 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
127 unlimit_core_size(void)
131 getrlimit(RLIMIT_CORE, &lim);
132 if (lim.rlim_max == 0)
135 _("%s: could not set core size: disallowed by hard limit\n"),
139 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
141 lim.rlim_cur = lim.rlim_max;
142 setrlimit(RLIMIT_CORE, &lim);
149 * Add an item at the end of a stringlist.
152 add_stringlist_item(_stringlist **listhead, const char *str)
154 _stringlist *newentry = pg_malloc(sizeof(_stringlist));
155 _stringlist *oldentry;
157 newentry->str = pg_strdup(str);
158 newentry->next = NULL;
159 if (*listhead == NULL)
160 *listhead = newentry;
163 for (oldentry = *listhead; oldentry->next; oldentry = oldentry->next)
165 oldentry->next = newentry;
173 free_stringlist(_stringlist **listhead)
175 if (listhead == NULL || *listhead == NULL)
177 if ((*listhead)->next != NULL)
178 free_stringlist(&((*listhead)->next));
179 free((*listhead)->str);
185 * Split a delimited string into a stringlist
188 split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
190 char *sc = pg_strdup(s);
191 char *token = strtok(sc, delim);
195 add_stringlist_item(listhead, token);
196 token = strtok(NULL, delim);
202 * Print a progress banner on stdout.
205 header(const char *fmt,...)
211 vsnprintf(tmp, sizeof(tmp), fmt, ap);
214 fprintf(stdout, "============== %-38s ==============\n", tmp);
219 * Print "doing something ..." --- supplied text should not end with newline
222 status(const char *fmt,...)
227 vfprintf(stdout, fmt, ap);
234 vfprintf(logfile, fmt, ap);
240 * Done "doing something ..."
245 fprintf(stdout, "\n");
248 fprintf(logfile, "\n");
252 * shut down temp postmaster
255 stop_postmaster(void)
257 if (postmaster_running)
259 /* We use pg_ctl to issue the kill and wait for stop */
260 char buf[MAXPGPATH * 2];
263 /* On Windows, system() seems not to force fflush, so... */
267 snprintf(buf, sizeof(buf),
268 "\"%s%spg_ctl\" stop -D \"%s/data\" -s",
269 bindir ? bindir : "",
275 fprintf(stderr, _("\n%s: could not stop postmaster: exit code was %d\n"),
277 _exit(2); /* not exit(), that could be recursive */
280 postmaster_running = false;
284 #ifdef HAVE_UNIX_SOCKETS
286 * Remove the socket temporary directory. pg_regress never waits for a
287 * postmaster exit, so it is indeterminate whether the postmaster has yet to
288 * unlink the socket and lock file. Unlink them here so we can proceed to
289 * remove the directory. Ignore errors; leaking a temporary directory is
290 * unimportant. This can run from a signal handler. The code is not
291 * acceptable in a Windows signal handler (see initdb.c:trapsig()), but
292 * Windows is not a HAVE_UNIX_SOCKETS platform.
297 Assert(temp_sockdir);
304 * Signal handler that calls remove_temp() and reraises the signal.
307 signal_remove_temp(int signum)
311 pqsignal(signum, SIG_DFL);
316 * Create a temporary directory suitable for the server's Unix-domain socket.
317 * The directory will have mode 0700 or stricter, so no other OS user can open
318 * our socket to exploit our use of trust authentication. Most systems
319 * constrain the length of socket paths well below _POSIX_PATH_MAX, so we
320 * place the directory under /tmp rather than relative to the possibly-deep
321 * current working directory.
323 * Compared to using the compiled-in DEFAULT_PGSOCKET_DIR, this also permits
324 * testing to work in builds that relocate it to a directory not writable to
325 * the build/test user.
328 make_temp_sockdir(void)
330 char *template = pg_strdup("/tmp/pg_regress-XXXXXX");
332 temp_sockdir = mkdtemp(template);
333 if (temp_sockdir == NULL)
335 fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
336 progname, template, strerror(errno));
340 /* Stage file names for remove_temp(). Unsafe in a signal handler. */
341 UNIXSOCK_PATH(sockself, port, temp_sockdir);
342 snprintf(socklock, sizeof(socklock), "%s.lock", sockself);
344 /* Remove the directory during clean exit. */
348 * Remove the directory before dying to the usual signals. Omit SIGQUIT,
349 * preserving it as a quick, untidy exit.
351 pqsignal(SIGHUP, signal_remove_temp);
352 pqsignal(SIGINT, signal_remove_temp);
353 pqsignal(SIGPIPE, signal_remove_temp);
354 pqsignal(SIGTERM, signal_remove_temp);
358 #endif /* HAVE_UNIX_SOCKETS */
361 * Check whether string matches pattern
363 * In the original shell script, this function was implemented using expr(1),
364 * which provides basic regular expressions restricted to match starting at
365 * the string start (in conventional regex terms, there's an implicit "^"
366 * at the start of the pattern --- but no implicit "$" at the end).
368 * For now, we only support "." and ".*" as non-literal metacharacters,
369 * because that's all that anyone has found use for in resultmap. This
370 * code could be extended if more functionality is needed.
373 string_matches_pattern(const char *str, const char *pattern)
375 while (*str && *pattern)
377 if (*pattern == '.' && pattern[1] == '*')
380 /* Trailing .* matches everything. */
381 if (*pattern == '\0')
385 * Otherwise, scan for a text position at which we can match the
386 * rest of the pattern.
391 * Optimization to prevent most recursion: don't recurse
392 * unless first pattern char might match this text char.
394 if (*str == *pattern || *pattern == '.')
396 if (string_matches_pattern(str, pattern))
404 * End of text with no match.
408 else if (*pattern != '.' && *str != *pattern)
411 * Not the single-character wildcard and no explicit match? Then
421 if (*pattern == '\0')
422 return true; /* end of pattern, so declare match */
424 /* End of input string. Do we have matching pattern remaining? */
425 while (*pattern == '.' && pattern[1] == '*')
427 if (*pattern == '\0')
428 return true; /* end of pattern, so declare match */
434 * Replace all occurrences of a string in a string with a different string.
435 * NOTE: Assumes there is enough room in the target buffer!
438 replace_string(char *string, char *replace, char *replacement)
442 while ((ptr = strstr(string, replace)) != NULL)
444 char *dup = pg_strdup(string);
446 strlcpy(string, dup, ptr - string + 1);
447 strcat(string, replacement);
448 strcat(string, dup + (ptr - string) + strlen(replace));
454 * Convert *.source found in the "source" directory, replacing certain tokens
455 * in the file contents with their intended values, and put the resulting files
456 * in the "dest" directory, replacing the ".source" prefix in their names with
460 convert_sourcefiles_in(char *source_subdir, char *dest_dir, char *dest_subdir, char *suffix)
462 char testtablespace[MAXPGPATH];
463 char indir[MAXPGPATH];
470 snprintf(indir, MAXPGPATH, "%s/%s", inputdir, source_subdir);
472 /* Check that indir actually exists and is a directory */
473 ret = stat(indir, &st);
474 if (ret != 0 || !S_ISDIR(st.st_mode))
477 * No warning, to avoid noise in tests that do not have these
478 * directories; for example, ecpg, contrib and src/pl.
483 names = pgfnames(indir);
485 /* Error logged in pgfnames */
488 snprintf(testtablespace, MAXPGPATH, "%s/testtablespace", outputdir);
493 * On Windows only, clean out the test tablespace dir, or create it if it
494 * doesn't exist. On other platforms we expect the Makefile to take care
495 * of that. (We don't migrate that functionality in here because it'd be
496 * harder to cope with platform-specific issues such as SELinux.)
498 * XXX it would be better if pg_regress.c had nothing at all to do with
499 * testtablespace, and this were handled by a .BAT file or similar on
500 * Windows. See pgsql-hackers discussion of 2008-01-18.
502 if (directory_exists(testtablespace))
503 if (!rmtree(testtablespace, true))
505 fprintf(stderr, _("\n%s: could not remove test tablespace \"%s\"\n"),
506 progname, testtablespace);
509 make_directory(testtablespace);
512 /* finally loop on each file and do the replacement */
513 for (name = names; *name; name++)
515 char srcfile[MAXPGPATH];
516 char destfile[MAXPGPATH];
517 char prefix[MAXPGPATH];
522 /* reject filenames not finishing in ".source" */
523 if (strlen(*name) < 8)
525 if (strcmp(*name + strlen(*name) - 7, ".source") != 0)
530 /* build the full actual paths to open */
531 snprintf(prefix, strlen(*name) - 6, "%s", *name);
532 snprintf(srcfile, MAXPGPATH, "%s/%s", indir, *name);
533 snprintf(destfile, MAXPGPATH, "%s/%s/%s.%s", dest_dir, dest_subdir,
536 infile = fopen(srcfile, "r");
539 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
540 progname, srcfile, strerror(errno));
543 outfile = fopen(destfile, "w");
546 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
547 progname, destfile, strerror(errno));
550 while (fgets(line, sizeof(line), infile))
552 replace_string(line, "@abs_srcdir@", inputdir);
553 replace_string(line, "@abs_builddir@", outputdir);
554 replace_string(line, "@testtablespace@", testtablespace);
555 replace_string(line, "@libdir@", dlpath);
556 replace_string(line, "@DLSUFFIX@", DLSUFFIX);
557 fputs(line, outfile);
564 * If we didn't process any files, complain because it probably means
565 * somebody neglected to pass the needed --inputdir argument.
569 fprintf(stderr, _("%s: no *.source files found in \"%s\"\n"),
574 pgfnames_cleanup(names);
577 /* Create the .sql and .out files from the .source files, if any */
579 convert_sourcefiles(void)
581 convert_sourcefiles_in("input", outputdir, "sql", "sql");
582 convert_sourcefiles_in("output", outputdir, "expected", "out");
586 * Scan resultmap file to find which platform-specific expected files to use.
588 * The format of each line of the file is
589 * testname/hostplatformpattern=substitutefile
590 * where the hostplatformpattern is evaluated per the rules of expr(1),
591 * namely, it is a standard regular expression with an implicit ^ at the start.
592 * (We currently support only a very limited subset of regular expressions,
593 * see string_matches_pattern() above.) What hostplatformpattern will be
594 * matched against is the config.guess output. (In the shell-script version,
595 * we also provided an indication of whether gcc or another compiler was in
596 * use, but that facility isn't used anymore.)
604 /* scan the file ... */
605 snprintf(buf, sizeof(buf), "%s/resultmap", inputdir);
609 /* OK if it doesn't exist, else complain */
612 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
613 progname, buf, strerror(errno));
617 while (fgets(buf, sizeof(buf), f))
624 /* strip trailing whitespace, especially the newline */
626 while (i > 0 && isspace((unsigned char) buf[i - 1]))
629 /* parse out the line fields */
630 file_type = strchr(buf, ':');
633 fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
639 platform = strchr(file_type, ':');
642 fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
647 expected = strchr(platform, '=');
650 fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
657 * if it's for current platform, save it in resultmap list. Note: by
658 * adding at the front of the list, we ensure that in ambiguous cases,
659 * the last match in the resultmap file is used. This mimics the
660 * behavior of the old shell script.
662 if (string_matches_pattern(host_platform, platform))
664 _resultmap *entry = pg_malloc(sizeof(_resultmap));
666 entry->test = pg_strdup(buf);
667 entry->type = pg_strdup(file_type);
668 entry->resultfile = pg_strdup(expected);
669 entry->next = resultmap;
677 * Check in resultmap if we should be looking at a different file
681 get_expectfile(const char *testname, const char *file)
687 * Determine the file type from the file name. This is just what is
688 * following the last dot in the file name.
690 if (!file || !(file_type = strrchr(file, '.')))
695 for (rm = resultmap; rm != NULL; rm = rm->next)
697 if (strcmp(testname, rm->test) == 0 && strcmp(file_type, rm->type) == 0)
699 return rm->resultfile;
707 * Handy subroutine for setting an environment variable "var" to "val"
710 doputenv(const char *var, const char *val)
714 s = psprintf("%s=%s", var, val);
719 * Prepare environment variables for running regression tests
722 initialize_environment(void)
724 putenv("PGAPPNAME=pg_regress");
729 * Clear out any non-C locale settings
731 unsetenv("LC_COLLATE");
732 unsetenv("LC_CTYPE");
733 unsetenv("LC_MONETARY");
734 unsetenv("LC_NUMERIC");
739 * Most platforms have adopted the POSIX locale as their
740 * implementation-defined default locale. Exceptions include native
741 * Windows, macOS with --enable-nls, and Cygwin with --enable-nls.
742 * (Use of --enable-nls matters because libintl replaces setlocale().)
743 * Also, PostgreSQL does not support macOS with locale environment
744 * variables unset; see PostmasterMain().
746 #if defined(WIN32) || defined(__CYGWIN__) || defined(__darwin__)
752 * Set translation-related settings to English; otherwise psql will
753 * produce translated messages and produce diffs. (XXX If we ever support
754 * translation of pg_regress, this needs to be moved elsewhere, where psql
755 * is actually called.)
757 unsetenv("LANGUAGE");
759 putenv("LC_MESSAGES=C");
762 * Set encoding as requested
765 doputenv("PGCLIENTENCODING", encoding);
767 unsetenv("PGCLIENTENCODING");
770 * Set timezone and datestyle for datetime-related tests
772 putenv("PGTZ=PST8PDT");
773 putenv("PGDATESTYLE=Postgres, MDY");
776 * Likewise set intervalstyle to ensure consistent results. This is a bit
777 * more painful because we must use PGOPTIONS, and we want to preserve the
778 * user's ability to set other variables through that.
781 const char *my_pgoptions = "-c intervalstyle=postgres_verbose";
782 const char *old_pgoptions = getenv("PGOPTIONS");
787 new_pgoptions = psprintf("PGOPTIONS=%s %s",
788 old_pgoptions, my_pgoptions);
789 putenv(new_pgoptions);
795 * Clear out any environment vars that might cause psql to connect to
796 * the wrong postmaster, or otherwise behave in nondefault ways. (Note
797 * we also use psql's -X switch consistently, so that ~/.psqlrc files
798 * won't mess things up.) Also, set PGPORT to the temp port, and set
799 * PGHOST depending on whether we are using TCP or Unix sockets.
801 unsetenv("PGDATABASE");
803 unsetenv("PGSERVICE");
804 unsetenv("PGSSLMODE");
805 unsetenv("PGREQUIRESSL");
806 unsetenv("PGCONNECT_TIMEOUT");
808 #ifdef HAVE_UNIX_SOCKETS
809 if (hostname != NULL)
810 doputenv("PGHOST", hostname);
813 sockdir = getenv("PG_REGRESS_SOCK_DIR");
815 sockdir = make_temp_sockdir();
816 doputenv("PGHOST", sockdir);
819 Assert(hostname != NULL);
820 doputenv("PGHOST", hostname);
822 unsetenv("PGHOSTADDR");
827 sprintf(s, "%d", port);
828 doputenv("PGPORT", s);
837 * When testing an existing install, we honor existing environment
838 * variables, except if they're overridden by command line options.
840 if (hostname != NULL)
842 doputenv("PGHOST", hostname);
843 unsetenv("PGHOSTADDR");
849 sprintf(s, "%d", port);
850 doputenv("PGPORT", s);
853 doputenv("PGUSER", user);
856 * Report what we're connecting to
858 pghost = getenv("PGHOST");
859 pgport = getenv("PGPORT");
860 #ifndef HAVE_UNIX_SOCKETS
862 pghost = "localhost";
865 if (pghost && pgport)
866 printf(_("(using postmaster on %s, port %s)\n"), pghost, pgport);
867 if (pghost && !pgport)
868 printf(_("(using postmaster on %s, default port)\n"), pghost);
869 if (!pghost && pgport)
870 printf(_("(using postmaster on Unix socket, port %s)\n"), pgport);
871 if (!pghost && !pgport)
872 printf(_("(using postmaster on Unix socket, default port)\n"));
875 convert_sourcefiles();
879 pg_attribute_unused()
881 fmtHba(const char *raw)
887 wp = ret = realloc(ret, 3 + strlen(raw) * 2);
890 for (rp = raw; *rp; rp++)
904 * Get account and domain/realm names for the current user. This is based on
905 * pg_SSPI_recvauth(). The returned strings use static storage.
908 current_windows_user(const char **acct, const char **dom)
910 static char accountname[MAXPGPATH];
911 static char domainname[MAXPGPATH];
913 TOKEN_USER *tokenuser;
915 DWORD accountnamesize = sizeof(accountname);
916 DWORD domainnamesize = sizeof(domainname);
917 SID_NAME_USE accountnameuse;
919 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token))
922 _("%s: could not open process token: error code %lu\n"),
923 progname, GetLastError());
927 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
930 _("%s: could not get token information buffer size: error code %lu\n"),
931 progname, GetLastError());
934 tokenuser = pg_malloc(retlen);
935 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
938 _("%s: could not get token information: error code %lu\n"),
939 progname, GetLastError());
943 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
944 domainname, &domainnamesize, &accountnameuse))
947 _("%s: could not look up account SID: error code %lu\n"),
948 progname, GetLastError());
959 * Rewrite pg_hba.conf and pg_ident.conf to use SSPI authentication. Permit
960 * the current OS user to authenticate as the bootstrap superuser and as any
961 * user named in a --create-role option.
964 config_sspi_auth(const char *pgdata)
966 const char *accountname,
968 const char *username;
971 char fname[MAXPGPATH];
978 * "username", the initdb-chosen bootstrap superuser name, may always
979 * match "accountname", the value SSPI authentication discovers. The
980 * underlying system functions do not clearly guarantee that.
982 current_windows_user(&accountname, &domainname);
983 username = get_user_name(&errstr);
984 if (username == NULL)
986 fprintf(stderr, "%s: %s\n", progname, errstr);
991 * Like initdb.c:setup_config(), determine whether the platform recognizes
992 * ::1 (IPv6 loopback) as a numeric host address string.
995 struct addrinfo *gai_result;
996 struct addrinfo hints;
999 hints.ai_flags = AI_NUMERICHOST;
1000 hints.ai_family = AF_UNSPEC;
1001 hints.ai_socktype = 0;
1002 hints.ai_protocol = 0;
1003 hints.ai_addrlen = 0;
1004 hints.ai_canonname = NULL;
1005 hints.ai_addr = NULL;
1006 hints.ai_next = NULL;
1008 have_ipv6 = (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0 &&
1009 getaddrinfo("::1", NULL, &hints, &gai_result) == 0);
1012 /* Check a Write outcome and report any error. */
1017 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"), \
1018 progname, fname, strerror(errno)); \
1023 res = snprintf(fname, sizeof(fname), "%s/pg_hba.conf", pgdata);
1024 if (res < 0 || res >= sizeof(fname) - 1)
1027 * Truncating this name is a fatal error, because we must not fail to
1028 * overwrite an original trust-authentication pg_hba.conf.
1030 fprintf(stderr, _("%s: directory name too long\n"), progname);
1033 hba = fopen(fname, "w");
1036 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1037 progname, fname, strerror(errno));
1040 CW(fputs("# Configuration written by config_sspi_auth()\n", hba) >= 0);
1041 CW(fputs("host all all 127.0.0.1/32 sspi include_realm=1 map=regress\n",
1044 CW(fputs("host all all ::1/128 sspi include_realm=1 map=regress\n",
1046 CW(fclose(hba) == 0);
1048 snprintf(fname, sizeof(fname), "%s/pg_ident.conf", pgdata);
1049 ident = fopen(fname, "w");
1052 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1053 progname, fname, strerror(errno));
1056 CW(fputs("# Configuration written by config_sspi_auth()\n", ident) >= 0);
1059 * Double-quote for the benefit of account names containing whitespace or
1060 * '#'. Windows forbids the double-quote character itself, so don't
1061 * bother escaping embedded double-quote characters.
1063 CW(fprintf(ident, "regress \"%s@%s\" %s\n",
1064 accountname, domainname, fmtHba(username)) >= 0);
1065 for (sl = extraroles; sl; sl = sl->next)
1066 CW(fprintf(ident, "regress \"%s@%s\" %s\n",
1067 accountname, domainname, fmtHba(sl->str)) >= 0);
1068 CW(fclose(ident) == 0);
1073 * Issue a command via psql, connecting to the specified database
1075 * Since we use system(), this doesn't return until the operation finishes
1078 psql_command(const char *database, const char *query,...)
1080 char query_formatted[1024];
1081 char query_escaped[2048];
1082 char psql_cmd[MAXPGPATH + 2048];
1087 /* Generate the query with insertion of sprintf arguments */
1088 va_start(args, query);
1089 vsnprintf(query_formatted, sizeof(query_formatted), query, args);
1092 /* Now escape any shell double-quote metacharacters */
1094 for (s = query_formatted; *s; s++)
1096 if (strchr("\\\"$`", *s))
1102 /* And now we can build and execute the shell command */
1103 snprintf(psql_cmd, sizeof(psql_cmd),
1104 "\"%s%spsql\" -X -c \"%s\" \"%s\"",
1105 bindir ? bindir : "",
1110 if (system(psql_cmd) != 0)
1112 /* psql probably already reported the error */
1113 fprintf(stderr, _("command failed: %s\n"), psql_cmd);
1119 * Spawn a process to execute the given shell command; don't wait for it
1121 * Returns the process ID (or HANDLE) so we can wait for it later
1124 spawn_process(const char *cmdline)
1130 * Must flush I/O buffers before fork. Ideally we'd use fflush(NULL) here
1131 * ... does anyone still care about systems where that doesn't work?
1141 fprintf(stderr, _("%s: could not fork: %s\n"),
1142 progname, strerror(errno));
1150 * Instead of using system(), exec the shell directly, and tell it to
1151 * "exec" the command too. This saves two useless processes per
1152 * parallel test case.
1156 cmdline2 = psprintf("exec %s", cmdline);
1157 execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
1158 fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
1159 progname, shellprog, strerror(errno));
1160 _exit(1); /* not exit() here... */
1165 PROCESS_INFORMATION pi;
1167 HANDLE restrictedToken;
1169 memset(&pi, 0, sizeof(pi));
1170 cmdline2 = psprintf("cmd /c \"%s\"", cmdline);
1172 if ((restrictedToken =
1173 CreateRestrictedProcess(cmdline2, &pi, progname)) == 0)
1176 CloseHandle(pi.hThread);
1182 * Count bytes in file
1185 file_size(const char *file)
1188 FILE *f = fopen(file, "r");
1192 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1193 progname, file, strerror(errno));
1196 fseek(f, 0, SEEK_END);
1203 * Count lines in file
1206 file_line_count(const char *file)
1210 FILE *f = fopen(file, "r");
1214 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1215 progname, file, strerror(errno));
1218 while ((c = fgetc(f)) != EOF)
1228 file_exists(const char *file)
1230 FILE *f = fopen(file, "r");
1239 directory_exists(const char *dir)
1243 if (stat(dir, &st) != 0)
1245 if (S_ISDIR(st.st_mode))
1250 /* Create a directory */
1252 make_directory(const char *dir)
1254 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
1256 fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
1257 progname, dir, strerror(errno));
1263 * In: filename.ext, Return: filename_i.ext, where 0 < i <= 9
1266 get_alternative_expectfile(const char *expectfile, int i)
1269 int ssize = strlen(expectfile) + 2 + 1;
1273 if (!(tmp = (char *) malloc(ssize)))
1276 if (!(s = (char *) malloc(ssize)))
1282 strcpy(tmp, expectfile);
1283 last_dot = strrchr(tmp, '.');
1291 snprintf(s, ssize, "%s_%d.%s", tmp, i, last_dot + 1);
1297 * Run a "diff" command and also check that it didn't crash
1300 run_diff(const char *cmd, const char *filename)
1305 if (!WIFEXITED(r) || WEXITSTATUS(r) > 1)
1307 fprintf(stderr, _("diff command failed with status %d: %s\n"), r, cmd);
1313 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
1314 * but produces nothing to stdout, so we check for that here.
1316 if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
1318 fprintf(stderr, _("diff command not found: %s\n"), cmd);
1323 return WEXITSTATUS(r);
1327 * Check the actual result file for the given test against expected results
1329 * Returns true if different (failure), false if correct match found.
1330 * In the true case, the diff is appended to the diffs file.
1333 results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
1335 char expectfile[MAXPGPATH];
1336 char diff[MAXPGPATH];
1337 char cmd[MAXPGPATH * 3];
1338 char best_expect_file[MAXPGPATH];
1340 int best_line_count;
1343 const char *platform_expectfile;
1346 * We can pass either the resultsfile or the expectfile, they should have
1347 * the same type (filename.type) anyway.
1349 platform_expectfile = get_expectfile(testname, resultsfile);
1351 strlcpy(expectfile, default_expectfile, sizeof(expectfile));
1352 if (platform_expectfile)
1355 * Replace everything after the last slash in expectfile with what the
1356 * platform_expectfile contains.
1358 char *p = strrchr(expectfile, '/');
1361 strcpy(++p, platform_expectfile);
1364 /* Name to use for temporary diff file */
1365 snprintf(diff, sizeof(diff), "%s.diff", resultsfile);
1367 /* OK, run the diff */
1368 snprintf(cmd, sizeof(cmd),
1369 "diff %s \"%s\" \"%s\" > \"%s\"",
1370 basic_diff_opts, expectfile, resultsfile, diff);
1372 /* Is the diff file empty? */
1373 if (run_diff(cmd, diff) == 0)
1379 /* There may be secondary comparison files that match better */
1380 best_line_count = file_line_count(diff);
1381 strcpy(best_expect_file, expectfile);
1383 for (i = 0; i <= 9; i++)
1385 char *alt_expectfile;
1387 alt_expectfile = get_alternative_expectfile(expectfile, i);
1388 if (!alt_expectfile)
1390 fprintf(stderr, _("Unable to check secondary comparison files: %s\n"),
1395 if (!file_exists(alt_expectfile))
1397 free(alt_expectfile);
1401 snprintf(cmd, sizeof(cmd),
1402 "diff %s \"%s\" \"%s\" > \"%s\"",
1403 basic_diff_opts, alt_expectfile, resultsfile, diff);
1405 if (run_diff(cmd, diff) == 0)
1408 free(alt_expectfile);
1412 l = file_line_count(diff);
1413 if (l < best_line_count)
1415 /* This diff was a better match than the last one */
1416 best_line_count = l;
1417 strlcpy(best_expect_file, alt_expectfile, sizeof(best_expect_file));
1419 free(alt_expectfile);
1423 * fall back on the canonical results file if we haven't tried it yet and
1424 * haven't found a complete match yet.
1427 if (platform_expectfile)
1429 snprintf(cmd, sizeof(cmd),
1430 "diff %s \"%s\" \"%s\" > \"%s\"",
1431 basic_diff_opts, default_expectfile, resultsfile, diff);
1433 if (run_diff(cmd, diff) == 0)
1435 /* No diff = no changes = good */
1440 l = file_line_count(diff);
1441 if (l < best_line_count)
1443 /* This diff was a better match than the last one */
1444 best_line_count = l;
1445 strlcpy(best_expect_file, default_expectfile, sizeof(best_expect_file));
1450 * Use the best comparison file to generate the "pretty" diff, which we
1451 * append to the diffs summary file.
1453 snprintf(cmd, sizeof(cmd),
1454 "diff %s \"%s\" \"%s\" >> \"%s\"",
1455 pretty_diff_opts, best_expect_file, resultsfile, difffilename);
1456 run_diff(cmd, difffilename);
1458 /* And append a separator */
1459 difffile = fopen(difffilename, "a");
1463 "\n======================================================================\n\n");
1472 * Wait for specified subprocesses to finish, and return their exit
1473 * statuses into statuses[]
1475 * If names isn't NULL, print each subprocess's name as it finishes
1477 * Note: it's OK to scribble on the pids array, but not on the names array
1480 wait_for_tests(PID_TYPE * pids, int *statuses, char **names, int num_tests)
1486 PID_TYPE *active_pids = pg_malloc(num_tests * sizeof(PID_TYPE));
1488 memcpy(active_pids, pids, num_tests * sizeof(PID_TYPE));
1491 tests_left = num_tests;
1492 while (tests_left > 0)
1499 p = wait(&exit_status);
1501 if (p == INVALID_PID)
1503 fprintf(stderr, _("failed to wait for subprocesses: %s\n"),
1511 r = WaitForMultipleObjects(tests_left, active_pids, FALSE, INFINITE);
1512 if (r < WAIT_OBJECT_0 || r >= WAIT_OBJECT_0 + tests_left)
1514 fprintf(stderr, _("failed to wait for subprocesses: error code %lu\n"),
1518 p = active_pids[r - WAIT_OBJECT_0];
1519 /* compact the active_pids array */
1520 active_pids[r - WAIT_OBJECT_0] = active_pids[tests_left - 1];
1523 for (i = 0; i < num_tests; i++)
1528 GetExitCodeProcess(pids[i], &exit_status);
1529 CloseHandle(pids[i]);
1531 pids[i] = INVALID_PID;
1532 statuses[i] = (int) exit_status;
1534 status(" %s", names[i]);
1547 * report nonzero exit code from a test process
1550 log_child_failure(int exitstatus)
1552 if (WIFEXITED(exitstatus))
1553 status(_(" (test process exited with exit code %d)"),
1554 WEXITSTATUS(exitstatus));
1555 else if (WIFSIGNALED(exitstatus))
1558 status(_(" (test process was terminated by exception 0x%X)"),
1559 WTERMSIG(exitstatus));
1560 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
1561 status(_(" (test process was terminated by signal %d: %s)"),
1562 WTERMSIG(exitstatus),
1563 WTERMSIG(exitstatus) < NSIG ?
1564 sys_siglist[WTERMSIG(exitstatus)] : "(unknown))");
1566 status(_(" (test process was terminated by signal %d)"),
1567 WTERMSIG(exitstatus));
1571 status(_(" (test process exited with unrecognized status %d)"),
1576 * Run all the tests specified in one schedule file
1579 run_schedule(const char *schedule, test_function tfunc)
1581 #define MAX_PARALLEL_TESTS 100
1582 char *tests[MAX_PARALLEL_TESTS];
1583 _stringlist *resultfiles[MAX_PARALLEL_TESTS];
1584 _stringlist *expectfiles[MAX_PARALLEL_TESTS];
1585 _stringlist *tags[MAX_PARALLEL_TESTS];
1586 PID_TYPE pids[MAX_PARALLEL_TESTS];
1587 int statuses[MAX_PARALLEL_TESTS];
1588 _stringlist *ignorelist = NULL;
1593 memset(resultfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1594 memset(expectfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1595 memset(tags, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1597 scf = fopen(schedule, "r");
1600 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1601 progname, schedule, strerror(errno));
1605 while (fgets(scbuf, sizeof(scbuf), scf))
1615 for (i = 0; i < MAX_PARALLEL_TESTS; i++)
1617 if (resultfiles[i] == NULL)
1619 free_stringlist(&resultfiles[i]);
1620 free_stringlist(&expectfiles[i]);
1621 free_stringlist(&tags[i]);
1624 /* strip trailing whitespace, especially the newline */
1626 while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1629 if (scbuf[0] == '\0' || scbuf[0] == '#')
1631 if (strncmp(scbuf, "test: ", 6) == 0)
1633 else if (strncmp(scbuf, "ignore: ", 8) == 0)
1636 while (*c && isspace((unsigned char) *c))
1638 add_stringlist_item(&ignorelist, c);
1641 * Note: ignore: lines do not run the test, they just say that
1642 * failure of this test when run later on is to be ignored. A bit
1643 * odd but that's how the shell-script version did it.
1649 fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
1650 schedule, line_num, scbuf);
1656 for (c = test; *c; c++)
1658 if (isspace((unsigned char) *c))
1665 if (num_tests >= MAX_PARALLEL_TESTS)
1667 /* can't print scbuf here, it's already been trashed */
1668 fprintf(stderr, _("too many parallel tests in schedule file \"%s\", line %d\n"),
1669 schedule, line_num);
1672 tests[num_tests] = c;
1680 fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
1681 schedule, line_num, scbuf);
1687 status(_("test %-24s ... "), tests[0]);
1688 pids[0] = (tfunc) (tests[0], &resultfiles[0], &expectfiles[0], &tags[0]);
1689 wait_for_tests(pids, statuses, NULL, 1);
1690 /* status line is finished below */
1692 else if (max_connections > 0 && max_connections < num_tests)
1696 status(_("parallel group (%d tests, in groups of %d): "),
1697 num_tests, max_connections);
1698 for (i = 0; i < num_tests; i++)
1700 if (i - oldest >= max_connections)
1702 wait_for_tests(pids + oldest, statuses + oldest,
1703 tests + oldest, i - oldest);
1706 pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1708 wait_for_tests(pids + oldest, statuses + oldest,
1709 tests + oldest, i - oldest);
1714 status(_("parallel group (%d tests): "), num_tests);
1715 for (i = 0; i < num_tests; i++)
1717 pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1719 wait_for_tests(pids, statuses, tests, num_tests);
1723 /* Check results for all tests */
1724 for (i = 0; i < num_tests; i++)
1729 bool differ = false;
1732 status(_(" %-24s ... "), tests[i]);
1735 * Advance over all three lists simultaneously.
1737 * Compare resultfiles[j] with expectfiles[j] always. Tags are
1738 * optional but if there are tags, the tag list has the same
1739 * length as the other two lists.
1741 for (rl = resultfiles[i], el = expectfiles[i], tl = tags[i];
1742 rl != NULL; /* rl and el have the same length */
1743 rl = rl->next, el = el->next)
1748 tl = tl->next; /* tl has the same length as rl and el
1751 newdiff = results_differ(tests[i], rl->str, el->str);
1754 printf("%s ", tl->str);
1761 bool ignore = false;
1764 for (sl = ignorelist; sl != NULL; sl = sl->next)
1766 if (strcmp(tests[i], sl->str) == 0)
1774 status(_("failed (ignored)"));
1775 fail_ignore_count++;
1779 status(_("FAILED"));
1789 if (statuses[i] != 0)
1790 log_child_failure(statuses[i]);
1796 free_stringlist(&ignorelist);
1805 run_single_test(const char *test, test_function tfunc)
1809 _stringlist *resultfiles = NULL;
1810 _stringlist *expectfiles = NULL;
1811 _stringlist *tags = NULL;
1815 bool differ = false;
1817 status(_("test %-24s ... "), test);
1818 pid = (tfunc) (test, &resultfiles, &expectfiles, &tags);
1819 wait_for_tests(&pid, &exit_status, NULL, 1);
1822 * Advance over all three lists simultaneously.
1824 * Compare resultfiles[j] with expectfiles[j] always. Tags are optional
1825 * but if there are tags, the tag list has the same length as the other
1828 for (rl = resultfiles, el = expectfiles, tl = tags;
1829 rl != NULL; /* rl and el have the same length */
1830 rl = rl->next, el = el->next)
1835 tl = tl->next; /* tl has the same length as rl and el if it
1838 newdiff = results_differ(test, rl->str, el->str);
1841 printf("%s ", tl->str);
1848 status(_("FAILED"));
1857 if (exit_status != 0)
1858 log_child_failure(exit_status);
1864 * Create the summary-output files (making them empty if already existing)
1867 open_result_files(void)
1869 char file[MAXPGPATH];
1872 /* create the log file (copy of running status output) */
1873 snprintf(file, sizeof(file), "%s/regression.out", outputdir);
1874 logfilename = pg_strdup(file);
1875 logfile = fopen(logfilename, "w");
1878 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1879 progname, logfilename, strerror(errno));
1883 /* create the diffs file as empty */
1884 snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
1885 difffilename = pg_strdup(file);
1886 difffile = fopen(difffilename, "w");
1889 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1890 progname, difffilename, strerror(errno));
1893 /* we don't keep the diffs file open continuously */
1896 /* also create the output directory if not present */
1897 snprintf(file, sizeof(file), "%s/results", outputdir);
1898 if (!directory_exists(file))
1899 make_directory(file);
1903 drop_database_if_exists(const char *dbname)
1905 header(_("dropping database \"%s\""), dbname);
1906 psql_command("postgres", "DROP DATABASE IF EXISTS \"%s\"", dbname);
1910 create_database(const char *dbname)
1915 * We use template0 so that any installation-local cruft in template1 will
1916 * not mess up the tests.
1918 header(_("creating database \"%s\""), dbname);
1920 psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'%s", dbname, encoding,
1921 (nolocale) ? " LC_COLLATE='C' LC_CTYPE='C'" : "");
1923 psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0%s", dbname,
1924 (nolocale) ? " LC_COLLATE='C' LC_CTYPE='C'" : "");
1925 psql_command(dbname,
1926 "ALTER DATABASE \"%s\" SET lc_messages TO 'C';"
1927 "ALTER DATABASE \"%s\" SET lc_monetary TO 'C';"
1928 "ALTER DATABASE \"%s\" SET lc_numeric TO 'C';"
1929 "ALTER DATABASE \"%s\" SET lc_time TO 'C';"
1930 "ALTER DATABASE \"%s\" SET timezone_abbreviations TO 'Default';",
1931 dbname, dbname, dbname, dbname, dbname);
1934 * Install any requested procedural languages. We use CREATE OR REPLACE
1935 * so that this will work whether or not the language is preinstalled.
1937 for (sl = loadlanguage; sl != NULL; sl = sl->next)
1939 header(_("installing %s"), sl->str);
1940 psql_command(dbname, "CREATE OR REPLACE LANGUAGE \"%s\"", sl->str);
1944 * Install any requested extensions. We use CREATE IF NOT EXISTS so that
1945 * this will work whether or not the extension is preinstalled.
1947 for (sl = loadextension; sl != NULL; sl = sl->next)
1949 header(_("installing %s"), sl->str);
1950 psql_command(dbname, "CREATE EXTENSION IF NOT EXISTS \"%s\"", sl->str);
1955 drop_role_if_exists(const char *rolename)
1957 header(_("dropping role \"%s\""), rolename);
1958 psql_command("postgres", "DROP ROLE IF EXISTS \"%s\"", rolename);
1962 create_role(const char *rolename, const _stringlist *granted_dbs)
1964 header(_("creating role \"%s\""), rolename);
1965 psql_command("postgres", "CREATE ROLE \"%s\" WITH LOGIN", rolename);
1966 for (; granted_dbs != NULL; granted_dbs = granted_dbs->next)
1968 psql_command("postgres", "GRANT ALL ON DATABASE \"%s\" TO \"%s\"",
1969 granted_dbs->str, rolename);
1976 printf(_("PostgreSQL regression test driver\n"));
1978 printf(_("Usage:\n %s [OPTION]... [EXTRA-TEST]...\n"), progname);
1980 printf(_("Options:\n"));
1981 printf(_(" --config-auth=DATADIR update authentication settings for DATADIR\n"));
1982 printf(_(" --create-role=ROLE create the specified role before testing\n"));
1983 printf(_(" --dbname=DB use database DB (default \"regression\")\n"));
1984 printf(_(" --debug turn on debug mode in programs that are run\n"));
1985 printf(_(" --dlpath=DIR look for dynamic libraries in DIR\n"));
1986 printf(_(" --encoding=ENCODING use ENCODING as the encoding\n"));
1987 printf(_(" --inputdir=DIR take input files from DIR (default \".\")\n"));
1988 printf(_(" --launcher=CMD use CMD as launcher of psql\n"));
1989 printf(_(" --load-extension=EXT load the named extension before running the\n"));
1990 printf(_(" tests; can appear multiple times\n"));
1991 printf(_(" --load-language=LANG load the named language before running the\n"));
1992 printf(_(" tests; can appear multiple times\n"));
1993 printf(_(" --max-connections=N maximum number of concurrent connections\n"));
1994 printf(_(" (default is 0, meaning unlimited)\n"));
1995 printf(_(" --outputdir=DIR place output files in DIR (default \".\")\n"));
1996 printf(_(" --schedule=FILE use test ordering schedule from FILE\n"));
1997 printf(_(" (can be used multiple times to concatenate)\n"));
1998 printf(_(" --temp-instance=DIR create a temporary instance in DIR\n"));
1999 printf(_(" --use-existing use an existing installation\n"));
2001 printf(_("Options for \"temp-instance\" mode:\n"));
2002 printf(_(" --no-locale use C locale\n"));
2003 printf(_(" --port=PORT start postmaster on PORT\n"));
2004 printf(_(" --temp-config=FILE append contents of FILE to temporary config\n"));
2006 printf(_("Options for using an existing installation:\n"));
2007 printf(_(" --host=HOST use postmaster running on HOST\n"));
2008 printf(_(" --port=PORT use postmaster running at PORT\n"));
2009 printf(_(" --user=USER connect as USER\n"));
2011 printf(_("The exit status is 0 if all tests passed, 1 if some tests failed, and 2\n"));
2012 printf(_("if the tests could not be run for some reason.\n"));
2014 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
2018 regression_main(int argc, char *argv[], init_function ifunc, test_function tfunc)
2020 static struct option long_options[] = {
2021 {"help", no_argument, NULL, 'h'},
2022 {"version", no_argument, NULL, 'V'},
2023 {"dbname", required_argument, NULL, 1},
2024 {"debug", no_argument, NULL, 2},
2025 {"inputdir", required_argument, NULL, 3},
2026 {"load-language", required_argument, NULL, 4},
2027 {"max-connections", required_argument, NULL, 5},
2028 {"encoding", required_argument, NULL, 6},
2029 {"outputdir", required_argument, NULL, 7},
2030 {"schedule", required_argument, NULL, 8},
2031 {"temp-instance", required_argument, NULL, 9},
2032 {"no-locale", no_argument, NULL, 10},
2033 {"host", required_argument, NULL, 13},
2034 {"port", required_argument, NULL, 14},
2035 {"user", required_argument, NULL, 15},
2036 {"bindir", required_argument, NULL, 16},
2037 {"dlpath", required_argument, NULL, 17},
2038 {"create-role", required_argument, NULL, 18},
2039 {"temp-config", required_argument, NULL, 19},
2040 {"use-existing", no_argument, NULL, 20},
2041 {"launcher", required_argument, NULL, 21},
2042 {"load-extension", required_argument, NULL, 22},
2043 {"config-auth", required_argument, NULL, 24},
2051 char buf[MAXPGPATH * 4];
2052 char buf2[MAXPGPATH * 4];
2054 progname = get_progname(argv[0]);
2055 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_regress"));
2057 atexit(stop_postmaster);
2059 #ifndef HAVE_UNIX_SOCKETS
2060 /* no unix domain sockets available, so change default */
2061 hostname = "localhost";
2065 * We call the initialization function here because that way we can set
2066 * default parameters and let them be overwritten by the commandline.
2070 if (getenv("PG_REGRESS_DIFF_OPTS"))
2071 pretty_diff_opts = getenv("PG_REGRESS_DIFF_OPTS");
2073 while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
2081 puts("pg_regress (PostgreSQL) " PG_VERSION);
2086 * If a default database was specified, we need to remove it
2087 * before we add the specified one.
2089 free_stringlist(&dblist);
2090 split_to_stringlist(optarg, ",", &dblist);
2096 inputdir = pg_strdup(optarg);
2099 add_stringlist_item(&loadlanguage, optarg);
2102 max_connections = atoi(optarg);
2105 encoding = pg_strdup(optarg);
2108 outputdir = pg_strdup(optarg);
2111 add_stringlist_item(&schedulelist, optarg);
2114 temp_instance = make_absolute_path(optarg);
2120 hostname = pg_strdup(optarg);
2123 port = atoi(optarg);
2124 port_specified_by_user = true;
2127 user = pg_strdup(optarg);
2130 /* "--bindir=" means to use PATH */
2132 bindir = pg_strdup(optarg);
2137 dlpath = pg_strdup(optarg);
2140 split_to_stringlist(optarg, ",", &extraroles);
2143 add_stringlist_item(&temp_configs, optarg);
2146 use_existing = true;
2149 launcher = pg_strdup(optarg);
2152 add_stringlist_item(&loadextension, optarg);
2155 config_auth_datadir = pg_strdup(optarg);
2158 /* getopt_long already emitted a complaint */
2159 fprintf(stderr, _("\nTry \"%s -h\" for more information.\n"),
2166 * if we still have arguments, they are extra tests to run
2168 while (argc - optind >= 1)
2170 add_stringlist_item(&extra_tests, argv[optind]);
2174 if (config_auth_datadir)
2177 config_sspi_auth(config_auth_datadir);
2182 if (temp_instance && !port_specified_by_user)
2185 * To reduce chances of interference with parallel installations, use
2186 * a port number starting in the private range (49152-65535)
2187 * calculated from the version number. This aids !HAVE_UNIX_SOCKETS
2188 * systems; elsewhere, the use of a private socket directory already
2189 * prevents interference.
2191 port = 0xC000 | (PG_VERSION_NUM & 0x3FFF);
2193 inputdir = make_absolute_path(inputdir);
2194 outputdir = make_absolute_path(outputdir);
2195 dlpath = make_absolute_path(dlpath);
2200 open_result_files();
2202 initialize_environment();
2204 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
2205 unlimit_core_size();
2211 const char *env_wait;
2215 * Prepare the temp instance
2218 if (directory_exists(temp_instance))
2220 header(_("removing existing temp instance"));
2221 if (!rmtree(temp_instance, true))
2223 fprintf(stderr, _("\n%s: could not remove temp instance \"%s\"\n"),
2224 progname, temp_instance);
2229 header(_("creating temporary instance"));
2231 /* make the temp instance top directory */
2232 make_directory(temp_instance);
2234 /* and a directory for log files */
2235 snprintf(buf, sizeof(buf), "%s/log", outputdir);
2236 if (!directory_exists(buf))
2237 make_directory(buf);
2240 header(_("initializing database system"));
2241 snprintf(buf, sizeof(buf),
2242 "\"%s%sinitdb\" -D \"%s/data\" --no-clean --no-sync%s%s > \"%s/log/initdb.log\" 2>&1",
2243 bindir ? bindir : "",
2246 debug ? " --debug" : "",
2247 nolocale ? " --no-locale" : "",
2251 fprintf(stderr, _("\n%s: initdb failed\nExamine %s/log/initdb.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2256 * Adjust the default postgresql.conf for regression testing. The user
2257 * can specify a file to be appended; in any case we expand logging
2258 * and set max_prepared_transactions to enable testing of prepared
2259 * xacts. (Note: to reduce the probability of unexpected shmmax
2260 * failures, don't set max_prepared_transactions any higher than
2261 * actually needed by the prepared_xacts regression test.)
2263 snprintf(buf, sizeof(buf), "%s/data/postgresql.conf", temp_instance);
2264 pg_conf = fopen(buf, "a");
2265 if (pg_conf == NULL)
2267 fprintf(stderr, _("\n%s: could not open \"%s\" for adding extra config: %s\n"), progname, buf, strerror(errno));
2270 fputs("\n# Configuration added by pg_regress\n\n", pg_conf);
2271 fputs("log_autovacuum_min_duration = 0\n", pg_conf);
2272 fputs("log_checkpoints = on\n", pg_conf);
2273 fputs("log_line_prefix = '%m [%p] %q%a '\n", pg_conf);
2274 fputs("log_lock_waits = on\n", pg_conf);
2275 fputs("log_temp_files = 128kB\n", pg_conf);
2276 fputs("max_prepared_transactions = 2\n", pg_conf);
2278 for (sl = temp_configs; sl != NULL; sl = sl->next)
2280 char *temp_config = sl->str;
2282 char line_buf[1024];
2284 extra_conf = fopen(temp_config, "r");
2285 if (extra_conf == NULL)
2287 fprintf(stderr, _("\n%s: could not open \"%s\" to read extra config: %s\n"), progname, temp_config, strerror(errno));
2290 while (fgets(line_buf, sizeof(line_buf), extra_conf) != NULL)
2291 fputs(line_buf, pg_conf);
2300 * Since we successfully used the same buffer for the much-longer
2301 * "initdb" command, this can't truncate.
2303 snprintf(buf, sizeof(buf), "%s/data", temp_instance);
2304 config_sspi_auth(buf);
2305 #elif !defined(HAVE_UNIX_SOCKETS)
2306 #error Platform has no means to secure the test installation.
2310 * Check if there is a postmaster running already.
2312 snprintf(buf2, sizeof(buf2),
2313 "\"%s%spsql\" -X postgres <%s 2>%s",
2314 bindir ? bindir : "",
2318 for (i = 0; i < 16; i++)
2320 if (system(buf2) == 0)
2324 if (port_specified_by_user || i == 15)
2326 fprintf(stderr, _("port %d apparently in use\n"), port);
2327 if (!port_specified_by_user)
2328 fprintf(stderr, _("%s: could not determine an available port\n"), progname);
2329 fprintf(stderr, _("Specify an unused port using the --port option or shut down any conflicting PostgreSQL servers.\n"));
2333 fprintf(stderr, _("port %d apparently in use, trying %d\n"), port, port + 1);
2335 sprintf(s, "%d", port);
2336 doputenv("PGPORT", s);
2343 * Start the temp postmaster
2345 header(_("starting postmaster"));
2346 snprintf(buf, sizeof(buf),
2347 "\"%s%spostgres\" -D \"%s/data\" -F%s "
2348 "-c \"listen_addresses=%s\" -k \"%s\" "
2349 "> \"%s/log/postmaster.log\" 2>&1",
2350 bindir ? bindir : "",
2352 temp_instance, debug ? " -d 5" : "",
2353 hostname ? hostname : "", sockdir ? sockdir : "",
2355 postmaster_pid = spawn_process(buf);
2356 if (postmaster_pid == INVALID_PID)
2358 fprintf(stderr, _("\n%s: could not spawn postmaster: %s\n"),
2359 progname, strerror(errno));
2364 * Wait till postmaster is able to accept connections; normally this
2365 * is only a second or so, but Cygwin is reportedly *much* slower, and
2366 * test builds using Valgrind or similar tools might be too. Hence,
2367 * allow the default timeout of 60 seconds to be overridden from the
2368 * PGCTLTIMEOUT environment variable.
2370 env_wait = getenv("PGCTLTIMEOUT");
2371 if (env_wait != NULL)
2373 wait_seconds = atoi(env_wait);
2374 if (wait_seconds <= 0)
2380 for (i = 0; i < wait_seconds; i++)
2382 /* Done if psql succeeds */
2383 if (system(buf2) == 0)
2387 * Fail immediately if postmaster has exited
2390 if (kill(postmaster_pid, 0) != 0)
2392 if (WaitForSingleObject(postmaster_pid, 0) == WAIT_OBJECT_0)
2395 fprintf(stderr, _("\n%s: postmaster failed\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
2399 pg_usleep(1000000L);
2401 if (i >= wait_seconds)
2403 fprintf(stderr, _("\n%s: postmaster did not respond within %d seconds\nExamine %s/log/postmaster.log for the reason\n"),
2404 progname, wait_seconds, outputdir);
2407 * If we get here, the postmaster is probably wedged somewhere in
2408 * startup. Try to kill it ungracefully rather than leaving a
2409 * stuck postmaster that might interfere with subsequent test
2413 if (kill(postmaster_pid, SIGKILL) != 0 &&
2415 fprintf(stderr, _("\n%s: could not kill failed postmaster: %s\n"),
2416 progname, strerror(errno));
2418 if (TerminateProcess(postmaster_pid, 255) == 0)
2419 fprintf(stderr, _("\n%s: could not kill failed postmaster: error code %lu\n"),
2420 progname, GetLastError());
2426 postmaster_running = true;
2429 /* need a series of two casts to convert HANDLE without compiler warning */
2430 #define ULONGPID(x) (unsigned long) (unsigned long long) (x)
2432 #define ULONGPID(x) (unsigned long) (x)
2434 printf(_("running on port %d with PID %lu\n"),
2435 port, ULONGPID(postmaster_pid));
2440 * Using an existing installation, so may need to get rid of
2441 * pre-existing database(s) and role(s)
2445 for (sl = dblist; sl; sl = sl->next)
2446 drop_database_if_exists(sl->str);
2447 for (sl = extraroles; sl; sl = sl->next)
2448 drop_role_if_exists(sl->str);
2453 * Create the test database(s) and role(s)
2457 for (sl = dblist; sl; sl = sl->next)
2458 create_database(sl->str);
2459 for (sl = extraroles; sl; sl = sl->next)
2460 create_role(sl->str, dblist);
2464 * Ready to run the tests
2466 header(_("running regression test queries"));
2468 for (sl = schedulelist; sl != NULL; sl = sl->next)
2470 run_schedule(sl->str, tfunc);
2473 for (sl = extra_tests; sl != NULL; sl = sl->next)
2475 run_single_test(sl->str, tfunc);
2479 * Shut down temp installation's postmaster
2483 header(_("shutting down postmaster"));
2488 * If there were no errors, remove the temp instance immediately to
2489 * conserve disk space. (If there were errors, we leave the instance in
2490 * place for possible manual investigation.)
2492 if (temp_instance && fail_count == 0 && fail_ignore_count == 0)
2494 header(_("removing temporary instance"));
2495 if (!rmtree(temp_instance, true))
2496 fprintf(stderr, _("\n%s: could not remove temp instance \"%s\"\n"),
2497 progname, temp_instance);
2503 * Emit nice-looking summary message
2505 if (fail_count == 0 && fail_ignore_count == 0)
2506 snprintf(buf, sizeof(buf),
2507 _(" All %d tests passed. "),
2509 else if (fail_count == 0) /* fail_count=0, fail_ignore_count>0 */
2510 snprintf(buf, sizeof(buf),
2511 _(" %d of %d tests passed, %d failed test(s) ignored. "),
2513 success_count + fail_ignore_count,
2515 else if (fail_ignore_count == 0) /* fail_count>0 && fail_ignore_count=0 */
2516 snprintf(buf, sizeof(buf),
2517 _(" %d of %d tests failed. "),
2519 success_count + fail_count);
2521 /* fail_count>0 && fail_ignore_count>0 */
2522 snprintf(buf, sizeof(buf),
2523 _(" %d of %d tests failed, %d of these failures ignored. "),
2524 fail_count + fail_ignore_count,
2525 success_count + fail_count + fail_ignore_count,
2529 for (i = strlen(buf); i > 0; i--)
2531 printf("\n%s\n", buf);
2532 for (i = strlen(buf); i > 0; i--)
2537 if (file_size(difffilename) > 0)
2539 printf(_("The differences that caused some tests to fail can be viewed in the\n"
2540 "file \"%s\". A copy of the test summary that you see\n"
2541 "above is saved in the file \"%s\".\n\n"),
2542 difffilename, logfilename);
2546 unlink(difffilename);
2547 unlink(logfilename);
2550 if (fail_count != 0)