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/multixact.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 1439 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().

1440 {
1441  Relation rel;
1442  Oid dboid;
1443  HeapTuple tuple,
1444  newtuple;
1445  Form_pg_database datform;
1446  ScanKeyData scankey;
1447  SysScanDesc scan;
1448  ListCell *option;
1449  bool dbistemplate = false;
1450  bool dballowconnections = true;
1451  int dbconnlimit = -1;
1452  DefElem *distemplate = NULL;
1453  DefElem *dallowconnections = NULL;
1454  DefElem *dconnlimit = NULL;
1455  DefElem *dtablespace = NULL;
1456  Datum new_record[Natts_pg_database];
1457  bool new_record_nulls[Natts_pg_database];
1458  bool new_record_repl[Natts_pg_database];
1459 
1460  /* Extract options from the statement node tree */
1461  foreach(option, stmt->options)
1462  {
1463  DefElem *defel = (DefElem *) lfirst(option);
1464 
1465  if (strcmp(defel->defname, "is_template") == 0)
1466  {
1467  if (distemplate)
1468  ereport(ERROR,
1469  (errcode(ERRCODE_SYNTAX_ERROR),
1470  errmsg("conflicting or redundant options"),
1471  parser_errposition(pstate, defel->location)));
1472  distemplate = defel;
1473  }
1474  else if (strcmp(defel->defname, "allow_connections") == 0)
1475  {
1476  if (dallowconnections)
1477  ereport(ERROR,
1478  (errcode(ERRCODE_SYNTAX_ERROR),
1479  errmsg("conflicting or redundant options"),
1480  parser_errposition(pstate, defel->location)));
1481  dallowconnections = defel;
1482  }
1483  else if (strcmp(defel->defname, "connection_limit") == 0)
1484  {
1485  if (dconnlimit)
1486  ereport(ERROR,
1487  (errcode(ERRCODE_SYNTAX_ERROR),
1488  errmsg("conflicting or redundant options"),
1489  parser_errposition(pstate, defel->location)));
1490  dconnlimit = defel;
1491  }
1492  else if (strcmp(defel->defname, "tablespace") == 0)
1493  {
1494  if (dtablespace)
1495  ereport(ERROR,
1496  (errcode(ERRCODE_SYNTAX_ERROR),
1497  errmsg("conflicting or redundant options"),
1498  parser_errposition(pstate, defel->location)));
1499  dtablespace = defel;
1500  }
1501  else
1502  ereport(ERROR,
1503  (errcode(ERRCODE_SYNTAX_ERROR),
1504  errmsg("option \"%s\" not recognized", defel->defname),
1505  parser_errposition(pstate, defel->location)));
1506  }
1507 
1508  if (dtablespace)
1509  {
1510  /*
1511  * While the SET TABLESPACE syntax doesn't allow any other options,
1512  * somebody could write "WITH TABLESPACE ...". Forbid any other
1513  * options from being specified in that case.
1514  */
1515  if (list_length(stmt->options) != 1)
1516  ereport(ERROR,
1517  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1518  errmsg("option \"%s\" cannot be specified with other options",
1519  dtablespace->defname),
1520  parser_errposition(pstate, dtablespace->location)));
1521  /* this case isn't allowed within a transaction block */
1522  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1523  movedb(stmt->dbname, defGetString(dtablespace));
1524  return InvalidOid;
1525  }
1526 
1527  if (distemplate && distemplate->arg)
1528  dbistemplate = defGetBoolean(distemplate);
1529  if (dallowconnections && dallowconnections->arg)
1530  dballowconnections = defGetBoolean(dallowconnections);
1531  if (dconnlimit && dconnlimit->arg)
1532  {
1533  dbconnlimit = defGetInt32(dconnlimit);
1534  if (dbconnlimit < -1)
1535  ereport(ERROR,
1536  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1537  errmsg("invalid connection limit: %d", dbconnlimit)));
1538  }
1539 
1540  /*
1541  * Get the old tuple. We don't need a lock on the database per se,
1542  * because we're not going to do anything that would mess up incoming
1543  * connections.
1544  */
1545  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1546  ScanKeyInit(&scankey,
1547  Anum_pg_database_datname,
1548  BTEqualStrategyNumber, F_NAMEEQ,
1549  CStringGetDatum(stmt->dbname));
1550  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1551  NULL, 1, &scankey);
1552  tuple = systable_getnext(scan);
1553  if (!HeapTupleIsValid(tuple))
1554  ereport(ERROR,
1555  (errcode(ERRCODE_UNDEFINED_DATABASE),
1556  errmsg("database \"%s\" does not exist", stmt->dbname)));
1557 
1558  datform = (Form_pg_database) GETSTRUCT(tuple);
1559  dboid = datform->oid;
1560 
1561  if (!pg_database_ownercheck(dboid, GetUserId()))
1563  stmt->dbname);
1564 
1565  /*
1566  * In order to avoid getting locked out and having to go through
1567  * standalone mode, we refuse to disallow connections to the database
1568  * we're currently connected to. Lockout can still happen with concurrent
1569  * sessions but the likeliness of that is not high enough to worry about.
1570  */
1571  if (!dballowconnections && dboid == MyDatabaseId)
1572  ereport(ERROR,
1573  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1574  errmsg("cannot disallow connections for current database")));
1575 
1576  /*
1577  * Build an updated tuple, perusing the information just obtained
1578  */
1579  MemSet(new_record, 0, sizeof(new_record));
1580  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1581  MemSet(new_record_repl, false, sizeof(new_record_repl));
1582 
1583  if (distemplate)
1584  {
1585  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1586  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1587  }
1588  if (dallowconnections)
1589  {
1590  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1591  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1592  }
1593  if (dconnlimit)
1594  {
1595  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1596  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1597  }
1598 
1599  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1600  new_record_nulls, new_record_repl);
1601  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
1602 
1603  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
1604 
1605  systable_endscan(scan);
1606 
1607  /* Close pg_database, but keep lock till commit */
1608  table_close(rel, NoLock);
1609 
1610  return dboid;
1611 }
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:445
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:1109
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 1644 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().

