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-2016, 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 = malloc(sizeof(_stringlist));
155 _stringlist *oldentry;
157 newentry->str = 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 = 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 -m fast",
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 = 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 = 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 = malloc(sizeof(_resultmap));
666 entry->test = strdup(buf);
667 entry->type = strdup(file_type);
668 entry->resultfile = 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, Darwin with --enable-nls, and Cygwin with --enable-nls.
742 * (Use of --enable-nls matters because libintl replaces setlocale().)
743 * Also, PostgreSQL does not support Darwin 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();
881 * Get account and domain/realm names for the current user. This is based on
882 * pg_SSPI_recvauth(). The returned strings use static storage.
885 current_windows_user(const char **acct, const char **dom)
887 static char accountname[MAXPGPATH];
888 static char domainname[MAXPGPATH];
890 TOKEN_USER *tokenuser;
892 DWORD accountnamesize = sizeof(accountname);
893 DWORD domainnamesize = sizeof(domainname);
894 SID_NAME_USE accountnameuse;
896 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token))
899 _("%s: could not open process token: error code %lu\n"),
900 progname, GetLastError());
904 if (!GetTokenInformation(token, TokenUser, NULL, 0, &retlen) && GetLastError() != 122)
907 _("%s: could not get token user size: error code %lu\n"),
908 progname, GetLastError());
911 tokenuser = malloc(retlen);
912 if (!GetTokenInformation(token, TokenUser, tokenuser, retlen, &retlen))
915 _("%s: could not get token user: error code %lu\n"),
916 progname, GetLastError());
920 if (!LookupAccountSid(NULL, tokenuser->User.Sid, accountname, &accountnamesize,
921 domainname, &domainnamesize, &accountnameuse))
924 _("%s: could not look up account SID: error code %lu\n"),
925 progname, GetLastError());
936 * Rewrite pg_hba.conf and pg_ident.conf to use SSPI authentication. Permit
937 * the current OS user to authenticate as the bootstrap superuser and as any
938 * user named in a --create-role option.
941 config_sspi_auth(const char *pgdata)
943 const char *accountname,
945 const char *username;
948 char fname[MAXPGPATH];
955 * "username", the initdb-chosen bootstrap superuser name, may always
956 * match "accountname", the value SSPI authentication discovers. The
957 * underlying system functions do not clearly guarantee that.
959 current_windows_user(&accountname, &domainname);
960 username = get_user_name(&errstr);
961 if (username == NULL)
963 fprintf(stderr, "%s: %s\n", progname, errstr);
968 * Like initdb.c:setup_config(), determine whether the platform recognizes
969 * ::1 (IPv6 loopback) as a numeric host address string.
972 struct addrinfo *gai_result;
973 struct addrinfo hints;
976 hints.ai_flags = AI_NUMERICHOST;
977 hints.ai_family = AF_UNSPEC;
978 hints.ai_socktype = 0;
979 hints.ai_protocol = 0;
980 hints.ai_addrlen = 0;
981 hints.ai_canonname = NULL;
982 hints.ai_addr = NULL;
983 hints.ai_next = NULL;
985 have_ipv6 = (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0 &&
986 getaddrinfo("::1", NULL, &hints, &gai_result) == 0);
989 /* Check a Write outcome and report any error. */
994 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"), \
995 progname, fname, strerror(errno)); \
1000 res = snprintf(fname, sizeof(fname), "%s/pg_hba.conf", pgdata);
1001 if (res < 0 || res >= sizeof(fname) - 1)
1004 * Truncating this name is a fatal error, because we must not fail to
1005 * overwrite an original trust-authentication pg_hba.conf.
1007 fprintf(stderr, _("%s: directory name too long\n"), progname);
1010 hba = fopen(fname, "w");
1013 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1014 progname, fname, strerror(errno));
1017 CW(fputs("# Configuration written by config_sspi_auth()\n", hba) >= 0);
1018 CW(fputs("host all all 127.0.0.1/32 sspi include_realm=1 map=regress\n",
1021 CW(fputs("host all all ::1/128 sspi include_realm=1 map=regress\n",
1023 CW(fclose(hba) == 0);
1025 snprintf(fname, sizeof(fname), "%s/pg_ident.conf", pgdata);
1026 ident = fopen(fname, "w");
1029 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1030 progname, fname, strerror(errno));
1033 CW(fputs("# Configuration written by config_sspi_auth()\n", ident) >= 0);
1036 * Double-quote for the benefit of account names containing whitespace or
1037 * '#'. Windows forbids the double-quote character itself, so don't
1038 * bother escaping embedded double-quote characters.
1040 CW(fprintf(ident, "regress \"%s@%s\" \"%s\"\n",
1041 accountname, domainname, username) >= 0);
1042 for (sl = extraroles; sl; sl = sl->next)
1043 CW(fprintf(ident, "regress \"%s@%s\" \"%s\"\n",
1044 accountname, domainname, sl->str) >= 0);
1045 CW(fclose(ident) == 0);
1050 * Issue a command via psql, connecting to the specified database
1052 * Since we use system(), this doesn't return until the operation finishes
1055 psql_command(const char *database, const char *query,...)
1057 char query_formatted[1024];
1058 char query_escaped[2048];
1059 char psql_cmd[MAXPGPATH + 2048];
1064 /* Generate the query with insertion of sprintf arguments */
1065 va_start(args, query);
1066 vsnprintf(query_formatted, sizeof(query_formatted), query, args);
1069 /* Now escape any shell double-quote metacharacters */
1071 for (s = query_formatted; *s; s++)
1073 if (strchr("\\\"$`", *s))
1079 /* And now we can build and execute the shell command */
1080 snprintf(psql_cmd, sizeof(psql_cmd),
1081 "\"%s%spsql\" -X -c \"%s\" \"%s\"",
1082 bindir ? bindir : "",
1087 if (system(psql_cmd) != 0)
1089 /* psql probably already reported the error */
1090 fprintf(stderr, _("command failed: %s\n"), psql_cmd);
1096 * Spawn a process to execute the given shell command; don't wait for it
1098 * Returns the process ID (or HANDLE) so we can wait for it later
1101 spawn_process(const char *cmdline)
1107 * Must flush I/O buffers before fork. Ideally we'd use fflush(NULL) here
1108 * ... does anyone still care about systems where that doesn't work?
1118 fprintf(stderr, _("%s: could not fork: %s\n"),
1119 progname, strerror(errno));
1127 * Instead of using system(), exec the shell directly, and tell it to
1128 * "exec" the command too. This saves two useless processes per
1129 * parallel test case.
1133 cmdline2 = psprintf("exec %s", cmdline);
1134 execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
1135 fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
1136 progname, shellprog, strerror(errno));
1137 _exit(1); /* not exit() here... */
1142 PROCESS_INFORMATION pi;
1144 HANDLE restrictedToken;
1146 memset(&pi, 0, sizeof(pi));
1147 cmdline2 = psprintf("cmd /c \"%s\"", cmdline);
1149 if ((restrictedToken =
1150 CreateRestrictedProcess(cmdline2, &pi, progname)) == 0)
1153 CloseHandle(pi.hThread);
1159 * Count bytes in file
1162 file_size(const char *file)
1165 FILE *f = fopen(file, "r");
1169 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1170 progname, file, strerror(errno));
1173 fseek(f, 0, SEEK_END);
1180 * Count lines in file
1183 file_line_count(const char *file)
1187 FILE *f = fopen(file, "r");
1191 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1192 progname, file, strerror(errno));
1195 while ((c = fgetc(f)) != EOF)
1205 file_exists(const char *file)
1207 FILE *f = fopen(file, "r");
1216 directory_exists(const char *dir)
1220 if (stat(dir, &st) != 0)
1222 if (S_ISDIR(st.st_mode))
1227 /* Create a directory */
1229 make_directory(const char *dir)
1231 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
1233 fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
1234 progname, dir, strerror(errno));
1240 * In: filename.ext, Return: filename_i.ext, where 0 < i <= 9
1243 get_alternative_expectfile(const char *expectfile, int i)
1246 int ssize = strlen(expectfile) + 2 + 1;
1250 if (!(tmp = (char *) malloc(ssize)))
1253 if (!(s = (char *) malloc(ssize)))
1259 strcpy(tmp, expectfile);
1260 last_dot = strrchr(tmp, '.');
1268 snprintf(s, ssize, "%s_%d.%s", tmp, i, last_dot + 1);
1274 * Run a "diff" command and also check that it didn't crash
1277 run_diff(const char *cmd, const char *filename)
1282 if (!WIFEXITED(r) || WEXITSTATUS(r) > 1)
1284 fprintf(stderr, _("diff command failed with status %d: %s\n"), r, cmd);
1290 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
1291 * but produces nothing to stdout, so we check for that here.
1293 if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
1295 fprintf(stderr, _("diff command not found: %s\n"), cmd);
1300 return WEXITSTATUS(r);
1304 * Check the actual result file for the given test against expected results
1306 * Returns true if different (failure), false if correct match found.
1307 * In the true case, the diff is appended to the diffs file.
1310 results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
1312 char expectfile[MAXPGPATH];
1313 char diff[MAXPGPATH];
1314 char cmd[MAXPGPATH * 3];
1315 char best_expect_file[MAXPGPATH];
1317 int best_line_count;
1320 const char *platform_expectfile;
1323 * We can pass either the resultsfile or the expectfile, they should have
1324 * the same type (filename.type) anyway.
1326 platform_expectfile = get_expectfile(testname, resultsfile);
1328 strlcpy(expectfile, default_expectfile, sizeof(expectfile));
1329 if (platform_expectfile)
1332 * Replace everything after the last slash in expectfile with what the
1333 * platform_expectfile contains.
1335 char *p = strrchr(expectfile, '/');
1338 strcpy(++p, platform_expectfile);
1341 /* Name to use for temporary diff file */
1342 snprintf(diff, sizeof(diff), "%s.diff", resultsfile);
1344 /* OK, run the diff */
1345 snprintf(cmd, sizeof(cmd),
1346 "diff %s \"%s\" \"%s\" > \"%s\"",
1347 basic_diff_opts, expectfile, resultsfile, diff);
1349 /* Is the diff file empty? */
1350 if (run_diff(cmd, diff) == 0)
1356 /* There may be secondary comparison files that match better */
1357 best_line_count = file_line_count(diff);
1358 strcpy(best_expect_file, expectfile);
1360 for (i = 0; i <= 9; i++)
1362 char *alt_expectfile;
1364 alt_expectfile = get_alternative_expectfile(expectfile, i);
1365 if (!alt_expectfile)
1367 fprintf(stderr, _("Unable to check secondary comparison files: %s\n"),
1372 if (!file_exists(alt_expectfile))
1374 free(alt_expectfile);
1378 snprintf(cmd, sizeof(cmd),
1379 "diff %s \"%s\" \"%s\" > \"%s\"",
1380 basic_diff_opts, alt_expectfile, resultsfile, diff);
1382 if (run_diff(cmd, diff) == 0)
1385 free(alt_expectfile);
1389 l = file_line_count(diff);
1390 if (l < best_line_count)
1392 /* This diff was a better match than the last one */
1393 best_line_count = l;
1394 strlcpy(best_expect_file, alt_expectfile, sizeof(best_expect_file));
1396 free(alt_expectfile);
1400 * fall back on the canonical results file if we haven't tried it yet and
1401 * haven't found a complete match yet.
1404 if (platform_expectfile)
1406 snprintf(cmd, sizeof(cmd),
1407 "diff %s \"%s\" \"%s\" > \"%s\"",
1408 basic_diff_opts, default_expectfile, resultsfile, diff);
1410 if (run_diff(cmd, diff) == 0)
1412 /* No diff = no changes = good */
1417 l = file_line_count(diff);
1418 if (l < best_line_count)
1420 /* This diff was a better match than the last one */
1421 best_line_count = l;
1422 strlcpy(best_expect_file, default_expectfile, sizeof(best_expect_file));
1427 * Use the best comparison file to generate the "pretty" diff, which we
1428 * append to the diffs summary file.
1430 snprintf(cmd, sizeof(cmd),
1431 "diff %s \"%s\" \"%s\" >> \"%s\"",
1432 pretty_diff_opts, best_expect_file, resultsfile, difffilename);
1433 run_diff(cmd, difffilename);
1435 /* And append a separator */
1436 difffile = fopen(difffilename, "a");
1440 "\n======================================================================\n\n");
1449 * Wait for specified subprocesses to finish, and return their exit
1450 * statuses into statuses[]
1452 * If names isn't NULL, print each subprocess's name as it finishes
1454 * Note: it's OK to scribble on the pids array, but not on the names array
1457 wait_for_tests(PID_TYPE * pids, int *statuses, char **names, int num_tests)
1463 PID_TYPE *active_pids = malloc(num_tests * sizeof(PID_TYPE));
1465 memcpy(active_pids, pids, num_tests * sizeof(PID_TYPE));
1468 tests_left = num_tests;
1469 while (tests_left > 0)
1476 p = wait(&exit_status);
1478 if (p == INVALID_PID)
1480 fprintf(stderr, _("failed to wait for subprocesses: %s\n"),
1488 r = WaitForMultipleObjects(tests_left, active_pids, FALSE, INFINITE);
1489 if (r < WAIT_OBJECT_0 || r >= WAIT_OBJECT_0 + tests_left)
1491 fprintf(stderr, _("failed to wait for subprocesses: error code %lu\n"),
1495 p = active_pids[r - WAIT_OBJECT_0];
1496 /* compact the active_pids array */
1497 active_pids[r - WAIT_OBJECT_0] = active_pids[tests_left - 1];
1500 for (i = 0; i < num_tests; i++)
1505 GetExitCodeProcess(pids[i], &exit_status);
1506 CloseHandle(pids[i]);
1508 pids[i] = INVALID_PID;
1509 statuses[i] = (int) exit_status;
1511 status(" %s", names[i]);
1524 * report nonzero exit code from a test process
1527 log_child_failure(int exitstatus)
1529 if (WIFEXITED(exitstatus))
1530 status(_(" (test process exited with exit code %d)"),
1531 WEXITSTATUS(exitstatus));
1532 else if (WIFSIGNALED(exitstatus))
1535 status(_(" (test process was terminated by exception 0x%X)"),
1536 WTERMSIG(exitstatus));
1537 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
1538 status(_(" (test process was terminated by signal %d: %s)"),
1539 WTERMSIG(exitstatus),
1540 WTERMSIG(exitstatus) < NSIG ?
1541 sys_siglist[WTERMSIG(exitstatus)] : "(unknown))");
1543 status(_(" (test process was terminated by signal %d)"),
1544 WTERMSIG(exitstatus));
1548 status(_(" (test process exited with unrecognized status %d)"),
1553 * Run all the tests specified in one schedule file
1556 run_schedule(const char *schedule, test_function tfunc)
1558 #define MAX_PARALLEL_TESTS 100
1559 char *tests[MAX_PARALLEL_TESTS];
1560 _stringlist *resultfiles[MAX_PARALLEL_TESTS];
1561 _stringlist *expectfiles[MAX_PARALLEL_TESTS];
1562 _stringlist *tags[MAX_PARALLEL_TESTS];
1563 PID_TYPE pids[MAX_PARALLEL_TESTS];
1564 int statuses[MAX_PARALLEL_TESTS];
1565 _stringlist *ignorelist = NULL;
1570 memset(resultfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1571 memset(expectfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1572 memset(tags, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1574 scf = fopen(schedule, "r");
1577 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
1578 progname, schedule, strerror(errno));
1582 while (fgets(scbuf, sizeof(scbuf), scf))
1592 for (i = 0; i < MAX_PARALLEL_TESTS; i++)
1594 if (resultfiles[i] == NULL)
1596 free_stringlist(&resultfiles[i]);
1597 free_stringlist(&expectfiles[i]);
1598 free_stringlist(&tags[i]);
1601 /* strip trailing whitespace, especially the newline */
1603 while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1606 if (scbuf[0] == '\0' || scbuf[0] == '#')
1608 if (strncmp(scbuf, "test: ", 6) == 0)
1610 else if (strncmp(scbuf, "ignore: ", 8) == 0)
1613 while (*c && isspace((unsigned char) *c))
1615 add_stringlist_item(&ignorelist, c);
1618 * Note: ignore: lines do not run the test, they just say that
1619 * failure of this test when run later on is to be ignored. A bit
1620 * odd but that's how the shell-script version did it.
1626 fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
1627 schedule, line_num, scbuf);
1633 for (c = test; *c; c++)
1635 if (isspace((unsigned char) *c))
1642 if (num_tests >= MAX_PARALLEL_TESTS)
1644 /* can't print scbuf here, it's already been trashed */
1645 fprintf(stderr, _("too many parallel tests in schedule file \"%s\", line %d\n"),
1646 schedule, line_num);
1649 tests[num_tests] = c;
1657 fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
1658 schedule, line_num, scbuf);
1664 status(_("test %-24s ... "), tests[0]);
1665 pids[0] = (tfunc) (tests[0], &resultfiles[0], &expectfiles[0], &tags[0]);
1666 wait_for_tests(pids, statuses, NULL, 1);
1667 /* status line is finished below */
1669 else if (max_connections > 0 && max_connections < num_tests)
1673 status(_("parallel group (%d tests, in groups of %d): "),
1674 num_tests, max_connections);
1675 for (i = 0; i < num_tests; i++)
1677 if (i - oldest >= max_connections)
1679 wait_for_tests(pids + oldest, statuses + oldest,
1680 tests + oldest, i - oldest);
1683 pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1685 wait_for_tests(pids + oldest, statuses + oldest,
1686 tests + oldest, i - oldest);
1691 status(_("parallel group (%d tests): "), num_tests);
1692 for (i = 0; i < num_tests; i++)
1694 pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1696 wait_for_tests(pids, statuses, tests, num_tests);
1700 /* Check results for all tests */
1701 for (i = 0; i < num_tests; i++)
1706 bool differ = false;
1709 status(_(" %-24s ... "), tests[i]);
1712 * Advance over all three lists simultaneously.
1714 * Compare resultfiles[j] with expectfiles[j] always. Tags are
1715 * optional but if there are tags, the tag list has the same
1716 * length as the other two lists.
1718 for (rl = resultfiles[i], el = expectfiles[i], tl = tags[i];
1719 rl != NULL; /* rl and el have the same length */
1720 rl = rl->next, el = el->next)
1725 tl = tl->next; /* tl has the same length as rl and el
1728 newdiff = results_differ(tests[i], rl->str, el->str);
1731 printf("%s ", tl->str);
1738 bool ignore = false;
1741 for (sl = ignorelist; sl != NULL; sl = sl->next)
1743 if (strcmp(tests[i], sl->str) == 0)
1751 status(_("failed (ignored)"));
1752 fail_ignore_count++;
1756 status(_("FAILED"));
1766 if (statuses[i] != 0)
1767 log_child_failure(statuses[i]);
1773 free_stringlist(&ignorelist);
1782 run_single_test(const char *test, test_function tfunc)
1786 _stringlist *resultfiles = NULL;
1787 _stringlist *expectfiles = NULL;
1788 _stringlist *tags = NULL;
1792 bool differ = false;
1794 status(_("test %-24s ... "), test);
1795 pid = (tfunc) (test, &resultfiles, &expectfiles, &tags);
1796 wait_for_tests(&pid, &exit_status, NULL, 1);
1799 * Advance over all three lists simultaneously.
1801 * Compare resultfiles[j] with expectfiles[j] always. Tags are optional
1802 * but if there are tags, the tag list has the same length as the other
1805 for (rl = resultfiles, el = expectfiles, tl = tags;
1806 rl != NULL; /* rl and el have the same length */
1807 rl = rl->next, el = el->next)
1812 tl = tl->next; /* tl has the same length as rl and el if it
1815 newdiff = results_differ(test, rl->str, el->str);
1818 printf("%s ", tl->str);
1825 status(_("FAILED"));
1834 if (exit_status != 0)
1835 log_child_failure(exit_status);
1841 * Create the summary-output files (making them empty if already existing)
1844 open_result_files(void)
1846 char file[MAXPGPATH];
1849 /* create the log file (copy of running status output) */
1850 snprintf(file, sizeof(file), "%s/regression.out", outputdir);
1851 logfilename = strdup(file);
1852 logfile = fopen(logfilename, "w");
1855 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1856 progname, logfilename, strerror(errno));
1860 /* create the diffs file as empty */
1861 snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
1862 difffilename = strdup(file);
1863 difffile = fopen(difffilename, "w");
1866 fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
1867 progname, difffilename, strerror(errno));
1870 /* we don't keep the diffs file open continuously */
1873 /* also create the output directory if not present */
1874 snprintf(file, sizeof(file), "%s/results", outputdir);
1875 if (!directory_exists(file))
1876 make_directory(file);
1880 drop_database_if_exists(const char *dbname)
1882 header(_("dropping database \"%s\""), dbname);
1883 psql_command("postgres", "DROP DATABASE IF EXISTS \"%s\"", dbname);
1887 create_database(const char *dbname)
1892 * We use template0 so that any installation-local cruft in template1 will
1893 * not mess up the tests.
1895 header(_("creating database \"%s\""), dbname);
1897 psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'%s", dbname, encoding,
1898 (nolocale) ? " LC_COLLATE='C' LC_CTYPE='C'" : "");
1900 psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0%s", dbname,
1901 (nolocale) ? " LC_COLLATE='C' LC_CTYPE='C'" : "");
1902 psql_command(dbname,
1903 "ALTER DATABASE \"%s\" SET lc_messages TO 'C';"
1904 "ALTER DATABASE \"%s\" SET lc_monetary TO 'C';"
1905 "ALTER DATABASE \"%s\" SET lc_numeric TO 'C';"
1906 "ALTER DATABASE \"%s\" SET lc_time TO 'C';"
1907 "ALTER DATABASE \"%s\" SET timezone_abbreviations TO 'Default';",
1908 dbname, dbname, dbname, dbname, dbname);
1911 * Install any requested procedural languages. We use CREATE OR REPLACE
1912 * so that this will work whether or not the language is preinstalled.
1914 for (sl = loadlanguage; sl != NULL; sl = sl->next)
1916 header(_("installing %s"), sl->str);
1917 psql_command(dbname, "CREATE OR REPLACE LANGUAGE \"%s\"", sl->str);
1921 * Install any requested extensions. We use CREATE IF NOT EXISTS so that
1922 * this will work whether or not the extension is preinstalled.
1924 for (sl = loadextension; sl != NULL; sl = sl->next)
1926 header(_("installing %s"), sl->str);
1927 psql_command(dbname, "CREATE EXTENSION IF NOT EXISTS \"%s\"", sl->str);
1932 drop_role_if_exists(const char *rolename)
1934 header(_("dropping role \"%s\""), rolename);
1935 psql_command("postgres", "DROP ROLE IF EXISTS \"%s\"", rolename);
1939 create_role(const char *rolename, const _stringlist *granted_dbs)
1941 header(_("creating role \"%s\""), rolename);
1942 psql_command("postgres", "CREATE ROLE \"%s\" WITH LOGIN", rolename);
1943 for (; granted_dbs != NULL; granted_dbs = granted_dbs->next)
1945 psql_command("postgres", "GRANT ALL ON DATABASE \"%s\" TO \"%s\"",
1946 granted_dbs->str, rolename);
1953 printf(_("PostgreSQL regression test driver\n"));
1955 printf(_("Usage:\n %s [OPTION]... [EXTRA-TEST]...\n"), progname);
1957 printf(_("Options:\n"));
1958 printf(_(" --config-auth=DATADIR update authentication settings for DATADIR\n"));
1959 printf(_(" --create-role=ROLE create the specified role before testing\n"));
1960 printf(_(" --dbname=DB use database DB (default \"regression\")\n"));
1961 printf(_(" --debug turn on debug mode in programs that are run\n"));
1962 printf(_(" --dlpath=DIR look for dynamic libraries in DIR\n"));
1963 printf(_(" --encoding=ENCODING use ENCODING as the encoding\n"));
1964 printf(_(" --inputdir=DIR take input files from DIR (default \".\")\n"));
1965 printf(_(" --launcher=CMD use CMD as launcher of psql\n"));
1966 printf(_(" --load-extension=EXT load the named extension before running the\n"));
1967 printf(_(" tests; can appear multiple times\n"));
1968 printf(_(" --load-language=LANG load the named language before running the\n"));
1969 printf(_(" tests; can appear multiple times\n"));
1970 printf(_(" --max-connections=N maximum number of concurrent connections\n"));
1971 printf(_(" (default is 0, meaning unlimited)\n"));
1972 printf(_(" --outputdir=DIR place output files in DIR (default \".\")\n"));
1973 printf(_(" --schedule=FILE use test ordering schedule from FILE\n"));
1974 printf(_(" (can be used multiple times to concatenate)\n"));
1975 printf(_(" --temp-instance=DIR create a temporary instance in DIR\n"));
1976 printf(_(" --use-existing use an existing installation\n"));
1978 printf(_("Options for \"temp-instance\" mode:\n"));
1979 printf(_(" --no-locale use C locale\n"));
1980 printf(_(" --port=PORT start postmaster on PORT\n"));
1981 printf(_(" --temp-config=FILE append contents of FILE to temporary config\n"));
1983 printf(_("Options for using an existing installation:\n"));
1984 printf(_(" --host=HOST use postmaster running on HOST\n"));
1985 printf(_(" --port=PORT use postmaster running at PORT\n"));
1986 printf(_(" --user=USER connect as USER\n"));
1988 printf(_("The exit status is 0 if all tests passed, 1 if some tests failed, and 2\n"));
1989 printf(_("if the tests could not be run for some reason.\n"));
1991 printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
1995 regression_main(int argc, char *argv[], init_function ifunc, test_function tfunc)
1997 static struct option long_options[] = {
1998 {"help", no_argument, NULL, 'h'},
1999 {"version", no_argument, NULL, 'V'},
2000 {"dbname", required_argument, NULL, 1},
2001 {"debug", no_argument, NULL, 2},
2002 {"inputdir", required_argument, NULL, 3},
2003 {"load-language", required_argument, NULL, 4},
2004 {"max-connections", required_argument, NULL, 5},
2005 {"encoding", required_argument, NULL, 6},
2006 {"outputdir", required_argument, NULL, 7},
2007 {"schedule", required_argument, NULL, 8},
2008 {"temp-instance", required_argument, NULL, 9},
2009 {"no-locale", no_argument, NULL, 10},
2010 {"host", required_argument, NULL, 13},
2011 {"port", required_argument, NULL, 14},
2012 {"user", required_argument, NULL, 15},
2013 {"bindir", required_argument, NULL, 16},
2014 {"dlpath", required_argument, NULL, 17},
2015 {"create-role", required_argument, NULL, 18},
2016 {"temp-config", required_argument, NULL, 19},
2017 {"use-existing", no_argument, NULL, 20},
2018 {"launcher", required_argument, NULL, 21},
2019 {"load-extension", required_argument, NULL, 22},
2020 {"config-auth", required_argument, NULL, 24},
2028 char buf[MAXPGPATH * 4];
2029 char buf2[MAXPGPATH * 4];
2031 progname = get_progname(argv[0]);
2032 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_regress"));
2034 atexit(stop_postmaster);
2036 #ifndef HAVE_UNIX_SOCKETS
2037 /* no unix domain sockets available, so change default */
2038 hostname = "localhost";
2042 * We call the initialization function here because that way we can set
2043 * default parameters and let them be overwritten by the commandline.
2047 if (getenv("PG_REGRESS_DIFF_OPTS"))
2048 pretty_diff_opts = getenv("PG_REGRESS_DIFF_OPTS");
2050 while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
2058 puts("pg_regress (PostgreSQL) " PG_VERSION);
2063 * If a default database was specified, we need to remove it
2064 * before we add the specified one.
2066 free_stringlist(&dblist);
2067 split_to_stringlist(strdup(optarg), ", ", &dblist);
2073 inputdir = strdup(optarg);
2076 add_stringlist_item(&loadlanguage, optarg);
2079 max_connections = atoi(optarg);
2082 encoding = strdup(optarg);
2085 outputdir = strdup(optarg);
2088 add_stringlist_item(&schedulelist, optarg);
2091 temp_instance = make_absolute_path(optarg);
2097 hostname = strdup(optarg);
2100 port = atoi(optarg);
2101 port_specified_by_user = true;
2104 user = strdup(optarg);
2107 /* "--bindir=" means to use PATH */
2109 bindir = strdup(optarg);
2114 dlpath = strdup(optarg);
2117 split_to_stringlist(strdup(optarg), ", ", &extraroles);
2120 add_stringlist_item(&temp_configs, optarg);
2123 use_existing = true;
2126 launcher = strdup(optarg);
2129 add_stringlist_item(&loadextension, optarg);
2132 config_auth_datadir = pstrdup(optarg);
2135 /* getopt_long already emitted a complaint */
2136 fprintf(stderr, _("\nTry \"%s -h\" for more information.\n"),
2143 * if we still have arguments, they are extra tests to run
2145 while (argc - optind >= 1)
2147 add_stringlist_item(&extra_tests, argv[optind]);
2151 if (config_auth_datadir)
2154 config_sspi_auth(config_auth_datadir);
2159 if (temp_instance && !port_specified_by_user)
2162 * To reduce chances of interference with parallel installations, use
2163 * a port number starting in the private range (49152-65535)
2164 * calculated from the version number. This aids !HAVE_UNIX_SOCKETS
2165 * systems; elsewhere, the use of a private socket directory already
2166 * prevents interference.
2168 port = 0xC000 | (PG_VERSION_NUM & 0x3FFF);
2170 inputdir = make_absolute_path(inputdir);
2171 outputdir = make_absolute_path(outputdir);
2172 dlpath = make_absolute_path(dlpath);
2177 open_result_files();
2179 initialize_environment();
2181 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
2182 unlimit_core_size();
2190 * Prepare the temp instance
2193 if (directory_exists(temp_instance))
2195 header(_("removing existing temp instance"));
2196 if (!rmtree(temp_instance, true))
2198 fprintf(stderr, _("\n%s: could not remove temp instance \"%s\"\n"),
2199 progname, temp_instance);
2204 header(_("creating temporary instance"));
2206 /* make the temp instance top directory */
2207 make_directory(temp_instance);
2209 /* and a directory for log files */
2210 snprintf(buf, sizeof(buf), "%s/log", outputdir);
2211 if (!directory_exists(buf))
2212 make_directory(buf);
2215 header(_("initializing database system"));
2216 snprintf(buf, sizeof(buf),
2217 "\"%s%sinitdb\" -D \"%s/data\" --noclean --nosync%s%s > \"%s/log/initdb.log\" 2>&1",
2218 bindir ? bindir : "",
2221 debug ? " --debug" : "",
2222 nolocale ? " --no-locale" : "",
2226 fprintf(stderr, _("\n%s: initdb failed\nExamine %s/log/initdb.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2231 * Adjust the default postgresql.conf for regression testing. The user
2232 * can specify a file to be appended; in any case we expand logging
2233 * and set max_prepared_transactions to enable testing of prepared
2234 * xacts. (Note: to reduce the probability of unexpected shmmax
2235 * failures, don't set max_prepared_transactions any higher than
2236 * actually needed by the prepared_xacts regression test.)
2238 snprintf(buf, sizeof(buf), "%s/data/postgresql.conf", temp_instance);
2239 pg_conf = fopen(buf, "a");
2240 if (pg_conf == NULL)
2242 fprintf(stderr, _("\n%s: could not open \"%s\" for adding extra config: %s\n"), progname, buf, strerror(errno));
2245 fputs("\n# Configuration added by pg_regress\n\n", pg_conf);
2246 fputs("log_autovacuum_min_duration = 0\n", pg_conf);
2247 fputs("log_checkpoints = on\n", pg_conf);
2248 fputs("log_lock_waits = on\n", pg_conf);
2249 fputs("log_temp_files = 128kB\n", pg_conf);
2250 fputs("max_prepared_transactions = 2\n", pg_conf);
2252 for (sl = temp_configs; sl != NULL; sl = sl->next)
2254 char *temp_config = sl->str;
2256 char line_buf[1024];
2258 extra_conf = fopen(temp_config, "r");
2259 if (extra_conf == NULL)
2261 fprintf(stderr, _("\n%s: could not open \"%s\" to read extra config: %s\n"), progname, temp_config, strerror(errno));
2264 while (fgets(line_buf, sizeof(line_buf), extra_conf) != NULL)
2265 fputs(line_buf, pg_conf);
2274 * Since we successfully used the same buffer for the much-longer
2275 * "initdb" command, this can't truncate.
2277 snprintf(buf, sizeof(buf), "%s/data", temp_instance);
2278 config_sspi_auth(buf);
2279 #elif !defined(HAVE_UNIX_SOCKETS)
2280 #error Platform has no means to secure the test installation.
2284 * Check if there is a postmaster running already.
2286 snprintf(buf2, sizeof(buf2),
2287 "\"%s%spsql\" -X postgres <%s 2>%s",
2288 bindir ? bindir : "",
2292 for (i = 0; i < 16; i++)
2294 if (system(buf2) == 0)
2298 if (port_specified_by_user || i == 15)
2300 fprintf(stderr, _("port %d apparently in use\n"), port);
2301 if (!port_specified_by_user)
2302 fprintf(stderr, _("%s: could not determine an available port\n"), progname);
2303 fprintf(stderr, _("Specify an unused port using the --port option or shut down any conflicting PostgreSQL servers.\n"));
2307 fprintf(stderr, _("port %d apparently in use, trying %d\n"), port, port + 1);
2309 sprintf(s, "%d", port);
2310 doputenv("PGPORT", s);
2317 * Start the temp postmaster
2319 header(_("starting postmaster"));
2320 snprintf(buf, sizeof(buf),
2321 "\"%s%spostgres\" -D \"%s/data\" -F%s "
2322 "-c \"listen_addresses=%s\" -k \"%s\" "
2323 "> \"%s/log/postmaster.log\" 2>&1",
2324 bindir ? bindir : "",
2326 temp_instance, debug ? " -d 5" : "",
2327 hostname ? hostname : "", sockdir ? sockdir : "",
2329 postmaster_pid = spawn_process(buf);
2330 if (postmaster_pid == INVALID_PID)
2332 fprintf(stderr, _("\n%s: could not spawn postmaster: %s\n"),
2333 progname, strerror(errno));
2338 * Wait till postmaster is able to accept connections (normally only a
2339 * second or so, but Cygwin is reportedly *much* slower). Don't wait
2342 for (i = 0; i < 60; i++)
2344 /* Done if psql succeeds */
2345 if (system(buf2) == 0)
2349 * Fail immediately if postmaster has exited
2352 if (kill(postmaster_pid, 0) != 0)
2354 if (WaitForSingleObject(postmaster_pid, 0) == WAIT_OBJECT_0)
2357 fprintf(stderr, _("\n%s: postmaster failed\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
2361 pg_usleep(1000000L);
2365 fprintf(stderr, _("\n%s: postmaster did not respond within 60 seconds\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
2368 * If we get here, the postmaster is probably wedged somewhere in
2369 * startup. Try to kill it ungracefully rather than leaving a
2370 * stuck postmaster that might interfere with subsequent test
2374 if (kill(postmaster_pid, SIGKILL) != 0 &&
2376 fprintf(stderr, _("\n%s: could not kill failed postmaster: %s\n"),
2377 progname, strerror(errno));
2379 if (TerminateProcess(postmaster_pid, 255) == 0)
2380 fprintf(stderr, _("\n%s: could not kill failed postmaster: error code %lu\n"),
2381 progname, GetLastError());
2387 postmaster_running = true;
2390 /* need a series of two casts to convert HANDLE without compiler warning */
2391 #define ULONGPID(x) (unsigned long) (unsigned long long) (x)
2393 #define ULONGPID(x) (unsigned long) (x)
2395 printf(_("running on port %d with PID %lu\n"),
2396 port, ULONGPID(postmaster_pid));
2401 * Using an existing installation, so may need to get rid of
2402 * pre-existing database(s) and role(s)
2406 for (sl = dblist; sl; sl = sl->next)
2407 drop_database_if_exists(sl->str);
2408 for (sl = extraroles; sl; sl = sl->next)
2409 drop_role_if_exists(sl->str);
2414 * Create the test database(s) and role(s)
2418 for (sl = dblist; sl; sl = sl->next)
2419 create_database(sl->str);
2420 for (sl = extraroles; sl; sl = sl->next)
2421 create_role(sl->str, dblist);
2425 * Ready to run the tests
2427 header(_("running regression test queries"));
2429 for (sl = schedulelist; sl != NULL; sl = sl->next)
2431 run_schedule(sl->str, tfunc);
2434 for (sl = extra_tests; sl != NULL; sl = sl->next)
2436 run_single_test(sl->str, tfunc);
2440 * Shut down temp installation's postmaster
2444 header(_("shutting down postmaster"));
2449 * If there were no errors, remove the temp instance immediately to
2450 * conserve disk space. (If there were errors, we leave the instance in
2451 * place for possible manual investigation.)
2453 if (temp_instance && fail_count == 0 && fail_ignore_count == 0)
2455 header(_("removing temporary instance"));
2456 if (!rmtree(temp_instance, true))
2457 fprintf(stderr, _("\n%s: could not remove temp instance \"%s\"\n"),
2458 progname, temp_instance);
2464 * Emit nice-looking summary message
2466 if (fail_count == 0 && fail_ignore_count == 0)
2467 snprintf(buf, sizeof(buf),
2468 _(" All %d tests passed. "),
2470 else if (fail_count == 0) /* fail_count=0, fail_ignore_count>0 */
2471 snprintf(buf, sizeof(buf),
2472 _(" %d of %d tests passed, %d failed test(s) ignored. "),
2474 success_count + fail_ignore_count,
2476 else if (fail_ignore_count == 0) /* fail_count>0 && fail_ignore_count=0 */
2477 snprintf(buf, sizeof(buf),
2478 _(" %d of %d tests failed. "),
2480 success_count + fail_count);
2482 /* fail_count>0 && fail_ignore_count>0 */
2483 snprintf(buf, sizeof(buf),
2484 _(" %d of %d tests failed, %d of these failures ignored. "),
2485 fail_count + fail_ignore_count,
2486 success_count + fail_count + fail_ignore_count,
2490 for (i = strlen(buf); i > 0; i--)
2492 printf("\n%s\n", buf);
2493 for (i = strlen(buf); i > 0; i--)
2498 if (file_size(difffilename) > 0)
2500 printf(_("The differences that caused some tests to fail can be viewed in the\n"
2501 "file \"%s\". A copy of the test summary that you see\n"
2502 "above is saved in the file \"%s\".\n\n"),
2503 difffilename, logfilename);
2507 unlink(difffilename);
2508 unlink(logfilename);
2511 if (fail_count != 0)