PostgreSQL Source Code  git master
dbcommands.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_database.h"
#include "catalog/pg_db_role_setting.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_tablespace.h"
#include "commands/comment.h"
#include "commands/dbcommands.h"
#include "commands/dbcommands_xlog.h"
#include "commands/defrem.h"
#include "commands/seclabel.h"
#include "commands/tablespace.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgwriter.h"
#include "replication/slot.h"
#include "storage/copydir.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#include "storage/ipc.h"
#include "storage/md.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/pg_locale.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for dbcommands.c:

Go to the source code of this file.

Data Structures

struct  createdb_failure_params
 
struct  movedb_failure_params
 

Functions

static void createdb_failure_callback (int code, Datum arg)
 
static void movedb (const char *dbname, const char *tblspcname)
 
static void movedb_failure_callback (int code, Datum arg)
 
static bool get_db_info (const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
 
static bool have_createdb_privilege (void)
 
static void remove_dbtablespaces (Oid db_id)
 
static bool check_db_file_conflict (Oid db_id)
 
static int errdetail_busy_db (int notherbackends, int npreparedxacts)
 
Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 
void dropdb (const char *dbname, bool missing_ok)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
Oid AlterDatabaseSet (AlterDatabaseSetStmt *stmt)
 
ObjectAddress AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
void dbase_redo (XLogReaderState *record)
 

Function Documentation

◆ AlterDatabase()

Oid AlterDatabase ( ParseState pstate,
AlterDatabaseStmt stmt,
bool  isTopLevel 
)

Definition at line 1438 of file dbcommands.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, BoolGetDatum, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum, DatabaseNameIndexId, AlterDatabaseStmt::dbname, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), heap_modify_tuple(), HeapTupleIsValid, Int32GetDatum, InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), DefElem::location, MemSet, movedb(), MyDatabaseId, NoLock, OBJECT_DATABASE, AlterDatabaseStmt::options, parser_errposition(), pg_database_ownercheck(), PreventInTransactionBlock(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by standard_ProcessUtility().

1439 {
1440  Relation rel;
1441  Oid dboid;
1442  HeapTuple tuple,
1443  newtuple;
1444  Form_pg_database datform;
1445  ScanKeyData scankey;
1446  SysScanDesc scan;
1447  ListCell *option;
1448  bool dbistemplate = false;
1449  bool dballowconnections = true;
1450  int dbconnlimit = -1;
1451  DefElem *distemplate = NULL;
1452  DefElem *dallowconnections = NULL;
1453  DefElem *dconnlimit = NULL;
1454  DefElem *dtablespace = NULL;
1455  Datum new_record[Natts_pg_database];
1456  bool new_record_nulls[Natts_pg_database];
1457  bool new_record_repl[Natts_pg_database];
1458 
1459  /* Extract options from the statement node tree */
1460  foreach(option, stmt->options)
1461  {
1462  DefElem *defel = (DefElem *) lfirst(option);
1463 
1464  if (strcmp(defel->defname, "is_template") == 0)
1465  {
1466  if (distemplate)
1467  ereport(ERROR,
1468  (errcode(ERRCODE_SYNTAX_ERROR),
1469  errmsg("conflicting or redundant options"),
1470  parser_errposition(pstate, defel->location)));
1471  distemplate = defel;
1472  }
1473  else if (strcmp(defel->defname, "allow_connections") == 0)
1474  {
1475  if (dallowconnections)
1476  ereport(ERROR,
1477  (errcode(ERRCODE_SYNTAX_ERROR),
1478  errmsg("conflicting or redundant options"),
1479  parser_errposition(pstate, defel->location)));
1480  dallowconnections = defel;
1481  }
1482  else if (strcmp(defel->defname, "connection_limit") == 0)
1483  {
1484  if (dconnlimit)
1485  ereport(ERROR,
1486  (errcode(ERRCODE_SYNTAX_ERROR),
1487  errmsg("conflicting or redundant options"),
1488  parser_errposition(pstate, defel->location)));
1489  dconnlimit = defel;
1490  }
1491  else if (strcmp(defel->defname, "tablespace") == 0)
1492  {
1493  if (dtablespace)
1494  ereport(ERROR,
1495  (errcode(ERRCODE_SYNTAX_ERROR),
1496  errmsg("conflicting or redundant options"),
1497  parser_errposition(pstate, defel->location)));
1498  dtablespace = defel;
1499  }
1500  else
1501  ereport(ERROR,
1502  (errcode(ERRCODE_SYNTAX_ERROR),
1503  errmsg("option \"%s\" not recognized", defel->defname),
1504  parser_errposition(pstate, defel->location)));
1505  }
1506 
1507  if (dtablespace)
1508  {
1509  /*
1510  * While the SET TABLESPACE syntax doesn't allow any other options,
1511  * somebody could write "WITH TABLESPACE ...". Forbid any other
1512  * options from being specified in that case.
1513  */
1514  if (list_length(stmt->options) != 1)
1515  ereport(ERROR,
1516  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1517  errmsg("option \"%s\" cannot be specified with other options",
1518  dtablespace->defname),
1519  parser_errposition(pstate, dtablespace->location)));
1520  /* this case isn't allowed within a transaction block */
1521  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1522  movedb(stmt->dbname, defGetString(dtablespace));
1523  return InvalidOid;
1524  }
1525 
1526  if (distemplate && distemplate->arg)
1527  dbistemplate = defGetBoolean(distemplate);
1528  if (dallowconnections && dallowconnections->arg)
1529  dballowconnections = defGetBoolean(dallowconnections);
1530  if (dconnlimit && dconnlimit->arg)
1531  {
1532  dbconnlimit = defGetInt32(dconnlimit);
1533  if (dbconnlimit < -1)
1534  ereport(ERROR,
1535  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1536  errmsg("invalid connection limit: %d", dbconnlimit)));
1537  }
1538 
1539  /*
1540  * Get the old tuple. We don't need a lock on the database per se,
1541  * because we're not going to do anything that would mess up incoming
1542  * connections.
1543  */
1544  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1545  ScanKeyInit(&scankey,
1546  Anum_pg_database_datname,
1547  BTEqualStrategyNumber, F_NAMEEQ,
1548  CStringGetDatum(stmt->dbname));
1549  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1550  NULL, 1, &scankey);
1551  tuple = systable_getnext(scan);
1552  if (!HeapTupleIsValid(tuple))
1553  ereport(ERROR,
1554  (errcode(ERRCODE_UNDEFINED_DATABASE),
1555  errmsg("database \"%s\" does not exist", stmt->dbname)));
1556 
1557  datform = (Form_pg_database) GETSTRUCT(tuple);
1558  dboid = datform->oid;
1559 
1560  if (!pg_database_ownercheck(dboid, GetUserId()))
1562  stmt->dbname);
1563 
1564  /*
1565  * In order to avoid getting locked out and having to go through
1566  * standalone mode, we refuse to disallow connections to the database
1567  * we're currently connected to. Lockout can still happen with concurrent
1568  * sessions but the likeliness of that is not high enough to worry about.
1569  */
1570  if (!dballowconnections && dboid == MyDatabaseId)
1571  ereport(ERROR,
1572  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1573  errmsg("cannot disallow connections for current database")));
1574 
1575  /*
1576  * Build an updated tuple, perusing the information just obtained
1577  */
1578  MemSet(new_record, 0, sizeof(new_record));
1579  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1580  MemSet(new_record_repl, false, sizeof(new_record_repl));
1581 
1582  if (distemplate)
1583  {
1584  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1585  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1586  }
1587  if (dallowconnections)
1588  {
1589  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1590  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1591  }
1592  if (dconnlimit)
1593  {
1594  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1595  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1596  }
1597 
1598  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1599  new_record_nulls, new_record_repl);
1600  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
1601 
1602  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
1603 
1604  systable_endscan(scan);
1605 
1606  /* Close pg_database, but keep lock till commit */
1607  table_close(rel, NoLock);
1608 
1609  return dboid;
1610 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
int32 defGetInt32(DefElem *def)
Definition: define.c:166
int errcode(int sqlerrcode)
Definition: elog.c:570
#define MemSet(start, val, len)
Definition: c.h:955
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
bool defGetBoolean(DefElem *def)
Definition: define.c:111
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ERROR
Definition: elog.h:43
char * defGetString(DefElem *def)
Definition: define.c:49
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
int location
Definition: parsenodes.h:733
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3328
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
Node * arg
Definition: parsenodes.h:731
uintptr_t Datum
Definition: postgres.h:367
Oid MyDatabaseId
Definition: globals.c:85
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1108
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define DatabaseNameIndexId
Definition: indexing.h:144
#define Int32GetDatum(X)
Definition: postgres.h:479
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
char * defname
Definition: parsenodes.h:730
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 1643 of file dbcommands.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, aclnewowner(), BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependencyOnOwner(), check_is_member_of_role(), CStringGetDatum, DatabaseNameIndexId, DatumGetAclP, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), have_createdb_privilege(), heap_freetuple(), heap_getattr, heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, OBJECT_DATABASE, ObjectAddressSet, ObjectIdGetDatum, pg_database_ownercheck(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

1644 {
1645  Oid db_id;
1646  HeapTuple tuple;
1647  Relation rel;
1648  ScanKeyData scankey;
1649  SysScanDesc scan;
1650  Form_pg_database datForm;
1651  ObjectAddress address;
1652 
1653  /*
1654  * Get the old tuple. We don't need a lock on the database per se,
1655  * because we're not going to do anything that would mess up incoming
1656  * connections.
1657  */
1658  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1659  ScanKeyInit(&scankey,
1660  Anum_pg_database_datname,
1661  BTEqualStrategyNumber, F_NAMEEQ,
1663  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1664  NULL, 1, &scankey);
1665  tuple = systable_getnext(scan);
1666  if (!HeapTupleIsValid(tuple))
1667  ereport(ERROR,
1668  (errcode(ERRCODE_UNDEFINED_DATABASE),
1669  errmsg("database \"%s\" does not exist", dbname)));
1670 
1671  datForm = (Form_pg_database) GETSTRUCT(tuple);
1672  db_id = datForm->oid;
1673 
1674  /*
1675  * If the new owner is the same as the existing owner, consider the
1676  * command to have succeeded. This is to be consistent with other
1677  * objects.
1678  */
1679  if (datForm->datdba != newOwnerId)
1680  {
1681  Datum repl_val[Natts_pg_database];
1682  bool repl_null[Natts_pg_database];
1683  bool repl_repl[Natts_pg_database];
1684  Acl *newAcl;
1685  Datum aclDatum;
1686  bool isNull;
1687  HeapTuple newtuple;
1688 
1689  /* Otherwise, must be owner of the existing object */
1690  if (!pg_database_ownercheck(db_id, GetUserId()))
1692  dbname);
1693 
1694  /* Must be able to become new owner */
1695  check_is_member_of_role(GetUserId(), newOwnerId);
1696 
1697  /*
1698  * must have createdb rights
1699  *
1700  * NOTE: This is different from other alter-owner checks in that the
1701  * current user is checked for createdb privileges instead of the
1702  * destination owner. This is consistent with the CREATE case for
1703  * databases. Because superusers will always have this right, we need
1704  * no special case for them.
1705  */
1706  if (!have_createdb_privilege())
1707  ereport(ERROR,
1708  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1709  errmsg("permission denied to change owner of database")));
1710 
1711  memset(repl_null, false, sizeof(repl_null));
1712  memset(repl_repl, false, sizeof(repl_repl));
1713 
1714  repl_repl[Anum_pg_database_datdba - 1] = true;
1715  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1716 
1717  /*
1718  * Determine the modified ACL for the new owner. This is only
1719  * necessary when the ACL is non-null.
1720  */
1721  aclDatum = heap_getattr(tuple,
1722  Anum_pg_database_datacl,
1723  RelationGetDescr(rel),
1724  &isNull);
1725  if (!isNull)
1726  {
1727  newAcl = aclnewowner(DatumGetAclP(aclDatum),
1728  datForm->datdba, newOwnerId);
1729  repl_repl[Anum_pg_database_datacl - 1] = true;
1730  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1731  }
1732 
1733  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1734  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1735 
1736  heap_freetuple(newtuple);
1737 
1738  /* Update owner dependency reference */
1739  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
1740  }
1741 
1742  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1743 
1744  ObjectAddressSet(address, DatabaseRelationId, db_id);
1745 
1746  systable_endscan(scan);
1747 
1748  /* Close pg_database, but keep lock till commit */
1749  table_close(rel, NoLock);
1750 
1751  return address;
1752 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define DatumGetAclP(X)
Definition: acl.h:120
#define PointerGetDatum(X)
Definition: postgres.h:556
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1887
int errcode(int sqlerrcode)
Definition: elog.c:570
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:310
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4954
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
char * dbname
Definition: streamutil.c:52
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define DatabaseNameIndexId
Definition: indexing.h:144
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1052
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 1617 of file dbcommands.c.

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), AlterDatabaseSetStmt::dbname, get_database_oid(), GetUserId(), InvalidOid, OBJECT_DATABASE, pg_database_ownercheck(), AlterDatabaseSetStmt::setstmt, shdepLockAndCheckObject(), and UnlockSharedObject().