1645 {
1646  Oid db_id;
1647  HeapTuple tuple;
1648  Relation rel;
1649  ScanKeyData scankey;
1650  SysScanDesc scan;
1651  Form_pg_database datForm;
1652  ObjectAddress address;
1653 
1654  /*
1655  * Get the old tuple. We don't need a lock on the database per se,
1656  * because we're not going to do anything that would mess up incoming
1657  * connections.
1658  */
1659  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1660  ScanKeyInit(&scankey,
1661  Anum_pg_database_datname,
1662  BTEqualStrategyNumber, F_NAMEEQ,
1664  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1665  NULL, 1, &scankey);
1666  tuple = systable_getnext(scan);
1667  if (!HeapTupleIsValid(tuple))
1668  ereport(ERROR,
1669  (errcode(ERRCODE_UNDEFINED_DATABASE),
1670  errmsg("database \"%s\" does not exist", dbname)));
1671 
1672  datForm = (Form_pg_database) GETSTRUCT(tuple);
1673  db_id = datForm->oid;
1674 
1675  /*
1676  * If the new owner is the same as the existing owner, consider the
1677  * command to have succeeded. This is to be consistent with other
1678  * objects.
1679  */
1680  if (datForm->datdba != newOwnerId)
1681  {
1682  Datum repl_val[Natts_pg_database];
1683  bool repl_null[Natts_pg_database];
1684  bool repl_repl[Natts_pg_database];
1685  Acl *newAcl;
1686  Datum aclDatum;
1687  bool isNull;
1688  HeapTuple newtuple;
1689 
1690  /* Otherwise, must be owner of the existing object */
1691  if (!pg_database_ownercheck(db_id, GetUserId()))
1693  dbname);
1694 
1695  /* Must be able to become new owner */
1696  check_is_member_of_role(GetUserId(), newOwnerId);
1697 
1698  /*
1699  * must have createdb rights
1700  *
1701  * NOTE: This is different from other alter-owner checks in that the
1702  * current user is checked for createdb privileges instead of the
1703  * destination owner. This is consistent with the CREATE case for
1704  * databases. Because superusers will always have this right, we need
1705  * no special case for them.
1706  */
1707  if (!have_createdb_privilege())
1708  ereport(ERROR,
1709  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1710  errmsg("permission denied to change owner of database")));
1711 
1712  memset(repl_null, false, sizeof(repl_null));
1713  memset(repl_repl, false, sizeof(repl_repl));
1714 
1715  repl_repl[Anum_pg_database_datdba - 1] = true;
1716  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1717 
1718  /*
1719  * Determine the modified ACL for the new owner. This is only
1720  * necessary when the ACL is non-null.
1721  */
1722  aclDatum = heap_getattr(tuple,
1723  Anum_pg_database_datacl,
1724  RelationGetDescr(rel),
1725  &isNull);
1726  if (!isNull)
1727  {
1728  newAcl = aclnewowner(DatumGetAclP(aclDatum),
1729  datForm->datdba, newOwnerId);
1730  repl_repl[Anum_pg_database_datacl - 1] = true;
1731  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1732  }
1733 
1734  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1735  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1736 
1737  heap_freetuple(newtuple);
1738 
1739  /* Update owner dependency reference */
1740  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
1741  }
1742 
1743  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1744 
1745  ObjectAddressSet(address, DatabaseRelationId, db_id);
1746 
1747  systable_endscan(scan);
1748 
1749  /* Close pg_database, but keep lock till commit */
1750  table_close(rel, NoLock);
1751 
1752  return address;
1753 }
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:445
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:1888
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 1618 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().

