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/ipc.h"
#include "storage/lmgr.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, bool force)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
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 1471 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().

1472 {
1473  Relation rel;
1474  Oid dboid;
1475  HeapTuple tuple,
1476  newtuple;
1477  Form_pg_database datform;
1478  ScanKeyData scankey;
1479  SysScanDesc scan;
1480  ListCell *option;
1481  bool dbistemplate = false;
1482  bool dballowconnections = true;
1483  int dbconnlimit = -1;
1484  DefElem *distemplate = NULL;
1485  DefElem *dallowconnections = NULL;
1486  DefElem *dconnlimit = NULL;
1487  DefElem *dtablespace = NULL;
1488  Datum new_record[Natts_pg_database];
1489  bool new_record_nulls[Natts_pg_database];
1490  bool new_record_repl[Natts_pg_database];
1491 
1492  /* Extract options from the statement node tree */
1493  foreach(option, stmt->options)
1494  {
1495  DefElem *defel = (DefElem *) lfirst(option);
1496 
1497  if (strcmp(defel->defname, "is_template") == 0)
1498  {
1499  if (distemplate)
1500  ereport(ERROR,
1501  (errcode(ERRCODE_SYNTAX_ERROR),
1502  errmsg("conflicting or redundant options"),
1503  parser_errposition(pstate, defel->location)));
1504  distemplate = defel;
1505  }
1506  else if (strcmp(defel->defname, "allow_connections") == 0)
1507  {
1508  if (dallowconnections)
1509  ereport(ERROR,
1510  (errcode(ERRCODE_SYNTAX_ERROR),
1511  errmsg("conflicting or redundant options"),
1512  parser_errposition(pstate, defel->location)));
1513  dallowconnections = defel;
1514  }
1515  else if (strcmp(defel->defname, "connection_limit") == 0)
1516  {
1517  if (dconnlimit)
1518  ereport(ERROR,
1519  (errcode(ERRCODE_SYNTAX_ERROR),
1520  errmsg("conflicting or redundant options"),
1521  parser_errposition(pstate, defel->location)));
1522  dconnlimit = defel;
1523  }
1524  else if (strcmp(defel->defname, "tablespace") == 0)
1525  {
1526  if (dtablespace)
1527  ereport(ERROR,
1528  (errcode(ERRCODE_SYNTAX_ERROR),
1529  errmsg("conflicting or redundant options"),
1530  parser_errposition(pstate, defel->location)));
1531  dtablespace = defel;
1532  }
1533  else
1534  ereport(ERROR,
1535  (errcode(ERRCODE_SYNTAX_ERROR),
1536  errmsg("option \"%s\" not recognized", defel->defname),
1537  parser_errposition(pstate, defel->location)));
1538  }
1539 
1540  if (dtablespace)
1541  {
1542  /*
1543  * While the SET TABLESPACE syntax doesn't allow any other options,
1544  * somebody could write "WITH TABLESPACE ...". Forbid any other
1545  * options from being specified in that case.
1546  */
1547  if (list_length(stmt->options) != 1)
1548  ereport(ERROR,
1549  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1550  errmsg("option \"%s\" cannot be specified with other options",
1551  dtablespace->defname),
1552  parser_errposition(pstate, dtablespace->location)));
1553  /* this case isn't allowed within a transaction block */
1554  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1555  movedb(stmt->dbname, defGetString(dtablespace));
1556  return InvalidOid;
1557  }
1558 
1559  if (distemplate && distemplate->arg)
1560  dbistemplate = defGetBoolean(distemplate);
1561  if (dallowconnections && dallowconnections->arg)
1562  dballowconnections = defGetBoolean(dallowconnections);
1563  if (dconnlimit && dconnlimit->arg)
1564  {
1565  dbconnlimit = defGetInt32(dconnlimit);
1566  if (dbconnlimit < -1)
1567  ereport(ERROR,
1568  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1569  errmsg("invalid connection limit: %d", dbconnlimit)));
1570  }
1571 
1572  /*
1573  * Get the old tuple. We don't need a lock on the database per se,
1574  * because we're not going to do anything that would mess up incoming
1575  * connections.
1576  */
1577  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1578  ScanKeyInit(&scankey,
1579  Anum_pg_database_datname,
1580  BTEqualStrategyNumber, F_NAMEEQ,
1581  CStringGetDatum(stmt->dbname));
1582  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1583  NULL, 1, &scankey);
1584  tuple = systable_getnext(scan);
1585  if (!HeapTupleIsValid(tuple))
1586  ereport(ERROR,
1587  (errcode(ERRCODE_UNDEFINED_DATABASE),
1588  errmsg("database \"%s\" does not exist", stmt->dbname)));
1589 
1590  datform = (Form_pg_database) GETSTRUCT(tuple);
1591  dboid = datform->oid;
1592 
1593  if (!pg_database_ownercheck(dboid, GetUserId()))
1595  stmt->dbname);
1596 
1597  /*
1598  * In order to avoid getting locked out and having to go through
1599  * standalone mode, we refuse to disallow connections to the database
1600  * we're currently connected to. Lockout can still happen with concurrent
1601  * sessions but the likeliness of that is not high enough to worry about.
1602  */
1603  if (!dballowconnections && dboid == MyDatabaseId)
1604  ereport(ERROR,
1605  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1606  errmsg("cannot disallow connections for current database")));
1607 
1608  /*
1609  * Build an updated tuple, perusing the information just obtained
1610  */
1611  MemSet(new_record, 0, sizeof(new_record));
1612  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1613  MemSet(new_record_repl, false, sizeof(new_record_repl));
1614 
1615  if (distemplate)
1616  {
1617  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1618  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1619  }
1620  if (dallowconnections)
1621  {
1622  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1623  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1624  }
1625  if (dconnlimit)
1626  {
1627  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1628  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1629  }
1630 
1631  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1632  new_record_nulls, new_record_repl);
1633  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
1634 
1635  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
1636 
1637  systable_endscan(scan);
1638 
1639  /* Close pg_database, but keep lock till commit */
1640  table_close(rel, NoLock);
1641 
1642  return dboid;
1643 }
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:448
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:608
#define MemSet(start, val, len)
Definition: c.h:962
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:3352
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:3331
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5171
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:1116
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:110
#define DatabaseNameIndexId
Definition: indexing.h:144
#define Int32GetDatum(X)
Definition: postgres.h:479
int errmsg(const char *fmt,...)
Definition: elog.c:822
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 1676 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().