Referenced by standard_ProcessUtility().

1618 {
1619  Oid datid = get_database_oid(stmt->dbname, false);
1620 
1621  /*
1622  * Obtain a lock on the database and make sure it didn't go away in the
1623  * meantime.
1624  */
1625  shdepLockAndCheckObject(DatabaseRelationId, datid);
1626 
1627  if (!pg_database_ownercheck(datid, GetUserId()))
1629  stmt->dbname);
1630 
1631  AlterSetting(datid, InvalidOid, stmt->setstmt);
1632 
1633  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
1634 
1635  return datid;
1636 }
Oid GetUserId(void)
Definition: miscinit.c:380
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
VariableSetStmt * setstmt
Definition: parsenodes.h:3124
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1025
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1072
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2052

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 1979 of file dbcommands.c.

References AccessShareLock, dstpath, ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), lstat, pfree(), stat, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by createdb().

1980 {
1981  bool result = false;
1982  Relation rel;
1983  TableScanDesc scan;
1984  HeapTuple tuple;
1985 
1986  rel = table_open(TableSpaceRelationId, AccessShareLock);
1987  scan = table_beginscan_catalog(rel, 0, NULL);
1988  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1989  {
1990  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
1991  Oid dsttablespace = spcform->oid;
1992  char *dstpath;
1993  struct stat st;
1994 
1995  /* Don't mess with the global tablespace */
1996  if (dsttablespace == GLOBALTABLESPACE_OID)
1997  continue;
1998 
1999  dstpath = GetDatabasePath(db_id, dsttablespace);
2000 
2001  if (lstat(dstpath, &st) == 0)
2002  {
2003  /* Found a conflicting file (or directory, whatever) */
2004  pfree(dstpath);
2005  result = true;
2006  break;
2007  }
2008 
2009  pfree(dstpath);
2010  }
2011 
2012  table_endscan(scan);
2014 
2015  return result;
2016 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1031
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
static char dstpath[MAXPGPATH]
Definition: file_ops.c:30
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define stat(a, b)
Definition: win32_port.h:264
#define lstat(path, sb)
Definition: win32_port.h:253
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ check_encoding_locale_matches()

void check_encoding_locale_matches ( int  encoding,
const char *  collate,
const char *  ctype 
)

Definition at line 755 of file dbcommands.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, pg_encoding_to_char(), pg_get_encoding_from_locale(), PG_SQL_ASCII, PG_UTF8, and superuser().

Referenced by createdb(), and DefineCollation().

756 {
757  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
758  int collate_encoding = pg_get_encoding_from_locale(collate, true);
759 
760  if (!(ctype_encoding == encoding ||
761  ctype_encoding == PG_SQL_ASCII ||
762  ctype_encoding == -1 ||
763 #ifdef WIN32
764  encoding == PG_UTF8 ||
765 #endif
766  (encoding == PG_SQL_ASCII && superuser())))
767  ereport(ERROR,
768  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
769  errmsg("encoding \"%s\" does not match locale \"%s\"",
771  ctype),
772  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
773  pg_encoding_to_char(ctype_encoding))));
774 
775  if (!(collate_encoding == encoding ||
776  collate_encoding == PG_SQL_ASCII ||
777  collate_encoding == -1 ||
778 #ifdef WIN32
779  encoding == PG_UTF8 ||
780 #endif
781  (encoding == PG_SQL_ASCII && superuser())))
782  ereport(ERROR,
783  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
784  errmsg("encoding \"%s\" does not match locale \"%s\"",
786  collate),
787  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
788  pg_encoding_to_char(collate_encoding))));
789 }
int errcode(int sqlerrcode)
Definition: elog.c:570
bool superuser(void)
Definition: superuser.c:47
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:433
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:607
int32 encoding
Definition: pg_database.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 100 of file dbcommands.c.

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, DefElem::arg, BoolGetDatum, CatalogTupleInsert(), check_db_file_conflict(), check_encoding_locale_matches(), check_is_member_of_role(), check_locale(), CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, copydir(), copyTemplateDependencies(), CountOtherDBBackends(), createdb_failure_callback(), CStringGetDatum, DatabaseOidIndexId, xl_dbase_create_rec::db_id, dbname, CreatedbStmt::dbname, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, createdb_failure_params::dest_dboid, DirectFunctionCall1, directory_is_empty(), dstpath, elog, encoding, ereport, errcode(), errdetail(), errdetail_busy_db(), errhint(), errmsg(), ERROR, ForceSyncCommit(), ForwardScanDirection, get_database_oid(), get_db_info(), get_role_oid(), get_tablespace_oid(), GetDatabasePath(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), have_createdb_privilege(), heap_form_tuple(), heap_getnext(), Int32GetDatum, InvokeObjectPostCreateHook, IsA, IsUnderPostmaster, lfirst, DefElem::location, MemSet, namein(), NoLock, OBJECT_TABLESPACE, ObjectIdGetDatum, OidIsValid, CreatedbStmt::options, parser_errposition(), pfree(), pg_database_ownercheck(), pg_encoding_to_char(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_tablespace_aclcheck(), PG_VALID_BE_ENCODING, pg_valid_server_encoding(), PointerGetDatum, recordDependencyOnOwner(), RelationGetDescr, RequestCheckpoint(), RowExclusiveLock, S_ISDIR, ShareLock, xl_dbase_create_rec::src_db_id, createdb_failure_params::src_dboid, xl_dbase_create_rec::src_tablespace_id, stat, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), xl_dbase_create_rec::tablespace_id, TransactionIdGetDatum, WARNING, XLOG_DBASE_CREATE, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by AlterRole(), CreateRole(), main(), and standard_ProcessUtility().