1619 {
1620  Oid datid = get_database_oid(stmt->dbname, false);
1621 
1622  /*
1623  * Obtain a lock on the database and make sure it didn't go away in the
1624  * meantime.
1625  */
1626  shdepLockAndCheckObject(DatabaseRelationId, datid);
1627 
1628  if (!pg_database_ownercheck(datid, GetUserId()))
1630  stmt->dbname);
1631 
1632  AlterSetting(datid, InvalidOid, stmt->setstmt);
1633 
1634  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
1635 
1636  return datid;
1637 }
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:3136
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:1023
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:2053

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 1980 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().

1981 {
1982  bool result = false;
1983  Relation rel;
1984  TableScanDesc scan;
1985  HeapTuple tuple;
1986 
1987  rel = table_open(TableSpaceRelationId, AccessShareLock);
1988  scan = table_beginscan_catalog(rel, 0, NULL);
1989  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1990  {
1991  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
1992  Oid dsttablespace = spcform->oid;
1993  char *dstpath;
1994  struct stat st;
1995 
1996  /* Don't mess with the global tablespace */
1997  if (dsttablespace == GLOBALTABLESPACE_OID)
1998  continue;
1999 
2000  dstpath = GetDatabasePath(db_id, dsttablespace);
2001 
2002  if (lstat(dstpath, &st) == 0)
2003  {
2004  /* Found a conflicting file (or directory, whatever) */
2005  pfree(dstpath);
2006  result = true;
2007  break;
2008  }
2009 
2010  pfree(dstpath);
2011  }
2012 
2013  table_endscan(scan);
2015 
2016  return result;
2017 }
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:1056
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:255
#define lstat(path, sb)
Definition: win32_port.h:244
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 756 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().

757 {
758  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
759  int collate_encoding = pg_get_encoding_from_locale(collate, true);
760 
761  if (!(ctype_encoding == encoding ||
762  ctype_encoding == PG_SQL_ASCII ||
763  ctype_encoding == -1 ||
764 #ifdef WIN32
765  encoding == PG_UTF8 ||
766 #endif
767  (encoding == PG_SQL_ASCII && superuser())))
768  ereport(ERROR,
769  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
770  errmsg("encoding \"%s\" does not match locale \"%s\"",
772  ctype),
773  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
774  pg_encoding_to_char(ctype_encoding))));
775 
776  if (!(collate_encoding == encoding ||
777  collate_encoding == PG_SQL_ASCII ||
778  collate_encoding == -1 ||
779 #ifdef WIN32
780  encoding == PG_UTF8 ||
781 #endif
782  (encoding == PG_SQL_ASCII && superuser())))
783  ereport(ERROR,
784  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
785  errmsg("encoding \"%s\" does not match locale \"%s\"",
787  collate),
788  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
789  pg_encoding_to_char(collate_encoding))));
790 }
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 101 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, InvalidMultiXactId, InvalidOid, InvalidTransactionId, 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().

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

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

Referenced by createdb().

795 {
797 
798  /*
799  * Release lock on source database before doing recursive remove. This is
800  * not essential but it seems desirable to release the lock as soon as
801  * possible.
802  */
803  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
804 
805  /* Throw away any successfully copied subdirectories */
807 }
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1913
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1023
#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 2121 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.

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

◆ dropdb()

void dropdb ( const char *  dbname,
bool  missing_ok 
)

Definition at line 814 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().