1677 {
1678  Oid db_id;
1679  HeapTuple tuple;
1680  Relation rel;
1681  ScanKeyData scankey;
1682  SysScanDesc scan;
1683  Form_pg_database datForm;
1684  ObjectAddress address;
1685 
1686  /*
1687  * Get the old tuple. We don't need a lock on the database per se,
1688  * because we're not going to do anything that would mess up incoming
1689  * connections.
1690  */
1691  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1692  ScanKeyInit(&scankey,
1693  Anum_pg_database_datname,
1694  BTEqualStrategyNumber, F_NAMEEQ,
1696  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1697  NULL, 1, &scankey);
1698  tuple = systable_getnext(scan);
1699  if (!HeapTupleIsValid(tuple))
1700  ereport(ERROR,
1701  (errcode(ERRCODE_UNDEFINED_DATABASE),
1702  errmsg("database \"%s\" does not exist", dbname)));
1703 
1704  datForm = (Form_pg_database) GETSTRUCT(tuple);
1705  db_id = datForm->oid;
1706 
1707  /*
1708  * If the new owner is the same as the existing owner, consider the
1709  * command to have succeeded. This is to be consistent with other
1710  * objects.
1711  */
1712  if (datForm->datdba != newOwnerId)
1713  {
1714  Datum repl_val[Natts_pg_database];
1715  bool repl_null[Natts_pg_database];
1716  bool repl_repl[Natts_pg_database];
1717  Acl *newAcl;
1718  Datum aclDatum;
1719  bool isNull;
1720  HeapTuple newtuple;
1721 
1722  /* Otherwise, must be owner of the existing object */
1723  if (!pg_database_ownercheck(db_id, GetUserId()))
1725  dbname);
1726 
1727  /* Must be able to become new owner */
1728  check_is_member_of_role(GetUserId(), newOwnerId);
1729 
1730  /*
1731  * must have createdb rights
1732  *
1733  * NOTE: This is different from other alter-owner checks in that the
1734  * current user is checked for createdb privileges instead of the
1735  * destination owner. This is consistent with the CREATE case for
1736  * databases. Because superusers will always have this right, we need
1737  * no special case for them.
1738  */
1739  if (!have_createdb_privilege())
1740  ereport(ERROR,
1741  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1742  errmsg("permission denied to change owner of database")));
1743 
1744  memset(repl_null, false, sizeof(repl_null));
1745  memset(repl_repl, false, sizeof(repl_repl));
1746 
1747  repl_repl[Anum_pg_database_datdba - 1] = true;
1748  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1749 
1750  /*
1751  * Determine the modified ACL for the new owner. This is only
1752  * necessary when the ACL is non-null.
1753  */
1754  aclDatum = heap_getattr(tuple,
1755  Anum_pg_database_datacl,
1756  RelationGetDescr(rel),
1757  &isNull);
1758  if (!isNull)
1759  {
1760  newAcl = aclnewowner(DatumGetAclP(aclDatum),
1761  datForm->datdba, newOwnerId);
1762  repl_repl[Anum_pg_database_datacl - 1] = true;
1763  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1764  }
1765 
1766  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1767  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1768 
1769  heap_freetuple(newtuple);
1770 
1771  /* Update owner dependency reference */
1772  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
1773  }
1774 
1775  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1776 
1777  ObjectAddressSet(address, DatabaseRelationId, db_id);
1778 
1779  systable_endscan(scan);
1780 
1781  /* Close pg_database, but keep lock till commit */
1782  table_close(rel, NoLock);
1783 
1784  return address;
1785 }
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:448
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:1920
int errcode(int sqlerrcode)
Definition: elog.c:608
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:309
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3352
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:4946
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5171
#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:50
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:822
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 1650 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().