101 {
102  TableScanDesc scan;
103  Relation rel;
104  Oid src_dboid;
105  Oid src_owner;
106  int src_encoding;
107  char *src_collate;
108  char *src_ctype;
109  bool src_istemplate;
110  bool src_allowconn;
111  Oid src_lastsysoid;
112  TransactionId src_frozenxid;
113  MultiXactId src_minmxid;
114  Oid src_deftablespace;
115  volatile Oid dst_deftablespace;
116  Relation pg_database_rel;
117  HeapTuple tuple;
118  Datum new_record[Natts_pg_database];
119  bool new_record_nulls[Natts_pg_database];
120  Oid dboid;
121  Oid datdba;
122  ListCell *option;
123  DefElem *dtablespacename = NULL;
124  DefElem *downer = NULL;
125  DefElem *dtemplate = NULL;
126  DefElem *dencoding = NULL;
127  DefElem *dlocale = NULL;
128  DefElem *dcollate = NULL;
129  DefElem *dctype = NULL;
130  DefElem *distemplate = NULL;
131  DefElem *dallowconnections = NULL;
132  DefElem *dconnlimit = NULL;
133  char *dbname = stmt->dbname;
134  char *dbowner = NULL;
135  const char *dbtemplate = NULL;
136  char *dbcollate = NULL;
137  char *dbctype = NULL;
138  char *canonname;
139  int encoding = -1;
140  bool dbistemplate = false;
141  bool dballowconnections = true;
142  int dbconnlimit = -1;
143  int notherbackends;
144  int npreparedxacts;
146 
147  /* Extract options from the statement node tree */
148  foreach(option, stmt->options)
149  {
150  DefElem *defel = (DefElem *) lfirst(option);
151 
152  if (strcmp(defel->defname, "tablespace") == 0)
153  {
154  if (dtablespacename)
155  ereport(ERROR,
156  (errcode(ERRCODE_SYNTAX_ERROR),
157  errmsg("conflicting or redundant options"),
158  parser_errposition(pstate, defel->location)));
159  dtablespacename = defel;
160  }
161  else if (strcmp(defel->defname, "owner") == 0)
162  {
163  if (downer)
164  ereport(ERROR,
165  (errcode(ERRCODE_SYNTAX_ERROR),
166  errmsg("conflicting or redundant options"),
167  parser_errposition(pstate, defel->location)));
168  downer = defel;
169  }
170  else if (strcmp(defel->defname, "template") == 0)
171  {
172  if (dtemplate)
173  ereport(ERROR,
174  (errcode(ERRCODE_SYNTAX_ERROR),
175  errmsg("conflicting or redundant options"),
176  parser_errposition(pstate, defel->location)));
177  dtemplate = defel;
178  }
179  else if (strcmp(defel->defname, "encoding") == 0)
180  {
181  if (dencoding)
182  ereport(ERROR,
183  (errcode(ERRCODE_SYNTAX_ERROR),
184  errmsg("conflicting or redundant options"),
185  parser_errposition(pstate, defel->location)));
186  dencoding = defel;
187  }
188  else if (strcmp(defel->defname, "locale") == 0)
189  {
190  if (dlocale)
191  ereport(ERROR,
192  (errcode(ERRCODE_SYNTAX_ERROR),
193  errmsg("conflicting or redundant options"),
194  parser_errposition(pstate, defel->location)));
195  dlocale = defel;
196  }
197  else if (strcmp(defel->defname, "lc_collate") == 0)
198  {
199  if (dcollate)
200  ereport(ERROR,
201  (errcode(ERRCODE_SYNTAX_ERROR),
202  errmsg("conflicting or redundant options"),
203  parser_errposition(pstate, defel->location)));
204  dcollate = defel;
205  }
206  else if (strcmp(defel->defname, "lc_ctype") == 0)
207  {
208  if (dctype)
209  ereport(ERROR,
210  (errcode(ERRCODE_SYNTAX_ERROR),
211  errmsg("conflicting or redundant options"),
212  parser_errposition(pstate, defel->location)));
213  dctype = defel;
214  }
215  else if (strcmp(defel->defname, "is_template") == 0)
216  {
217  if (distemplate)
218  ereport(ERROR,
219  (errcode(ERRCODE_SYNTAX_ERROR),
220  errmsg("conflicting or redundant options"),
221  parser_errposition(pstate, defel->location)));
222  distemplate = defel;
223  }
224  else if (strcmp(defel->defname, "allow_connections") == 0)
225  {
226  if (dallowconnections)
227  ereport(ERROR,
228  (errcode(ERRCODE_SYNTAX_ERROR),
229  errmsg("conflicting or redundant options"),
230  parser_errposition(pstate, defel->location)));
231  dallowconnections = defel;
232  }
233  else if (strcmp(defel->defname, "connection_limit") == 0)
234  {
235  if (dconnlimit)
236  ereport(ERROR,
237  (errcode(ERRCODE_SYNTAX_ERROR),
238  errmsg("conflicting or redundant options"),
239  parser_errposition(pstate, defel->location)));
240  dconnlimit = defel;
241  }
242  else if (strcmp(defel->defname, "location") == 0)
243  {
245  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
246  errmsg("LOCATION is not supported anymore"),
247  errhint("Consider using tablespaces instead."),
248  parser_errposition(pstate, defel->location)));
249  }
250  else
251  ereport(ERROR,
252  (errcode(ERRCODE_SYNTAX_ERROR),
253  errmsg("option \"%s\" not recognized", defel->defname),
254  parser_errposition(pstate, defel->location)));
255  }
256 
257  if (dlocale && (dcollate || dctype))
258  ereport(ERROR,
259  (errcode(ERRCODE_SYNTAX_ERROR),
260  errmsg("conflicting or redundant options"),
261  errdetail("LOCALE cannot be specified together with LC_COLLATE or LC_CTYPE.")));
262 
263  if (downer && downer->arg)
264  dbowner = defGetString(downer);
265  if (dtemplate && dtemplate->arg)
266  dbtemplate = defGetString(dtemplate);
267  if (dencoding && dencoding->arg)
268  {
269  const char *encoding_name;
270 
271  if (IsA(dencoding->arg, Integer))
272  {
273  encoding = defGetInt32(dencoding);
274  encoding_name = pg_encoding_to_char(encoding);
275  if (strcmp(encoding_name, "") == 0 ||
276  pg_valid_server_encoding(encoding_name) < 0)
277  ereport(ERROR,
278  (errcode(ERRCODE_UNDEFINED_OBJECT),
279  errmsg("%d is not a valid encoding code",
280  encoding),
281  parser_errposition(pstate, dencoding->location)));
282  }
283  else
284  {
285  encoding_name = defGetString(dencoding);
286  encoding = pg_valid_server_encoding(encoding_name);
287  if (encoding < 0)
288  ereport(ERROR,
289  (errcode(ERRCODE_UNDEFINED_OBJECT),
290  errmsg("%s is not a valid encoding name",
291  encoding_name),
292  parser_errposition(pstate, dencoding->location)));
293  }
294  }
295  if (dlocale && dlocale->arg)
296  {
297  dbcollate = defGetString(dlocale);
298  dbctype = defGetString(dlocale);
299  }
300  if (dcollate && dcollate->arg)
301  dbcollate = defGetString(dcollate);
302  if (dctype && dctype->arg)
303  dbctype = defGetString(dctype);
304  if (distemplate && distemplate->arg)
305  dbistemplate = defGetBoolean(distemplate);
306  if (dallowconnections && dallowconnections->arg)
307  dballowconnections = defGetBoolean(dallowconnections);
308  if (dconnlimit && dconnlimit->arg)
309  {
310  dbconnlimit = defGetInt32(dconnlimit);
311  if (dbconnlimit < -1)
312  ereport(ERROR,
313  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
314  errmsg("invalid connection limit: %d", dbconnlimit)));
315  }
316 
317  /* obtain OID of proposed owner */
318  if (dbowner)
319  datdba = get_role_oid(dbowner, false);
320  else
321  datdba = GetUserId();
322 
323  /*
324  * To create a database, must have createdb privilege and must be able to
325  * become the target role (this does not imply that the target role itself
326  * must have createdb privilege). The latter provision guards against
327  * "giveaway" attacks. Note that a superuser will always have both of
328  * these privileges a fortiori.
329  */
331  ereport(ERROR,
332  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
333  errmsg("permission denied to create database")));
334 
336 
337  /*
338  * Lookup database (template) to be cloned, and obtain share lock on it.
339  * ShareLock allows two CREATE DATABASEs to work from the same template
340  * concurrently, while ensuring no one is busy dropping it in parallel
341  * (which would be Very Bad since we'd likely get an incomplete copy
342  * without knowing it). This also prevents any new connections from being
343  * made to the source until we finish copying it, so we can be sure it
344  * won't change underneath us.
345  */
346  if (!dbtemplate)
347  dbtemplate = "template1"; /* Default template database name */
348 
349  if (!get_db_info(dbtemplate, ShareLock,
350  &src_dboid, &src_owner, &src_encoding,
351  &src_istemplate, &src_allowconn, &src_lastsysoid,
352  &src_frozenxid, &src_minmxid, &src_deftablespace,
353  &src_collate, &src_ctype))
354  ereport(ERROR,
355  (errcode(ERRCODE_UNDEFINED_DATABASE),
356  errmsg("template database \"%s\" does not exist",
357  dbtemplate)));
358 
359  /*
360  * Permission check: to copy a DB that's not marked datistemplate, you
361  * must be superuser or the owner thereof.
362  */
363  if (!src_istemplate)
364  {
365  if (!pg_database_ownercheck(src_dboid, GetUserId()))
366  ereport(ERROR,
367  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
368  errmsg("permission denied to copy database \"%s\"",
369  dbtemplate)));
370  }
371 
372  /* If encoding or locales are defaulted, use source's setting */
373  if (encoding < 0)
374  encoding = src_encoding;
375  if (dbcollate == NULL)
376  dbcollate = src_collate;
377  if (dbctype == NULL)
378  dbctype = src_ctype;
379 
380  /* Some encodings are client only */
381  if (!PG_VALID_BE_ENCODING(encoding))
382  ereport(ERROR,
383  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
384  errmsg("invalid server encoding %d", encoding)));
385 
386  /* Check that the chosen locales are valid, and get canonical spellings */
387  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
388  ereport(ERROR,
389  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
390  errmsg("invalid locale name: \"%s\"", dbcollate)));
391  dbcollate = canonname;
392  if (!check_locale(LC_CTYPE, dbctype, &canonname))
393  ereport(ERROR,
394  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
395  errmsg("invalid locale name: \"%s\"", dbctype)));
396  dbctype = canonname;
397 
398  check_encoding_locale_matches(encoding, dbcollate, dbctype);
399 
400  /*
401  * Check that the new encoding and locale settings match the source
402  * database. We insist on this because we simply copy the source data ---
403  * any non-ASCII data would be wrongly encoded, and any indexes sorted
404  * according to the source locale would be wrong.
405  *
406  * However, we assume that template0 doesn't contain any non-ASCII data
407  * nor any indexes that depend on collation or ctype, so template0 can be
408  * used as template for creating a database with any encoding or locale.
409  */
410  if (strcmp(dbtemplate, "template0") != 0)
411  {
412  if (encoding != src_encoding)
413  ereport(ERROR,
414  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
415  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
416  pg_encoding_to_char(encoding),
417  pg_encoding_to_char(src_encoding)),
418  errhint("Use the same encoding as in the template database, or use template0 as template.")));
419 
420  if (strcmp(dbcollate, src_collate) != 0)
421  ereport(ERROR,
422  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
423  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
424  dbcollate, src_collate),
425  errhint("Use the same collation as in the template database, or use template0 as template.")));
426 
427  if (strcmp(dbctype, src_ctype) != 0)
428  ereport(ERROR,
429  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
430  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
431  dbctype, src_ctype),
432  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
433  }
434 
435  /* Resolve default tablespace for new database */
436  if (dtablespacename && dtablespacename->arg)
437  {
438  char *tablespacename;
439  AclResult aclresult;
440 
441  tablespacename = defGetString(dtablespacename);
442  dst_deftablespace = get_tablespace_oid(tablespacename, false);
443  /* check permissions */
444  aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
445  ACL_CREATE);
446  if (aclresult != ACLCHECK_OK)
448  tablespacename);
449 
450  /* pg_global must never be the default tablespace */
451  if (dst_deftablespace == GLOBALTABLESPACE_OID)
452  ereport(ERROR,
453  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
454  errmsg("pg_global cannot be used as default tablespace")));
455 
456  /*
457  * If we are trying to change the default tablespace of the template,
458  * we require that the template not have any files in the new default
459  * tablespace. This is necessary because otherwise the copied
460  * database would contain pg_class rows that refer to its default
461  * tablespace both explicitly (by OID) and implicitly (as zero), which
462  * would cause problems. For example another CREATE DATABASE using
463  * the copied database as template, and trying to change its default
464  * tablespace again, would yield outright incorrect results (it would
465  * improperly move tables to the new default tablespace that should
466  * stay in the same tablespace).
467  */
468  if (dst_deftablespace != src_deftablespace)
469  {
470  char *srcpath;
471  struct stat st;
472 
473  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
474 
475  if (stat(srcpath, &st) == 0 &&
476  S_ISDIR(st.st_mode) &&
477  !directory_is_empty(srcpath))
478  ereport(ERROR,
479  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
480  errmsg("cannot assign new default tablespace \"%s\"",
481  tablespacename),
482  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
483  dbtemplate)));
484  pfree(srcpath);
485  }
486  }
487  else
488  {
489  /* Use template database's default tablespace */
490  dst_deftablespace = src_deftablespace;
491  /* Note there is no additional permission check in this path */
492  }
493 
494  /*
495  * If built with appropriate switch, whine when regression-testing
496  * conventions for database names are violated. But don't complain during
497  * initdb.
498  */
499 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
500  if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
501  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
502 #endif
503 
504  /*
505  * Check for db name conflict. This is just to give a more friendly error
506  * message than "unique index violation". There's a race condition but
507  * we're willing to accept the less friendly message in that case.
508  */
509  if (OidIsValid(get_database_oid(dbname, true)))
510  ereport(ERROR,
511  (errcode(ERRCODE_DUPLICATE_DATABASE),
512  errmsg("database \"%s\" already exists", dbname)));
513 
514  /*
515  * The source DB can't have any active backends, except this one
516  * (exception is to allow CREATE DB while connected to template1).
517  * Otherwise we might copy inconsistent data.
518  *
519  * This should be last among the basic error checks, because it involves
520  * potential waiting; we may as well throw an error first if we're gonna
521  * throw one.
522  */
523  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
524  ereport(ERROR,
525  (errcode(ERRCODE_OBJECT_IN_USE),
526  errmsg("source database \"%s\" is being accessed by other users",
527  dbtemplate),
528  errdetail_busy_db(notherbackends, npreparedxacts)));
529 
530  /*
531  * Select an OID for the new database, checking that it doesn't have a
532  * filename conflict with anything already existing in the tablespace
533  * directories.
534  */
535  pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
536 
537  do
538  {
539  dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
540  Anum_pg_database_oid);
541  } while (check_db_file_conflict(dboid));
542 
543  /*
544  * Insert a new tuple into pg_database. This establishes our ownership of
545  * the new database name (anyone else trying to insert the same name will
546  * block on the unique index, and fail after we commit).
547  */
548 
549  /* Form tuple */
550  MemSet(new_record, 0, sizeof(new_record));
551  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
552 
553  new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
554  new_record[Anum_pg_database_datname - 1] =
556  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
557  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
558  new_record[Anum_pg_database_datcollate - 1] =
560  new_record[Anum_pg_database_datctype - 1] =
562  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
563  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
564  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
565  new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
566  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
567  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
568  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
569 
570  /*
571  * We deliberately set datacl to default (NULL), rather than copying it
572  * from the template database. Copying it would be a bad idea when the
573  * owner is not the same as the template's owner.
574  */
575  new_record_nulls[Anum_pg_database_datacl - 1] = true;
576 
577  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
578  new_record, new_record_nulls);
579 
580  CatalogTupleInsert(pg_database_rel, tuple);
581 
582  /*
583  * Now generate additional catalog entries associated with the new DB
584  */
585 
586  /* Register owner dependency */
587  recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
588 
589  /* Create pg_shdepend entries for objects within database */
590  copyTemplateDependencies(src_dboid, dboid);
591 
592  /* Post creation hook for new database */
593  InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
594 
595  /*
596  * Force a checkpoint before starting the copy. This will force all dirty
597  * buffers, including those of unlogged tables, out to disk, to ensure
598  * source database is up-to-date on disk for the copy.
599  * FlushDatabaseBuffers() would suffice for that, but we also want to
600  * process any pending unlink requests. Otherwise, if a checkpoint
601  * happened while we're copying files, a file might be deleted just when
602  * we're about to copy it, causing the lstat() call in copydir() to fail
603  * with ENOENT.
604  */
607 
608  /*
609  * Once we start copying subdirectories, we need to be able to clean 'em
610  * up if we fail. Use an ENSURE block to make sure this happens. (This
611  * is not a 100% solution, because of the possibility of failure during
612  * transaction commit after we leave this routine, but it should handle
613  * most scenarios.)
614  */
615  fparms.src_dboid = src_dboid;
616  fparms.dest_dboid = dboid;
618  PointerGetDatum(&fparms));
619  {
620  /*
621  * Iterate through all tablespaces of the template database, and copy
622  * each one to the new database.
623  */
624  rel = table_open(TableSpaceRelationId, AccessShareLock);
625  scan = table_beginscan_catalog(rel, 0, NULL);
626  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
627  {
628  Form_pg_tablespace spaceform = (Form_pg_tablespace) GETSTRUCT(tuple);
629  Oid srctablespace = spaceform->oid;
630  Oid dsttablespace;
631  char *srcpath;
632  char *dstpath;
633  struct stat st;
634 
635  /* No need to copy global tablespace */
636  if (srctablespace == GLOBALTABLESPACE_OID)
637  continue;
638 
639  srcpath = GetDatabasePath(src_dboid, srctablespace);
640 
641  if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
642  directory_is_empty(srcpath))
643  {
644  /* Assume we can ignore it */
645  pfree(srcpath);
646  continue;
647  }
648 
649  if (srctablespace == src_deftablespace)
650  dsttablespace = dst_deftablespace;
651  else
652  dsttablespace = srctablespace;
653 
654  dstpath = GetDatabasePath(dboid, dsttablespace);
655 
656  /*
657  * Copy this subdirectory to the new location
658  *
659  * We don't need to copy subdirectories
660  */
661  copydir(srcpath, dstpath, false);
662 
663  /* Record the filesystem change in XLOG */
664  {
665  xl_dbase_create_rec xlrec;
666 
667  xlrec.db_id = dboid;
668  xlrec.tablespace_id = dsttablespace;
669  xlrec.src_db_id = src_dboid;
670  xlrec.src_tablespace_id = srctablespace;
671 
672  XLogBeginInsert();
673  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
674 
675  (void) XLogInsert(RM_DBASE_ID,
677  }
678  }
679  table_endscan(scan);
681 
682  /*
683  * We force a checkpoint before committing. This effectively means
684  * that committed XLOG_DBASE_CREATE operations will never need to be
685  * replayed (at least not in ordinary crash recovery; we still have to
686  * make the XLOG entry for the benefit of PITR operations). This
687  * avoids two nasty scenarios:
688  *
689  * #1: When PITR is off, we don't XLOG the contents of newly created
690  * indexes; therefore the drop-and-recreate-whole-directory behavior
691  * of DBASE_CREATE replay would lose such indexes.
692  *
693  * #2: Since we have to recopy the source database during DBASE_CREATE
694  * replay, we run the risk of copying changes in it that were
695  * committed after the original CREATE DATABASE command but before the
696  * system crash that led to the replay. This is at least unexpected
697  * and at worst could lead to inconsistencies, eg duplicate table
698  * names.
699  *
700  * (Both of these were real bugs in releases 8.0 through 8.0.3.)
701  *
702  * In PITR replay, the first of these isn't an issue, and the second
703  * is only a risk if the CREATE DATABASE and subsequent template
704  * database change both occur while a base backup is being taken.
705  * There doesn't seem to be much we can do about that except document
706  * it as a limitation.
707  *
708  * Perhaps if we ever implement CREATE DATABASE in a less cheesy way,
709  * we can avoid this.
710  */
712 
713  /*
714  * Close pg_database, but keep lock till commit.
715  */
716  table_close(pg_database_rel, NoLock);
717 
718  /*
719  * Force synchronous commit, thus minimizing the window between
720  * creation of the database files and committal of the transaction. If
721  * we crash before committing, we'll have a DB that's taking up disk
722  * space but is not in pg_database, which is not good.
723  */
724  ForceSyncCommit();
725  }
727  PointerGetDatum(&fparms));
728 
729  return dboid;
730 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:323
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:216
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:974
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Definition: dbcommands.c:755
uint32 TransactionId
Definition: c.h:507
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:501
#define PointerGetDatum(X)
Definition: postgres.h:556
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1887
static void createdb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:793
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:269
#define AccessShareLock
Definition: lockdefs.h:36
void ForceSyncCommit(void)
Definition: xact.c:1051
int32 defGetInt32(DefElem *def)
Definition: define.c:166
int errcode(int sqlerrcode)
Definition: elog.c:570
#define MemSet(start, val, len)
Definition: c.h:955
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
bool directory_is_empty(const char *path)
Definition: tablespace.c:847
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:616
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
unsigned int Oid
Definition: postgres_ext.h:31
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
Definition: dbcommands.c:1766
#define OidIsValid(objectId)
Definition: c.h:638
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5191
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
bool defGetBoolean(DefElem *def)
Definition: define.c:111
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
char * defGetString(DefElem *def)
Definition: define.c:49
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:1979
char * dbname
Definition: parsenodes.h:3105
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
bool IsUnderPostmaster
Definition: globals.c:109
int location
Definition: parsenodes.h:733
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
#define DatabaseOidIndexId
Definition: indexing.h:146
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4954
#define CHECKPOINT_FORCE
Definition: xlog.h:215
#define ereport(elevel, rest)
Definition: elog.h:141
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
static char dstpath[MAXPGPATH]
Definition: file_ops.c:30
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
Definition: pg_shdepend.c:796
Node * arg
Definition: parsenodes.h:731
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:264
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define TransactionIdGetDatum(X)
Definition: postgres.h:521
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
#define BoolGetDatum(X)
Definition: postgres.h:402
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2052
#define CHECKPOINT_WAIT
Definition: xlog.h:219
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:607
TransactionId MultiXactId
Definition: c.h:517
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:295
#define lfirst(lc)
Definition: pg_list.h:190
char * dbname
Definition: streamutil.c:52
List * options
Definition: parsenodes.h:3106
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define XLOG_DBASE_CREATE
int32 encoding
Definition: pg_database.h:41
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
#define S_ISDIR(m)
Definition: win32_port.h:305
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
#define Int32GetDatum(X)
Definition: postgres.h:479
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define ShareLock
Definition: lockdefs.h:41
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
char * defname
Definition: parsenodes.h:730
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2907
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2022
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:183
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 793 of file dbcommands.c.