815 {
816  Oid db_id;
817  bool db_istemplate;
818  Relation pgdbrel;
819  HeapTuple tup;
820  int notherbackends;
821  int npreparedxacts;
822  int nslots,
823  nslots_active;
824  int nsubscriptions;
825 
826  /*
827  * Look up the target database's OID, and get exclusive lock on it. We
828  * need this to ensure that no new backend starts up in the target
829  * database while we are deleting it (see postinit.c), and that no one is
830  * using it as a CREATE DATABASE template or trying to delete it for
831  * themselves.
832  */
833  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
834 
835  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
836  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
837  {
838  if (!missing_ok)
839  {
840  ereport(ERROR,
841  (errcode(ERRCODE_UNDEFINED_DATABASE),
842  errmsg("database \"%s\" does not exist", dbname)));
843  }
844  else
845  {
846  /* Close pg_database, release the lock, since we changed nothing */
847  table_close(pgdbrel, RowExclusiveLock);
848  ereport(NOTICE,
849  (errmsg("database \"%s\" does not exist, skipping",
850  dbname)));
851  return;
852  }
853  }
854 
855  /*
856  * Permission checks
857  */
858  if (!pg_database_ownercheck(db_id, GetUserId()))
860  dbname);
861 
862  /* DROP hook for the database being removed */
863  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
864 
865  /*
866  * Disallow dropping a DB that is marked istemplate. This is just to
867  * prevent people from accidentally dropping template0 or template1; they
868  * can do so if they're really determined ...
869  */
870  if (db_istemplate)
871  ereport(ERROR,
872  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
873  errmsg("cannot drop a template database")));
874 
875  /* Obviously can't drop my own database */
876  if (db_id == MyDatabaseId)
877  ereport(ERROR,
878  (errcode(ERRCODE_OBJECT_IN_USE),
879  errmsg("cannot drop the currently open database")));
880 
881  /*
882  * Check whether there are active logical slots that refer to the
883  * to-be-dropped database. The database lock we are holding prevents the
884  * creation of new slots using the database or existing slots becoming
885  * active.
886  */
887  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
888  if (nslots_active)
889  {
890  ereport(ERROR,
891  (errcode(ERRCODE_OBJECT_IN_USE),
892  errmsg("database \"%s\" is used by an active logical replication slot",
893  dbname),
894  errdetail_plural("There is %d active slot.",
895  "There are %d active slots.",
896  nslots_active, nslots_active)));
897  }
898 
899  /*
900  * Check for other backends in the target database. (Because we hold the
901  * database lock, no new ones can start after this.)
902  *
903  * As in CREATE DATABASE, check this after other error conditions.
904  */
905  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
906  ereport(ERROR,
907  (errcode(ERRCODE_OBJECT_IN_USE),
908  errmsg("database \"%s\" is being accessed by other users",
909  dbname),
910  errdetail_busy_db(notherbackends, npreparedxacts)));
911 
912  /*
913  * Check if there are subscriptions defined in the target database.
914  *
915  * We can't drop them automatically because they might be holding
916  * resources in other databases/instances.
917  */
918  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
919  ereport(ERROR,
920  (errcode(ERRCODE_OBJECT_IN_USE),
921  errmsg("database \"%s\" is being used by logical replication subscription",
922  dbname),
923  errdetail_plural("There is %d subscription.",
924  "There are %d subscriptions.",
925  nsubscriptions, nsubscriptions)));
926 
927  /*
928  * Remove the database's tuple from pg_database.
929  */
931  if (!HeapTupleIsValid(tup))
932  elog(ERROR, "cache lookup failed for database %u", db_id);
933 
934  CatalogTupleDelete(pgdbrel, &tup->t_self);
935 
936  ReleaseSysCache(tup);
937 
938  /*
939  * Delete any comments or security labels associated with the database.
940  */
941  DeleteSharedComments(db_id, DatabaseRelationId);
942  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
943 
944  /*
945  * Remove settings associated with this database
946  */
947  DropSetting(db_id, InvalidOid);
948 
949  /*
950  * Remove shared dependency references for the database.
951  */
953 
954  /*
955  * Drop db-specific replication slots.
956  */
958 
959  /*
960  * Drop pages for this database that are in the shared buffer cache. This
961  * is important to ensure that no remaining backend tries to write out a
962  * dirty buffer to the dead database later...
963  */
964  DropDatabaseBuffers(db_id);
965 
966  /*
967  * Tell the stats collector to forget it immediately, too.
968  */
969  pgstat_drop_database(db_id);
970 
971  /*
972  * Tell checkpointer to forget any pending fsync and unlink requests for
973  * files in the database; else the fsyncs will fail at next checkpoint, or
974  * worse, it will delete files that belong to a newly created database
975  * with the same OID.
976  */
978 
979  /*
980  * Force a checkpoint to make sure the checkpointer has received the
981  * message sent by ForgetDatabaseSyncRequests. On Windows, this also
982  * ensures that background procs don't hold any open files, which would
983  * cause rmdir() to fail.
984  */
986 
987  /*
988  * Remove all tablespace subdirs belonging to the database.
989  */
990  remove_dbtablespaces(db_id);
991 
992  /*
993  * Close pg_database, but keep lock till commit.
994  */
995  table_close(pgdbrel, NoLock);
996 
997  /*
998  * Force synchronous commit, thus minimizing the window between removal of
999  * the database files and committal of the transaction. If we crash before
1000  * committing, we'll have a DB that's gone on disk but still there
1001  * according to pg_database, which is not good.
1002  */
1003  ForceSyncCommit();
1004 }
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:1913
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:1767
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:2023
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void DropSetting(Oid databaseid, Oid roleid)
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3099
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 2023 of file dbcommands.c.

References errdetail(), and errdetail_plural().

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

2024 {
2025  if (notherbackends > 0 && npreparedxacts > 0)
2026 
2027  /*
2028  * We don't deal with singular versus plural here, since gettext
2029  * doesn't support multiple plurals in one string.
2030  */
2031  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2032  notherbackends, npreparedxacts);
2033  else if (notherbackends > 0)
2034  errdetail_plural("There is %d other session using the database.",
2035  "There are %d other sessions using the database.",
2036  notherbackends,
2037  notherbackends);
2038  else
2039  errdetail_plural("There is %d prepared transaction using the database.",
2040  "There are %d prepared transactions using the database.",
2041  npreparedxacts,
2042  npreparedxacts);
2043  return 0; /* just to keep ereport macro happy */
2044 }
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 2100 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().

2101 {
2102  HeapTuple dbtuple;
2103  char *result;
2104 
2105  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2106  if (HeapTupleIsValid(dbtuple))
2107  {
2108  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2109  ReleaseSysCache(dbtuple);
2110  }
2111  else
2112  result = NULL;
2113 
2114  return result;
2115 }
#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:1186
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 2053 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().