1651 {
1652  Oid datid = get_database_oid(stmt->dbname, false);
1653 
1654  /*
1655  * Obtain a lock on the database and make sure it didn't go away in the
1656  * meantime.
1657  */
1658  shdepLockAndCheckObject(DatabaseRelationId, datid);
1659 
1660  if (!pg_database_ownercheck(datid, GetUserId()))
1662  stmt->dbname);
1663 
1664  AlterSetting(datid, InvalidOid, stmt->setstmt);
1665 
1666  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
1667 
1668  return datid;
1669 }
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:3352
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1023
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1071
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5171
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2108

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

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

2036 {
2037  bool result = false;
2038  Relation rel;
2039  TableScanDesc scan;
2040  HeapTuple tuple;
2041 
2042  rel = table_open(TableSpaceRelationId, AccessShareLock);
2043  scan = table_beginscan_catalog(rel, 0, NULL);
2044  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2045  {
2046  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2047  Oid dsttablespace = spcform->oid;
2048  char *dstpath;
2049  struct stat st;
2050 
2051  /* Don't mess with the global tablespace */
2052  if (dsttablespace == GLOBALTABLESPACE_OID)
2053  continue;
2054 
2055  dstpath = GetDatabasePath(db_id, dsttablespace);
2056 
2057  if (lstat(dstpath, &st) == 0)
2058  {
2059  /* Found a conflicting file (or directory, whatever) */
2060  pfree(dstpath);
2061  result = true;
2062  break;
2063  }
2064 
2065  pfree(dstpath);
2066  }
2067 
2068  table_endscan(scan);
2070 
2071  return result;
2072 }
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 755 of file dbcommands.c.

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

