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)
 
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 1438 of file dbcommands.c.

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

Referenced by standard_ProcessUtility().

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

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 1643 of file dbcommands.c.

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

Referenced by ExecAlterOwnerStmt().

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

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 1617 of file dbcommands.c.

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

Referenced by standard_ProcessUtility().

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

◆ check_encoding_locale_matches()

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

Definition at line 755 of file dbcommands.c.

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

Referenced by createdb(), and DefineCollation().

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

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 100 of file dbcommands.c.

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

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

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

◆ dropdb()

void dropdb ( const char *  dbname,
bool  missing_ok 
)

Definition at line 813 of file dbcommands.c.

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

Referenced by standard_ProcessUtility().

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

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 2099 of file dbcommands.c.

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

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 2052 of file dbcommands.c.

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

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

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

◆ RenameDatabase()

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

Definition at line 1010 of file dbcommands.c.

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

Referenced by ExecRenameStmt().

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