References DatumGetPointer, createdb_failure_params::dest_dboid, remove_dbtablespaces(), ShareLock, createdb_failure_params::src_dboid, and UnlockSharedObject().

Referenced by createdb().

794 {
796 
797  /*
798  * Release lock on source database before doing recursive remove. This is
799  * not essential but it seems desirable to release the lock as soon as
800  * possible.
801  */
802  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
803 
804  /* Throw away any successfully copied subdirectories */
806 }
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1912
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1025
#define DatumGetPointer(X)
Definition: postgres.h:549
#define ShareLock
Definition: lockdefs.h:41
void * arg

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 2120 of file dbcommands.c.

References AccessExclusiveLock, Assert, copydir(), xl_dbase_create_rec::db_id, xl_dbase_drop_rec::db_id, DropDatabaseBuffers(), elog, ereport, errmsg(), FlushDatabaseBuffers(), ForgetDatabaseSyncRequests(), GetDatabasePath(), InHotStandby, LockSharedObjectForSession(), PANIC, ReplicationSlotsDropDBSlots(), ResolveRecoveryConflictWithDatabase(), rmtree(), S_ISDIR, xl_dbase_create_rec::src_db_id, xl_dbase_create_rec::src_tablespace_id, stat, xl_dbase_create_rec::tablespace_id, xl_dbase_drop_rec::tablespace_id, UnlockSharedObjectForSession(), WARNING, XLOG_DBASE_CREATE, XLOG_DBASE_DROP, XLogDropDatabase(), XLogRecGetData, XLogRecGetInfo, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