2054 {
2055  Relation pg_database;
2056  ScanKeyData entry[1];
2057  SysScanDesc scan;
2058  HeapTuple dbtuple;
2059  Oid oid;
2060 
2061  /*
2062  * There's no syscache for pg_database indexed by name, so we must look
2063  * the hard way.
2064  */
2065  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2066  ScanKeyInit(&entry[0],
2067  Anum_pg_database_datname,
2068  BTEqualStrategyNumber, F_NAMEEQ,
2070  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2071  NULL, 1, entry);
2072 
2073  dbtuple = systable_getnext(scan);
2074 
2075  /* We assume that there can be at most one matching tuple */
2076  if (HeapTupleIsValid(dbtuple))
2077  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2078  else
2079  oid = InvalidOid;
2080 
2081  systable_endscan(scan);
2082  table_close(pg_database, AccessShareLock);
2083 
2084  if (!OidIsValid(oid) && !missing_ok)
2085  ereport(ERROR,
2086  (errcode(ERRCODE_UNDEFINED_DATABASE),
2087  errmsg("database \"%s\" does not exist",
2088  dbname)));
2089 
2090  return oid;
2091 }
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 1767 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().

1773 {
1774  bool result = false;
1775  Relation relation;
1776 
1777  AssertArg(name);
1778 
1779  /* Caller may wish to grab a better lock on pg_database beforehand... */
1780  relation = table_open(DatabaseRelationId, AccessShareLock);
1781 
1782  /*
1783  * Loop covers the rare case where the database is renamed before we can
1784  * lock it. We try again just in case we can find a new one of the same
1785  * name.
1786  */
1787  for (;;)
1788  {
1789  ScanKeyData scanKey;
1790  SysScanDesc scan;
1791  HeapTuple tuple;
1792  Oid dbOid;
1793 
1794  /*
1795  * there's no syscache for database-indexed-by-name, so must do it the
1796  * hard way
1797  */
1798  ScanKeyInit(&scanKey,
1799  Anum_pg_database_datname,
1800  BTEqualStrategyNumber, F_NAMEEQ,
1802 
1803  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
1804  NULL, 1, &scanKey);
1805 
1806  tuple = systable_getnext(scan);
1807 
1808  if (!HeapTupleIsValid(tuple))
1809  {
1810  /* definitely no database of that name */
1811  systable_endscan(scan);
1812  break;
1813  }
1814 
1815  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
1816 
1817  systable_endscan(scan);
1818 
1819  /*
1820  * Now that we have a database OID, we can try to lock the DB.
1821  */
1822  if (lockmode != NoLock)
1823  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1824 
1825  /*
1826  * And now, re-fetch the tuple by OID. If it's still there and still
1827  * the same name, we win; else, drop the lock and loop back to try
1828  * again.
1829  */
1830  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
1831  if (HeapTupleIsValid(tuple))
1832  {
1833  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1834 
1835  if (strcmp(name, NameStr(dbform->datname)) == 0)
1836  {
1837  /* oid of the database */
1838  if (dbIdP)
1839  *dbIdP = dbOid;
1840  /* oid of the owner */
1841  if (ownerIdP)
1842  *ownerIdP = dbform->datdba;
1843  /* character encoding */
1844  if (encodingP)
1845  *encodingP = dbform->encoding;
1846  /* allowed as template? */
1847  if (dbIsTemplateP)
1848  *dbIsTemplateP = dbform->datistemplate;
1849  /* allowing connections? */
1850  if (dbAllowConnP)
1851  *dbAllowConnP = dbform->datallowconn;
1852  /* last system OID used in database */
1853  if (dbLastSysOidP)
1854  *dbLastSysOidP = dbform->datlastsysoid;
1855  /* limit of frozen XIDs */
1856  if (dbFrozenXidP)
1857  *dbFrozenXidP = dbform->datfrozenxid;
1858  /* minimum MultiXactId */
1859  if (dbMinMultiP)
1860  *dbMinMultiP = dbform->datminmxid;
1861  /* default tablespace for this database */
1862  if (dbTablespace)
1863  *dbTablespace = dbform->dattablespace;
1864  /* default locale settings for this database */
1865  if (dbCollate)
1866  *dbCollate = pstrdup(NameStr(dbform->datcollate));
1867  if (dbCtype)
1868  *dbCtype = pstrdup(NameStr(dbform->datctype));
1869  ReleaseSysCache(tuple);
1870  result = true;
1871  break;
1872  }
1873  /* can only get here if it was just renamed */
1874  ReleaseSysCache(tuple);
1875  }
1876 
1877  if (lockmode != NoLock)
1878  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1879  }
1880 
1881  table_close(relation, AccessShareLock);
1882 
1883  return result;
1884 }
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:1186
#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:1023
#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:1002
#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 1888 of file dbcommands.c.

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

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

1889 {
1890  bool result = false;
1891  HeapTuple utup;
1892 
1893  /* Superusers can always do everything */
1894  if (superuser())
1895  return true;
1896 
1898  if (HeapTupleIsValid(utup))
1899  {
1900  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
1901  ReleaseSysCache(utup);
1902  }
1903  return result;
1904 }
#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 1109 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().

