1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/init/postinit.c,v 1.207 2010/03/24 21:25:50 sriggs Exp $
14 *-------------------------------------------------------------------------
22 #include "access/heapam.h"
23 #include "access/sysattr.h"
24 #include "access/xact.h"
25 #include "catalog/catalog.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_database.h"
30 #include "catalog/pg_db_role_setting.h"
31 #include "catalog/pg_tablespace.h"
32 #include "libpq/auth.h"
33 #include "libpq/libpq-be.h"
34 #include "mb/pg_wchar.h"
35 #include "miscadmin.h"
37 #include "postmaster/autovacuum.h"
38 #include "postmaster/postmaster.h"
39 #include "replication/walsender.h"
40 #include "storage/bufmgr.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/lmgr.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "storage/procsignal.h"
47 #include "storage/sinvaladt.h"
48 #include "storage/smgr.h"
49 #include "tcop/tcopprot.h"
50 #include "utils/acl.h"
51 #include "utils/fmgroids.h"
52 #include "utils/guc.h"
53 #include "utils/pg_locale.h"
54 #include "utils/portal.h"
55 #include "utils/ps_status.h"
56 #include "utils/snapmgr.h"
57 #include "utils/syscache.h"
58 #include "utils/tqual.h"
61 static HeapTuple GetDatabaseTuple(const char *dbname);
62 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
63 static void PerformAuthentication(Port *port);
64 static void CheckMyDatabase(const char *name, bool am_superuser);
65 static void InitCommunication(void);
66 static void ShutdownPostgres(int code, Datum arg);
67 static bool ThereIsAtLeastOneRole(void);
68 static void process_settings(Oid databaseid, Oid roleid);
71 /*** InitPostgres support ***/
75 * GetDatabaseTuple -- fetch the pg_database row for a database
77 * This is used during backend startup when we don't yet have any access to
78 * system catalogs in general. In the worst case, we can seqscan pg_database
79 * using nothing but the hard-wired descriptor that relcache.c creates for
80 * pg_database. In more typical cases, relcache.c was able to load
81 * descriptors for both pg_database and its indexes from the shared relcache
82 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
83 * tells whether we got the cached descriptors.
86 GetDatabaseTuple(const char *dbname)
97 Anum_pg_database_datname,
98 BTEqualStrategyNumber, F_NAMEEQ,
99 CStringGetDatum(dbname));
102 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
103 * built the critical shared relcache entries (i.e., we're starting up
104 * without a shared relcache cache file).
106 relation = heap_open(DatabaseRelationId, AccessShareLock);
107 scan = systable_beginscan(relation, DatabaseNameIndexId,
108 criticalSharedRelcachesBuilt,
112 tuple = systable_getnext(scan);
114 /* Must copy tuple before releasing buffer */
115 if (HeapTupleIsValid(tuple))
116 tuple = heap_copytuple(tuple);
119 systable_endscan(scan);
120 heap_close(relation, AccessShareLock);
126 * GetDatabaseTupleByOid -- as above, but search by database OID
129 GetDatabaseTupleByOid(Oid dboid)
140 ObjectIdAttributeNumber,
141 BTEqualStrategyNumber, F_OIDEQ,
142 ObjectIdGetDatum(dboid));
145 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
146 * built the critical shared relcache entries (i.e., we're starting up
147 * without a shared relcache cache file).
149 relation = heap_open(DatabaseRelationId, AccessShareLock);
150 scan = systable_beginscan(relation, DatabaseOidIndexId,
151 criticalSharedRelcachesBuilt,
155 tuple = systable_getnext(scan);
157 /* Must copy tuple before releasing buffer */
158 if (HeapTupleIsValid(tuple))
159 tuple = heap_copytuple(tuple);
162 systable_endscan(scan);
163 heap_close(relation, AccessShareLock);
170 * PerformAuthentication -- authenticate a remote client
172 * returns: nothing. Will not return at all if there's any failure.
175 PerformAuthentication(Port *port)
177 /* This should be set already, but let's make sure */
178 ClientAuthInProgress = true; /* limit visibility of log messages */
181 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
182 * etcetera from the postmaster, and have to load them ourselves. Note we
183 * are loading them into the startup transaction's memory context, not
184 * PostmasterContext, but that shouldn't matter.
186 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
192 * It makes no sense to continue if we fail to load the HBA file,
193 * since there is no way to connect to the database in this case.
196 (errmsg("could not load pg_hba.conf")));
202 * Set up a timeout in case a buggy or malicious client fails to respond
203 * during authentication. Since we're inside a transaction and might do
204 * database access, we have to use the statement_timeout infrastructure.
206 if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
207 elog(FATAL, "could not set timer for authorization timeout");
210 * Now perform authentication exchange.
212 ClientAuthentication(port); /* might not return, if failure */
215 * Done with authentication. Disable the timeout, and log if needed.
217 if (!disable_sig_alarm(true))
218 elog(FATAL, "could not disable timer for authorization timeout");
221 * Log connection for streaming replication even if Log_connections disabled.
225 (errmsg("replication connection authorized: user=%s host=%s%s%s",
227 port->remote_host, port->remote_port[0] ? " port=" : "",
228 port->remote_port)));
230 else if (Log_connections)
232 (errmsg("connection authorized: user=%s database=%s",
233 port->user_name, port->database_name)));
235 set_ps_display("startup", false);
237 ClientAuthInProgress = false; /* client_min_messages is active now */
242 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
245 CheckMyDatabase(const char *name, bool am_superuser)
248 Form_pg_database dbform;
252 /* Fetch our pg_database row normally, via syscache */
253 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
254 if (!HeapTupleIsValid(tup))
255 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
256 dbform = (Form_pg_database) GETSTRUCT(tup);
258 /* This recheck is strictly paranoia */
259 if (strcmp(name, NameStr(dbform->datname)) != 0)
261 (errcode(ERRCODE_UNDEFINED_DATABASE),
262 errmsg("database \"%s\" has disappeared from pg_database",
264 errdetail("Database OID %u now seems to belong to \"%s\".",
265 MyDatabaseId, NameStr(dbform->datname))));
268 * Check permissions to connect to the database.
270 * These checks are not enforced when in standalone mode, so that there is
271 * a way to recover from disabling all access to all databases, for
272 * example "UPDATE pg_database SET datallowconn = false;".
274 * We do not enforce them for autovacuum worker processes either.
276 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
279 * Check that the database is currently allowing connections.
281 if (!dbform->datallowconn)
283 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
284 errmsg("database \"%s\" is not currently accepting connections",
288 * Check privilege to connect to the database. (The am_superuser test
289 * is redundant, but since we have the flag, might as well check it
290 * and save a few cycles.)
293 pg_database_aclcheck(MyDatabaseId, GetUserId(),
294 ACL_CONNECT) != ACLCHECK_OK)
296 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
297 errmsg("permission denied for database \"%s\"", name),
298 errdetail("User does not have CONNECT privilege.")));
301 * Check connection limit for this database.
303 * There is a race condition here --- we create our PGPROC before
304 * checking for other PGPROCs. If two backends did this at about the
305 * same time, they might both think they were over the limit, while
306 * ideally one should succeed and one fail. Getting that to work
307 * exactly seems more trouble than it is worth, however; instead we
308 * just document that the connection limit is approximate.
310 if (dbform->datconnlimit >= 0 &&
312 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
314 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
315 errmsg("too many connections for database \"%s\"",
320 * OK, we're golden. Next to-do item is to save the encoding info out of
321 * the pg_database tuple.
323 SetDatabaseEncoding(dbform->encoding);
324 /* Record it as a GUC internal option, too */
325 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
326 PGC_INTERNAL, PGC_S_OVERRIDE);
327 /* If we have no other source of client_encoding, use server encoding */
328 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
329 PGC_BACKEND, PGC_S_DEFAULT);
331 /* assign locale variables */
332 collate = NameStr(dbform->datcollate);
333 ctype = NameStr(dbform->datctype);
335 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
337 (errmsg("database locale is incompatible with operating system"),
338 errdetail("The database was initialized with LC_COLLATE \"%s\", "
339 " which is not recognized by setlocale().", collate),
340 errhint("Recreate the database with another locale or install the missing locale.")));
342 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
344 (errmsg("database locale is incompatible with operating system"),
345 errdetail("The database was initialized with LC_CTYPE \"%s\", "
346 " which is not recognized by setlocale().", ctype),
347 errhint("Recreate the database with another locale or install the missing locale.")));
349 /* Make the locale settings visible as GUC variables, too */
350 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
351 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
353 /* Use the right encoding in translated messages */
355 pg_bind_textdomain_codeset(textdomain(NULL));
358 ReleaseSysCache(tup);
363 /* --------------------------------
366 * This routine initializes stuff needed for ipc, locking, etc.
367 * it should be called something more informative.
368 * --------------------------------
371 InitCommunication(void)
374 * initialize shared memory and semaphores appropriately.
376 if (!IsUnderPostmaster) /* postmaster already did this */
379 * We're running a postgres bootstrap process or a standalone backend.
380 * Create private "shmem" and semaphores.
382 CreateSharedMemoryAndSemaphores(true, 0);
388 * pg_split_opts -- split a string of options and append it to an argv array
390 * NB: the input string is destructively modified! Also, caller is responsible
391 * for ensuring the argv array is large enough. The maximum possible number
392 * of arguments added by this routine is (strlen(optstr) + 1) / 2.
394 * Since no current POSTGRES arguments require any quoting characters,
395 * we can use the simple-minded tactic of assuming each set of space-
396 * delimited characters is a separate argv element.
398 * If you don't like that, well, we *used* to pass the whole option string
399 * as ONE argument to execl(), which was even less intelligent...
402 pg_split_opts(char **argv, int *argcp, char *optstr)
406 while (isspace((unsigned char) *optstr))
410 argv[(*argcp)++] = optstr;
411 while (*optstr && !isspace((unsigned char) *optstr))
420 * Early initialization of a backend (either standalone or under postmaster).
421 * This happens even before InitPostgres.
423 * If you're wondering why this is separate from InitPostgres at all:
424 * the critical distinction is that this stuff has to happen before we can
425 * run XLOG-related initialization, which is done before InitPostgres --- in
426 * fact, for cases such as the background writer process, InitPostgres may
427 * never be done at all.
433 * Attach to shared memory and semaphores, and initialize our
434 * input/output/debugging file descriptors.
439 /* Do local initialization of file, storage and buffer managers */
442 InitBufferPoolAccess();
446 /* --------------------------------
448 * Initialize POSTGRES.
450 * The database can be specified by name, using the in_dbname parameter, or by
451 * OID, using the dboid parameter. In the latter case, the actual database
452 * name can be returned to the caller in out_dbname. If out_dbname isn't
453 * NULL, it must point to a buffer of size NAMEDATALEN.
455 * In bootstrap mode no parameters are used. The autovacuum launcher process
456 * doesn't use any parameters either, because it only goes far enough to be
457 * able to read pg_database; it doesn't connect to any particular database.
458 * In walsender mode only username is used.
460 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
461 * already have a PGPROC struct ... but it's not completely filled in yet.
464 * Be very careful with the order of calls in the InitPostgres function.
465 * --------------------------------
468 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
471 bool bootstrap = IsBootstrapProcessingMode();
475 char dbname[NAMEDATALEN];
477 elog(DEBUG3, "InitPostgres");
480 * Add my PGPROC struct to the ProcArray.
482 * Once I have done this, I am visible to other backends!
487 * Initialize my entry in the shared-invalidation manager's array of
490 * Sets up MyBackendId, a unique backend identifier.
492 MyBackendId = InvalidBackendId;
494 SharedInvalBackendInit(false);
496 if (MyBackendId > MaxBackends || MyBackendId <= 0)
497 elog(FATAL, "bad backend id: %d", MyBackendId);
499 /* Now that we have a BackendId, we can participate in ProcSignal */
500 ProcSignalInit(MyBackendId);
503 * bufmgr needs another initialization call too
505 InitBufferPoolBackend();
508 * Initialize local process's access to XLOG, if appropriate. In
509 * bootstrap case we skip this since StartupXLOG() was run instead.
512 (void) RecoveryInProgress();
515 * Initialize the relation cache and the system catalog caches. Note that
516 * no catalog access happens here; we only set up the hashtable structure.
517 * We must do this before starting a transaction because transaction abort
518 * would try to touch these hashtables.
520 RelationCacheInitialize();
524 /* Initialize portal manager */
525 EnablePortalManager();
527 /* Initialize stats collection --- must happen before first xact */
532 * Load relcache entries for the shared system catalogs. This must create
533 * at least an entry for pg_database.
535 RelationCacheInitializePhase2();
538 * Set up process-exit callback to do pre-shutdown cleanup. This has to
539 * be after we've initialized all the low-level modules like the buffer
540 * manager, because during shutdown this has to run before the low-level
541 * modules start to close down. On the other hand, we want it in place
542 * before we begin our first transaction --- if we fail during the
543 * initialization transaction, as is entirely possible, we need the
544 * AbortTransaction call to clean up.
546 on_shmem_exit(ShutdownPostgres, 0);
548 /* The autovacuum launcher is done here */
549 if (IsAutoVacuumLauncherProcess())
553 * Start a new transaction here before first access to db, and get a
554 * snapshot. We don't have a use for the snapshot itself, but we're
555 * interested in the secondary effect that it sets RecentGlobalXmin. (This
556 * is critical for anything that reads heap pages, because HOT may decide
557 * to prune them even if the process doesn't attempt to modify any
562 StartTransactionCommand();
563 (void) GetTransactionSnapshot();
567 * Set up the global variables holding database id and default tablespace.
568 * But note we won't actually try to touch the database just yet.
570 * We take a shortcut in the bootstrap and walsender case, otherwise we
571 * have to look up the db's entry in pg_database.
573 if (bootstrap || am_walsender)
575 MyDatabaseId = TemplateDbOid;
576 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
578 else if (in_dbname != NULL)
581 Form_pg_database dbform;
583 tuple = GetDatabaseTuple(in_dbname);
584 if (!HeapTupleIsValid(tuple))
586 (errcode(ERRCODE_UNDEFINED_DATABASE),
587 errmsg("database \"%s\" does not exist", in_dbname)));
588 dbform = (Form_pg_database) GETSTRUCT(tuple);
589 MyDatabaseId = HeapTupleGetOid(tuple);
590 MyDatabaseTableSpace = dbform->dattablespace;
591 /* take database name from the caller, just for paranoia */
592 strlcpy(dbname, in_dbname, sizeof(dbname));
596 /* caller specified database by OID */
598 Form_pg_database dbform;
600 tuple = GetDatabaseTupleByOid(dboid);
601 if (!HeapTupleIsValid(tuple))
603 (errcode(ERRCODE_UNDEFINED_DATABASE),
604 errmsg("database %u does not exist", dboid)));
605 dbform = (Form_pg_database) GETSTRUCT(tuple);
606 MyDatabaseId = HeapTupleGetOid(tuple);
607 MyDatabaseTableSpace = dbform->dattablespace;
608 Assert(MyDatabaseId == dboid);
609 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
610 /* pass the database name back to the caller */
612 strcpy(out_dbname, dbname);
615 /* Now we can mark our PGPROC entry with the database ID */
616 /* (We assume this is an atomic store so no lock is needed) */
617 MyProc->databaseId = MyDatabaseId;
620 * Now, take a writer's lock on the database we are trying to connect to.
621 * If there is a concurrently running DROP DATABASE on that database, this
622 * will block us until it finishes (and has committed its update of
625 * Note that the lock is not held long, only until the end of this startup
626 * transaction. This is OK since we are already advertising our use of
627 * the database in the PGPROC array; anyone trying a DROP DATABASE after
628 * this point will see us there.
630 * Note: use of RowExclusiveLock here is reasonable because we envision
631 * our session as being a concurrent writer of the database. If we had a
632 * way of declaring a session as being guaranteed-read-only, we could use
633 * AccessShareLock for such sessions and thereby not conflict against
636 if (!bootstrap && !am_walsender)
637 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
641 * Recheck pg_database to make sure the target database hasn't gone away.
642 * If there was a concurrent DROP DATABASE, this ensures we will die
643 * cleanly without creating a mess.
645 if (!bootstrap && !am_walsender)
649 tuple = GetDatabaseTuple(dbname);
650 if (!HeapTupleIsValid(tuple) ||
651 MyDatabaseId != HeapTupleGetOid(tuple) ||
652 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
654 (errcode(ERRCODE_UNDEFINED_DATABASE),
655 errmsg("database \"%s\" does not exist", dbname),
656 errdetail("It seems to have just been dropped or renamed.")));
660 * Now we should be able to access the database directory safely. Verify
661 * it's there and looks reasonable.
663 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
665 if (!bootstrap && !am_walsender)
667 if (access(fullpath, F_OK) == -1)
671 (errcode(ERRCODE_UNDEFINED_DATABASE),
672 errmsg("database \"%s\" does not exist",
674 errdetail("The database subdirectory \"%s\" is missing.",
678 (errcode_for_file_access(),
679 errmsg("could not access directory \"%s\": %m",
683 ValidatePgVersion(fullpath);
686 SetDatabasePath(fullpath);
689 * It's now possible to do real access to the system catalogs.
691 * Load relcache entries for the system catalogs. This must create at
692 * least the minimum set of "nailed-in" cache entries.
694 RelationCacheInitializePhase3();
697 * Perform client authentication if necessary, then figure out our
698 * postgres user ID, and see if we are a superuser.
700 * In standalone mode and in autovacuum worker processes, we use a fixed
701 * ID, otherwise we figure it out from the authenticated user name.
703 if (bootstrap || IsAutoVacuumWorkerProcess())
705 InitializeSessionUserIdStandalone();
708 else if (!IsUnderPostmaster)
710 InitializeSessionUserIdStandalone();
712 if (!ThereIsAtLeastOneRole())
714 (errcode(ERRCODE_UNDEFINED_OBJECT),
715 errmsg("no roles are defined in this database system"),
716 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
721 /* normal multiuser case */
722 Assert(MyProcPort != NULL);
723 PerformAuthentication(MyProcPort);
724 InitializeSessionUserId(username);
725 am_superuser = superuser();
728 /* set up ACL framework (so CheckMyDatabase can check permissions) */
731 /* Process pg_db_role_setting options */
732 process_settings(MyDatabaseId, GetSessionUserId());
735 * Re-read the pg_database row for our database, check permissions and set
736 * up database-specific GUC settings. We can't do this until all the
737 * database-access infrastructure is up. (Also, it wants to know if the
738 * user is a superuser, so the above stuff has to happen first.)
740 if (!bootstrap && !am_walsender)
741 CheckMyDatabase(dbname, am_superuser);
744 * If we're trying to shut down, only superusers can connect.
747 MyProcPort != NULL &&
748 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
750 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
751 errmsg("must be superuser to connect during database shutdown")));
754 * Check a normal user hasn't connected to a superuser reserved slot.
757 ReservedBackends > 0 &&
758 !HaveNFreeProcs(ReservedBackends))
760 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
761 errmsg("connection limit exceeded for non-superusers")));
764 * Now process any command-line switches that were included in the startup
765 * packet, if we are in a regular backend. We couldn't do this before
766 * because we didn't know if client is a superuser.
768 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
770 if (MyProcPort != NULL &&
771 MyProcPort->cmdline_options != NULL)
774 * The maximum possible number of commandline arguments that could
775 * come from MyProcPort->cmdline_options is (strlen + 1) / 2; see
782 maxac = 2 + (strlen(MyProcPort->cmdline_options) + 1) / 2;
784 av = (char **) palloc(maxac * sizeof(char *));
787 av[ac++] = "postgres";
789 /* Note this mangles MyProcPort->cmdline_options */
790 pg_split_opts(av, &ac, MyProcPort->cmdline_options);
796 (void) process_postgres_switches(ac, av, gucctx);
800 * Process any additional GUC variable settings passed in startup packet.
801 * These are handled exactly like command-line variables.
803 if (MyProcPort != NULL)
805 ListCell *gucopts = list_head(MyProcPort->guc_options);
812 name = lfirst(gucopts);
813 gucopts = lnext(gucopts);
815 value = lfirst(gucopts);
816 gucopts = lnext(gucopts);
818 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
822 /* Apply PostAuthDelay as soon as we've read all options */
823 if (PostAuthDelay > 0)
824 pg_usleep(PostAuthDelay * 1000000L);
827 * Initialize various default states that can't be set up until we've
828 * selected the active user and gotten the right GUC settings.
831 /* set default namespace search path */
832 InitializeSearchPath();
834 /* initialize client encoding */
835 InitializeClientEncoding();
837 /* reset the database for walsender */
839 MyProc->databaseId = MyDatabaseId = InvalidOid;
841 /* report this backend in the PgBackendStatus array */
845 /* close the transaction we started above */
847 CommitTransactionCommand();
851 * Load GUC settings from pg_db_role_setting.
853 * We try specific settings for the database/role combination, as well as
854 * general for this database and for this user.
857 process_settings(Oid databaseid, Oid roleid)
861 if (!IsUnderPostmaster)
864 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
866 /* Later settings are ignored if set earlier. */
867 ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
868 ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
869 ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
871 heap_close(relsetting, AccessShareLock);
875 * Backend-shutdown callback. Do cleanup that we want to be sure happens
876 * before all the supporting modules begin to nail their doors shut via
877 * their own callbacks.
879 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
880 * via separate callbacks that execute before this one. We don't combine the
881 * callbacks because we still want this one to happen if the user-level
885 ShutdownPostgres(int code, Datum arg)
887 /* Make sure we've killed any active transaction */
888 AbortOutOfAnyTransaction();
891 * User locks are not released by transaction end, so be sure to release
894 LockReleaseAll(USER_LOCKMETHOD, true);
899 * Returns true if at least one role is defined in this database cluster.
902 ThereIsAtLeastOneRole(void)
904 Relation pg_authid_rel;
908 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
910 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
911 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
914 heap_close(pg_authid_rel, AccessShareLock);