1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/init/postinit.c
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_startup_options(Port *port, bool am_superuser);
69 static void process_settings(Oid databaseid, Oid roleid);
72 /*** InitPostgres support ***/
76 * GetDatabaseTuple -- fetch the pg_database row for a database
78 * This is used during backend startup when we don't yet have any access to
79 * system catalogs in general. In the worst case, we can seqscan pg_database
80 * using nothing but the hard-wired descriptor that relcache.c creates for
81 * pg_database. In more typical cases, relcache.c was able to load
82 * descriptors for both pg_database and its indexes from the shared relcache
83 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
84 * tells whether we got the cached descriptors.
87 GetDatabaseTuple(const char *dbname)
98 Anum_pg_database_datname,
99 BTEqualStrategyNumber, F_NAMEEQ,
100 CStringGetDatum(dbname));
103 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
104 * built the critical shared relcache entries (i.e., we're starting up
105 * without a shared relcache cache file).
107 relation = heap_open(DatabaseRelationId, AccessShareLock);
108 scan = systable_beginscan(relation, DatabaseNameIndexId,
109 criticalSharedRelcachesBuilt,
113 tuple = systable_getnext(scan);
115 /* Must copy tuple before releasing buffer */
116 if (HeapTupleIsValid(tuple))
117 tuple = heap_copytuple(tuple);
120 systable_endscan(scan);
121 heap_close(relation, AccessShareLock);
127 * GetDatabaseTupleByOid -- as above, but search by database OID
130 GetDatabaseTupleByOid(Oid dboid)
141 ObjectIdAttributeNumber,
142 BTEqualStrategyNumber, F_OIDEQ,
143 ObjectIdGetDatum(dboid));
146 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
147 * built the critical shared relcache entries (i.e., we're starting up
148 * without a shared relcache cache file).
150 relation = heap_open(DatabaseRelationId, AccessShareLock);
151 scan = systable_beginscan(relation, DatabaseOidIndexId,
152 criticalSharedRelcachesBuilt,
156 tuple = systable_getnext(scan);
158 /* Must copy tuple before releasing buffer */
159 if (HeapTupleIsValid(tuple))
160 tuple = heap_copytuple(tuple);
163 systable_endscan(scan);
164 heap_close(relation, AccessShareLock);
171 * PerformAuthentication -- authenticate a remote client
173 * returns: nothing. Will not return at all if there's any failure.
176 PerformAuthentication(Port *port)
178 /* This should be set already, but let's make sure */
179 ClientAuthInProgress = true; /* limit visibility of log messages */
182 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
183 * etcetera from the postmaster, and have to load them ourselves. Note we
184 * are loading them into the startup transaction's memory context, not
185 * PostmasterContext, but that shouldn't matter.
187 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
193 * It makes no sense to continue if we fail to load the HBA file,
194 * since there is no way to connect to the database in this case.
197 (errmsg("could not load pg_hba.conf")));
203 * Set up a timeout in case a buggy or malicious client fails to respond
204 * during authentication. Since we're inside a transaction and might do
205 * database access, we have to use the statement_timeout infrastructure.
207 if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
208 elog(FATAL, "could not set timer for authorization timeout");
211 * Now perform authentication exchange.
213 ClientAuthentication(port); /* might not return, if failure */
216 * Done with authentication. Disable the timeout, and log if needed.
218 if (!disable_sig_alarm(true))
219 elog(FATAL, "could not disable timer for authorization timeout");
225 (errmsg("replication connection authorized: user=%s",
229 (errmsg("connection authorized: user=%s database=%s",
230 port->user_name, port->database_name)));
233 set_ps_display("startup", false);
235 ClientAuthInProgress = false; /* client_min_messages is active now */
240 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
243 CheckMyDatabase(const char *name, bool am_superuser)
246 Form_pg_database dbform;
250 /* Fetch our pg_database row normally, via syscache */
251 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
252 if (!HeapTupleIsValid(tup))
253 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
254 dbform = (Form_pg_database) GETSTRUCT(tup);
256 /* This recheck is strictly paranoia */
257 if (strcmp(name, NameStr(dbform->datname)) != 0)
259 (errcode(ERRCODE_UNDEFINED_DATABASE),
260 errmsg("database \"%s\" has disappeared from pg_database",
262 errdetail("Database OID %u now seems to belong to \"%s\".",
263 MyDatabaseId, NameStr(dbform->datname))));
266 * Check permissions to connect to the database.
268 * These checks are not enforced when in standalone mode, so that there is
269 * a way to recover from disabling all access to all databases, for
270 * example "UPDATE pg_database SET datallowconn = false;".
272 * We do not enforce them for autovacuum worker processes either.
274 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
277 * Check that the database is currently allowing connections.
279 if (!dbform->datallowconn)
281 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
282 errmsg("database \"%s\" is not currently accepting connections",
286 * Check privilege to connect to the database. (The am_superuser test
287 * is redundant, but since we have the flag, might as well check it
288 * and save a few cycles.)
291 pg_database_aclcheck(MyDatabaseId, GetUserId(),
292 ACL_CONNECT) != ACLCHECK_OK)
294 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
295 errmsg("permission denied for database \"%s\"", name),
296 errdetail("User does not have CONNECT privilege.")));
299 * Check connection limit for this database.
301 * There is a race condition here --- we create our PGPROC before
302 * checking for other PGPROCs. If two backends did this at about the
303 * same time, they might both think they were over the limit, while
304 * ideally one should succeed and one fail. Getting that to work
305 * exactly seems more trouble than it is worth, however; instead we
306 * just document that the connection limit is approximate.
308 if (dbform->datconnlimit >= 0 &&
310 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
312 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
313 errmsg("too many connections for database \"%s\"",
318 * OK, we're golden. Next to-do item is to save the encoding info out of
319 * the pg_database tuple.
321 SetDatabaseEncoding(dbform->encoding);
322 /* Record it as a GUC internal option, too */
323 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
324 PGC_INTERNAL, PGC_S_OVERRIDE);
325 /* If we have no other source of client_encoding, use server encoding */
326 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
327 PGC_BACKEND, PGC_S_DEFAULT);
329 /* assign locale variables */
330 collate = NameStr(dbform->datcollate);
331 ctype = NameStr(dbform->datctype);
333 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
335 (errmsg("database locale is incompatible with operating system"),
336 errdetail("The database was initialized with LC_COLLATE \"%s\", "
337 " which is not recognized by setlocale().", collate),
338 errhint("Recreate the database with another locale or install the missing locale.")));
340 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
342 (errmsg("database locale is incompatible with operating system"),
343 errdetail("The database was initialized with LC_CTYPE \"%s\", "
344 " which is not recognized by setlocale().", ctype),
345 errhint("Recreate the database with another locale or install the missing locale.")));
347 /* Make the locale settings visible as GUC variables, too */
348 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
349 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
351 /* Use the right encoding in translated messages */
353 pg_bind_textdomain_codeset(textdomain(NULL));
356 ReleaseSysCache(tup);
361 /* --------------------------------
364 * This routine initializes stuff needed for ipc, locking, etc.
365 * it should be called something more informative.
366 * --------------------------------
369 InitCommunication(void)
372 * initialize shared memory and semaphores appropriately.
374 if (!IsUnderPostmaster) /* postmaster already did this */
377 * We're running a postgres bootstrap process or a standalone backend.
378 * Create private "shmem" and semaphores.
380 CreateSharedMemoryAndSemaphores(true, 0);
386 * pg_split_opts -- split a string of options and append it to an argv array
388 * NB: the input string is destructively modified! Also, caller is responsible
389 * for ensuring the argv array is large enough. The maximum possible number
390 * of arguments added by this routine is (strlen(optstr) + 1) / 2.
392 * Since no current POSTGRES arguments require any quoting characters,
393 * we can use the simple-minded tactic of assuming each set of space-
394 * delimited characters is a separate argv element.
396 * If you don't like that, well, we *used* to pass the whole option string
397 * as ONE argument to execl(), which was even less intelligent...
400 pg_split_opts(char **argv, int *argcp, char *optstr)
404 while (isspace((unsigned char) *optstr))
408 argv[(*argcp)++] = optstr;
409 while (*optstr && !isspace((unsigned char) *optstr))
418 * Early initialization of a backend (either standalone or under postmaster).
419 * This happens even before InitPostgres.
421 * This is separate from InitPostgres because it is also called by auxiliary
422 * processes, such as the background writer process, which may not call
423 * InitPostgres at all.
429 * Attach to shared memory and semaphores, and initialize our
430 * input/output/debugging file descriptors.
435 /* Do local initialization of file, storage and buffer managers */
438 InitBufferPoolAccess();
442 /* --------------------------------
444 * Initialize POSTGRES.
446 * The database can be specified by name, using the in_dbname parameter, or by
447 * OID, using the dboid parameter. In the latter case, the actual database
448 * name can be returned to the caller in out_dbname. If out_dbname isn't
449 * NULL, it must point to a buffer of size NAMEDATALEN.
451 * In bootstrap mode no parameters are used. The autovacuum launcher process
452 * doesn't use any parameters either, because it only goes far enough to be
453 * able to read pg_database; it doesn't connect to any particular database.
454 * In walsender mode only username is used.
456 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
457 * already have a PGPROC struct ... but it's not completely filled in yet.
460 * Be very careful with the order of calls in the InitPostgres function.
461 * --------------------------------
464 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
467 bool bootstrap = IsBootstrapProcessingMode();
470 char dbname[NAMEDATALEN];
472 elog(DEBUG3, "InitPostgres");
475 * Add my PGPROC struct to the ProcArray.
477 * Once I have done this, I am visible to other backends!
482 * Initialize my entry in the shared-invalidation manager's array of
485 * Sets up MyBackendId, a unique backend identifier.
487 MyBackendId = InvalidBackendId;
489 SharedInvalBackendInit(false);
491 if (MyBackendId > MaxBackends || MyBackendId <= 0)
492 elog(FATAL, "bad backend id: %d", MyBackendId);
494 /* Now that we have a BackendId, we can participate in ProcSignal */
495 ProcSignalInit(MyBackendId);
498 * bufmgr needs another initialization call too
500 InitBufferPoolBackend();
503 * Initialize local process's access to XLOG.
505 if (IsUnderPostmaster)
508 * The postmaster already started the XLOG machinery, but we need to
509 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
510 * This is handled by calling RecoveryInProgress and ignoring the
513 (void) RecoveryInProgress();
518 * We are either a bootstrap process or a standalone backend. Either
519 * way, start up the XLOG machinery, and register to have it closed
523 on_shmem_exit(ShutdownXLOG, 0);
527 * Initialize the relation cache and the system catalog caches. Note that
528 * no catalog access happens here; we only set up the hashtable structure.
529 * We must do this before starting a transaction because transaction abort
530 * would try to touch these hashtables.
532 RelationCacheInitialize();
536 /* Initialize portal manager */
537 EnablePortalManager();
539 /* Initialize stats collection --- must happen before first xact */
544 * Load relcache entries for the shared system catalogs. This must create
545 * at least entries for pg_database and catalogs used for authentication.
547 RelationCacheInitializePhase2();
550 * Set up process-exit callback to do pre-shutdown cleanup. This has to
551 * be after we've initialized all the low-level modules like the buffer
552 * manager, because during shutdown this has to run before the low-level
553 * modules start to close down. On the other hand, we want it in place
554 * before we begin our first transaction --- if we fail during the
555 * initialization transaction, as is entirely possible, we need the
556 * AbortTransaction call to clean up.
558 on_shmem_exit(ShutdownPostgres, 0);
560 /* The autovacuum launcher is done here */
561 if (IsAutoVacuumLauncherProcess())
565 * Start a new transaction here before first access to db, and get a
566 * snapshot. We don't have a use for the snapshot itself, but we're
567 * interested in the secondary effect that it sets RecentGlobalXmin. (This
568 * is critical for anything that reads heap pages, because HOT may decide
569 * to prune them even if the process doesn't attempt to modify any
574 StartTransactionCommand();
575 (void) GetTransactionSnapshot();
579 * Perform client authentication if necessary, then figure out our
580 * postgres user ID, and see if we are a superuser.
582 * In standalone mode and in autovacuum worker processes, we use a fixed
583 * ID, otherwise we figure it out from the authenticated user name.
585 if (bootstrap || IsAutoVacuumWorkerProcess())
587 InitializeSessionUserIdStandalone();
590 else if (!IsUnderPostmaster)
592 InitializeSessionUserIdStandalone();
594 if (!ThereIsAtLeastOneRole())
596 (errcode(ERRCODE_UNDEFINED_OBJECT),
597 errmsg("no roles are defined in this database system"),
598 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
603 /* normal multiuser case */
604 Assert(MyProcPort != NULL);
605 PerformAuthentication(MyProcPort);
606 InitializeSessionUserId(username);
607 am_superuser = superuser();
611 * If we're trying to shut down, only superusers can connect, and new
612 * replication connections are not allowed.
614 if ((!am_superuser || am_walsender) &&
615 MyProcPort != NULL &&
616 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
620 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
621 errmsg("new replication connections are not allowed during database shutdown")));
624 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
625 errmsg("must be superuser to connect during database shutdown")));
629 * Binary upgrades only allowed super-user connections
631 if (IsBinaryUpgrade && !am_superuser)
634 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
635 errmsg("must be superuser to connect in binary upgrade mode")));
639 * The last few connections slots are reserved for superusers. Although
640 * replication connections currently require superuser privileges, we
641 * don't allow them to consume the reserved slots, which are intended for
644 if ((!am_superuser || am_walsender) &&
645 ReservedBackends > 0 &&
646 !HaveNFreeProcs(ReservedBackends))
648 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
649 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
652 * If walsender, we don't want to connect to any particular database. Just
653 * finish the backend startup by processing any options from the startup
654 * packet, and we're done.
660 /* must have authenticated as a replication role */
661 if (!is_authenticated_user_replication_role())
663 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
664 errmsg("must be replication role to start walsender")));
666 /* process any options passed in the startup packet */
667 if (MyProcPort != NULL)
668 process_startup_options(MyProcPort, am_superuser);
670 /* Apply PostAuthDelay as soon as we've read all options */
671 if (PostAuthDelay > 0)
672 pg_usleep(PostAuthDelay * 1000000L);
674 /* initialize client encoding */
675 InitializeClientEncoding();
677 /* report this backend in the PgBackendStatus array */
680 /* close the transaction we started above */
681 CommitTransactionCommand();
687 * Set up the global variables holding database id and default tablespace.
688 * But note we won't actually try to touch the database just yet.
690 * We take a shortcut in the bootstrap case, otherwise we have to look up
691 * the db's entry in pg_database.
695 MyDatabaseId = TemplateDbOid;
696 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
698 else if (in_dbname != NULL)
701 Form_pg_database dbform;
703 tuple = GetDatabaseTuple(in_dbname);
704 if (!HeapTupleIsValid(tuple))
706 (errcode(ERRCODE_UNDEFINED_DATABASE),
707 errmsg("database \"%s\" does not exist", in_dbname)));
708 dbform = (Form_pg_database) GETSTRUCT(tuple);
709 MyDatabaseId = HeapTupleGetOid(tuple);
710 MyDatabaseTableSpace = dbform->dattablespace;
711 /* take database name from the caller, just for paranoia */
712 strlcpy(dbname, in_dbname, sizeof(dbname));
716 /* caller specified database by OID */
718 Form_pg_database dbform;
720 tuple = GetDatabaseTupleByOid(dboid);
721 if (!HeapTupleIsValid(tuple))
723 (errcode(ERRCODE_UNDEFINED_DATABASE),
724 errmsg("database %u does not exist", dboid)));
725 dbform = (Form_pg_database) GETSTRUCT(tuple);
726 MyDatabaseId = HeapTupleGetOid(tuple);
727 MyDatabaseTableSpace = dbform->dattablespace;
728 Assert(MyDatabaseId == dboid);
729 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
730 /* pass the database name back to the caller */
732 strcpy(out_dbname, dbname);
735 /* Now we can mark our PGPROC entry with the database ID */
736 /* (We assume this is an atomic store so no lock is needed) */
737 MyProc->databaseId = MyDatabaseId;
740 * Now, take a writer's lock on the database we are trying to connect to.
741 * If there is a concurrently running DROP DATABASE on that database, this
742 * will block us until it finishes (and has committed its update of
745 * Note that the lock is not held long, only until the end of this startup
746 * transaction. This is OK since we are already advertising our use of
747 * the database in the PGPROC array; anyone trying a DROP DATABASE after
748 * this point will see us there.
750 * Note: use of RowExclusiveLock here is reasonable because we envision
751 * our session as being a concurrent writer of the database. If we had a
752 * way of declaring a session as being guaranteed-read-only, we could use
753 * AccessShareLock for such sessions and thereby not conflict against
757 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
761 * Recheck pg_database to make sure the target database hasn't gone away.
762 * If there was a concurrent DROP DATABASE, this ensures we will die
763 * cleanly without creating a mess.
769 tuple = GetDatabaseTuple(dbname);
770 if (!HeapTupleIsValid(tuple) ||
771 MyDatabaseId != HeapTupleGetOid(tuple) ||
772 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
774 (errcode(ERRCODE_UNDEFINED_DATABASE),
775 errmsg("database \"%s\" does not exist", dbname),
776 errdetail("It seems to have just been dropped or renamed.")));
780 * Now we should be able to access the database directory safely. Verify
781 * it's there and looks reasonable.
783 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
787 if (access(fullpath, F_OK) == -1)
791 (errcode(ERRCODE_UNDEFINED_DATABASE),
792 errmsg("database \"%s\" does not exist",
794 errdetail("The database subdirectory \"%s\" is missing.",
798 (errcode_for_file_access(),
799 errmsg("could not access directory \"%s\": %m",
803 ValidatePgVersion(fullpath);
806 SetDatabasePath(fullpath);
809 * It's now possible to do real access to the system catalogs.
811 * Load relcache entries for the system catalogs. This must create at
812 * least the minimum set of "nailed-in" cache entries.
814 RelationCacheInitializePhase3();
816 /* set up ACL framework (so CheckMyDatabase can check permissions) */
820 * Re-read the pg_database row for our database, check permissions and set
821 * up database-specific GUC settings. We can't do this until all the
822 * database-access infrastructure is up. (Also, it wants to know if the
823 * user is a superuser, so the above stuff has to happen first.)
826 CheckMyDatabase(dbname, am_superuser);
829 * Now process any command-line switches and any additional GUC variable
830 * settings passed in the startup packet. We couldn't do this before
831 * because we didn't know if client is a superuser.
833 if (MyProcPort != NULL)
834 process_startup_options(MyProcPort, am_superuser);
836 /* Process pg_db_role_setting options */
837 process_settings(MyDatabaseId, GetSessionUserId());
839 /* Apply PostAuthDelay as soon as we've read all options */
840 if (PostAuthDelay > 0)
841 pg_usleep(PostAuthDelay * 1000000L);
844 * Initialize various default states that can't be set up until we've
845 * selected the active user and gotten the right GUC settings.
848 /* set default namespace search path */
849 InitializeSearchPath();
851 /* initialize client encoding */
852 InitializeClientEncoding();
854 /* report this backend in the PgBackendStatus array */
858 /* close the transaction we started above */
860 CommitTransactionCommand();
864 * Process any command-line switches and any additional GUC variable
865 * settings passed in the startup packet.
868 process_startup_options(Port *port, bool am_superuser)
873 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
876 * First process any command-line switches that were included in the
877 * startup packet, if we are in a regular backend.
879 if (port->cmdline_options != NULL)
882 * The maximum possible number of commandline arguments that could
883 * come from port->cmdline_options is (strlen + 1) / 2; see
890 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
892 av = (char **) palloc(maxac * sizeof(char *));
895 av[ac++] = "postgres";
897 /* Note this mangles port->cmdline_options */
898 pg_split_opts(av, &ac, port->cmdline_options);
904 (void) process_postgres_switches(ac, av, gucctx);
908 * Process any additional GUC variable settings passed in startup packet.
909 * These are handled exactly like command-line variables.
911 gucopts = list_head(port->guc_options);
917 name = lfirst(gucopts);
918 gucopts = lnext(gucopts);
920 value = lfirst(gucopts);
921 gucopts = lnext(gucopts);
923 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
928 * Load GUC settings from pg_db_role_setting.
930 * We try specific settings for the database/role combination, as well as
931 * general for this database and for this user.
934 process_settings(Oid databaseid, Oid roleid)
938 if (!IsUnderPostmaster)
941 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
943 /* Later settings are ignored if set earlier. */
944 ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
945 ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
946 ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
948 heap_close(relsetting, AccessShareLock);
952 * Backend-shutdown callback. Do cleanup that we want to be sure happens
953 * before all the supporting modules begin to nail their doors shut via
954 * their own callbacks.
956 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
957 * via separate callbacks that execute before this one. We don't combine the
958 * callbacks because we still want this one to happen if the user-level
962 ShutdownPostgres(int code, Datum arg)
964 /* Make sure we've killed any active transaction */
965 AbortOutOfAnyTransaction();
968 * User locks are not released by transaction end, so be sure to release
971 LockReleaseAll(USER_LOCKMETHOD, true);
976 * Returns true if at least one role is defined in this database cluster.
979 ThereIsAtLeastOneRole(void)
981 Relation pg_authid_rel;
985 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
987 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
988 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
991 heap_close(pg_authid_rel, AccessShareLock);