PostgreSQL Source Code  git master
dbcommands.h File Reference
Include dependency graph for dbcommands.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void dropdb (const char *dbname, bool missing_ok, bool force)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
Oid AlterDatabaseSet (AlterDatabaseSetStmt *stmt)
 
ObjectAddress AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 

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:454
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:454
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:3156
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_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:588
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:454
Oid GetUserId(void)
Definition: miscinit.c:380
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
#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:3137
#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:588
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:3138
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:849
#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: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:3168
int location
Definition: parsenodes.h:733
#define ereport(elevel, rest)
Definition: elog.h:141
bool missing_ok
Definition: parsenodes.h:3167
#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:3166

◆ 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:1248
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:975
#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:3109
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:896
void RequestCheckpoint(int flags)
Definition: checkpointer.c:896

◆ 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

◆ 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