2121 {
2122  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2123 
2124  /* Backup blocks are not used in dbase records */
2125  Assert(!XLogRecHasAnyBlockRefs(record));
2126 
2127  if (info == XLOG_DBASE_CREATE)
2128  {
2130  char *src_path;
2131  char *dst_path;
2132  struct stat st;
2133 
2134  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
2135  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2136 
2137  /*
2138  * Our theory for replaying a CREATE is to forcibly drop the target
2139  * subdirectory if present, then re-copy the source data. This may be
2140  * more work than needed, but it is simple to implement.
2141  */
2142  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
2143  {
2144  if (!rmtree(dst_path, true))
2145  /* If this failed, copydir() below is going to error. */
2146  ereport(WARNING,
2147  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2148  dst_path)));
2149  }
2150 
2151  /*
2152  * Force dirty buffers out to disk, to ensure source database is
2153  * up-to-date for the copy.
2154  */
2156 
2157  /*
2158  * Copy this subdirectory to the new location
2159  *
2160  * We don't need to copy subdirectories
2161  */
2162  copydir(src_path, dst_path, false);
2163  }
2164  else if (info == XLOG_DBASE_DROP)
2165  {
2166  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
2167  char *dst_path;
2168 
2169  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2170 
2171  if (InHotStandby)
2172  {
2173  /*
2174  * Lock database while we resolve conflicts to ensure that
2175  * InitPostgres() cannot fully re-execute concurrently. This
2176  * avoids backends re-connecting automatically to same database,
2177  * which can happen in some cases.
2178  *
2179  * This will lock out walsenders trying to connect to db-specific
2180  * slots for logical decoding too, so it's safe for us to drop
2181  * slots.
2182  */
2183  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2185  }
2186 
2187  /* Drop any database-specific replication slots */
2189 
2190  /* Drop pages for this database that are in the shared buffer cache */
2191  DropDatabaseBuffers(xlrec->db_id);
2192 
2193  /* Also, clean out any fsync requests that might be pending in md.c */
2195 
2196  /* Clean out the xlog relcache too */
2197  XLogDropDatabase(xlrec->db_id);
2198 
2199  /* And remove the physical files */
2200  if (!rmtree(dst_path, true))
2201  ereport(WARNING,
2202  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2203  dst_path)));
2204 
2205  if (InHotStandby)
2206  {
2207  /*
2208  * Release locks prior to commit. XXX There is a race condition
2209  * here that may allow backends to reconnect, but the window for
2210  * this is small because the gap between here and commit is mostly
2211  * fairly small and it is unlikely that people will be dropping
2212  * databases that we are trying to connect to anyway.
2213  */
2214  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2215  }
2216  }
2217  else
2218  elog(PANIC, "dbase_redo: unknown op code %u", info);
2219 }
unsigned char uint8
Definition: c.h:356
#define InHotStandby
Definition: xlog.h:74
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
#define PANIC
Definition: elog.h:53
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define XLogRecGetData(decoder)
Definition: xlogreader.h:237
#define XLOG_DBASE_DROP
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1064
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3290
#define ereport(elevel, rest)
Definition: elog.h:141
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:233
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:264
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:983
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:346
#define Assert(condition)
Definition: c.h:732
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLOG_DBASE_CREATE
#define S_ISDIR(m)
Definition: win32_port.h:305
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:617
#define elog(elevel,...)
Definition: elog.h:226
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:239
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3087
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:896

◆ dropdb()

void dropdb ( const char *  dbname,
bool  missing_ok 
)

Definition at line 813 of file dbcommands.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleDelete(), CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, CountDBSubscriptions(), CountOtherDBBackends(), DATABASEOID, DeleteSharedComments(), DeleteSharedSecurityLabel(), DropDatabaseBuffers(), dropDatabaseDependencies(), DropSetting(), elog, ereport, errcode(), errdetail_busy_db(), errdetail_plural(), errmsg(), ERROR, ForceSyncCommit(), ForgetDatabaseSyncRequests(), get_db_info(), GetUserId(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, MyDatabaseId, NoLock, NOTICE, OBJECT_DATABASE, ObjectIdGetDatum, pg_database_ownercheck(), pgstat_drop_database(), ReleaseSysCache(), remove_dbtablespaces(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), RequestCheckpoint(), RowExclusiveLock, SearchSysCache1(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by standard_ProcessUtility().

814 {
815  Oid db_id;
816  bool db_istemplate;
817  Relation pgdbrel;
818  HeapTuple tup;
819  int notherbackends;
820  int npreparedxacts;
821  int nslots,
822  nslots_active;
823  int nsubscriptions;
824 
825  /*
826  * Look up the target database's OID, and get exclusive lock on it. We
827  * need this to ensure that no new backend starts up in the target
828  * database while we are deleting it (see postinit.c), and that no one is
829  * using it as a CREATE DATABASE template or trying to delete it for
830  * themselves.
831  */
832  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
833 
834  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
835  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
836  {
837  if (!missing_ok)
838  {
839  ereport(ERROR,
840  (errcode(ERRCODE_UNDEFINED_DATABASE),
841  errmsg("database \"%s\" does not exist", dbname)));
842  }
843  else
844  {
845  /* Close pg_database, release the lock, since we changed nothing */
846  table_close(pgdbrel, RowExclusiveLock);
847  ereport(NOTICE,
848  (errmsg("database \"%s\" does not exist, skipping",
849  dbname)));
850  return;
851  }
852  }
853 
854  /*
855  * Permission checks
856  */
857  if (!pg_database_ownercheck(db_id, GetUserId()))
859  dbname);
860 
861  /* DROP hook for the database being removed */
862  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
863 
864  /*
865  * Disallow dropping a DB that is marked istemplate. This is just to
866  * prevent people from accidentally dropping template0 or template1; they
867  * can do so if they're really determined ...
868  */
869  if (db_istemplate)
870  ereport(ERROR,
871  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
872  errmsg("cannot drop a template database")));
873 
874  /* Obviously can't drop my own database */
875  if (db_id == MyDatabaseId)
876  ereport(ERROR,
877  (errcode(ERRCODE_OBJECT_IN_USE),
878  errmsg("cannot drop the currently open database")));
879 
880  /*
881  * Check whether there are active logical slots that refer to the
882  * to-be-dropped database. The database lock we are holding prevents the
883  * creation of new slots using the database or existing slots becoming
884  * active.
885  */
886  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
887  if (nslots_active)
888  {
889  ereport(ERROR,
890  (errcode(ERRCODE_OBJECT_IN_USE),
891  errmsg("database \"%s\" is used by an active logical replication slot",
892  dbname),
893  errdetail_plural("There is %d active slot.",
894  "There are %d active slots.",
895  nslots_active, nslots_active)));
896  }
897 
898  /*
899  * Check for other backends in the target database. (Because we hold the
900  * database lock, no new ones can start after this.)
901  *
902  * As in CREATE DATABASE, check this after other error conditions.
903  */
904  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
905  ereport(ERROR,
906  (errcode(ERRCODE_OBJECT_IN_USE),
907  errmsg("database \"%s\" is being accessed by other users",
908  dbname),
909  errdetail_busy_db(notherbackends, npreparedxacts)));
910 
911  /*
912  * Check if there are subscriptions defined in the target database.
913  *
914  * We can't drop them automatically because they might be holding
915  * resources in other databases/instances.
916  */
917  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
918  ereport(ERROR,
919  (errcode(ERRCODE_OBJECT_IN_USE),
920  errmsg("database \"%s\" is being used by logical replication subscription",
921  dbname),
922  errdetail_plural("There is %d subscription.",
923  "There are %d subscriptions.",
924  nsubscriptions, nsubscriptions)));
925 
926  /*
927  * Remove the database's tuple from pg_database.
928  */
930  if (!HeapTupleIsValid(tup))
931  elog(ERROR, "cache lookup failed for database %u", db_id);
932 
933  CatalogTupleDelete(pgdbrel, &tup->t_self);
934 
935  ReleaseSysCache(tup);
936 
937  /*
938  * Delete any comments or security labels associated with the database.
939  */
940  DeleteSharedComments(db_id, DatabaseRelationId);
941  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
942 
943  /*
944  * Remove settings associated with this database
945  */
946  DropSetting(db_id, InvalidOid);
947 
948  /*
949  * Remove shared dependency references for the database.
950  */
952 
953  /*
954  * Drop db-specific replication slots.
955  */
957 
958  /*
959  * Drop pages for this database that are in the shared buffer cache. This
960  * is important to ensure that no remaining backend tries to write out a
961  * dirty buffer to the dead database later...
962  */
963  DropDatabaseBuffers(db_id);
964 
965  /*
966  * Tell the stats collector to forget it immediately, too.
967  */
968  pgstat_drop_database(db_id);
969 
970  /*
971  * Tell checkpointer to forget any pending fsync and unlink requests for
972  * files in the database; else the fsyncs will fail at next checkpoint, or
973  * worse, it will delete files that belong to a newly created database
974  * with the same OID.
975  */
977 
978  /*
979  * Force a checkpoint to make sure the checkpointer has received the
980  * message sent by ForgetDatabaseSyncRequests. On Windows, this also
981  * ensures that background procs don't hold any open files, which would
982  * cause rmdir() to fail.
983  */
985 
986  /*
987  * Remove all tablespace subdirs belonging to the database.
988  */
989  remove_dbtablespaces(db_id);
990 
991  /*
992  * Close pg_database, but keep lock till commit.
993  */
994  table_close(pgdbrel, NoLock);
995 
996  /*
997  * Force synchronous commit, thus minimizing the window between removal of
998  * the database files and committal of the transaction. If we crash before
999  * committing, we'll have a DB that's gone on disk but still there
1000  * according to pg_database, which is not good.
1001  */
1002  ForceSyncCommit();
1003 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid GetUserId(void)
Definition: miscinit.c:380
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
int CountDBSubscriptions(Oid dbid)
void ForceSyncCommit(void)
Definition: xact.c:1051
int errcode(int sqlerrcode)
Definition: elog.c:570
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1912
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
unsigned int Oid
Definition: postgres_ext.h:31
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
Definition: dbcommands.c:1766
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CHECKPOINT_FORCE
Definition: xlog.h:215
#define ereport(elevel, rest)
Definition: elog.h:141
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
void pgstat_drop_database(Oid databaseid)
Definition: pgstat.c:1255
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:860
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:983
#define NOTICE
Definition: elog.h:37
#define CHECKPOINT_WAIT
Definition: xlog.h:219
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:373
char * dbname
Definition: streamutil.c:52
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:952
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:840
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:414
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2907
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2022
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void DropSetting(Oid databaseid, Oid roleid)
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3087
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:896
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 2022 of file dbcommands.c.

References errdetail(), and errdetail_plural().

Referenced by createdb(), dropdb(), movedb(), and RenameDatabase().

2023 {
2024  if (notherbackends > 0 && npreparedxacts > 0)
2025 
2026  /*
2027  * We don't deal with singular versus plural here, since gettext
2028  * doesn't support multiple plurals in one string.
2029  */
2030  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2031  notherbackends, npreparedxacts);
2032  else if (notherbackends > 0)
2033  errdetail_plural("There is %d other session using the database.",
2034  "There are %d other sessions using the database.",
2035  notherbackends,
2036  notherbackends);
2037  else
2038  errdetail_plural("There is %d prepared transaction using the database.",
2039  "There are %d prepared transactions using the database.",
2040  npreparedxacts,
2041  npreparedxacts);
2042  return 0; /* just to keep ereport macro happy */
2043 }
int errdetail(const char *fmt,...)
Definition: elog.c:860
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:952

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 2099 of file dbcommands.c.

