1 /*-------------------------------------------------------------------------
4 * Database management commands (create/drop database).
6 * Note: database creation/destruction commands use exclusive locks on
7 * the database objects (as expressed by LockSharedObject()) to avoid
8 * stepping on each others' toes. Formerly we used table-level locks
9 * on pg_database, but that's too coarse-grained.
11 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
16 * src/backend/commands/dbcommands.c
18 *-------------------------------------------------------------------------
27 #include "access/genam.h"
28 #include "access/heapam.h"
29 #include "access/htup_details.h"
30 #include "access/xact.h"
31 #include "access/xloginsert.h"
32 #include "access/xlogutils.h"
33 #include "catalog/catalog.h"
34 #include "catalog/dependency.h"
35 #include "catalog/indexing.h"
36 #include "catalog/objectaccess.h"
37 #include "catalog/pg_authid.h"
38 #include "catalog/pg_database.h"
39 #include "catalog/pg_db_role_setting.h"
40 #include "catalog/pg_tablespace.h"
41 #include "commands/comment.h"
42 #include "commands/dbcommands.h"
43 #include "commands/dbcommands_xlog.h"
44 #include "commands/defrem.h"
45 #include "commands/seclabel.h"
46 #include "commands/tablespace.h"
47 #include "mb/pg_wchar.h"
48 #include "miscadmin.h"
50 #include "postmaster/bgwriter.h"
51 #include "replication/slot.h"
52 #include "storage/copydir.h"
53 #include "storage/fd.h"
54 #include "storage/lmgr.h"
55 #include "storage/ipc.h"
56 #include "storage/procarray.h"
57 #include "storage/smgr.h"
58 #include "utils/acl.h"
59 #include "utils/builtins.h"
60 #include "utils/fmgroids.h"
61 #include "utils/pg_locale.h"
62 #include "utils/snapmgr.h"
63 #include "utils/syscache.h"
64 #include "utils/tqual.h"
69 Oid src_dboid; /* source (template) DB */
70 Oid dest_dboid; /* DB we are trying to create */
71 } createdb_failure_params;
75 Oid dest_dboid; /* DB we are trying to move */
76 Oid dest_tsoid; /* tablespace we are trying to move to */
77 } movedb_failure_params;
79 /* non-export function prototypes */
80 static void createdb_failure_callback(int code, Datum arg);
81 static void movedb(const char *dbname, const char *tblspcname);
82 static void movedb_failure_callback(int code, Datum arg);
83 static bool get_db_info(const char *name, LOCKMODE lockmode,
84 Oid *dbIdP, Oid *ownerIdP,
85 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
86 Oid *dbLastSysOidP, TransactionId *dbFrozenXidP,
87 MultiXactId *dbMinMultiP,
88 Oid *dbTablespace, char **dbCollate, char **dbCtype);
89 static bool have_createdb_privilege(void);
90 static void remove_dbtablespaces(Oid db_id);
91 static bool check_db_file_conflict(Oid db_id);
92 static int errdetail_busy_db(int notherbackends, int npreparedxacts);
99 createdb(ParseState *pstate, const CreatedbStmt *stmt)
111 TransactionId src_frozenxid;
112 MultiXactId src_minmxid;
113 Oid src_deftablespace;
114 volatile Oid dst_deftablespace;
115 Relation pg_database_rel;
117 Datum new_record[Natts_pg_database];
118 bool new_record_nulls[Natts_pg_database];
122 DefElem *dtablespacename = NULL;
123 DefElem *downer = NULL;
124 DefElem *dtemplate = NULL;
125 DefElem *dencoding = NULL;
126 DefElem *dcollate = NULL;
127 DefElem *dctype = NULL;
128 DefElem *distemplate = NULL;
129 DefElem *dallowconnections = NULL;
130 DefElem *dconnlimit = NULL;
131 char *dbname = stmt->dbname;
132 char *dbowner = NULL;
133 const char *dbtemplate = NULL;
134 char *dbcollate = NULL;
135 char *dbctype = NULL;
138 bool dbistemplate = false;
139 bool dballowconnections = true;
140 int dbconnlimit = -1;
143 createdb_failure_params fparms;
145 /* Extract options from the statement node tree */
146 foreach(option, stmt->options)
148 DefElem *defel = (DefElem *) lfirst(option);
150 if (strcmp(defel->defname, "tablespace") == 0)
154 (errcode(ERRCODE_SYNTAX_ERROR),
155 errmsg("conflicting or redundant options"),
156 parser_errposition(pstate, defel->location)));
157 dtablespacename = defel;
159 else if (strcmp(defel->defname, "owner") == 0)
163 (errcode(ERRCODE_SYNTAX_ERROR),
164 errmsg("conflicting or redundant options"),
165 parser_errposition(pstate, defel->location)));
168 else if (strcmp(defel->defname, "template") == 0)
172 (errcode(ERRCODE_SYNTAX_ERROR),
173 errmsg("conflicting or redundant options"),
174 parser_errposition(pstate, defel->location)));
177 else if (strcmp(defel->defname, "encoding") == 0)
181 (errcode(ERRCODE_SYNTAX_ERROR),
182 errmsg("conflicting or redundant options"),
183 parser_errposition(pstate, defel->location)));
186 else if (strcmp(defel->defname, "lc_collate") == 0)
190 (errcode(ERRCODE_SYNTAX_ERROR),
191 errmsg("conflicting or redundant options"),
192 parser_errposition(pstate, defel->location)));
195 else if (strcmp(defel->defname, "lc_ctype") == 0)
199 (errcode(ERRCODE_SYNTAX_ERROR),
200 errmsg("conflicting or redundant options"),
201 parser_errposition(pstate, defel->location)));
204 else if (strcmp(defel->defname, "is_template") == 0)
208 (errcode(ERRCODE_SYNTAX_ERROR),
209 errmsg("conflicting or redundant options"),
210 parser_errposition(pstate, defel->location)));
213 else if (strcmp(defel->defname, "allow_connections") == 0)
215 if (dallowconnections)
217 (errcode(ERRCODE_SYNTAX_ERROR),
218 errmsg("conflicting or redundant options"),
219 parser_errposition(pstate, defel->location)));
220 dallowconnections = defel;
222 else if (strcmp(defel->defname, "connection_limit") == 0)
226 (errcode(ERRCODE_SYNTAX_ERROR),
227 errmsg("conflicting or redundant options"),
228 parser_errposition(pstate, defel->location)));
231 else if (strcmp(defel->defname, "location") == 0)
234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
235 errmsg("LOCATION is not supported anymore"),
236 errhint("Consider using tablespaces instead."),
237 parser_errposition(pstate, defel->location)));
241 (errcode(ERRCODE_SYNTAX_ERROR),
242 errmsg("option \"%s\" not recognized", defel->defname),
243 parser_errposition(pstate, defel->location)));
246 if (downer && downer->arg)
247 dbowner = defGetString(downer);
248 if (dtemplate && dtemplate->arg)
249 dbtemplate = defGetString(dtemplate);
250 if (dencoding && dencoding->arg)
252 const char *encoding_name;
254 if (IsA(dencoding->arg, Integer))
256 encoding = defGetInt32(dencoding);
257 encoding_name = pg_encoding_to_char(encoding);
258 if (strcmp(encoding_name, "") == 0 ||
259 pg_valid_server_encoding(encoding_name) < 0)
261 (errcode(ERRCODE_UNDEFINED_OBJECT),
262 errmsg("%d is not a valid encoding code",
264 parser_errposition(pstate, dencoding->location)));
268 encoding_name = defGetString(dencoding);
269 encoding = pg_valid_server_encoding(encoding_name);
272 (errcode(ERRCODE_UNDEFINED_OBJECT),
273 errmsg("%s is not a valid encoding name",
275 parser_errposition(pstate, dencoding->location)));
278 if (dcollate && dcollate->arg)
279 dbcollate = defGetString(dcollate);
280 if (dctype && dctype->arg)
281 dbctype = defGetString(dctype);
282 if (distemplate && distemplate->arg)
283 dbistemplate = defGetBoolean(distemplate);
284 if (dallowconnections && dallowconnections->arg)
285 dballowconnections = defGetBoolean(dallowconnections);
286 if (dconnlimit && dconnlimit->arg)
288 dbconnlimit = defGetInt32(dconnlimit);
289 if (dbconnlimit < -1)
291 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
292 errmsg("invalid connection limit: %d", dbconnlimit)));
295 /* obtain OID of proposed owner */
297 datdba = get_role_oid(dbowner, false);
299 datdba = GetUserId();
302 * To create a database, must have createdb privilege and must be able to
303 * become the target role (this does not imply that the target role itself
304 * must have createdb privilege). The latter provision guards against
305 * "giveaway" attacks. Note that a superuser will always have both of
306 * these privileges a fortiori.
308 if (!have_createdb_privilege())
310 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
311 errmsg("permission denied to create database")));
313 check_is_member_of_role(GetUserId(), datdba);
316 * Lookup database (template) to be cloned, and obtain share lock on it.
317 * ShareLock allows two CREATE DATABASEs to work from the same template
318 * concurrently, while ensuring no one is busy dropping it in parallel
319 * (which would be Very Bad since we'd likely get an incomplete copy
320 * without knowing it). This also prevents any new connections from being
321 * made to the source until we finish copying it, so we can be sure it
322 * won't change underneath us.
325 dbtemplate = "template1"; /* Default template database name */
327 if (!get_db_info(dbtemplate, ShareLock,
328 &src_dboid, &src_owner, &src_encoding,
329 &src_istemplate, &src_allowconn, &src_lastsysoid,
330 &src_frozenxid, &src_minmxid, &src_deftablespace,
331 &src_collate, &src_ctype))
333 (errcode(ERRCODE_UNDEFINED_DATABASE),
334 errmsg("template database \"%s\" does not exist",
338 * Permission check: to copy a DB that's not marked datistemplate, you
339 * must be superuser or the owner thereof.
343 if (!pg_database_ownercheck(src_dboid, GetUserId()))
345 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
346 errmsg("permission denied to copy database \"%s\"",
350 /* If encoding or locales are defaulted, use source's setting */
352 encoding = src_encoding;
353 if (dbcollate == NULL)
354 dbcollate = src_collate;
358 /* Some encodings are client only */
359 if (!PG_VALID_BE_ENCODING(encoding))
361 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
362 errmsg("invalid server encoding %d", encoding)));
364 /* Check that the chosen locales are valid, and get canonical spellings */
365 if (!check_locale(LC_COLLATE, dbcollate, &canonname))
367 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
368 errmsg("invalid locale name: \"%s\"", dbcollate)));
369 dbcollate = canonname;
370 if (!check_locale(LC_CTYPE, dbctype, &canonname))
372 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
373 errmsg("invalid locale name: \"%s\"", dbctype)));
376 check_encoding_locale_matches(encoding, dbcollate, dbctype);
379 * Check that the new encoding and locale settings match the source
380 * database. We insist on this because we simply copy the source data ---
381 * any non-ASCII data would be wrongly encoded, and any indexes sorted
382 * according to the source locale would be wrong.
384 * However, we assume that template0 doesn't contain any non-ASCII data
385 * nor any indexes that depend on collation or ctype, so template0 can be
386 * used as template for creating a database with any encoding or locale.
388 if (strcmp(dbtemplate, "template0") != 0)
390 if (encoding != src_encoding)
392 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
393 errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
394 pg_encoding_to_char(encoding),
395 pg_encoding_to_char(src_encoding)),
396 errhint("Use the same encoding as in the template database, or use template0 as template.")));
398 if (strcmp(dbcollate, src_collate) != 0)
400 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
401 errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
402 dbcollate, src_collate),
403 errhint("Use the same collation as in the template database, or use template0 as template.")));
405 if (strcmp(dbctype, src_ctype) != 0)
407 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
408 errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
410 errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
413 /* Resolve default tablespace for new database */
414 if (dtablespacename && dtablespacename->arg)
416 char *tablespacename;
419 tablespacename = defGetString(dtablespacename);
420 dst_deftablespace = get_tablespace_oid(tablespacename, false);
421 /* check permissions */
422 aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
424 if (aclresult != ACLCHECK_OK)
425 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
428 /* pg_global must never be the default tablespace */
429 if (dst_deftablespace == GLOBALTABLESPACE_OID)
431 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
432 errmsg("pg_global cannot be used as default tablespace")));
435 * If we are trying to change the default tablespace of the template,
436 * we require that the template not have any files in the new default
437 * tablespace. This is necessary because otherwise the copied
438 * database would contain pg_class rows that refer to its default
439 * tablespace both explicitly (by OID) and implicitly (as zero), which
440 * would cause problems. For example another CREATE DATABASE using
441 * the copied database as template, and trying to change its default
442 * tablespace again, would yield outright incorrect results (it would
443 * improperly move tables to the new default tablespace that should
444 * stay in the same tablespace).
446 if (dst_deftablespace != src_deftablespace)
451 srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
453 if (stat(srcpath, &st) == 0 &&
454 S_ISDIR(st.st_mode) &&
455 !directory_is_empty(srcpath))
457 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
458 errmsg("cannot assign new default tablespace \"%s\"",
460 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
467 /* Use template database's default tablespace */
468 dst_deftablespace = src_deftablespace;
469 /* Note there is no additional permission check in this path */
473 * Check for db name conflict. This is just to give a more friendly error
474 * message than "unique index violation". There's a race condition but
475 * we're willing to accept the less friendly message in that case.
477 if (OidIsValid(get_database_oid(dbname, true)))
479 (errcode(ERRCODE_DUPLICATE_DATABASE),
480 errmsg("database \"%s\" already exists", dbname)));
483 * The source DB can't have any active backends, except this one
484 * (exception is to allow CREATE DB while connected to template1).
485 * Otherwise we might copy inconsistent data.
487 * This should be last among the basic error checks, because it involves
488 * potential waiting; we may as well throw an error first if we're gonna
491 if (CountOtherDBBackends(src_dboid, ¬herbackends, &npreparedxacts))
493 (errcode(ERRCODE_OBJECT_IN_USE),
494 errmsg("source database \"%s\" is being accessed by other users",
496 errdetail_busy_db(notherbackends, npreparedxacts)));
499 * Select an OID for the new database, checking that it doesn't have a
500 * filename conflict with anything already existing in the tablespace
503 pg_database_rel = heap_open(DatabaseRelationId, RowExclusiveLock);
507 dboid = GetNewOid(pg_database_rel);
508 } while (check_db_file_conflict(dboid));
511 * Insert a new tuple into pg_database. This establishes our ownership of
512 * the new database name (anyone else trying to insert the same name will
513 * block on the unique index, and fail after we commit).
517 MemSet(new_record, 0, sizeof(new_record));
518 MemSet(new_record_nulls, false, sizeof(new_record_nulls));
520 new_record[Anum_pg_database_datname - 1] =
521 DirectFunctionCall1(namein, CStringGetDatum(dbname));
522 new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
523 new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
524 new_record[Anum_pg_database_datcollate - 1] =
525 DirectFunctionCall1(namein, CStringGetDatum(dbcollate));
526 new_record[Anum_pg_database_datctype - 1] =
527 DirectFunctionCall1(namein, CStringGetDatum(dbctype));
528 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
529 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
530 new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
531 new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
532 new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
533 new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
534 new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
537 * We deliberately set datacl to default (NULL), rather than copying it
538 * from the template database. Copying it would be a bad idea when the
539 * owner is not the same as the template's owner.
541 new_record_nulls[Anum_pg_database_datacl - 1] = true;
543 tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
544 new_record, new_record_nulls);
546 HeapTupleSetOid(tuple, dboid);
548 simple_heap_insert(pg_database_rel, tuple);
551 CatalogUpdateIndexes(pg_database_rel, tuple);
554 * Now generate additional catalog entries associated with the new DB
557 /* Register owner dependency */
558 recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
560 /* Create pg_shdepend entries for objects within database */
561 copyTemplateDependencies(src_dboid, dboid);
563 /* Post creation hook for new database */
564 InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
567 * Force a checkpoint before starting the copy. This will force all dirty
568 * buffers, including those of unlogged tables, out to disk, to ensure
569 * source database is up-to-date on disk for the copy.
570 * FlushDatabaseBuffers() would suffice for that, but we also want to
571 * process any pending unlink requests. Otherwise, if a checkpoint
572 * happened while we're copying files, a file might be deleted just when
573 * we're about to copy it, causing the lstat() call in copydir() to fail
576 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT
577 | CHECKPOINT_FLUSH_ALL);
580 * Once we start copying subdirectories, we need to be able to clean 'em
581 * up if we fail. Use an ENSURE block to make sure this happens. (This
582 * is not a 100% solution, because of the possibility of failure during
583 * transaction commit after we leave this routine, but it should handle
586 fparms.src_dboid = src_dboid;
587 fparms.dest_dboid = dboid;
588 PG_ENSURE_ERROR_CLEANUP(createdb_failure_callback,
589 PointerGetDatum(&fparms));
592 * Iterate through all tablespaces of the template database, and copy
593 * each one to the new database.
595 rel = heap_open(TableSpaceRelationId, AccessShareLock);
596 scan = heap_beginscan_catalog(rel, 0, NULL);
597 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
599 Oid srctablespace = HeapTupleGetOid(tuple);
605 /* No need to copy global tablespace */
606 if (srctablespace == GLOBALTABLESPACE_OID)
609 srcpath = GetDatabasePath(src_dboid, srctablespace);
611 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
612 directory_is_empty(srcpath))
614 /* Assume we can ignore it */
619 if (srctablespace == src_deftablespace)
620 dsttablespace = dst_deftablespace;
622 dsttablespace = srctablespace;
624 dstpath = GetDatabasePath(dboid, dsttablespace);
627 * Copy this subdirectory to the new location
629 * We don't need to copy subdirectories
631 copydir(srcpath, dstpath, false);
633 /* Record the filesystem change in XLOG */
635 xl_dbase_create_rec xlrec;
638 xlrec.tablespace_id = dsttablespace;
639 xlrec.src_db_id = src_dboid;
640 xlrec.src_tablespace_id = srctablespace;
643 XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
645 (void) XLogInsert(RM_DBASE_ID,
646 XLOG_DBASE_CREATE | XLR_SPECIAL_REL_UPDATE);
650 heap_close(rel, AccessShareLock);
653 * We force a checkpoint before committing. This effectively means
654 * that committed XLOG_DBASE_CREATE operations will never need to be
655 * replayed (at least not in ordinary crash recovery; we still have to
656 * make the XLOG entry for the benefit of PITR operations). This
657 * avoids two nasty scenarios:
659 * #1: When PITR is off, we don't XLOG the contents of newly created
660 * indexes; therefore the drop-and-recreate-whole-directory behavior
661 * of DBASE_CREATE replay would lose such indexes.
663 * #2: Since we have to recopy the source database during DBASE_CREATE
664 * replay, we run the risk of copying changes in it that were
665 * committed after the original CREATE DATABASE command but before the
666 * system crash that led to the replay. This is at least unexpected
667 * and at worst could lead to inconsistencies, eg duplicate table
670 * (Both of these were real bugs in releases 8.0 through 8.0.3.)
672 * In PITR replay, the first of these isn't an issue, and the second
673 * is only a risk if the CREATE DATABASE and subsequent template
674 * database change both occur while a base backup is being taken.
675 * There doesn't seem to be much we can do about that except document
676 * it as a limitation.
678 * Perhaps if we ever implement CREATE DATABASE in a less cheesy way,
681 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT);
684 * Close pg_database, but keep lock till commit.
686 heap_close(pg_database_rel, NoLock);
689 * Force synchronous commit, thus minimizing the window between
690 * creation of the database files and commital of the transaction. If
691 * we crash before committing, we'll have a DB that's taking up disk
692 * space but is not in pg_database, which is not good.
696 PG_END_ENSURE_ERROR_CLEANUP(createdb_failure_callback,
697 PointerGetDatum(&fparms));
703 * Check whether chosen encoding matches chosen locale settings. This
704 * restriction is necessary because libc's locale-specific code usually
705 * fails when presented with data in an encoding it's not expecting. We
706 * allow mismatch in four cases:
708 * 1. locale encoding = SQL_ASCII, which means that the locale is C/POSIX
709 * which works with any encoding.
711 * 2. locale encoding = -1, which means that we couldn't determine the
712 * locale's encoding and have to trust the user to get it right.
714 * 3. selected encoding is UTF8 and platform is win32. This is because
715 * UTF8 is a pseudo codepage that is supported in all locales since it's
716 * converted to UTF16 before being used.
718 * 4. selected encoding is SQL_ASCII, but only if you're a superuser. This
719 * is risky but we have historically allowed it --- notably, the
720 * regression tests require it.
722 * Note: if you change this policy, fix initdb to match.
725 check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
727 int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
728 int collate_encoding = pg_get_encoding_from_locale(collate, true);
730 if (!(ctype_encoding == encoding ||
731 ctype_encoding == PG_SQL_ASCII ||
732 ctype_encoding == -1 ||
734 encoding == PG_UTF8 ||
736 (encoding == PG_SQL_ASCII && superuser())))
738 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
739 errmsg("encoding \"%s\" does not match locale \"%s\"",
740 pg_encoding_to_char(encoding),
742 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
743 pg_encoding_to_char(ctype_encoding))));
745 if (!(collate_encoding == encoding ||
746 collate_encoding == PG_SQL_ASCII ||
747 collate_encoding == -1 ||
749 encoding == PG_UTF8 ||
751 (encoding == PG_SQL_ASCII && superuser())))
753 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
754 errmsg("encoding \"%s\" does not match locale \"%s\"",
755 pg_encoding_to_char(encoding),
757 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
758 pg_encoding_to_char(collate_encoding))));
761 /* Error cleanup callback for createdb */
763 createdb_failure_callback(int code, Datum arg)
765 createdb_failure_params *fparms = (createdb_failure_params *) DatumGetPointer(arg);
768 * Release lock on source database before doing recursive remove. This is
769 * not essential but it seems desirable to release the lock as soon as
772 UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
774 /* Throw away any successfully copied subdirectories */
775 remove_dbtablespaces(fparms->dest_dboid);
783 dropdb(const char *dbname, bool missing_ok)
795 * Look up the target database's OID, and get exclusive lock on it. We
796 * need this to ensure that no new backend starts up in the target
797 * database while we are deleting it (see postinit.c), and that no one is
798 * using it as a CREATE DATABASE template or trying to delete it for
801 pgdbrel = heap_open(DatabaseRelationId, RowExclusiveLock);
803 if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
804 &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
809 (errcode(ERRCODE_UNDEFINED_DATABASE),
810 errmsg("database \"%s\" does not exist", dbname)));
814 /* Close pg_database, release the lock, since we changed nothing */
815 heap_close(pgdbrel, RowExclusiveLock);
817 (errmsg("database \"%s\" does not exist, skipping",
826 if (!pg_database_ownercheck(db_id, GetUserId()))
827 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
830 /* DROP hook for the database being removed */
831 InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
834 * Disallow dropping a DB that is marked istemplate. This is just to
835 * prevent people from accidentally dropping template0 or template1; they
836 * can do so if they're really determined ...
840 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
841 errmsg("cannot drop a template database")));
843 /* Obviously can't drop my own database */
844 if (db_id == MyDatabaseId)
846 (errcode(ERRCODE_OBJECT_IN_USE),
847 errmsg("cannot drop the currently open database")));
850 * Check whether there are, possibly unconnected, logical slots that refer
851 * to the to-be-dropped database. The database lock we are holding
852 * prevents the creation of new slots using the database.
854 if (ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active))
856 (errcode(ERRCODE_OBJECT_IN_USE),
857 errmsg("database \"%s\" is used by a logical replication slot",
859 errdetail_plural("There is %d slot, %d of them active.",
860 "There are %d slots, %d of them active.",
862 nslots, nslots_active)));
865 * Check for other backends in the target database. (Because we hold the
866 * database lock, no new ones can start after this.)
868 * As in CREATE DATABASE, check this after other error conditions.
870 if (CountOtherDBBackends(db_id, ¬herbackends, &npreparedxacts))
872 (errcode(ERRCODE_OBJECT_IN_USE),
873 errmsg("database \"%s\" is being accessed by other users",
875 errdetail_busy_db(notherbackends, npreparedxacts)));
878 * Remove the database's tuple from pg_database.
880 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(db_id));
881 if (!HeapTupleIsValid(tup))
882 elog(ERROR, "cache lookup failed for database %u", db_id);
884 simple_heap_delete(pgdbrel, &tup->t_self);
886 ReleaseSysCache(tup);
889 * Delete any comments or security labels associated with the database.
891 DeleteSharedComments(db_id, DatabaseRelationId);
892 DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
895 * Remove settings associated with this database
897 DropSetting(db_id, InvalidOid);
900 * Remove shared dependency references for the database.
902 dropDatabaseDependencies(db_id);
905 * Drop pages for this database that are in the shared buffer cache. This
906 * is important to ensure that no remaining backend tries to write out a
907 * dirty buffer to the dead database later...
909 DropDatabaseBuffers(db_id);
912 * Tell the stats collector to forget it immediately, too.
914 pgstat_drop_database(db_id);
917 * Tell checkpointer to forget any pending fsync and unlink requests for
918 * files in the database; else the fsyncs will fail at next checkpoint, or
919 * worse, it will delete files that belong to a newly created database
922 ForgetDatabaseFsyncRequests(db_id);
925 * Force a checkpoint to make sure the checkpointer has received the
926 * message sent by ForgetDatabaseFsyncRequests. On Windows, this also
927 * ensures that background procs don't hold any open files, which would
928 * cause rmdir() to fail.
930 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT);
933 * Remove all tablespace subdirs belonging to the database.
935 remove_dbtablespaces(db_id);
938 * Close pg_database, but keep lock till commit.
940 heap_close(pgdbrel, NoLock);
943 * Force synchronous commit, thus minimizing the window between removal of
944 * the database files and commital of the transaction. If we crash before
945 * committing, we'll have a DB that's gone on disk but still there
946 * according to pg_database, which is not good.
956 RenameDatabase(const char *oldname, const char *newname)
963 ObjectAddress address;
966 * Look up the target database's OID, and get exclusive lock on it. We
967 * need this for the same reasons as DROP DATABASE.
969 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
971 if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
972 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
974 (errcode(ERRCODE_UNDEFINED_DATABASE),
975 errmsg("database \"%s\" does not exist", oldname)));
978 if (!pg_database_ownercheck(db_id, GetUserId()))
979 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
982 /* must have createdb rights */
983 if (!have_createdb_privilege())
985 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
986 errmsg("permission denied to rename database")));
989 * Make sure the new name doesn't exist. See notes for same error in
992 if (OidIsValid(get_database_oid(newname, true)))
994 (errcode(ERRCODE_DUPLICATE_DATABASE),
995 errmsg("database \"%s\" already exists", newname)));
998 * XXX Client applications probably store the current database somewhere,
999 * so renaming it could cause confusion. On the other hand, there may not
1000 * be an actual problem besides a little confusion, so think about this
1003 if (db_id == MyDatabaseId)
1005 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1006 errmsg("current database cannot be renamed")));
1009 * Make sure the database does not have active sessions. This is the same
1010 * concern as above, but applied to other sessions.
1012 * As in CREATE DATABASE, check this after other error conditions.
1014 if (CountOtherDBBackends(db_id, ¬herbackends, &npreparedxacts))
1016 (errcode(ERRCODE_OBJECT_IN_USE),
1017 errmsg("database \"%s\" is being accessed by other users",
1019 errdetail_busy_db(notherbackends, npreparedxacts)));
1022 newtup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1023 if (!HeapTupleIsValid(newtup))
1024 elog(ERROR, "cache lookup failed for database %u", db_id);
1025 namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1026 simple_heap_update(rel, &newtup->t_self, newtup);
1027 CatalogUpdateIndexes(rel, newtup);
1029 InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1031 ObjectAddressSet(address, DatabaseRelationId, db_id);
1034 * Close pg_database, but keep lock till commit.
1036 heap_close(rel, NoLock);
1043 * ALTER DATABASE SET TABLESPACE
1046 movedb(const char *dbname, const char *tblspcname)
1056 Datum new_record[Natts_pg_database];
1057 bool new_record_nulls[Natts_pg_database];
1058 bool new_record_repl[Natts_pg_database];
1059 ScanKeyData scankey;
1060 SysScanDesc sysscan;
1061 AclResult aclresult;
1065 struct dirent *xlde;
1066 movedb_failure_params fparms;
1069 * Look up the target database's OID, and get exclusive lock on it. We
1070 * need this to ensure that no new backend starts up in the database while
1071 * we are moving it, and that no one is using it as a CREATE DATABASE
1072 * template or trying to delete it.
1074 pgdbrel = heap_open(DatabaseRelationId, RowExclusiveLock);
1076 if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1077 NULL, NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL))
1079 (errcode(ERRCODE_UNDEFINED_DATABASE),
1080 errmsg("database \"%s\" does not exist", dbname)));
1083 * We actually need a session lock, so that the lock will persist across
1084 * the commit/restart below. (We could almost get away with letting the
1085 * lock be released at commit, except that someone could try to move
1086 * relations of the DB back into the old directory while we rmtree() it.)
1088 LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1089 AccessExclusiveLock);
1094 if (!pg_database_ownercheck(db_id, GetUserId()))
1095 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1099 * Obviously can't move the tables of my own database
1101 if (db_id == MyDatabaseId)
1103 (errcode(ERRCODE_OBJECT_IN_USE),
1104 errmsg("cannot change the tablespace of the currently open database")));
1107 * Get tablespace's oid
1109 dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1114 aclresult = pg_tablespace_aclcheck(dst_tblspcoid, GetUserId(),
1116 if (aclresult != ACLCHECK_OK)
1117 aclcheck_error(aclresult, ACL_KIND_TABLESPACE,
1121 * pg_global must never be the default tablespace
1123 if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1125 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1126 errmsg("pg_global cannot be used as default tablespace")));
1129 * No-op if same tablespace
1131 if (src_tblspcoid == dst_tblspcoid)
1133 heap_close(pgdbrel, NoLock);
1134 UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1135 AccessExclusiveLock);
1140 * Check for other backends in the target database. (Because we hold the
1141 * database lock, no new ones can start after this.)
1143 * As in CREATE DATABASE, check this after other error conditions.
1145 if (CountOtherDBBackends(db_id, ¬herbackends, &npreparedxacts))
1147 (errcode(ERRCODE_OBJECT_IN_USE),
1148 errmsg("database \"%s\" is being accessed by other users",
1150 errdetail_busy_db(notherbackends, npreparedxacts)));
1153 * Get old and new database paths
1155 src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1156 dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1159 * Force a checkpoint before proceeding. This will force all dirty
1160 * buffers, including those of unlogged tables, out to disk, to ensure
1161 * source database is up-to-date on disk for the copy.
1162 * FlushDatabaseBuffers() would suffice for that, but we also want to
1163 * process any pending unlink requests. Otherwise, the check for existing
1164 * files in the target directory might fail unnecessarily, not to mention
1165 * that the copy might fail due to source files getting deleted under it.
1166 * On Windows, this also ensures that background procs don't hold any open
1167 * files, which would cause rmdir() to fail.
1169 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT
1170 | CHECKPOINT_FLUSH_ALL);
1173 * Now drop all buffers holding data of the target database; they should
1174 * no longer be dirty so DropDatabaseBuffers is safe.
1176 * It might seem that we could just let these buffers age out of shared
1177 * buffers naturally, since they should not get referenced anymore. The
1178 * problem with that is that if the user later moves the database back to
1179 * its original tablespace, any still-surviving buffers would appear to
1180 * contain valid data again --- but they'd be missing any changes made in
1181 * the database while it was in the new tablespace. In any case, freeing
1182 * buffers that should never be used again seems worth the cycles.
1184 * Note: it'd be sufficient to get rid of buffers matching db_id and
1185 * src_tblspcoid, but bufmgr.c presently provides no API for that.
1187 DropDatabaseBuffers(db_id);
1190 * Check for existence of files in the target directory, i.e., objects of
1191 * this database that are already in the target tablespace. We can't
1192 * allow the move in such a case, because we would need to change those
1193 * relations' pg_class.reltablespace entries to zero, and we don't have
1194 * access to the DB's pg_class to do so.
1196 dstdir = AllocateDir(dst_dbpath);
1199 while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1201 if (strcmp(xlde->d_name, ".") == 0 ||
1202 strcmp(xlde->d_name, "..") == 0)
1206 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1207 errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1208 dbname, tblspcname),
1209 errhint("You must move them back to the database's default tablespace before using this command.")));
1215 * The directory exists but is empty. We must remove it before using
1216 * the copydir function.
1218 if (rmdir(dst_dbpath) != 0)
1219 elog(ERROR, "could not remove directory \"%s\": %m",
1224 * Use an ENSURE block to make sure we remove the debris if the copy fails
1225 * (eg, due to out-of-disk-space). This is not a 100% solution, because
1226 * of the possibility of failure during transaction commit, but it should
1227 * handle most scenarios.
1229 fparms.dest_dboid = db_id;
1230 fparms.dest_tsoid = dst_tblspcoid;
1231 PG_ENSURE_ERROR_CLEANUP(movedb_failure_callback,
1232 PointerGetDatum(&fparms));
1235 * Copy files from the old tablespace to the new one
1237 copydir(src_dbpath, dst_dbpath, false);
1240 * Record the filesystem change in XLOG
1243 xl_dbase_create_rec xlrec;
1245 xlrec.db_id = db_id;
1246 xlrec.tablespace_id = dst_tblspcoid;
1247 xlrec.src_db_id = db_id;
1248 xlrec.src_tablespace_id = src_tblspcoid;
1251 XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
1253 (void) XLogInsert(RM_DBASE_ID,
1254 XLOG_DBASE_CREATE | XLR_SPECIAL_REL_UPDATE);
1258 * Update the database's pg_database tuple
1260 ScanKeyInit(&scankey,
1261 Anum_pg_database_datname,
1262 BTEqualStrategyNumber, F_NAMEEQ,
1263 CStringGetDatum(dbname));
1264 sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
1266 oldtuple = systable_getnext(sysscan);
1267 if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
1269 (errcode(ERRCODE_UNDEFINED_DATABASE),
1270 errmsg("database \"%s\" does not exist", dbname)));
1272 MemSet(new_record, 0, sizeof(new_record));
1273 MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1274 MemSet(new_record_repl, false, sizeof(new_record_repl));
1276 new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
1277 new_record_repl[Anum_pg_database_dattablespace - 1] = true;
1279 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
1281 new_record_nulls, new_record_repl);
1282 simple_heap_update(pgdbrel, &oldtuple->t_self, newtuple);
1284 /* Update indexes */
1285 CatalogUpdateIndexes(pgdbrel, newtuple);
1287 InvokeObjectPostAlterHook(DatabaseRelationId,
1288 HeapTupleGetOid(newtuple), 0);
1290 systable_endscan(sysscan);
1293 * Force another checkpoint here. As in CREATE DATABASE, this is to
1294 * ensure that we don't have to replay a committed XLOG_DBASE_CREATE
1295 * operation, which would cause us to lose any unlogged operations
1296 * done in the new DB tablespace before the next checkpoint.
1298 RequestCheckpoint(CHECKPOINT_IMMEDIATE | CHECKPOINT_FORCE | CHECKPOINT_WAIT);
1301 * Force synchronous commit, thus minimizing the window between
1302 * copying the database files and commital of the transaction. If we
1303 * crash before committing, we'll leave an orphaned set of files on
1304 * disk, which is not fatal but not good either.
1309 * Close pg_database, but keep lock till commit.
1311 heap_close(pgdbrel, NoLock);
1313 PG_END_ENSURE_ERROR_CLEANUP(movedb_failure_callback,
1314 PointerGetDatum(&fparms));
1317 * Commit the transaction so that the pg_database update is committed. If
1318 * we crash while removing files, the database won't be corrupt, we'll
1319 * just leave some orphaned files in the old directory.
1321 * (This is OK because we know we aren't inside a transaction block.)
1323 * XXX would it be safe/better to do this inside the ensure block? Not
1324 * convinced it's a good idea; consider elog just after the transaction
1327 PopActiveSnapshot();
1328 CommitTransactionCommand();
1330 /* Start new transaction for the remaining work; don't need a snapshot */
1331 StartTransactionCommand();
1334 * Remove files from the old tablespace
1336 if (!rmtree(src_dbpath, true))
1338 (errmsg("some useless files may be left behind in old database directory \"%s\"",
1342 * Record the filesystem change in XLOG
1345 xl_dbase_drop_rec xlrec;
1347 xlrec.db_id = db_id;
1348 xlrec.tablespace_id = src_tblspcoid;
1351 XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1353 (void) XLogInsert(RM_DBASE_ID,
1354 XLOG_DBASE_DROP | XLR_SPECIAL_REL_UPDATE);
1357 /* Now it's safe to release the database lock */
1358 UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1359 AccessExclusiveLock);
1362 /* Error cleanup callback for movedb */
1364 movedb_failure_callback(int code, Datum arg)
1366 movedb_failure_params *fparms = (movedb_failure_params *) DatumGetPointer(arg);
1369 /* Get rid of anything we managed to copy to the target directory */
1370 dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
1372 (void) rmtree(dstpath, true);
1377 * ALTER DATABASE name ...
1380 AlterDatabase(ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
1386 ScanKeyData scankey;
1389 bool dbistemplate = false;
1390 bool dballowconnections = true;
1391 int dbconnlimit = -1;
1392 DefElem *distemplate = NULL;
1393 DefElem *dallowconnections = NULL;
1394 DefElem *dconnlimit = NULL;
1395 DefElem *dtablespace = NULL;
1396 Datum new_record[Natts_pg_database];
1397 bool new_record_nulls[Natts_pg_database];
1398 bool new_record_repl[Natts_pg_database];
1400 /* Extract options from the statement node tree */
1401 foreach(option, stmt->options)
1403 DefElem *defel = (DefElem *) lfirst(option);
1405 if (strcmp(defel->defname, "is_template") == 0)
1409 (errcode(ERRCODE_SYNTAX_ERROR),
1410 errmsg("conflicting or redundant options"),
1411 parser_errposition(pstate, defel->location)));
1412 distemplate = defel;
1414 else if (strcmp(defel->defname, "allow_connections") == 0)
1416 if (dallowconnections)
1418 (errcode(ERRCODE_SYNTAX_ERROR),
1419 errmsg("conflicting or redundant options"),
1420 parser_errposition(pstate, defel->location)));
1421 dallowconnections = defel;
1423 else if (strcmp(defel->defname, "connection_limit") == 0)
1427 (errcode(ERRCODE_SYNTAX_ERROR),
1428 errmsg("conflicting or redundant options"),
1429 parser_errposition(pstate, defel->location)));
1432 else if (strcmp(defel->defname, "tablespace") == 0)
1436 (errcode(ERRCODE_SYNTAX_ERROR),
1437 errmsg("conflicting or redundant options"),
1438 parser_errposition(pstate, defel->location)));
1439 dtablespace = defel;
1443 (errcode(ERRCODE_SYNTAX_ERROR),
1444 errmsg("option \"%s\" not recognized", defel->defname),
1445 parser_errposition(pstate, defel->location)));
1451 * While the SET TABLESPACE syntax doesn't allow any other options,
1452 * somebody could write "WITH TABLESPACE ...". Forbid any other
1453 * options from being specified in that case.
1455 if (list_length(stmt->options) != 1)
1457 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1458 errmsg("option \"%s\" cannot be specified with other options",
1459 dtablespace->defname),
1460 parser_errposition(pstate, dtablespace->location)));
1461 /* this case isn't allowed within a transaction block */
1462 PreventTransactionChain(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1463 movedb(stmt->dbname, defGetString(dtablespace));
1467 if (distemplate && distemplate->arg)
1468 dbistemplate = defGetBoolean(distemplate);
1469 if (dallowconnections && dallowconnections->arg)
1470 dballowconnections = defGetBoolean(dallowconnections);
1471 if (dconnlimit && dconnlimit->arg)
1473 dbconnlimit = defGetInt32(dconnlimit);
1474 if (dbconnlimit < -1)
1476 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1477 errmsg("invalid connection limit: %d", dbconnlimit)));
1481 * Get the old tuple. We don't need a lock on the database per se,
1482 * because we're not going to do anything that would mess up incoming
1485 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
1486 ScanKeyInit(&scankey,
1487 Anum_pg_database_datname,
1488 BTEqualStrategyNumber, F_NAMEEQ,
1489 CStringGetDatum(stmt->dbname));
1490 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1492 tuple = systable_getnext(scan);
1493 if (!HeapTupleIsValid(tuple))
1495 (errcode(ERRCODE_UNDEFINED_DATABASE),
1496 errmsg("database \"%s\" does not exist", stmt->dbname)));
1498 dboid = HeapTupleGetOid(tuple);
1500 if (!pg_database_ownercheck(HeapTupleGetOid(tuple), GetUserId()))
1501 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1505 * In order to avoid getting locked out and having to go through
1506 * standalone mode, we refuse to disallow connections to the database
1507 * we're currently connected to. Lockout can still happen with concurrent
1508 * sessions but the likeliness of that is not high enough to worry about.
1510 if (!dballowconnections && dboid == MyDatabaseId)
1512 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1513 errmsg("cannot disallow connections for current database")));
1516 * Build an updated tuple, perusing the information just obtained
1518 MemSet(new_record, 0, sizeof(new_record));
1519 MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1520 MemSet(new_record_repl, false, sizeof(new_record_repl));
1524 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1525 new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1527 if (dallowconnections)
1529 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1530 new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1534 new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1535 new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1538 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1539 new_record_nulls, new_record_repl);
1540 simple_heap_update(rel, &tuple->t_self, newtuple);
1542 /* Update indexes */
1543 CatalogUpdateIndexes(rel, newtuple);
1545 InvokeObjectPostAlterHook(DatabaseRelationId,
1546 HeapTupleGetOid(newtuple), 0);
1548 systable_endscan(scan);
1550 /* Close pg_database, but keep lock till commit */
1551 heap_close(rel, NoLock);
1558 * ALTER DATABASE name SET ...
1561 AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
1563 Oid datid = get_database_oid(stmt->dbname, false);
1566 * Obtain a lock on the database and make sure it didn't go away in the
1569 shdepLockAndCheckObject(DatabaseRelationId, datid);
1571 if (!pg_database_ownercheck(datid, GetUserId()))
1572 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1575 AlterSetting(datid, InvalidOid, stmt->setstmt);
1577 UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
1584 * ALTER DATABASE name OWNER TO newowner
1587 AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
1592 ScanKeyData scankey;
1594 Form_pg_database datForm;
1595 ObjectAddress address;
1598 * Get the old tuple. We don't need a lock on the database per se,
1599 * because we're not going to do anything that would mess up incoming
1602 rel = heap_open(DatabaseRelationId, RowExclusiveLock);
1603 ScanKeyInit(&scankey,
1604 Anum_pg_database_datname,
1605 BTEqualStrategyNumber, F_NAMEEQ,
1606 CStringGetDatum(dbname));
1607 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1609 tuple = systable_getnext(scan);
1610 if (!HeapTupleIsValid(tuple))
1612 (errcode(ERRCODE_UNDEFINED_DATABASE),
1613 errmsg("database \"%s\" does not exist", dbname)));
1615 db_id = HeapTupleGetOid(tuple);
1616 datForm = (Form_pg_database) GETSTRUCT(tuple);
1619 * If the new owner is the same as the existing owner, consider the
1620 * command to have succeeded. This is to be consistent with other
1623 if (datForm->datdba != newOwnerId)
1625 Datum repl_val[Natts_pg_database];
1626 bool repl_null[Natts_pg_database];
1627 bool repl_repl[Natts_pg_database];
1633 /* Otherwise, must be owner of the existing object */
1634 if (!pg_database_ownercheck(HeapTupleGetOid(tuple), GetUserId()))
1635 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_DATABASE,
1638 /* Must be able to become new owner */
1639 check_is_member_of_role(GetUserId(), newOwnerId);
1642 * must have createdb rights
1644 * NOTE: This is different from other alter-owner checks in that the
1645 * current user is checked for createdb privileges instead of the
1646 * destination owner. This is consistent with the CREATE case for
1647 * databases. Because superusers will always have this right, we need
1648 * no special case for them.
1650 if (!have_createdb_privilege())
1652 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1653 errmsg("permission denied to change owner of database")));
1655 memset(repl_null, false, sizeof(repl_null));
1656 memset(repl_repl, false, sizeof(repl_repl));
1658 repl_repl[Anum_pg_database_datdba - 1] = true;
1659 repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1662 * Determine the modified ACL for the new owner. This is only
1663 * necessary when the ACL is non-null.
1665 aclDatum = heap_getattr(tuple,
1666 Anum_pg_database_datacl,
1667 RelationGetDescr(rel),
1671 newAcl = aclnewowner(DatumGetAclP(aclDatum),
1672 datForm->datdba, newOwnerId);
1673 repl_repl[Anum_pg_database_datacl - 1] = true;
1674 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1677 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1678 simple_heap_update(rel, &newtuple->t_self, newtuple);
1679 CatalogUpdateIndexes(rel, newtuple);
1681 heap_freetuple(newtuple);
1683 /* Update owner dependency reference */
1684 changeDependencyOnOwner(DatabaseRelationId, HeapTupleGetOid(tuple),
1688 InvokeObjectPostAlterHook(DatabaseRelationId, HeapTupleGetOid(tuple), 0);
1690 ObjectAddressSet(address, DatabaseRelationId, db_id);
1692 systable_endscan(scan);
1694 /* Close pg_database, but keep lock till commit */
1695 heap_close(rel, NoLock);
1706 * Look up info about the database named "name". If the database exists,
1707 * obtain the specified lock type on it, fill in any of the remaining
1708 * parameters that aren't NULL, and return TRUE. If no such database,
1712 get_db_info(const char *name, LOCKMODE lockmode,
1713 Oid *dbIdP, Oid *ownerIdP,
1714 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
1715 Oid *dbLastSysOidP, TransactionId *dbFrozenXidP,
1716 MultiXactId *dbMinMultiP,
1717 Oid *dbTablespace, char **dbCollate, char **dbCtype)
1719 bool result = false;
1724 /* Caller may wish to grab a better lock on pg_database beforehand... */
1725 relation = heap_open(DatabaseRelationId, AccessShareLock);
1728 * Loop covers the rare case where the database is renamed before we can
1729 * lock it. We try again just in case we can find a new one of the same
1734 ScanKeyData scanKey;
1740 * there's no syscache for database-indexed-by-name, so must do it the
1743 ScanKeyInit(&scanKey,
1744 Anum_pg_database_datname,
1745 BTEqualStrategyNumber, F_NAMEEQ,
1746 CStringGetDatum(name));
1748 scan = systable_beginscan(relation, DatabaseNameIndexId, true,
1751 tuple = systable_getnext(scan);
1753 if (!HeapTupleIsValid(tuple))
1755 /* definitely no database of that name */
1756 systable_endscan(scan);
1760 dbOid = HeapTupleGetOid(tuple);
1762 systable_endscan(scan);
1765 * Now that we have a database OID, we can try to lock the DB.
1767 if (lockmode != NoLock)
1768 LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1771 * And now, re-fetch the tuple by OID. If it's still there and still
1772 * the same name, we win; else, drop the lock and loop back to try
1775 tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
1776 if (HeapTupleIsValid(tuple))
1778 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1780 if (strcmp(name, NameStr(dbform->datname)) == 0)
1782 /* oid of the database */
1785 /* oid of the owner */
1787 *ownerIdP = dbform->datdba;
1788 /* character encoding */
1790 *encodingP = dbform->encoding;
1791 /* allowed as template? */
1793 *dbIsTemplateP = dbform->datistemplate;
1794 /* allowing connections? */
1796 *dbAllowConnP = dbform->datallowconn;
1797 /* last system OID used in database */
1799 *dbLastSysOidP = dbform->datlastsysoid;
1800 /* limit of frozen XIDs */
1802 *dbFrozenXidP = dbform->datfrozenxid;
1803 /* minimum MultixactId */
1805 *dbMinMultiP = dbform->datminmxid;
1806 /* default tablespace for this database */
1808 *dbTablespace = dbform->dattablespace;
1809 /* default locale settings for this database */
1811 *dbCollate = pstrdup(NameStr(dbform->datcollate));
1813 *dbCtype = pstrdup(NameStr(dbform->datctype));
1814 ReleaseSysCache(tuple);
1818 /* can only get here if it was just renamed */
1819 ReleaseSysCache(tuple);
1822 if (lockmode != NoLock)
1823 UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1826 heap_close(relation, AccessShareLock);
1831 /* Check if current user has createdb privileges */
1833 have_createdb_privilege(void)
1835 bool result = false;
1838 /* Superusers can always do everything */
1842 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
1843 if (HeapTupleIsValid(utup))
1845 result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
1846 ReleaseSysCache(utup);
1852 * Remove tablespace directories
1854 * We don't know what tablespaces db_id is using, so iterate through all
1855 * tablespaces removing <tablespace>/db_id
1858 remove_dbtablespaces(Oid db_id)
1864 rel = heap_open(TableSpaceRelationId, AccessShareLock);
1865 scan = heap_beginscan_catalog(rel, 0, NULL);
1866 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1868 Oid dsttablespace = HeapTupleGetOid(tuple);
1872 /* Don't mess with the global tablespace */
1873 if (dsttablespace == GLOBALTABLESPACE_OID)
1876 dstpath = GetDatabasePath(db_id, dsttablespace);
1878 if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1880 /* Assume we can ignore it */
1885 if (!rmtree(dstpath, true))
1887 (errmsg("some useless files may be left behind in old database directory \"%s\"",
1890 /* Record the filesystem change in XLOG */
1892 xl_dbase_drop_rec xlrec;
1894 xlrec.db_id = db_id;
1895 xlrec.tablespace_id = dsttablespace;
1898 XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1900 (void) XLogInsert(RM_DBASE_ID,
1901 XLOG_DBASE_DROP | XLR_SPECIAL_REL_UPDATE);
1908 heap_close(rel, AccessShareLock);
1912 * Check for existing files that conflict with a proposed new DB OID;
1913 * return TRUE if there are any
1915 * If there were a subdirectory in any tablespace matching the proposed new
1916 * OID, we'd get a create failure due to the duplicate name ... and then we'd
1917 * try to remove that already-existing subdirectory during the cleanup in
1918 * remove_dbtablespaces. Nuking existing files seems like a bad idea, so
1919 * instead we make this extra check before settling on the OID of the new
1920 * database. This exactly parallels what GetNewRelFileNode() does for table
1921 * relfilenode values.
1924 check_db_file_conflict(Oid db_id)
1926 bool result = false;
1931 rel = heap_open(TableSpaceRelationId, AccessShareLock);
1932 scan = heap_beginscan_catalog(rel, 0, NULL);
1933 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1935 Oid dsttablespace = HeapTupleGetOid(tuple);
1939 /* Don't mess with the global tablespace */
1940 if (dsttablespace == GLOBALTABLESPACE_OID)
1943 dstpath = GetDatabasePath(db_id, dsttablespace);
1945 if (lstat(dstpath, &st) == 0)
1947 /* Found a conflicting file (or directory, whatever) */
1957 heap_close(rel, AccessShareLock);
1963 * Issue a suitable errdetail message for a busy database
1966 errdetail_busy_db(int notherbackends, int npreparedxacts)
1968 if (notherbackends > 0 && npreparedxacts > 0)
1971 * We don't deal with singular versus plural here, since gettext
1972 * doesn't support multiple plurals in one string.
1974 errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
1975 notherbackends, npreparedxacts);
1976 else if (notherbackends > 0)
1977 errdetail_plural("There is %d other session using the database.",
1978 "There are %d other sessions using the database.",
1982 errdetail_plural("There is %d prepared transaction using the database.",
1983 "There are %d prepared transactions using the database.",
1986 return 0; /* just to keep ereport macro happy */
1990 * get_database_oid - given a database name, look up the OID
1992 * If missing_ok is false, throw an error if database name not found. If
1993 * true, just return InvalidOid.
1996 get_database_oid(const char *dbname, bool missing_ok)
1998 Relation pg_database;
1999 ScanKeyData entry[1];
2005 * There's no syscache for pg_database indexed by name, so we must look
2008 pg_database = heap_open(DatabaseRelationId, AccessShareLock);
2009 ScanKeyInit(&entry[0],
2010 Anum_pg_database_datname,
2011 BTEqualStrategyNumber, F_NAMEEQ,
2012 CStringGetDatum(dbname));
2013 scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2016 dbtuple = systable_getnext(scan);
2018 /* We assume that there can be at most one matching tuple */
2019 if (HeapTupleIsValid(dbtuple))
2020 oid = HeapTupleGetOid(dbtuple);
2024 systable_endscan(scan);
2025 heap_close(pg_database, AccessShareLock);
2027 if (!OidIsValid(oid) && !missing_ok)
2029 (errcode(ERRCODE_UNDEFINED_DATABASE),
2030 errmsg("database \"%s\" does not exist",
2038 * get_database_name - given a database OID, look up the name
2040 * Returns a palloc'd string, or NULL if no such database.
2043 get_database_name(Oid dbid)
2048 dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2049 if (HeapTupleIsValid(dbtuple))
2051 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2052 ReleaseSysCache(dbtuple);
2061 * DATABASE resource manager's routines
2064 dbase_redo(XLogReaderState *record)
2066 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2068 /* Backup blocks are not used in dbase records */
2069 Assert(!XLogRecHasAnyBlockRefs(record));
2071 if (info == XLOG_DBASE_CREATE)
2073 xl_dbase_create_rec *xlrec = (xl_dbase_create_rec *) XLogRecGetData(record);
2078 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
2079 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2082 * Our theory for replaying a CREATE is to forcibly drop the target
2083 * subdirectory if present, then re-copy the source data. This may be
2084 * more work than needed, but it is simple to implement.
2086 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
2088 if (!rmtree(dst_path, true))
2089 /* If this failed, copydir() below is going to error. */
2091 (errmsg("some useless files may be left behind in old database directory \"%s\"",
2096 * Force dirty buffers out to disk, to ensure source database is
2097 * up-to-date for the copy.
2099 FlushDatabaseBuffers(xlrec->src_db_id);
2102 * Copy this subdirectory to the new location
2104 * We don't need to copy subdirectories
2106 copydir(src_path, dst_path, false);
2108 else if (info == XLOG_DBASE_DROP)
2110 xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
2113 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2118 * Lock database while we resolve conflicts to ensure that
2119 * InitPostgres() cannot fully re-execute concurrently. This
2120 * avoids backends re-connecting automatically to same database,
2121 * which can happen in some cases.
2123 LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2124 ResolveRecoveryConflictWithDatabase(xlrec->db_id);
2127 /* Drop pages for this database that are in the shared buffer cache */
2128 DropDatabaseBuffers(xlrec->db_id);
2130 /* Also, clean out any fsync requests that might be pending in md.c */
2131 ForgetDatabaseFsyncRequests(xlrec->db_id);
2133 /* Clean out the xlog relcache too */
2134 XLogDropDatabase(xlrec->db_id);
2136 /* And remove the physical files */
2137 if (!rmtree(dst_path, true))
2139 (errmsg("some useless files may be left behind in old database directory \"%s\"",
2145 * Release locks prior to commit. XXX There is a race condition
2146 * here that may allow backends to reconnect, but the window for
2147 * this is small because the gap between here and commit is mostly
2148 * fairly small and it is unlikely that people will be dropping
2149 * databases that we are trying to connect to anyway.
2151 UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2155 elog(PANIC, "dbase_redo: unknown op code %u", info);