1110 {
1111  Oid db_id;
1112  Relation pgdbrel;
1113  int notherbackends;
1114  int npreparedxacts;
1115  HeapTuple oldtuple,
1116  newtuple;
1117  Oid src_tblspcoid,
1118  dst_tblspcoid;
1119  Datum new_record[Natts_pg_database];
1120  bool new_record_nulls[Natts_pg_database];
1121  bool new_record_repl[Natts_pg_database];
1122  ScanKeyData scankey;
1123  SysScanDesc sysscan;
1124  AclResult aclresult;
1125  char *src_dbpath;
1126  char *dst_dbpath;
1127  DIR *dstdir;
1128  struct dirent *xlde;
1129  movedb_failure_params fparms;
1130 
1131  /*
1132  * Look up the target database's OID, and get exclusive lock on it. We
1133  * need this to ensure that no new backend starts up in the database while
1134  * we are moving it, and that no one is using it as a CREATE DATABASE
1135  * template or trying to delete it.
1136  */
1137  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1138 
1139  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1140  NULL, NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL))
1141  ereport(ERROR,
1142  (errcode(ERRCODE_UNDEFINED_DATABASE),
1143  errmsg("database \"%s\" does not exist", dbname)));
1144 
1145  /*
1146  * We actually need a session lock, so that the lock will persist across
1147  * the commit/restart below. (We could almost get away with letting the
1148  * lock be released at commit, except that someone could try to move
1149  * relations of the DB back into the old directory while we rmtree() it.)
1150  */
1151  LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1153 
1154  /*
1155  * Permission checks
1156  */
1157  if (!pg_database_ownercheck(db_id, GetUserId()))
1159  dbname);
1160 
1161  /*
1162  * Obviously can't move the tables of my own database
1163  */
1164  if (db_id == MyDatabaseId)
1165  ereport(ERROR,
1166  (errcode(ERRCODE_OBJECT_IN_USE),
1167  errmsg("cannot change the tablespace of the currently open database")));
1168 
1169  /*
1170  * Get tablespace's oid
1171  */
1172  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1173 
1174  /*
1175  * Permission checks
1176  */
1177  aclresult = pg_tablespace_aclcheck(dst_tblspcoid, GetUserId(),
1178  ACL_CREATE);
1179  if (aclresult != ACLCHECK_OK)
1180  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1181  tblspcname);
1182 
1183  /*
1184  * pg_global must never be the default tablespace
1185  */
1186  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1187  ereport(ERROR,
1188  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1189  errmsg("pg_global cannot be used as default tablespace")));
1190 
1191  /*
1192  * No-op if same tablespace
1193  */
1194  if (src_tblspcoid == dst_tblspcoid)
1195  {
1196  table_close(pgdbrel, NoLock);
1197  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1199  return;
1200  }
1201 
1202  /*
1203  * Check for other backends in the target database. (Because we hold the
1204  * database lock, no new ones can start after this.)
1205  *
1206  * As in CREATE DATABASE, check this after other error conditions.
1207  */
1208  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1209  ereport(ERROR,
1210  (errcode(ERRCODE_OBJECT_IN_USE),
1211  errmsg("database \"%s\" is being accessed by other users",
1212  dbname),
1213  errdetail_busy_db(notherbackends, npreparedxacts)));
1214 
1215  /*
1216  * Get old and new database paths
1217  */
1218  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1219  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1220 
1221  /*
1222  * Force a checkpoint before proceeding. This will force all dirty
1223  * buffers, including those of unlogged tables, out to disk, to ensure
1224  * source database is up-to-date on disk for the copy.
1225  * FlushDatabaseBuffers() would suffice for that, but we also want to
1226  * process any pending unlink requests. Otherwise, the check for existing
1227  * files in the target directory might fail unnecessarily, not to mention
1228  * that the copy might fail due to source files getting deleted under it.
1229  * On Windows, this also ensures that background procs don't hold any open
1230  * files, which would cause rmdir() to fail.
1231  */
1234 
1235  /*
1236  * Now drop all buffers holding data of the target database; they should
1237  * no longer be dirty so DropDatabaseBuffers is safe.
1238  *
1239  * It might seem that we could just let these buffers age out of shared
1240  * buffers naturally, since they should not get referenced anymore. The
1241  * problem with that is that if the user later moves the database back to
1242  * its original tablespace, any still-surviving buffers would appear to
1243  * contain valid data again --- but they'd be missing any changes made in
1244  * the database while it was in the new tablespace. In any case, freeing
1245  * buffers that should never be used again seems worth the cycles.
1246  *
1247  * Note: it'd be sufficient to get rid of buffers matching db_id and
1248  * src_tblspcoid, but bufmgr.c presently provides no API for that.
1249  */
1250  DropDatabaseBuffers(db_id);
1251 
1252  /*
1253  * Check for existence of files in the target directory, i.e., objects of
1254  * this database that are already in the target tablespace. We can't
1255  * allow the move in such a case, because we would need to change those
1256  * relations' pg_class.reltablespace entries to zero, and we don't have
1257  * access to the DB's pg_class to do so.
1258  */
1259  dstdir = AllocateDir(dst_dbpath);
1260  if (dstdir != NULL)
1261  {
1262  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1263  {
1264  if (strcmp(xlde->d_name, ".") == 0 ||
1265  strcmp(xlde->d_name, "..") == 0)
1266  continue;
1267 
1268  ereport(ERROR,
1269  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1270  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1271  dbname, tblspcname),
1272  errhint("You must move them back to the database's default tablespace before using this command.")));
1273  }
1274 
1275  FreeDir(dstdir);
1276 
1277  /*
1278  * The directory exists but is empty. We must remove it before using
1279  * the copydir function.
1280  */
1281  if (rmdir(dst_dbpath) != 0)
1282  elog(ERROR, "could not remove directory \"%s\": %m",
1283  dst_dbpath);
1284  }
1285 
1286  /*
1287  * Use an ENSURE block to make sure we remove the debris if the copy fails
1288  * (eg, due to out-of-disk-space). This is not a 100% solution, because
1289  * of the possibility of failure during transaction commit, but it should
1290  * handle most scenarios.
1291  */
1292  fparms.dest_dboid = db_id;
1293  fparms.dest_tsoid = dst_tblspcoid;
1295  PointerGetDatum(&fparms));
1296  {
1297  /*
1298  * Copy files from the old tablespace to the new one
1299  */
1300  copydir(src_dbpath, dst_dbpath, false);
1301 
1302  /*
1303  * Record the filesystem change in XLOG
1304  */
1305  {
1306  xl_dbase_create_rec xlrec;
1307 
1308  xlrec.db_id = db_id;
1309  xlrec.tablespace_id = dst_tblspcoid;
1310  xlrec.src_db_id = db_id;
1311  xlrec.src_tablespace_id = src_tblspcoid;
1312 
1313  XLogBeginInsert();
1314  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
1315 
1316  (void) XLogInsert(RM_DBASE_ID,
1318  }
1319 
1320  /*
1321  * Update the database's pg_database tuple
1322  */
1323  ScanKeyInit(&scankey,
1324  Anum_pg_database_datname,
1325  BTEqualStrategyNumber, F_NAMEEQ,
1327  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
1328  NULL, 1, &scankey);
1329  oldtuple = systable_getnext(sysscan);
1330  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
1331  ereport(ERROR,
1332  (errcode(ERRCODE_UNDEFINED_DATABASE),
1333  errmsg("database \"%s\" does not exist", dbname)));
1334 
1335  MemSet(new_record, 0, sizeof(new_record));
1336  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1337  MemSet(new_record_repl, false, sizeof(new_record_repl));
1338 
1339  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
1340  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
1341 
1342  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
1343  new_record,
1344  new_record_nulls, new_record_repl);
1345  CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
1346 
1347  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1348 
1349  systable_endscan(sysscan);
1350 
1351  /*
1352  * Force another checkpoint here. As in CREATE DATABASE, this is to
1353  * ensure that we don't have to replay a committed XLOG_DBASE_CREATE
1354  * operation, which would cause us to lose any unlogged operations
1355  * done in the new DB tablespace before the next checkpoint.
1356  */
1358 
1359  /*
1360  * Force synchronous commit, thus minimizing the window between
1361  * copying the database files and committal of the transaction. If we
1362  * crash before committing, we'll leave an orphaned set of files on
1363  * disk, which is not fatal but not good either.
1364  */
1365  ForceSyncCommit();
1366 
1367  /*
1368  * Close pg_database, but keep lock till commit.
1369  */
1370  table_close(pgdbrel, NoLock);
1371  }
1373  PointerGetDatum(&fparms));
1374 
1375  /*
1376  * Commit the transaction so that the pg_database update is committed. If
1377  * we crash while removing files, the database won't be corrupt, we'll
1378  * just leave some orphaned files in the old directory.
1379  *
1380  * (This is OK because we know we aren't inside a transaction block.)
1381  *
1382  * XXX would it be safe/better to do this inside the ensure block? Not
1383  * convinced it's a good idea; consider elog just after the transaction
1384  * really commits.
1385  */
1388 
1389  /* Start new transaction for the remaining work; don't need a snapshot */
1391 
1392  /*
1393  * Remove files from the old tablespace
1394  */
1395  if (!rmtree(src_dbpath, true))
1396  ereport(WARNING,
1397  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1398  src_dbpath)));
1399 
1400  /*
1401  * Record the filesystem change in XLOG
1402  */
1403  {
1404  xl_dbase_drop_rec xlrec;
1405 
1406  xlrec.db_id = db_id;
1407  xlrec.tablespace_id = src_tblspcoid;
1408 
1409  XLogBeginInsert();
1410  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1411 
1412  (void) XLogInsert(RM_DBASE_ID,
1414  }
1415 
1416  /* Now it's safe to release the database lock */
1417  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1419 }
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:445
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:1767
Definition: dirent.h:9
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1423
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:1044
#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:1062
#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:2466
#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:2532
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:2023
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:3099
#define BTEqualStrategyNumber
Definition: stratnum.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2584
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952