References DATABASEOID, datname, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), and SearchSysCache1().

Referenced by AfterTriggerSetState(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), calculate_database_size(), CreateProceduralLanguage(), CreatePublication(), CreateSchemaCommand(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), exec_object_restorecon(), ExpandColumnRefStar(), GetNewMultiXactId(), GetNewTransactionId(), getObjectDescription(), getObjectIdentityParts(), heap_vacuum_rel(), IdentifySystem(), InitTempTableNamespace(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), perform_work_item(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RenameSchema(), SetMultiXactIdLimit(), SetTransactionIdLimit(), shdepLockAndCheckObject(), and transformColumnRef().

2100 {
2101  HeapTuple dbtuple;
2102  char *result;
2103 
2104  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2105  if (HeapTupleIsValid(dbtuple))
2106  {
2107  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2108  ReleaseSysCache(dbtuple);
2109  }
2110  else
2111  result = NULL;
2112 
2113  return result;
2114 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
char * pstrdup(const char *in)
Definition: mcxt.c:1161
NameData datname
Definition: pg_database.h:35
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define NameStr(name)
Definition: c.h:609

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 2052 of file dbcommands.c.

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum, DatabaseNameIndexId, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, InvalidOid, OidIsValid, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by AlterDatabaseSet(), AlterRoleSet(), CommentObject(), convert_database_name(), createdb(), get_object_address_unqualified(), objectNamesToOids(), pg_database_size_name(), RenameDatabase(), and sepgsql_database_post_create().

2053 {
2054  Relation pg_database;
2055  ScanKeyData entry[1];
2056  SysScanDesc scan;
2057  HeapTuple dbtuple;
2058  Oid oid;
2059 
2060  /*
2061  * There's no syscache for pg_database indexed by name, so we must look
2062  * the hard way.
2063  */
2064  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2065  ScanKeyInit(&entry[0],
2066  Anum_pg_database_datname,
2067  BTEqualStrategyNumber, F_NAMEEQ,
2069  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2070  NULL, 1, entry);
2071 
2072  dbtuple = systable_getnext(scan);
2073 
2074  /* We assume that there can be at most one matching tuple */
2075  if (HeapTupleIsValid(dbtuple))
2076  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2077  else
2078  oid = InvalidOid;
2079 
2080  systable_endscan(scan);
2081  table_close(pg_database, AccessShareLock);
2082 
2083  if (!OidIsValid(oid) && !missing_ok)
2084  ereport(ERROR,
2085  (errcode(ERRCODE_UNDEFINED_DATABASE),
2086  errmsg("database \"%s\" does not exist",
2087  dbname)));
2088 
2089  return oid;
2090 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:578
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
char * dbname
Definition: streamutil.c:52
#define DatabaseNameIndexId
Definition: indexing.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ get_db_info()

static bool get_db_info ( const char *  name,
LOCKMODE  lockmode,
Oid dbIdP,
Oid ownerIdP,
int *  encodingP,
bool dbIsTemplateP,
bool dbAllowConnP,
Oid dbLastSysOidP,
TransactionId dbFrozenXidP,
MultiXactId dbMinMultiP,
Oid dbTablespace,
char **  dbCollate,
char **  dbCtype 
)
static

Definition at line 1766 of file dbcommands.c.

References AccessShareLock, AssertArg, BTEqualStrategyNumber, CStringGetDatum, DatabaseNameIndexId, DATABASEOID, GETSTRUCT, HeapTupleIsValid, LockSharedObject(), NameStr, NoLock, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), ScanKeyInit(), SearchSysCache1(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and UnlockSharedObject().

Referenced by createdb(), dropdb(), movedb(), and RenameDatabase().

1772 {
1773  bool result = false;
1774  Relation relation;
1775 
1776  AssertArg(name);
1777 
1778  /* Caller may wish to grab a better lock on pg_database beforehand... */
1779  relation = table_open(DatabaseRelationId, AccessShareLock);
1780 
1781  /*
1782  * Loop covers the rare case where the database is renamed before we can
1783  * lock it. We try again just in case we can find a new one of the same
1784  * name.
1785  */
1786  for (;;)
1787  {
1788  ScanKeyData scanKey;
1789  SysScanDesc scan;
1790  HeapTuple tuple;
1791  Oid dbOid;
1792 
1793  /*
1794  * there's no syscache for database-indexed-by-name, so must do it the
1795  * hard way
1796  */
1797  ScanKeyInit(&scanKey,
1798  Anum_pg_database_datname,
1799  BTEqualStrategyNumber, F_NAMEEQ,
1801 
1802  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
1803  NULL, 1, &scanKey);
1804 
1805  tuple = systable_getnext(scan);
1806 
1807  if (!HeapTupleIsValid(tuple))
1808  {
1809  /* definitely no database of that name */
1810  systable_endscan(scan);
1811  break;
1812  }
1813 
1814  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
1815 
1816  systable_endscan(scan);
1817 
1818  /*
1819  * Now that we have a database OID, we can try to lock the DB.
1820  */
1821  if (lockmode != NoLock)
1822  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1823 
1824  /*
1825  * And now, re-fetch the tuple by OID. If it's still there and still
1826  * the same name, we win; else, drop the lock and loop back to try
1827  * again.
1828  */
1829  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
1830  if (HeapTupleIsValid(tuple))
1831  {
1832  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1833 
1834  if (strcmp(name, NameStr(dbform->datname)) == 0)
1835  {
1836  /* oid of the database */
1837  if (dbIdP)
1838  *dbIdP = dbOid;
1839  /* oid of the owner */
1840  if (ownerIdP)
1841  *ownerIdP = dbform->datdba;
1842  /* character encoding */
1843  if (encodingP)
1844  *encodingP = dbform->encoding;
1845  /* allowed as template? */
1846  if (dbIsTemplateP)
1847  *dbIsTemplateP = dbform->datistemplate;
1848  /* allowing connections? */
1849  if (dbAllowConnP)
1850  *dbAllowConnP = dbform->datallowconn;
1851  /* last system OID used in database */
1852  if (dbLastSysOidP)
1853  *dbLastSysOidP = dbform->datlastsysoid;
1854  /* limit of frozen XIDs */
1855  if (dbFrozenXidP)
1856  *dbFrozenXidP = dbform->datfrozenxid;
1857  /* minimum MultiXactId */
1858  if (dbMinMultiP)
1859  *dbMinMultiP = dbform->datminmxid;
1860  /* default tablespace for this database */
1861  if (dbTablespace)
1862  *dbTablespace = dbform->dattablespace;
1863  /* default locale settings for this database */
1864  if (dbCollate)
1865  *dbCollate = pstrdup(NameStr(dbform->datcollate));
1866  if (dbCtype)
1867  *dbCtype = pstrdup(NameStr(dbform->datctype));
1868  ReleaseSysCache(tuple);
1869  result = true;
1870  break;
1871  }
1872  /* can only get here if it was just renamed */
1873  ReleaseSysCache(tuple);
1874  }
1875 
1876  if (lockmode != NoLock)
1877  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1878  }
1879 
1880  table_close(relation, AccessShareLock);
1881 
1882  return result;
1883 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1025
#define NoLock
Definition: lockdefs.h:34
#define CStringGetDatum(X)
Definition: postgres.h:578
#define AssertArg(condition)
Definition: c.h:734
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1004
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define DatabaseNameIndexId
Definition: indexing.h:144
const char * name
Definition: encode.c:521
#define NameStr(name)
Definition: c.h:609
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ have_createdb_privilege()

static bool have_createdb_privilege ( void  )
static

Definition at line 1887 of file dbcommands.c.

References AUTHOID, GETSTRUCT, GetUserId(), HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), rolcreatedb, SearchSysCache1(), and superuser().

Referenced by AlterDatabaseOwner(), createdb(), and RenameDatabase().

1888 {
1889  bool result = false;
1890  HeapTuple utup;
1891 
1892  /* Superusers can always do everything */
1893  if (superuser())
1894  return true;
1895 
1897  if (HeapTupleIsValid(utup))
1898  {
1899  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
1900  ReleaseSysCache(utup);
1901  }
1902  return result;
1903 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:380
bool superuser(void)
Definition: superuser.c:47
bool rolcreatedb
Definition: pg_authid.h:38
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1124
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ movedb()

static void movedb ( const char *  dbname,
const char *  tblspcname 
)
static

Definition at line 1108 of file dbcommands.c.

References AccessExclusiveLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AllocateDir(), BTEqualStrategyNumber, CatalogTupleUpdate(), CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, CommitTransactionCommand(), copydir(), CountOtherDBBackends(), CStringGetDatum, dirent::d_name, DatabaseNameIndexId, xl_dbase_create_rec::db_id, xl_dbase_drop_rec::db_id, movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, DropDatabaseBuffers(), elog, ereport, errcode(), errdetail_busy_db(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FreeDir(), get_db_info(), get_tablespace_oid(), GetDatabasePath(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, LockSharedObjectForSession(), MemSet, movedb_failure_callback(), MyDatabaseId, NoLock, OBJECT_DATABASE, OBJECT_TABLESPACE, ObjectIdGetDatum, pg_database_ownercheck(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_tablespace_aclcheck(), PointerGetDatum, PopActiveSnapshot(), ReadDir(), RelationGetDescr, RequestCheckpoint(), rmtree(), RowExclusiveLock, ScanKeyInit(), xl_dbase_create_rec::src_db_id, xl_dbase_create_rec::src_tablespace_id, StartTransactionCommand(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), xl_dbase_create_rec::tablespace_id, xl_dbase_drop_rec::tablespace_id, UnlockSharedObjectForSession(), WARNING, XLOG_DBASE_CREATE, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by AlterDatabase().

1109 {
1110  Oid db_id;
1111  Relation pgdbrel;
1112  int notherbackends;
1113  int npreparedxacts;
1114  HeapTuple oldtuple,
1115  newtuple;
1116  Oid src_tblspcoid,
1117  dst_tblspcoid;
1118  Datum new_record[Natts_pg_database];
1119  bool new_record_nulls[Natts_pg_database];
1120  bool new_record_repl[Natts_pg_database];
1121  ScanKeyData scankey;
1122  SysScanDesc sysscan;
1123  AclResult aclresult;
1124  char *src_dbpath;
1125  char *dst_dbpath;
1126  DIR *dstdir;
1127  struct dirent *xlde;
1128  movedb_failure_params fparms;
1129 
1130  /*
1131  * Look up the target database's OID, and get exclusive lock on it. We
1132  * need this to ensure that no new backend starts up in the database while
1133  * we are moving it, and that no one is using it as a CREATE DATABASE
1134  * template or trying to delete it.
1135  */
1136  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1137 
1138  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1139  NULL, NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL))
1140  ereport(ERROR,
1141  (errcode(ERRCODE_UNDEFINED_DATABASE),
1142  errmsg("database \"%s\" does not exist", dbname)));
1143 
1144  /*
1145  * We actually need a session lock, so that the lock will persist across
1146  * the commit/restart below. (We could almost get away with letting the
1147  * lock be released at commit, except that someone could try to move
1148  * relations of the DB back into the old directory while we rmtree() it.)
1149  */
1150  LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1152 
1153  /*
1154  * Permission checks
1155  */
1156  if (!pg_database_ownercheck(db_id, GetUserId()))
1158  dbname);
1159 
1160  /*
1161  * Obviously can't move the tables of my own database
1162  */
1163  if (db_id == MyDatabaseId)
1164  ereport(ERROR,
1165  (errcode(ERRCODE_OBJECT_IN_USE),
1166  errmsg("cannot change the tablespace of the currently open database")));
1167 
1168  /*
1169  * Get tablespace's oid
1170  */
1171  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1172 
1173  /*
1174  * Permission checks
1175  */
1176  aclresult = pg_tablespace_aclcheck(dst_tblspcoid, GetUserId(),
1177  ACL_CREATE);
1178  if (aclresult != ACLCHECK_OK)
1179  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1180  tblspcname);
1181 
1182  /*
1183  * pg_global must never be the default tablespace
1184  */
1185  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1186  ereport(ERROR,
1187  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1188  errmsg("pg_global cannot be used as default tablespace")));
1189 
1190  /*
1191  * No-op if same tablespace
1192  */
1193  if (src_tblspcoid == dst_tblspcoid)
1194  {
1195  table_close(pgdbrel, NoLock);
1196  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1198  return;
1199  }
1200 
1201  /*
1202  * Check for other backends in the target database. (Because we hold the
1203  * database lock, no new ones can start after this.)
1204  *
1205  * As in CREATE DATABASE, check this after other error conditions.
1206  */
1207  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1208  ereport(ERROR,
1209  (errcode(ERRCODE_OBJECT_IN_USE),
1210  errmsg("database \"%s\" is being accessed by other users",
1211  dbname),
1212  errdetail_busy_db(notherbackends, npreparedxacts)));
1213 
1214  /*
1215  * Get old and new database paths
1216  */
1217  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1218  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1219 
1220  /*
1221  * Force a checkpoint before proceeding. This will force all dirty
1222  * buffers, including those of unlogged tables, out to disk, to ensure
1223  * source database is up-to-date on disk for the copy.
1224  * FlushDatabaseBuffers() would suffice for that, but we also want to
1225  * process any pending unlink requests. Otherwise, the check for existing
1226  * files in the target directory might fail unnecessarily, not to mention
1227  * that the copy might fail due to source files getting deleted under it.
1228  * On Windows, this also ensures that background procs don't hold any open
1229  * files, which would cause rmdir() to fail.
1230  */
1233 
1234  /*
1235  * Now drop all buffers holding data of the target database; they should
1236  * no longer be dirty so DropDatabaseBuffers is safe.
1237  *
1238  * It might seem that we could just let these buffers age out of shared
1239  * buffers naturally, since they should not get referenced anymore. The
1240  * problem with that is that if the user later moves the database back to
1241  * its original tablespace, any still-surviving buffers would appear to
1242  * contain valid data again --- but they'd be missing any changes made in
1243  * the database while it was in the new tablespace. In any case, freeing
1244  * buffers that should never be used again seems worth the cycles.
1245  *
1246  * Note: it'd be sufficient to get rid of buffers matching db_id and
1247  * src_tblspcoid, but bufmgr.c presently provides no API for that.
1248  */
1249  DropDatabaseBuffers(db_id);
1250 
1251  /*
1252  * Check for existence of files in the target directory, i.e., objects of
1253  * this database that are already in the target tablespace. We can't
1254  * allow the move in such a case, because we would need to change those
1255  * relations' pg_class.reltablespace entries to zero, and we don't have
1256  * access to the DB's pg_class to do so.
1257  */
1258  dstdir = AllocateDir(dst_dbpath);
1259  if (dstdir != NULL)
1260  {
1261  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1262  {
1263  if (strcmp(xlde->d_name, ".") == 0 ||
1264  strcmp(xlde->d_name, "..") == 0)
1265  continue;
1266 
1267  ereport(ERROR,
1268  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1269  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1270  dbname, tblspcname),
1271  errhint("You must move them back to the database's default tablespace before using this command.")));
1272  }
1273 
1274  FreeDir(dstdir);
1275 
1276  /*
1277  * The directory exists but is empty. We must remove it before using
1278  * the copydir function.
1279  */
1280  if (rmdir(dst_dbpath) != 0)
1281  elog(ERROR, "could not remove directory \"%s\": %m",
1282  dst_dbpath);
1283  }
1284 
1285  /*
1286  * Use an ENSURE block to make sure we remove the debris if the copy fails
1287  * (eg, due to out-of-disk-space). This is not a 100% solution, because
1288  * of the possibility of failure during transaction commit, but it should
1289  * handle most scenarios.
1290  */
1291  fparms.dest_dboid = db_id;
1292  fparms.dest_tsoid = dst_tblspcoid;
1294  PointerGetDatum(&fparms));
1295  {
1296  /*
1297  * Copy files from the old tablespace to the new one
1298  */
1299  copydir(src_dbpath, dst_dbpath, false);
1300 
1301  /*
1302  * Record the filesystem change in XLOG
1303  */
1304  {
1305  xl_dbase_create_rec xlrec;
1306 
1307  xlrec.db_id = db_id;
1308  xlrec.tablespace_id = dst_tblspcoid;
1309  xlrec.src_db_id = db_id;
1310  xlrec.src_tablespace_id = src_tblspcoid;
1311 
1312  XLogBeginInsert();
1313  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
1314 
1315  (void) XLogInsert(RM_DBASE_ID,
1317  }
1318 
1319  /*
1320  * Update the database's pg_database tuple
1321  */
1322  ScanKeyInit(&scankey,
1323  Anum_pg_database_datname,
1324  BTEqualStrategyNumber, F_NAMEEQ,
1326  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
1327  NULL, 1, &scankey);
1328  oldtuple = systable_getnext(sysscan);
1329  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
1330  ereport(ERROR,
1331  (errcode(ERRCODE_UNDEFINED_DATABASE),
1332  errmsg("database \"%s\" does not exist", dbname)));
1333 
1334  MemSet(new_record, 0, sizeof(new_record));
1335  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1336  MemSet(new_record_repl, false, sizeof(new_record_repl));
1337 
1338  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
1339  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
1340 
1341  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
1342  new_record,
1343  new_record_nulls, new_record_repl);
1344  CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
1345 
1346  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1347 
1348  systable_endscan(sysscan);
1349 
1350  /*
1351  * Force another checkpoint here. As in CREATE DATABASE, this is to
1352  * ensure that we don't have to replay a committed XLOG_DBASE_CREATE
1353  * operation, which would cause us to lose any unlogged operations
1354  * done in the new DB tablespace before the next checkpoint.
1355  */
1357 
1358  /*
1359  * Force synchronous commit, thus minimizing the window between
1360  * copying the database files and committal of the transaction. If we
1361  * crash before committing, we'll leave an orphaned set of files on
1362  * disk, which is not fatal but not good either.
1363  */
1364  ForceSyncCommit();
1365 
1366  /*
1367  * Close pg_database, but keep lock till commit.
1368  */
1369  table_close(pgdbrel, NoLock);
1370  }
1372  PointerGetDatum(&fparms));
1373 
1374  /*
1375  * Commit the transaction so that the pg_database update is committed. If
1376  * we crash while removing files, the database won't be corrupt, we'll
1377  * just leave some orphaned files in the old directory.
1378  *
1379  * (This is OK because we know we aren't inside a transaction block.)
1380  *
1381  * XXX would it be safe/better to do this inside the ensure block? Not
1382  * convinced it's a good idea; consider elog just after the transaction
1383  * really commits.
1384  */
1387 
1388  /* Start new transaction for the remaining work; don't need a snapshot */
1390 
1391  /*
1392  * Remove files from the old tablespace
1393  */
1394  if (!rmtree(src_dbpath, true))
1395  ereport(WARNING,
1396  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1397  src_dbpath)));
1398 
1399  /*
1400  * Record the filesystem change in XLOG
1401  */
1402  {
1403  xl_dbase_drop_rec xlrec;
1404 
1405  xlrec.db_id = db_id;
1406  xlrec.tablespace_id = src_tblspcoid;
1407 
1408  XLogBeginInsert();
1409  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1410 
1411  (void) XLogInsert(RM_DBASE_ID,
1413  }
1414 
1415  /* Now it's safe to release the database lock */
1416  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1418 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:216
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:974
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:525
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
#define PointerGetDatum(X)
Definition: postgres.h:556
void CommitTransactionCommand(void)
Definition: xact.c:2895
void ForceSyncCommit(void)
Definition: xact.c:1051
int errcode(int sqlerrcode)
Definition: elog.c:570
#define MemSet(start, val, len)
Definition: c.h:955
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
unsigned int Oid
Definition: postgres_ext.h:31
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
Definition: dbcommands.c:1766
Definition: dirent.h:9
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1422
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:352
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:444
Definition: dirent.c:25
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:84
#define XLOG_DBASE_DROP
ItemPointerData t_self
Definition: htup.h:65
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1064
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2468
#define CHECKPOINT_FORCE
Definition: xlog.h:215
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
Oid MyDatabaseId
Definition: globals.c:85
#define CHECKPOINT_WAIT
Definition: xlog.h:219
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2534
void StartTransactionCommand(void)
Definition: xact.c:2794
char * dbname
Definition: streamutil.c:52
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define XLOG_DBASE_CREATE
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
#define DatabaseNameIndexId
Definition: indexing.h:144
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2907
char d_name[MAX_PATH]
Definition: dirent.h:14
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2022
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void XLogBeginInsert(void)
Definition: xloginsert.c:120
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3087
#define BTEqualStrategyNumber
Definition: stratnum.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2586
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952

◆ movedb_failure_callback()

static void movedb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1422 of file dbcommands.c.

References DatumGetPointer, movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, dstpath, GetDatabasePath(), and rmtree().

Referenced by movedb().

1423 {
1425  char *dstpath;
1426 
1427  /* Get rid of anything we managed to copy to the target directory */
1428  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
1429 
1430  (void) rmtree(dstpath, true);
1431 }
static char dstpath[MAXPGPATH]
Definition: file_ops.c:30
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
#define DatumGetPointer(X)
Definition: postgres.h:549
void * arg

◆ remove_dbtablespaces()

static void remove_dbtablespaces ( Oid  db_id)
static

Definition at line 1912 of file dbcommands.c.

References AccessShareLock, xl_dbase_drop_rec::db_id, dstpath, ereport, errmsg(), ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), lstat, pfree(), rmtree(), S_ISDIR, stat, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), xl_dbase_drop_rec::tablespace_id, WARNING, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by createdb_failure_callback(), and dropdb().

