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.214 2010/09/13 09:00:30 heikki 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_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");
222 * Log connection for streaming replication even if Log_connections
227 if (port->remote_port[0])
229 (errmsg("replication connection authorized: user=%s host=%s port=%s",
232 port->remote_port)));
235 (errmsg("replication connection authorized: user=%s host=%s",
237 port->remote_host)));
239 else if (Log_connections)
241 (errmsg("connection authorized: user=%s database=%s",
242 port->user_name, port->database_name)));
244 set_ps_display("startup", false);
246 ClientAuthInProgress = false; /* client_min_messages is active now */
251 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
254 CheckMyDatabase(const char *name, bool am_superuser)
257 Form_pg_database dbform;
261 /* Fetch our pg_database row normally, via syscache */
262 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
263 if (!HeapTupleIsValid(tup))
264 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
265 dbform = (Form_pg_database) GETSTRUCT(tup);
267 /* This recheck is strictly paranoia */
268 if (strcmp(name, NameStr(dbform->datname)) != 0)
270 (errcode(ERRCODE_UNDEFINED_DATABASE),
271 errmsg("database \"%s\" has disappeared from pg_database",
273 errdetail("Database OID %u now seems to belong to \"%s\".",
274 MyDatabaseId, NameStr(dbform->datname))));
277 * Check permissions to connect to the database.
279 * These checks are not enforced when in standalone mode, so that there is
280 * a way to recover from disabling all access to all databases, for
281 * example "UPDATE pg_database SET datallowconn = false;".
283 * We do not enforce them for autovacuum worker processes either.
285 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
288 * Check that the database is currently allowing connections.
290 if (!dbform->datallowconn)
292 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
293 errmsg("database \"%s\" is not currently accepting connections",
297 * Check privilege to connect to the database. (The am_superuser test
298 * is redundant, but since we have the flag, might as well check it
299 * and save a few cycles.)
302 pg_database_aclcheck(MyDatabaseId, GetUserId(),
303 ACL_CONNECT) != ACLCHECK_OK)
305 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
306 errmsg("permission denied for database \"%s\"", name),
307 errdetail("User does not have CONNECT privilege.")));
310 * Check connection limit for this database.
312 * There is a race condition here --- we create our PGPROC before
313 * checking for other PGPROCs. If two backends did this at about the
314 * same time, they might both think they were over the limit, while
315 * ideally one should succeed and one fail. Getting that to work
316 * exactly seems more trouble than it is worth, however; instead we
317 * just document that the connection limit is approximate.
319 if (dbform->datconnlimit >= 0 &&
321 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
323 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
324 errmsg("too many connections for database \"%s\"",
329 * OK, we're golden. Next to-do item is to save the encoding info out of
330 * the pg_database tuple.
332 SetDatabaseEncoding(dbform->encoding);
333 /* Record it as a GUC internal option, too */
334 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
335 PGC_INTERNAL, PGC_S_OVERRIDE);
336 /* If we have no other source of client_encoding, use server encoding */
337 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
338 PGC_BACKEND, PGC_S_DEFAULT);
340 /* assign locale variables */
341 collate = NameStr(dbform->datcollate);
342 ctype = NameStr(dbform->datctype);
344 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
346 (errmsg("database locale is incompatible with operating system"),
347 errdetail("The database was initialized with LC_COLLATE \"%s\", "
348 " which is not recognized by setlocale().", collate),
349 errhint("Recreate the database with another locale or install the missing locale.")));
351 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
353 (errmsg("database locale is incompatible with operating system"),
354 errdetail("The database was initialized with LC_CTYPE \"%s\", "
355 " which is not recognized by setlocale().", ctype),
356 errhint("Recreate the database with another locale or install the missing locale.")));
358 /* Make the locale settings visible as GUC variables, too */
359 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
360 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
362 /* Use the right encoding in translated messages */
364 pg_bind_textdomain_codeset(textdomain(NULL));
367 ReleaseSysCache(tup);
372 /* --------------------------------
375 * This routine initializes stuff needed for ipc, locking, etc.
376 * it should be called something more informative.
377 * --------------------------------
380 InitCommunication(void)
383 * initialize shared memory and semaphores appropriately.
385 if (!IsUnderPostmaster) /* postmaster already did this */
388 * We're running a postgres bootstrap process or a standalone backend.
389 * Create private "shmem" and semaphores.
391 CreateSharedMemoryAndSemaphores(true, 0);
397 * pg_split_opts -- split a string of options and append it to an argv array
399 * NB: the input string is destructively modified! Also, caller is responsible
400 * for ensuring the argv array is large enough. The maximum possible number
401 * of arguments added by this routine is (strlen(optstr) + 1) / 2.
403 * Since no current POSTGRES arguments require any quoting characters,
404 * we can use the simple-minded tactic of assuming each set of space-
405 * delimited characters is a separate argv element.
407 * If you don't like that, well, we *used* to pass the whole option string
408 * as ONE argument to execl(), which was even less intelligent...
411 pg_split_opts(char **argv, int *argcp, char *optstr)
415 while (isspace((unsigned char) *optstr))
419 argv[(*argcp)++] = optstr;
420 while (*optstr && !isspace((unsigned char) *optstr))
429 * Early initialization of a backend (either standalone or under postmaster).
430 * This happens even before InitPostgres.
432 * This is separate from InitPostgres because it is also called by auxiliary
433 * processes, such as the background writer process, which may not call
434 * InitPostgres at all.
440 * Attach to shared memory and semaphores, and initialize our
441 * input/output/debugging file descriptors.
446 /* Do local initialization of file, storage and buffer managers */
449 InitBufferPoolAccess();
453 /* --------------------------------
455 * Initialize POSTGRES.
457 * The database can be specified by name, using the in_dbname parameter, or by
458 * OID, using the dboid parameter. In the latter case, the actual database
459 * name can be returned to the caller in out_dbname. If out_dbname isn't
460 * NULL, it must point to a buffer of size NAMEDATALEN.
462 * In bootstrap mode no parameters are used. The autovacuum launcher process
463 * doesn't use any parameters either, because it only goes far enough to be
464 * able to read pg_database; it doesn't connect to any particular database.
465 * In walsender mode only username is used.
467 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
468 * already have a PGPROC struct ... but it's not completely filled in yet.
471 * Be very careful with the order of calls in the InitPostgres function.
472 * --------------------------------
475 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
478 bool bootstrap = IsBootstrapProcessingMode();
481 char dbname[NAMEDATALEN];
483 elog(DEBUG3, "InitPostgres");
486 * Add my PGPROC struct to the ProcArray.
488 * Once I have done this, I am visible to other backends!
493 * Initialize my entry in the shared-invalidation manager's array of
496 * Sets up MyBackendId, a unique backend identifier.
498 MyBackendId = InvalidBackendId;
500 SharedInvalBackendInit(false);
502 if (MyBackendId > MaxBackends || MyBackendId <= 0)
503 elog(FATAL, "bad backend id: %d", MyBackendId);
505 /* Now that we have a BackendId, we can participate in ProcSignal */
506 ProcSignalInit(MyBackendId);
509 * bufmgr needs another initialization call too
511 InitBufferPoolBackend();
514 * Initialize local process's access to XLOG.
516 if (IsUnderPostmaster)
519 * The postmaster already started the XLOG machinery, but we need to
520 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
521 * This is handled by calling RecoveryInProgress and ignoring the
524 (void) RecoveryInProgress();
529 * We are either a bootstrap process or a standalone backend. Either
530 * way, start up the XLOG machinery, and register to have it closed
534 on_shmem_exit(ShutdownXLOG, 0);
538 * Initialize the relation cache and the system catalog caches. Note that
539 * no catalog access happens here; we only set up the hashtable structure.
540 * We must do this before starting a transaction because transaction abort
541 * would try to touch these hashtables.
543 RelationCacheInitialize();
547 /* Initialize portal manager */
548 EnablePortalManager();
550 /* Initialize stats collection --- must happen before first xact */
555 * Load relcache entries for the shared system catalogs. This must create
556 * at least entries for pg_database and catalogs used for authentication.
558 RelationCacheInitializePhase2();
561 * Set up process-exit callback to do pre-shutdown cleanup. This has to
562 * be after we've initialized all the low-level modules like the buffer
563 * manager, because during shutdown this has to run before the low-level
564 * modules start to close down. On the other hand, we want it in place
565 * before we begin our first transaction --- if we fail during the
566 * initialization transaction, as is entirely possible, we need the
567 * AbortTransaction call to clean up.
569 on_shmem_exit(ShutdownPostgres, 0);
571 /* The autovacuum launcher is done here */
572 if (IsAutoVacuumLauncherProcess())
576 * Start a new transaction here before first access to db, and get a
577 * snapshot. We don't have a use for the snapshot itself, but we're
578 * interested in the secondary effect that it sets RecentGlobalXmin. (This
579 * is critical for anything that reads heap pages, because HOT may decide
580 * to prune them even if the process doesn't attempt to modify any
585 StartTransactionCommand();
586 (void) GetTransactionSnapshot();
590 * Perform client authentication if necessary, then figure out our
591 * postgres user ID, and see if we are a superuser.
593 * In standalone mode and in autovacuum worker processes, we use a fixed
594 * ID, otherwise we figure it out from the authenticated user name.
596 if (bootstrap || IsAutoVacuumWorkerProcess())
598 InitializeSessionUserIdStandalone();
601 else if (!IsUnderPostmaster)
603 InitializeSessionUserIdStandalone();
605 if (!ThereIsAtLeastOneRole())
607 (errcode(ERRCODE_UNDEFINED_OBJECT),
608 errmsg("no roles are defined in this database system"),
609 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
614 /* normal multiuser case */
615 Assert(MyProcPort != NULL);
616 PerformAuthentication(MyProcPort);
617 InitializeSessionUserId(username);
618 am_superuser = superuser();
622 * If we're trying to shut down, only superusers can connect, and new
623 * replication connections are not allowed.
625 if ((!am_superuser || am_walsender) &&
626 MyProcPort != NULL &&
627 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
631 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
632 errmsg("new replication connections are not allowed during database shutdown")));
635 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
636 errmsg("must be superuser to connect during database shutdown")));
640 * The last few connections slots are reserved for superusers. Although
641 * replication connections currently require superuser privileges, we
642 * don't allow them to consume the reserved slots, which are intended for
645 if ((!am_superuser || am_walsender) &&
646 ReservedBackends > 0 &&
647 !HaveNFreeProcs(ReservedBackends))
649 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
650 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
653 * If walsender, we don't want to connect to any particular database.
654 * Just finish the backend startup by processing any options from the
655 * startup packet, and we're done.
661 /* must have authenticated as a superuser */
664 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
665 errmsg("must be superuser to start walsender")));
667 /* process any options passed in the startup packet */
668 if (MyProcPort != NULL)
669 process_startup_options(MyProcPort, am_superuser);
671 /* Apply PostAuthDelay as soon as we've read all options */
672 if (PostAuthDelay > 0)
673 pg_usleep(PostAuthDelay * 1000000L);
675 /* initialize client encoding */
676 InitializeClientEncoding();
678 /* report this backend in the PgBackendStatus array */
681 /* close the transaction we started above */
682 CommitTransactionCommand();
688 * Set up the global variables holding database id and default tablespace.
689 * But note we won't actually try to touch the database just yet.
691 * We take a shortcut in the bootstrap case, otherwise we have to look up
692 * the db's entry in pg_database.
696 MyDatabaseId = TemplateDbOid;
697 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
699 else if (in_dbname != NULL)
702 Form_pg_database dbform;
704 tuple = GetDatabaseTuple(in_dbname);
705 if (!HeapTupleIsValid(tuple))
707 (errcode(ERRCODE_UNDEFINED_DATABASE),
708 errmsg("database \"%s\" does not exist", in_dbname)));
709 dbform = (Form_pg_database) GETSTRUCT(tuple);
710 MyDatabaseId = HeapTupleGetOid(tuple);
711 MyDatabaseTableSpace = dbform->dattablespace;
712 /* take database name from the caller, just for paranoia */
713 strlcpy(dbname, in_dbname, sizeof(dbname));
717 /* caller specified database by OID */
719 Form_pg_database dbform;
721 tuple = GetDatabaseTupleByOid(dboid);
722 if (!HeapTupleIsValid(tuple))
724 (errcode(ERRCODE_UNDEFINED_DATABASE),
725 errmsg("database %u does not exist", dboid)));
726 dbform = (Form_pg_database) GETSTRUCT(tuple);
727 MyDatabaseId = HeapTupleGetOid(tuple);
728 MyDatabaseTableSpace = dbform->dattablespace;
729 Assert(MyDatabaseId == dboid);
730 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
731 /* pass the database name back to the caller */
733 strcpy(out_dbname, dbname);
736 /* Now we can mark our PGPROC entry with the database ID */
737 /* (We assume this is an atomic store so no lock is needed) */
738 MyProc->databaseId = MyDatabaseId;
741 * Now, take a writer's lock on the database we are trying to connect to.
742 * If there is a concurrently running DROP DATABASE on that database, this
743 * will block us until it finishes (and has committed its update of
746 * Note that the lock is not held long, only until the end of this startup
747 * transaction. This is OK since we are already advertising our use of
748 * the database in the PGPROC array; anyone trying a DROP DATABASE after
749 * this point will see us there.
751 * Note: use of RowExclusiveLock here is reasonable because we envision
752 * our session as being a concurrent writer of the database. If we had a
753 * way of declaring a session as being guaranteed-read-only, we could use
754 * AccessShareLock for such sessions and thereby not conflict against
758 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
762 * Recheck pg_database to make sure the target database hasn't gone away.
763 * If there was a concurrent DROP DATABASE, this ensures we will die
764 * cleanly without creating a mess.
770 tuple = GetDatabaseTuple(dbname);
771 if (!HeapTupleIsValid(tuple) ||
772 MyDatabaseId != HeapTupleGetOid(tuple) ||
773 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
775 (errcode(ERRCODE_UNDEFINED_DATABASE),
776 errmsg("database \"%s\" does not exist", dbname),
777 errdetail("It seems to have just been dropped or renamed.")));
781 * Now we should be able to access the database directory safely. Verify
782 * it's there and looks reasonable.
784 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
788 if (access(fullpath, F_OK) == -1)
792 (errcode(ERRCODE_UNDEFINED_DATABASE),
793 errmsg("database \"%s\" does not exist",
795 errdetail("The database subdirectory \"%s\" is missing.",
799 (errcode_for_file_access(),
800 errmsg("could not access directory \"%s\": %m",
804 ValidatePgVersion(fullpath);
807 SetDatabasePath(fullpath);
810 * It's now possible to do real access to the system catalogs.
812 * Load relcache entries for the system catalogs. This must create at
813 * least the minimum set of "nailed-in" cache entries.
815 RelationCacheInitializePhase3();
817 /* set up ACL framework (so CheckMyDatabase can check permissions) */
821 * Re-read the pg_database row for our database, check permissions and set
822 * up database-specific GUC settings. We can't do this until all the
823 * database-access infrastructure is up. (Also, it wants to know if the
824 * user is a superuser, so the above stuff has to happen first.)
827 CheckMyDatabase(dbname, am_superuser);
830 * Now process any command-line switches and any additional GUC variable
831 * settings passed in the startup packet. We couldn't do this before
832 * because we didn't know if client is a superuser.
834 if (MyProcPort != NULL)
835 process_startup_options(MyProcPort, am_superuser);
837 /* Process pg_db_role_setting options */
838 process_settings(MyDatabaseId, GetSessionUserId());
840 /* Apply PostAuthDelay as soon as we've read all options */
841 if (PostAuthDelay > 0)
842 pg_usleep(PostAuthDelay * 1000000L);
845 * Initialize various default states that can't be set up until we've
846 * selected the active user and gotten the right GUC settings.
849 /* set default namespace search path */
850 InitializeSearchPath();
852 /* initialize client encoding */
853 InitializeClientEncoding();
855 /* report this backend in the PgBackendStatus array */
859 /* close the transaction we started above */
861 CommitTransactionCommand();
865 * Process any command-line switches and any additional GUC variable
866 * settings passed in the startup packet.
869 process_startup_options(Port *port, bool am_superuser)
874 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
877 * First process any command-line switches that were included in the
878 * startup packet, if we are in a regular backend.
880 if (port->cmdline_options != NULL)
883 * The maximum possible number of commandline arguments that could
884 * come from port->cmdline_options is (strlen + 1) / 2; see
891 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
893 av = (char **) palloc(maxac * sizeof(char *));
896 av[ac++] = "postgres";
898 /* Note this mangles port->cmdline_options */
899 pg_split_opts(av, &ac, port->cmdline_options);
905 (void) process_postgres_switches(ac, av, gucctx);
909 * Process any additional GUC variable settings passed in startup packet.
910 * These are handled exactly like command-line variables.
912 gucopts = list_head(port->guc_options);
918 name = lfirst(gucopts);
919 gucopts = lnext(gucopts);
921 value = lfirst(gucopts);
922 gucopts = lnext(gucopts);
924 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
929 * Load GUC settings from pg_db_role_setting.
931 * We try specific settings for the database/role combination, as well as
932 * general for this database and for this user.
935 process_settings(Oid databaseid, Oid roleid)
939 if (!IsUnderPostmaster)
942 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
944 /* Later settings are ignored if set earlier. */
945 ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
946 ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
947 ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
949 heap_close(relsetting, AccessShareLock);
953 * Backend-shutdown callback. Do cleanup that we want to be sure happens
954 * before all the supporting modules begin to nail their doors shut via
955 * their own callbacks.
957 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
958 * via separate callbacks that execute before this one. We don't combine the
959 * callbacks because we still want this one to happen if the user-level
963 ShutdownPostgres(int code, Datum arg)
965 /* Make sure we've killed any active transaction */
966 AbortOutOfAnyTransaction();
969 * User locks are not released by transaction end, so be sure to release
972 LockReleaseAll(USER_LOCKMETHOD, true);
977 * Returns true if at least one role is defined in this database cluster.
980 ThereIsAtLeastOneRole(void)
982 Relation pg_authid_rel;
986 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
988 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
989 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
992 heap_close(pg_authid_rel, AccessShareLock);