◆ movedb_failure_callback()

static void movedb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1423 of file dbcommands.c.

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

Referenced by movedb().

1424 {
1426  char *dstpath;
1427 
1428  /* Get rid of anything we managed to copy to the target directory */
1429  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
1430 
1431  (void) rmtree(dstpath, true);
1432 }
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 1913 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().

1914 {
1915  Relation rel;
1916  TableScanDesc scan;
1917  HeapTuple tuple;
1918 
1919  rel = table_open(TableSpaceRelationId, AccessShareLock);
1920  scan = table_beginscan_catalog(rel, 0, NULL);
1921  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1922  {
1923  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
1924  Oid dsttablespace = spcform->oid;
1925  char *dstpath;
1926  struct stat st;
1927 
1928  /* Don't mess with the global tablespace */
1929  if (dsttablespace == GLOBALTABLESPACE_OID)
1930  continue;
1931 
1932  dstpath = GetDatabasePath(db_id, dsttablespace);
1933 
1934  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1935  {
1936  /* Assume we can ignore it */
1937  pfree(dstpath);
1938  continue;
1939  }
1940 
1941  if (!rmtree(dstpath, true))
1942  ereport(WARNING,
1943  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1944  dstpath)));
1945 
1946  /* Record the filesystem change in XLOG */
1947  {
1948  xl_dbase_drop_rec xlrec;
1949 
1950  xlrec.db_id = db_id;
1951  xlrec.tablespace_id = dsttablespace;
1952 
1953  XLogBeginInsert();
1954  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1955 
1956  (void) XLogInsert(RM_DBASE_ID,
1958  }
1959 
1960  pfree(dstpath);
1961  }
1962 
1963  table_endscan(scan);
1965 }
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:1056
#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:255
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:296
#define lstat(path, sb)
Definition: win32_port.h:244
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 1011 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().