1913 {
1914  Relation rel;
1915  TableScanDesc scan;
1916  HeapTuple tuple;
1917 
1918  rel = table_open(TableSpaceRelationId, AccessShareLock);
1919  scan = table_beginscan_catalog(rel, 0, NULL);
1920  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1921  {
1922  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
1923  Oid dsttablespace = spcform->oid;
1924  char *dstpath;
1925  struct stat st;
1926 
1927  /* Don't mess with the global tablespace */
1928  if (dsttablespace == GLOBALTABLESPACE_OID)
1929  continue;
1930 
1931  dstpath = GetDatabasePath(db_id, dsttablespace);
1932 
1933  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1934  {
1935  /* Assume we can ignore it */
1936  pfree(dstpath);
1937  continue;
1938  }
1939 
1940  if (!rmtree(dstpath, true))
1941  ereport(WARNING,
1942  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1943  dstpath)));
1944 
1945  /* Record the filesystem change in XLOG */
1946  {
1947  xl_dbase_drop_rec xlrec;
1948 
1949  xlrec.db_id = db_id;
1950  xlrec.tablespace_id = dsttablespace;
1951 
1952  XLogBeginInsert();
1953  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1954 
1955  (void) XLogInsert(RM_DBASE_ID,
1957  }
1958 
1959  pfree(dstpath);
1960  }
1961 
1962  table_endscan(scan);
1964 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1031
#define XLOG_DBASE_DROP
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
#define ereport(elevel, rest)
Definition: elog.h:141
static char dstpath[MAXPGPATH]
Definition: file_ops.c:30
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:264
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define S_ISDIR(m)
Definition: win32_port.h:305
#define lstat(path, sb)
Definition: win32_port.h:253
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
int errmsg(const char *fmt,...)
Definition: elog.c:784
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120