Referenced by createdb(), and DefineCollation().

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

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 100 of file dbcommands.c.

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, DefElem::arg, BoolGetDatum, CatalogTupleInsert(), check_db_file_conflict(), check_encoding_locale_matches(), check_is_member_of_role(), check_locale(), CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, copydir(), copyTemplateDependencies(), CountOtherDBBackends(), createdb_failure_callback(), CStringGetDatum, DatabaseOidIndexId, xl_dbase_create_rec::db_id, dbname, CreatedbStmt::dbname, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, createdb_failure_params::dest_dboid, DirectFunctionCall1, directory_is_empty(), dstpath, elog, encoding, ereport, errcode(), errdetail(), errdetail_busy_db(), errhint(), errmsg(), ERROR, ForceSyncCommit(), ForwardScanDirection, get_database_oid(), get_db_info(), get_role_oid(), get_tablespace_oid(), GetDatabasePath(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), have_createdb_privilege(), heap_form_tuple(), heap_getnext(), Int32GetDatum, 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().

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

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 793 of file dbcommands.c.

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

Referenced by createdb().

794 {
796 
797  /*
798  * Release lock on source database before doing recursive remove. This is
799  * not essential but it seems desirable to release the lock as soon as
800  * possible.
801  */
802  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
803 
804  /* Throw away any successfully copied subdirectories */
806 }
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1945
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 2176 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(), i, InHotStandby, LockSharedObjectForSession(), xl_dbase_drop_rec::ntablespaces, PANIC, pfree(), 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_ids, UnlockSharedObjectForSession(), WARNING, XLOG_DBASE_CREATE, XLOG_DBASE_DROP, XLogDropDatabase(), XLogRecGetData, XLogRecGetInfo, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

2177 {
2178  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2179 
2180  /* Backup blocks are not used in dbase records */
2181  Assert(!XLogRecHasAnyBlockRefs(record));
2182 
2183  if (info == XLOG_DBASE_CREATE)
2184  {
2186  char *src_path;
2187  char *dst_path;
2188  struct stat st;
2189 
2190  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
2191  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2192 
2193  /*
2194  * Our theory for replaying a CREATE is to forcibly drop the target
2195  * subdirectory if present, then re-copy the source data. This may be
2196  * more work than needed, but it is simple to implement.
2197  */
2198  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
2199  {
2200  if (!rmtree(dst_path, true))
2201  /* If this failed, copydir() below is going to error. */
2202  ereport(WARNING,
2203  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2204  dst_path)));
2205  }
2206 
2207  /*
2208  * Force dirty buffers out to disk, to ensure source database is
2209  * up-to-date for the copy.
2210  */
2212 
2213  /*
2214  * Copy this subdirectory to the new location
2215  *
2216  * We don't need to copy subdirectories
2217  */
2218  copydir(src_path, dst_path, false);
2219  }
2220  else if (info == XLOG_DBASE_DROP)
2221  {
2222  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
2223  char *dst_path;
2224  int i;
2225 
2226  if (InHotStandby)
2227  {
2228  /*
2229  * Lock database while we resolve conflicts to ensure that
2230  * InitPostgres() cannot fully re-execute concurrently. This
2231  * avoids backends re-connecting automatically to same database,
2232  * which can happen in some cases.
2233  *
2234  * This will lock out walsenders trying to connect to db-specific
2235  * slots for logical decoding too, so it's safe for us to drop
2236  * slots.
2237  */
2238  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2240  }
2241 
2242  /* Drop any database-specific replication slots */
2244 
2245  /* Drop pages for this database that are in the shared buffer cache */
2246  DropDatabaseBuffers(xlrec->db_id);
2247 
2248  /* Also, clean out any fsync requests that might be pending in md.c */
2250 
2251  /* Clean out the xlog relcache too */
2252  XLogDropDatabase(xlrec->db_id);
2253 
2254  for (i = 0; i < xlrec->ntablespaces; i++)
2255  {
2256  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
2257 
2258  /* And remove the physical files */
2259  if (!rmtree(dst_path, true))
2260  ereport(WARNING,
2261  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2262  dst_path)));
2263  pfree(dst_path);
2264  }
2265 
2266  if (InHotStandby)
2267  {
2268  /*
2269  * Release locks prior to commit. XXX There is a race condition
2270  * here that may allow backends to reconnect, but the window for
2271  * this is small because the gap between here and commit is mostly
2272  * fairly small and it is unlikely that people will be dropping
2273  * databases that we are trying to connect to anyway.
2274  */
2275  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
2276  }
2277  }
2278  else
2279  elog(PANIC, "dbase_redo: unknown op code %u", info);
2280 }
unsigned char uint8
Definition: c.h:357
#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
void pfree(void *pointer)
Definition: mcxt.c:1056
#define XLogRecGetData(decoder)
Definition: xlogreader.h:283
#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:279
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:739
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLOG_DBASE_CREATE
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
#define S_ISDIR(m)
Definition: win32_port.h:296
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:822
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:617
#define elog(elevel,...)
Definition: elog.h:228
int i
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:285
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3099
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:896

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 1446 of file dbcommands.c.