1012 {
1013  Oid db_id;
1014  HeapTuple newtup;
1015  Relation rel;
1016  int notherbackends;
1017  int npreparedxacts;
1018  ObjectAddress address;
1019 
1020  /*
1021  * Look up the target database's OID, and get exclusive lock on it. We
1022  * need this for the same reasons as DROP DATABASE.
1023  */
1024  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1025 
1026  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1027  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1028  ereport(ERROR,
1029  (errcode(ERRCODE_UNDEFINED_DATABASE),
1030  errmsg("database \"%s\" does not exist", oldname)));
1031 
1032  /* must be owner */
1033  if (!pg_database_ownercheck(db_id, GetUserId()))
1035  oldname);
1036 
1037  /* must have createdb rights */
1038  if (!have_createdb_privilege())
1039  ereport(ERROR,
1040  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1041  errmsg("permission denied to rename database")));
1042 
1043  /*
1044  * If built with appropriate switch, whine when regression-testing
1045  * conventions for database names are violated.
1046  */
1047 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1048  if (strstr(newname, "regression") == NULL)
1049  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1050 #endif
1051 
1052  /*
1053  * Make sure the new name doesn't exist. See notes for same error in
1054  * CREATE DATABASE.
1055  */
1056  if (OidIsValid(get_database_oid(newname, true)))
1057  ereport(ERROR,
1058  (errcode(ERRCODE_DUPLICATE_DATABASE),
1059  errmsg("database \"%s\" already exists", newname)));
1060 
1061  /*
1062  * XXX Client applications probably store the current database somewhere,
1063  * so renaming it could cause confusion. On the other hand, there may not
1064  * be an actual problem besides a little confusion, so think about this
1065  * and decide.
1066  */
1067  if (db_id == MyDatabaseId)
1068  ereport(ERROR,
1069  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1070  errmsg("current database cannot be renamed")));
1071 
1072  /*
1073  * Make sure the database does not have active sessions. This is the same
1074  * concern as above, but applied to other sessions.
1075  *
1076  * As in CREATE DATABASE, check this after other error conditions.
1077  */
1078  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1079  ereport(ERROR,
1080  (errcode(ERRCODE_OBJECT_IN_USE),
1081  errmsg("database \"%s\" is being accessed by other users",
1082  oldname),
1083  errdetail_busy_db(notherbackends, npreparedxacts)));
1084 
1085  /* rename */
1087  if (!HeapTupleIsValid(newtup))
1088  elog(ERROR, "cache lookup failed for database %u", db_id);
1089  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1090  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1091 
1092  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1093 
1094  ObjectAddressSet(address, DatabaseRelationId, db_id);
1095 
1096  /*
1097  * Close pg_database, but keep lock till commit.
1098  */
1099  table_close(rel, NoLock);
1100 
1101  return address;
1102 }
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:1888
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:1767
#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:2053
#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:2023
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39