◆ RenameDatabase()

ObjectAddress RenameDatabase ( const char *  oldname,
const char *  newname 
)

Definition at line 1010 of file dbcommands.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), CountOtherDBBackends(), DATABASEOID, datname, elog, ereport, errcode(), errdetail_busy_db(), errmsg(), ERROR, get_database_oid(), get_db_info(), GETSTRUCT, GetUserId(), have_createdb_privilege(), HeapTupleIsValid, InvokeObjectPostAlterHook, MyDatabaseId, namestrcpy(), NoLock, OBJECT_DATABASE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, pg_database_ownercheck(), RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), table_open(), and WARNING.

Referenced by ExecRenameStmt().

1011 {
1012  Oid db_id;
1013  HeapTuple newtup;
1014  Relation rel;
1015  int notherbackends;
1016  int npreparedxacts;
1017  ObjectAddress address;
1018 
1019  /*
1020  * Look up the target database's OID, and get exclusive lock on it. We
1021  * need this for the same reasons as DROP DATABASE.
1022  */
1023  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1024 
1025  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1026  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1027  ereport(ERROR,
1028  (errcode(ERRCODE_UNDEFINED_DATABASE),
1029  errmsg("database \"%s\" does not exist", oldname)));
1030 
1031  /* must be owner */
1032  if (!pg_database_ownercheck(db_id, GetUserId()))
1034  oldname);
1035 
1036  /* must have createdb rights */
1037  if (!have_createdb_privilege())
1038  ereport(ERROR,
1039  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1040  errmsg("permission denied to rename database")));
1041 
1042  /*
1043  * If built with appropriate switch, whine when regression-testing
1044  * conventions for database names are violated.
1045  */
1046 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1047  if (strstr(newname, "regression") == NULL)
1048  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1049 #endif
1050 
1051  /*
1052  * Make sure the new name doesn't exist. See notes for same error in
1053  * CREATE DATABASE.
1054  */
1055  if (OidIsValid(get_database_oid(newname, true)))
1056  ereport(ERROR,
1057  (errcode(ERRCODE_DUPLICATE_DATABASE),
1058  errmsg("database \"%s\" already exists", newname)));
1059 
1060  /*
1061  * XXX Client applications probably store the current database somewhere,
1062  * so renaming it could cause confusion. On the other hand, there may not
1063  * be an actual problem besides a little confusion, so think about this
1064  * and decide.
1065  */
1066  if (db_id == MyDatabaseId)
1067  ereport(ERROR,
1068  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1069  errmsg("current database cannot be renamed")));
1070 
1071  /*
1072  * Make sure the database does not have active sessions. This is the same
1073  * concern as above, but applied to other sessions.
1074  *
1075  * As in CREATE DATABASE, check this after other error conditions.
1076  */
1077  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1078  ereport(ERROR,
1079  (errcode(ERRCODE_OBJECT_IN_USE),
1080  errmsg("database \"%s\" is being accessed by other users",
1081  oldname),
1082  errdetail_busy_db(notherbackends, npreparedxacts)));
1083 
1084  /* rename */
1086  if (!HeapTupleIsValid(newtup))
1087  elog(ERROR, "cache lookup failed for database %u", db_id);
1088  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1089  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1090 
1091  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1092 
1093  ObjectAddressSet(address, DatabaseRelationId, db_id);
1094 
1095  /*
1096  * Close pg_database, but keep lock till commit.
1097  */
1098  table_close(rel, NoLock);
1099 
1100  return address;
1101 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:380
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1887
int errcode(int sqlerrcode)
Definition: elog.c:570
NameData datname
Definition: pg_database.h:35
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:250
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
Definition: dbcommands.c:1766
#define OidIsValid(objectId)
Definition: c.h:638
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5173
#define WARNING
Definition: elog.h:40
Oid MyDatabaseId
Definition: globals.c:85
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2052
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2907
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2022
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39