References DropdbStmt::dbname, DefElem::defname, dropdb(), ereport, errcode(), errmsg(), ERROR, lfirst, DefElem::location, DropdbStmt::missing_ok, DropdbStmt::options, and parser_errposition().

Referenced by standard_ProcessUtility().

1447 {
1448  bool force = false;
1449  ListCell *lc;
1450 
1451  foreach(lc, stmt->options)
1452  {
1453  DefElem *opt = (DefElem *) lfirst(lc);
1454 
1455  if (strcmp(opt->defname, "force") == 0)
1456  force = true;
1457  else
1458  ereport(ERROR,
1459  (errcode(ERRCODE_SYNTAX_ERROR),
1460  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
1461  parser_errposition(pstate, opt->location)));
1462  }
1463 
1464  dropdb(stmt->dbname, stmt->missing_ok, force);
1465 }
int errcode(int sqlerrcode)
Definition: elog.c:608
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:813
#define ERROR
Definition: elog.h:43
List * options
Definition: parsenodes.h:3148
int location
Definition: parsenodes.h:733
#define ereport(elevel, rest)
Definition: elog.h:141
bool missing_ok
Definition: parsenodes.h:3147
#define lfirst(lc)
Definition: pg_list.h:190
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * defname
Definition: parsenodes.h:730
char * dbname
Definition: parsenodes.h:3146

◆ dropdb()

void dropdb ( const char *  dbname,
bool  missing_ok,
bool  force 
)

Definition at line 813 of file dbcommands.c.

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

Referenced by DropDatabase().

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

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 2078 of file dbcommands.c.

References errdetail(), and errdetail_plural().

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

2079 {
2080  if (notherbackends > 0 && npreparedxacts > 0)
2081 
2082  /*
2083  * We don't deal with singular versus plural here, since gettext
2084  * doesn't support multiple plurals in one string.
2085  */
2086  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2087  notherbackends, npreparedxacts);
2088  else if (notherbackends > 0)
2089  errdetail_plural("There is %d other session using the database.",
2090  "There are %d other sessions using the database.",
2091  notherbackends,
2092  notherbackends);
2093  else
2094  errdetail_plural("There is %d prepared transaction using the database.",
2095  "There are %d prepared transactions using the database.",
2096  npreparedxacts,
2097  npreparedxacts);
2098  return 0; /* just to keep ereport macro happy */
2099 }
int errdetail(const char *fmt,...)
Definition: elog.c:955
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1047

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 2155 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(), TerminateOtherDBBackends(), and transformColumnRef().

2156 {
2157  HeapTuple dbtuple;
2158  char *result;
2159 
2160  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2161  if (HeapTupleIsValid(dbtuple))
2162  {
2163  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2164  ReleaseSysCache(dbtuple);
2165  }
2166  else
2167  result = NULL;
2168 
2169  return result;
2170 }
#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:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define NameStr(name)
Definition: c.h:616

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

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

2109 {
2110  Relation pg_database;
2111  ScanKeyData entry[1];
2112  SysScanDesc scan;
2113  HeapTuple dbtuple;
2114  Oid oid;
2115 
2116  /*
2117  * There's no syscache for pg_database indexed by name, so we must look
2118  * the hard way.
2119  */
2120  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2121  ScanKeyInit(&entry[0],
2122  Anum_pg_database_datname,
2123  BTEqualStrategyNumber, F_NAMEEQ,
2125  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2126  NULL, 1, entry);
2127 
2128  dbtuple = systable_getnext(scan);
2129 
2130  /* We assume that there can be at most one matching tuple */
2131  if (HeapTupleIsValid(dbtuple))
2132  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2133  else
2134  oid = InvalidOid;
2135 
2136  systable_endscan(scan);
2137  table_close(pg_database, AccessShareLock);
2138 
2139  if (!OidIsValid(oid) && !missing_ok)
2140  ereport(ERROR,
2141  (errcode(ERRCODE_UNDEFINED_DATABASE),
2142  errmsg("database \"%s\" does not exist",
2143  dbname)));
2144 
2145  return oid;
2146 }
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:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
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:50
#define DatabaseNameIndexId
Definition: indexing.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:822
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 1799 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().

1805 {
1806  bool result = false;
1807  Relation relation;
1808 
1809  AssertArg(name);
1810 
1811  /* Caller may wish to grab a better lock on pg_database beforehand... */
1812  relation = table_open(DatabaseRelationId, AccessShareLock);
1813 
1814  /*
1815  * Loop covers the rare case where the database is renamed before we can
1816  * lock it. We try again just in case we can find a new one of the same
1817  * name.
1818  */
1819  for (;;)
1820  {
1821  ScanKeyData scanKey;
1822  SysScanDesc scan;
1823  HeapTuple tuple;
1824  Oid dbOid;
1825 
1826  /*
1827  * there's no syscache for database-indexed-by-name, so must do it the
1828  * hard way
1829  */
1830  ScanKeyInit(&scanKey,
1831  Anum_pg_database_datname,
1832  BTEqualStrategyNumber, F_NAMEEQ,
1834 
1835  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
1836  NULL, 1, &scanKey);
1837 
1838  tuple = systable_getnext(scan);
1839 
1840  if (!HeapTupleIsValid(tuple))
1841  {
1842  /* definitely no database of that name */
1843  systable_endscan(scan);
1844  break;
1845  }
1846 
1847  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
1848 
1849  systable_endscan(scan);
1850 
1851  /*
1852  * Now that we have a database OID, we can try to lock the DB.
1853  */
1854  if (lockmode != NoLock)
1855  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1856 
1857  /*
1858  * And now, re-fetch the tuple by OID. If it's still there and still
1859  * the same name, we win; else, drop the lock and loop back to try
1860  * again.
1861  */
1862  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
1863  if (HeapTupleIsValid(tuple))
1864  {
1865  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1866 
1867  if (strcmp(name, NameStr(dbform->datname)) == 0)
1868  {
1869  /* oid of the database */
1870  if (dbIdP)
1871  *dbIdP = dbOid;
1872  /* oid of the owner */
1873  if (ownerIdP)
1874  *ownerIdP = dbform->datdba;
1875  /* character encoding */
1876  if (encodingP)
1877  *encodingP = dbform->encoding;
1878  /* allowed as template? */
1879  if (dbIsTemplateP)
1880  *dbIsTemplateP = dbform->datistemplate;
1881  /* allowing connections? */
1882  if (dbAllowConnP)
1883  *dbAllowConnP = dbform->datallowconn;
1884  /* last system OID used in database */
1885  if (dbLastSysOidP)
1886  *dbLastSysOidP = dbform->datlastsysoid;
1887  /* limit of frozen XIDs */
1888  if (dbFrozenXidP)
1889  *dbFrozenXidP = dbform->datfrozenxid;
1890  /* minimum MultiXactId */
1891  if (dbMinMultiP)
1892  *dbMinMultiP = dbform->datminmxid;
1893  /* default tablespace for this database */
1894  if (dbTablespace)
1895  *dbTablespace = dbform->dattablespace;
1896  /* default locale settings for this database */
1897  if (dbCollate)
1898  *dbCollate = pstrdup(NameStr(dbform->datcollate));
1899  if (dbCtype)
1900  *dbCtype = pstrdup(NameStr(dbform->datctype));
1901  ReleaseSysCache(tuple);
1902  result = true;
1903  break;
1904  }
1905  /* can only get here if it was just renamed */
1906  ReleaseSysCache(tuple);
1907  }
1908 
1909  if (lockmode != NoLock)
1910  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1911  }
1912 
1913  table_close(relation, AccessShareLock);
1914 
1915  return result;
1916 }
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:741
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
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:616
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 1920 of file dbcommands.c.

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

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

1921 {
1922  bool result = false;
1923  HeapTuple utup;
1924 
1925  /* Superusers can always do everything */
1926  if (superuser())
1927  return true;
1928 
1930  if (HeapTupleIsValid(utup))
1931  {
1932  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
1933  ReleaseSysCache(utup);
1934  }
1935  return result;
1936 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Oid GetUserId(void)
Definition: miscinit.c:380
bool superuser(void)
Definition: superuser.c:46
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:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ movedb()

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

Definition at line 1116 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, xl_dbase_drop_rec::ntablespaces, 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, UnlockSharedObjectForSession(), WARNING, XLOG_DBASE_CREATE, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by AlterDatabase().

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

◆ movedb_failure_callback()

static void movedb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1431 of file dbcommands.c.

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

Referenced by movedb().

1432 {
1434  char *dstpath;
1435 
1436  /* Get rid of anything we managed to copy to the target directory */
1437  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
1438 
1439  (void) rmtree(dstpath, true);
1440 }
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 1945 of file dbcommands.c.

References AccessShareLock, xl_dbase_drop_rec::db_id, dstpath, ereport, errmsg(), ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), i, lappend_oid(), lfirst_oid, list_free(), list_length(), lstat, MinSizeOfDbaseDropRec, NIL, xl_dbase_drop_rec::ntablespaces, palloc(), pfree(), rmtree(), S_ISDIR, stat, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), WARNING, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by createdb_failure_callback(), and dropdb().

1946 {
1947  Relation rel;
1948  TableScanDesc scan;
1949  HeapTuple tuple;
1950  List *ltblspc = NIL;
1951  ListCell *cell;
1952  int ntblspc;
1953  int i;
1954  Oid *tablespace_ids;
1955 
1956  rel = table_open(TableSpaceRelationId, AccessShareLock);
1957  scan = table_beginscan_catalog(rel, 0, NULL);
1958  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1959  {
1960  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
1961  Oid dsttablespace = spcform->oid;
1962  char *dstpath;
1963  struct stat st;
1964 
1965  /* Don't mess with the global tablespace */
1966  if (dsttablespace == GLOBALTABLESPACE_OID)
1967  continue;
1968 
1969  dstpath = GetDatabasePath(db_id, dsttablespace);
1970 
1971  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1972  {
1973  /* Assume we can ignore it */
1974  pfree(dstpath);
1975  continue;
1976  }
1977 
1978  if (!rmtree(dstpath, true))
1979  ereport(WARNING,
1980  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1981  dstpath)));
1982 
1983  ltblspc = lappend_oid(ltblspc, dsttablespace);
1984  pfree(dstpath);
1985  }
1986 
1987  ntblspc = list_length(ltblspc);
1988  if (ntblspc == 0)
1989  {
1990  table_endscan(scan);
1992  return;
1993  }
1994 
1995  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
1996  i = 0;
1997  foreach(cell, ltblspc)
1998  tablespace_ids[i++] = lfirst_oid(cell);
1999 
2000  /* Record the filesystem change in XLOG */
2001  {
2002  xl_dbase_drop_rec xlrec;
2003 
2004  xlrec.db_id = db_id;
2005  xlrec.ntablespaces = ntblspc;
2006 
2007  XLogBeginInsert();
2008  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
2009  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
2010 
2011  (void) XLogInsert(RM_DBASE_ID,
2013  }
2014 
2015  list_free(ltblspc);
2016  pfree(tablespace_ids);
2017 
2018  table_endscan(scan);
2020 }
#define NIL
Definition: pg_list.h:65
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 MinSizeOfDbaseDropRec
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
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
static int list_length(const List *l)
Definition: pg_list.h:169
#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
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
void list_free(List *list)
Definition: list.c:1377
int i
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120
Definition: pg_list.h:50
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ RenameDatabase()

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

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

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