PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 missingok)
 
char * get_database_name (Oid dbid)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 

Function Documentation

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

Definition at line 1397 of file dbcommands.c.

References ACL_KIND_DATABASE, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_database_datallowconn, Anum_pg_database_datconnlimit, Anum_pg_database_datistemplate, Anum_pg_database_datname, DefElem::arg, BoolGetDatum, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum, DatabaseNameIndexId, DatabaseRelationId, AlterDatabaseStmt::dbname, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, GetUserId(), heap_close, heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, Int32GetDatum, InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), DefElem::location, MemSet, movedb(), MyDatabaseId, Natts_pg_database, NoLock, AlterDatabaseStmt::options, parser_errposition(), pg_database_ownercheck(), PreventTransactionChain(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and HeapTupleData::t_self.

Referenced by standard_ProcessUtility().

1398 {
1399  Relation rel;
1400  Oid dboid;
1401  HeapTuple tuple,
1402  newtuple;
1403  ScanKeyData scankey;
1404  SysScanDesc scan;
1405  ListCell *option;
1406  bool dbistemplate = false;
1407  bool dballowconnections = true;
1408  int dbconnlimit = -1;
1409  DefElem *distemplate = NULL;
1410  DefElem *dallowconnections = NULL;
1411  DefElem *dconnlimit = NULL;
1412  DefElem *dtablespace = NULL;
1413  Datum new_record[Natts_pg_database];
1414  bool new_record_nulls[Natts_pg_database];
1415  bool new_record_repl[Natts_pg_database];
1416 
1417  /* Extract options from the statement node tree */
1418  foreach(option, stmt->options)
1419  {
1420  DefElem *defel = (DefElem *) lfirst(option);
1421 
1422  if (strcmp(defel->defname, "is_template") == 0)
1423  {
1424  if (distemplate)
1425  ereport(ERROR,
1426  (errcode(ERRCODE_SYNTAX_ERROR),
1427  errmsg("conflicting or redundant options"),
1428  parser_errposition(pstate, defel->location)));
1429  distemplate = defel;
1430  }
1431  else if (strcmp(defel->defname, "allow_connections") == 0)
1432  {
1433  if (dallowconnections)
1434  ereport(ERROR,
1435  (errcode(ERRCODE_SYNTAX_ERROR),
1436  errmsg("conflicting or redundant options"),
1437  parser_errposition(pstate, defel->location)));
1438  dallowconnections = defel;
1439  }
1440  else if (strcmp(defel->defname, "connection_limit") == 0)
1441  {
1442  if (dconnlimit)
1443  ereport(ERROR,
1444  (errcode(ERRCODE_SYNTAX_ERROR),
1445  errmsg("conflicting or redundant options"),
1446  parser_errposition(pstate, defel->location)));
1447  dconnlimit = defel;
1448  }
1449  else if (strcmp(defel->defname, "tablespace") == 0)
1450  {
1451  if (dtablespace)
1452  ereport(ERROR,
1453  (errcode(ERRCODE_SYNTAX_ERROR),
1454  errmsg("conflicting or redundant options"),
1455  parser_errposition(pstate, defel->location)));
1456  dtablespace = defel;
1457  }
1458  else
1459  ereport(ERROR,
1460  (errcode(ERRCODE_SYNTAX_ERROR),
1461  errmsg("option \"%s\" not recognized", defel->defname),
1462  parser_errposition(pstate, defel->location)));
1463  }
1464 
1465  if (dtablespace)
1466  {
1467  /*
1468  * While the SET TABLESPACE syntax doesn't allow any other options,
1469  * somebody could write "WITH TABLESPACE ...". Forbid any other
1470  * options from being specified in that case.
1471  */
1472  if (list_length(stmt->options) != 1)
1473  ereport(ERROR,
1474  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1475  errmsg("option \"%s\" cannot be specified with other options",
1476  dtablespace->defname),
1477  parser_errposition(pstate, dtablespace->location)));
1478  /* this case isn't allowed within a transaction block */
1479  PreventTransactionChain(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1480  movedb(stmt->dbname, defGetString(dtablespace));
1481  return InvalidOid;
1482  }
1483 
1484  if (distemplate && distemplate->arg)
1485  dbistemplate = defGetBoolean(distemplate);
1486  if (dallowconnections && dallowconnections->arg)
1487  dballowconnections = defGetBoolean(dallowconnections);
1488  if (dconnlimit && dconnlimit->arg)
1489  {
1490  dbconnlimit = defGetInt32(dconnlimit);
1491  if (dbconnlimit < -1)
1492  ereport(ERROR,
1493  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1494  errmsg("invalid connection limit: %d", dbconnlimit)));
1495  }
1496 
1497  /*
1498  * Get the old tuple. We don't need a lock on the database per se,
1499  * because we're not going to do anything that would mess up incoming
1500  * connections.
1501  */
1503  ScanKeyInit(&scankey,
1505  BTEqualStrategyNumber, F_NAMEEQ,
1506  CStringGetDatum(stmt->dbname));
1507  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1508  NULL, 1, &scankey);
1509  tuple = systable_getnext(scan);
1510  if (!HeapTupleIsValid(tuple))
1511  ereport(ERROR,
1512  (errcode(ERRCODE_UNDEFINED_DATABASE),
1513  errmsg("database \"%s\" does not exist", stmt->dbname)));
1514 
1515  dboid = HeapTupleGetOid(tuple);
1516 
1519  stmt->dbname);
1520 
1521  /*
1522  * In order to avoid getting locked out and having to go through
1523  * standalone mode, we refuse to disallow connections to the database
1524  * we're currently connected to. Lockout can still happen with concurrent
1525  * sessions but the likeliness of that is not high enough to worry about.
1526  */
1527  if (!dballowconnections && dboid == MyDatabaseId)
1528  ereport(ERROR,
1529  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1530  errmsg("cannot disallow connections for current database")));
1531 
1532  /*
1533  * Build an updated tuple, perusing the information just obtained
1534  */
1535  MemSet(new_record, 0, sizeof(new_record));
1536  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1537  MemSet(new_record_repl, false, sizeof(new_record_repl));
1538 
1539  if (distemplate)
1540  {
1541  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1542  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1543  }
1544  if (dallowconnections)
1545  {
1546  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1547  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1548  }
1549  if (dconnlimit)
1550  {
1551  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1552  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1553  }
1554 
1555  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1556  new_record_nulls, new_record_repl);
1557  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
1558 
1560  HeapTupleGetOid(newtuple), 0);
1561 
1562  systable_endscan(scan);
1563 
1564  /* Close pg_database, but keep lock till commit */
1565  heap_close(rel, NoLock);
1566 
1567  return dboid;
1568 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define Anum_pg_database_datconnlimit
Definition: pg_database.h:71
#define Natts_pg_database
Definition: pg_database.h:63
#define RelationGetDescr(relation)
Definition: rel.h:428
Oid GetUserId(void)
Definition: miscinit.c:284
#define DatabaseRelationId
Definition: pg_database.h:29
int32 defGetInt32(DefElem *def)
Definition: define.c:166
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:846
#define heap_close(r, l)
Definition: heapam.h:97
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:328
bool defGetBoolean(DefElem *def)
Definition: define.c:111
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ERROR
Definition: elog.h:43
#define Anum_pg_database_datname
Definition: pg_database.h:64
char * defGetString(DefElem *def)
Definition: define.c:49
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
int location
Definition: parsenodes.h:722
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
#define Anum_pg_database_datistemplate
Definition: pg_database.h:69
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
#define Anum_pg_database_datallowconn
Definition: pg_database.h:70
Node * arg
Definition: parsenodes.h:720
uintptr_t Datum
Definition: postgres.h:372
Oid MyDatabaseId
Definition: globals.c:77
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define BoolGetDatum(X)
Definition: postgres.h:408
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define lfirst(lc)
Definition: pg_list.h:106
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1066
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
#define DatabaseNameIndexId
Definition: indexing.h:140
#define Int32GetDatum(X)
Definition: postgres.h:485
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
char * defname
Definition: parsenodes.h:719
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void PreventTransactionChain(bool isTopLevel, const char *stmtType)
Definition: xact.c:3161
ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 1601 of file dbcommands.c.

References ACL_KIND_DATABASE, aclcheck_error(), ACLCHECK_NOT_OWNER, aclnewowner(), Anum_pg_database_datacl, Anum_pg_database_datdba, Anum_pg_database_datname, BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependencyOnOwner(), check_is_member_of_role(), CStringGetDatum, DatabaseNameIndexId, DatabaseRelationId, DatumGetAclP, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), have_createdb_privilege(), heap_close, heap_freetuple(), heap_getattr, heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, Natts_pg_database, NoLock, ObjectAddressSet, ObjectIdGetDatum, pg_database_ownercheck(), PointerGetDatum, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and HeapTupleData::t_self.

Referenced by ExecAlterOwnerStmt().

1602 {
1603  Oid db_id;
1604  HeapTuple tuple;
1605  Relation rel;
1606  ScanKeyData scankey;
1607  SysScanDesc scan;
1608  Form_pg_database datForm;
1609  ObjectAddress address;
1610 
1611  /*
1612  * Get the old tuple. We don't need a lock on the database per se,
1613  * because we're not going to do anything that would mess up incoming
1614  * connections.
1615  */
1617  ScanKeyInit(&scankey,
1619  BTEqualStrategyNumber, F_NAMEEQ,
1621  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1622  NULL, 1, &scankey);
1623  tuple = systable_getnext(scan);
1624  if (!HeapTupleIsValid(tuple))
1625  ereport(ERROR,
1626  (errcode(ERRCODE_UNDEFINED_DATABASE),
1627  errmsg("database \"%s\" does not exist", dbname)));
1628 
1629  db_id = HeapTupleGetOid(tuple);
1630  datForm = (Form_pg_database) GETSTRUCT(tuple);
1631 
1632  /*
1633  * If the new owner is the same as the existing owner, consider the
1634  * command to have succeeded. This is to be consistent with other
1635  * objects.
1636  */
1637  if (datForm->datdba != newOwnerId)
1638  {
1639  Datum repl_val[Natts_pg_database];
1640  bool repl_null[Natts_pg_database];
1641  bool repl_repl[Natts_pg_database];
1642  Acl *newAcl;
1643  Datum aclDatum;
1644  bool isNull;
1645  HeapTuple newtuple;
1646 
1647  /* Otherwise, must be owner of the existing object */
1650  dbname);
1651 
1652  /* Must be able to become new owner */
1653  check_is_member_of_role(GetUserId(), newOwnerId);
1654 
1655  /*
1656  * must have createdb rights
1657  *
1658  * NOTE: This is different from other alter-owner checks in that the
1659  * current user is checked for createdb privileges instead of the
1660  * destination owner. This is consistent with the CREATE case for
1661  * databases. Because superusers will always have this right, we need
1662  * no special case for them.
1663  */
1664  if (!have_createdb_privilege())
1665  ereport(ERROR,
1666  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1667  errmsg("permission denied to change owner of database")));
1668 
1669  memset(repl_null, false, sizeof(repl_null));
1670  memset(repl_repl, false, sizeof(repl_repl));
1671 
1672  repl_repl[Anum_pg_database_datdba - 1] = true;
1673  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1674 
1675  /*
1676  * Determine the modified ACL for the new owner. This is only
1677  * necessary when the ACL is non-null.
1678  */
1679  aclDatum = heap_getattr(tuple,
1681  RelationGetDescr(rel),
1682  &isNull);
1683  if (!isNull)
1684  {
1685  newAcl = aclnewowner(DatumGetAclP(aclDatum),
1686  datForm->datdba, newOwnerId);
1687  repl_repl[Anum_pg_database_datacl - 1] = true;
1688  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1689  }
1690 
1691  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1692  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1693 
1694  heap_freetuple(newtuple);
1695 
1696  /* Update owner dependency reference */
1698  newOwnerId);
1699  }
1700 
1702 
1703  ObjectAddressSet(address, DatabaseRelationId, db_id);
1704 
1705  systable_endscan(scan);
1706 
1707  /* Close pg_database, but keep lock till commit */
1708  heap_close(rel, NoLock);
1709 
1710  return address;
1711 }
#define Anum_pg_database_datdba
Definition: pg_database.h:65
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define Natts_pg_database
Definition: pg_database.h:63
#define RelationGetDescr(relation)
Definition: rel.h:428
Oid GetUserId(void)
Definition: miscinit.c:284
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
#define DatumGetAclP(X)
Definition: acl.h:121
#define PointerGetDatum(X)
Definition: postgres.h:562
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1846
#define DatabaseRelationId
Definition: pg_database.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
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:328
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:304
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define Anum_pg_database_datname
Definition: pg_database.h:64
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4874
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
#define Anum_pg_database_datacl
Definition: pg_database.h:76
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
uintptr_t Datum
Definition: postgres.h:372
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
char * dbname
Definition: streamutil.c:39
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define DatabaseNameIndexId
Definition: indexing.h:140
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1050
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 1575 of file dbcommands.c.

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

Referenced by standard_ProcessUtility().

1576 {
1577  Oid datid = get_database_oid(stmt->dbname, false);
1578 
1579  /*
1580  * Obtain a lock on the database and make sure it didn't go away in the
1581  * meantime.
1582  */
1584 
1585  if (!pg_database_ownercheck(datid, GetUserId()))
1587  stmt->dbname);
1588 
1589  AlterSetting(datid, InvalidOid, stmt->setstmt);
1590 
1592 
1593  return datid;
1594 }
Oid GetUserId(void)
Definition: miscinit.c:284
#define DatabaseRelationId
Definition: pg_database.h:29
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:3045
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:892
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:987
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2009
void check_encoding_locale_matches ( int  encoding,
const char *  collate,
const char *  ctype 
)

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

723 {
724  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
725  int collate_encoding = pg_get_encoding_from_locale(collate, true);
726 
727  if (!(ctype_encoding == encoding ||
728  ctype_encoding == PG_SQL_ASCII ||
729  ctype_encoding == -1 ||
730 #ifdef WIN32
731  encoding == PG_UTF8 ||
732 #endif
733  (encoding == PG_SQL_ASCII && superuser())))
734  ereport(ERROR,
735  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
736  errmsg("encoding \"%s\" does not match locale \"%s\"",
738  ctype),
739  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
740  pg_encoding_to_char(ctype_encoding))));
741 
742  if (!(collate_encoding == encoding ||
743  collate_encoding == PG_SQL_ASCII ||
744  collate_encoding == -1 ||
745 #ifdef WIN32
746  encoding == PG_UTF8 ||
747 #endif
748  (encoding == PG_SQL_ASCII && superuser())))
749  ereport(ERROR,
750  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
751  errmsg("encoding \"%s\" does not match locale \"%s\"",
753  collate),
754  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
755  pg_encoding_to_char(collate_encoding))));
756 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:433
static char * encoding
Definition: initdb.c:122
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:607
int errmsg(const char *fmt,...)
Definition: elog.c:797
Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 99 of file dbcommands.c.

References AccessShareLock, ACL_CREATE, ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_OK, Anum_pg_database_datacl, Anum_pg_database_datallowconn, Anum_pg_database_datcollate, Anum_pg_database_datconnlimit, Anum_pg_database_datctype, Anum_pg_database_datdba, Anum_pg_database_datfrozenxid, Anum_pg_database_datistemplate, Anum_pg_database_datlastsysoid, Anum_pg_database_datminmxid, Anum_pg_database_datname, Anum_pg_database_dattablespace, Anum_pg_database_encoding, 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, DatabaseRelationId, xl_dbase_create_rec::db_id, dbname, CreatedbStmt::dbname, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, createdb_failure_params::dest_dboid, DirectFunctionCall1, directory_is_empty(), dstpath, 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(), GetNewOid(), GetUserId(), GLOBALTABLESPACE_OID, have_createdb_privilege(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_form_tuple(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleSetOid, Int32GetDatum, InvokeObjectPostCreateHook, IsA, lfirst, DefElem::location, MemSet, namein(), Natts_pg_database, NoLock, 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, ShareLock, xl_dbase_create_rec::src_db_id, createdb_failure_params::src_dboid, xl_dbase_create_rec::src_tablespace_id, xl_dbase_create_rec::tablespace_id, TableSpaceRelationId, TransactionIdGetDatum, WARNING, XLOG_DBASE_CREATE, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

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

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

Definition at line 780 of file dbcommands.c.

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

Referenced by standard_ProcessUtility().

781 {
782  Oid db_id;
783  bool db_istemplate;
784  Relation pgdbrel;
785  HeapTuple tup;
786  int notherbackends;
787  int npreparedxacts;
788  int nslots,
789  nslots_active;
790  int nsubscriptions;
791 
792  /*
793  * Look up the target database's OID, and get exclusive lock on it. We
794  * need this to ensure that no new backend starts up in the target
795  * database while we are deleting it (see postinit.c), and that no one is
796  * using it as a CREATE DATABASE template or trying to delete it for
797  * themselves.
798  */
800 
801  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
802  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
803  {
804  if (!missing_ok)
805  {
806  ereport(ERROR,
807  (errcode(ERRCODE_UNDEFINED_DATABASE),
808  errmsg("database \"%s\" does not exist", dbname)));
809  }
810  else
811  {
812  /* Close pg_database, release the lock, since we changed nothing */
813  heap_close(pgdbrel, RowExclusiveLock);
814  ereport(NOTICE,
815  (errmsg("database \"%s\" does not exist, skipping",
816  dbname)));
817  return;
818  }
819  }
820 
821  /*
822  * Permission checks
823  */
824  if (!pg_database_ownercheck(db_id, GetUserId()))
826  dbname);
827 
828  /* DROP hook for the database being removed */
830 
831  /*
832  * Disallow dropping a DB that is marked istemplate. This is just to
833  * prevent people from accidentally dropping template0 or template1; they
834  * can do so if they're really determined ...
835  */
836  if (db_istemplate)
837  ereport(ERROR,
838  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
839  errmsg("cannot drop a template database")));
840 
841  /* Obviously can't drop my own database */
842  if (db_id == MyDatabaseId)
843  ereport(ERROR,
844  (errcode(ERRCODE_OBJECT_IN_USE),
845  errmsg("cannot drop the currently open database")));
846 
847  /*
848  * Check whether there are active logical slots that refer to the
849  * to-be-dropped database. The database lock we are holding prevents the
850  * creation of new slots using the database or existing slots becoming
851  * active.
852  */
853  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
854  if (nslots_active)
855  {
856  ereport(ERROR,
857  (errcode(ERRCODE_OBJECT_IN_USE),
858  errmsg("database \"%s\" is used by an active logical replication slot",
859  dbname),
860  errdetail_plural("There is %d active slot",
861  "There are %d active slots",
862  nslots_active, nslots_active)));
863  }
864 
865  /*
866  * Check for other backends in the target database. (Because we hold the
867  * database lock, no new ones can start after this.)
868  *
869  * As in CREATE DATABASE, check this after other error conditions.
870  */
871  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
872  ereport(ERROR,
873  (errcode(ERRCODE_OBJECT_IN_USE),
874  errmsg("database \"%s\" is being accessed by other users",
875  dbname),
876  errdetail_busy_db(notherbackends, npreparedxacts)));
877 
878  /*
879  * Check if there are subscriptions defined in the target database.
880  *
881  * We can't drop them automatically because they might be holding
882  * resources in other databases/instances.
883  */
884  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
885  ereport(ERROR,
886  (errcode(ERRCODE_OBJECT_IN_USE),
887  errmsg("database \"%s\" is being used by logical replication subscription",
888  dbname),
889  errdetail_plural("There is %d subscription.",
890  "There are %d subscriptions.",
891  nsubscriptions, nsubscriptions)));
892 
893  /*
894  * Remove the database's tuple from pg_database.
895  */
897  if (!HeapTupleIsValid(tup))
898  elog(ERROR, "cache lookup failed for database %u", db_id);
899 
900  CatalogTupleDelete(pgdbrel, &tup->t_self);
901 
902  ReleaseSysCache(tup);
903 
904  /*
905  * Delete any comments or security labels associated with the database.
906  */
909 
910  /*
911  * Remove settings associated with this database
912  */
913  DropSetting(db_id, InvalidOid);
914 
915  /*
916  * Remove shared dependency references for the database.
917  */
919 
920  /*
921  * Drop db-specific replication slots.
922  */
924 
925  /*
926  * Drop pages for this database that are in the shared buffer cache. This
927  * is important to ensure that no remaining backend tries to write out a
928  * dirty buffer to the dead database later...
929  */
930  DropDatabaseBuffers(db_id);
931 
932  /*
933  * Tell the stats collector to forget it immediately, too.
934  */
935  pgstat_drop_database(db_id);
936 
937  /*
938  * Tell checkpointer to forget any pending fsync and unlink requests for
939  * files in the database; else the fsyncs will fail at next checkpoint, or
940  * worse, it will delete files that belong to a newly created database
941  * with the same OID.
942  */
944 
945  /*
946  * Force a checkpoint to make sure the checkpointer has received the
947  * message sent by ForgetDatabaseFsyncRequests. On Windows, this also
948  * ensures that background procs don't hold any open files, which would
949  * cause rmdir() to fail.
950  */
952 
953  /*
954  * Remove all tablespace subdirs belonging to the database.
955  */
956  remove_dbtablespaces(db_id);
957 
958  /*
959  * Close pg_database, but keep lock till commit.
960  */
961  heap_close(pgdbrel, NoLock);
962 
963  /*
964  * Force synchronous commit, thus minimizing the window between removal of
965  * the database files and committal of the transaction. If we crash before
966  * committing, we'll have a DB that's gone on disk but still there
967  * according to pg_database, which is not good.
968  */
969  ForceSyncCommit();
970 }
Oid GetUserId(void)
Definition: miscinit.c:284
#define DatabaseRelationId
Definition: pg_database.h:29
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
int CountDBSubscriptions(Oid dbid)
void ForceSyncCommit(void)
Definition: xact.c:971
int errcode(int sqlerrcode)
Definition: elog.c:575
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1871
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:255
#define heap_close(r, l)
Definition: heapam.h:97
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:1725
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:159
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CHECKPOINT_FORCE
Definition: xlog.h:179
#define ereport(elevel, rest)
Definition: elog.h:122
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
void pgstat_drop_database(Oid databaseid)
Definition: pgstat.c:1250
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:775
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Oid MyDatabaseId
Definition: globals.c:77
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
void ForgetDatabaseFsyncRequests(Oid dbid)
Definition: md.c:1685
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define CHECKPOINT_WAIT
Definition: xlog.h:183
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:373
char * dbname
Definition: streamutil.c:39
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:965
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:833
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:414
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:178
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2890
#define elog
Definition: elog.h:219
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:1979
void DropSetting(Oid databaseid, Oid roleid)
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3043
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:889
void RequestCheckpoint(int flags)
Definition: checkpointer.c:966
char* get_database_name ( Oid  dbid)

Definition at line 2056 of file dbcommands.c.

References DATABASEOID, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), result, 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(), IdentifySystem(), InitTempTableNamespace(), lazy_vacuum_rel(), 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().

2057 {
2058  HeapTuple dbtuple;
2059  char *result;
2060 
2061  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2062  if (HeapTupleIsValid(dbtuple))
2063  {
2064  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2065  ReleaseSysCache(dbtuple);
2066  }
2067  else
2068  result = NULL;
2069 
2070  return result;
2071 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
char * pstrdup(const char *in)
Definition: mcxt.c:1076
return result
Definition: formatting.c:1633
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:159
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NameStr(name)
Definition: c.h:493
Oid get_database_oid ( const char *  dbname,
bool  missingok 
)

Definition at line 2009 of file dbcommands.c.

References AccessShareLock, Anum_pg_database_datname, BTEqualStrategyNumber, CStringGetDatum, DatabaseNameIndexId, DatabaseRelationId, ereport, errcode(), errmsg(), ERROR, heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, OidIsValid, ScanKeyInit(), systable_beginscan(), systable_endscan(), and systable_getnext().

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

2010 {
2011  Relation pg_database;
2012  ScanKeyData entry[1];
2013  SysScanDesc scan;
2014  HeapTuple dbtuple;
2015  Oid oid;
2016 
2017  /*
2018  * There's no syscache for pg_database indexed by name, so we must look
2019  * the hard way.
2020  */
2022  ScanKeyInit(&entry[0],
2024  BTEqualStrategyNumber, F_NAMEEQ,
2026  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2027  NULL, 1, entry);
2028 
2029  dbtuple = systable_getnext(scan);
2030 
2031  /* We assume that there can be at most one matching tuple */
2032  if (HeapTupleIsValid(dbtuple))
2033  oid = HeapTupleGetOid(dbtuple);
2034  else
2035  oid = InvalidOid;
2036 
2037  systable_endscan(scan);
2038  heap_close(pg_database, AccessShareLock);
2039 
2040  if (!OidIsValid(oid) && !missing_ok)
2041  ereport(ERROR,
2042  (errcode(ERRCODE_UNDEFINED_DATABASE),
2043  errmsg("database \"%s\" does not exist",
2044  dbname)));
2045 
2046  return oid;
2047 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define DatabaseRelationId
Definition: pg_database.h:29
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ERROR
Definition: elog.h:43
#define Anum_pg_database_datname
Definition: pg_database.h:64
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
char * dbname
Definition: streamutil.c:39
#define DatabaseNameIndexId
Definition: indexing.h:140
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define BTEqualStrategyNumber
Definition: stratnum.h:31
ObjectAddress RenameDatabase ( const char *  oldname,
const char *  newname 
)

Definition at line 977 of file dbcommands.c.

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

Referenced by ExecRenameStmt().

978 {
979  Oid db_id;
980  HeapTuple newtup;
981  Relation rel;
982  int notherbackends;
983  int npreparedxacts;
984  ObjectAddress address;
985 
986  /*
987  * Look up the target database's OID, and get exclusive lock on it. We
988  * need this for the same reasons as DROP DATABASE.
989  */
991 
992  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
993  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
994  ereport(ERROR,
995  (errcode(ERRCODE_UNDEFINED_DATABASE),
996  errmsg("database \"%s\" does not exist", oldname)));
997 
998  /* must be owner */
999  if (!pg_database_ownercheck(db_id, GetUserId()))
1001  oldname);
1002 
1003  /* must have createdb rights */
1004  if (!have_createdb_privilege())
1005  ereport(ERROR,
1006  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1007  errmsg("permission denied to rename database")));
1008 
1009  /*
1010  * Make sure the new name doesn't exist. See notes for same error in
1011  * CREATE DATABASE.
1012  */
1013  if (OidIsValid(get_database_oid(newname, true)))
1014  ereport(ERROR,
1015  (errcode(ERRCODE_DUPLICATE_DATABASE),
1016  errmsg("database \"%s\" already exists", newname)));
1017 
1018  /*
1019  * XXX Client applications probably store the current database somewhere,
1020  * so renaming it could cause confusion. On the other hand, there may not
1021  * be an actual problem besides a little confusion, so think about this
1022  * and decide.
1023  */
1024  if (db_id == MyDatabaseId)
1025  ereport(ERROR,
1026  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1027  errmsg("current database cannot be renamed")));
1028 
1029  /*
1030  * Make sure the database does not have active sessions. This is the same
1031  * concern as above, but applied to other sessions.
1032  *
1033  * As in CREATE DATABASE, check this after other error conditions.
1034  */
1035  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1036  ereport(ERROR,
1037  (errcode(ERRCODE_OBJECT_IN_USE),
1038  errmsg("database \"%s\" is being accessed by other users",
1039  oldname),
1040  errdetail_busy_db(notherbackends, npreparedxacts)));
1041 
1042  /* rename */
1044  if (!HeapTupleIsValid(newtup))
1045  elog(ERROR, "cache lookup failed for database %u", db_id);
1046  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1047  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1048 
1050 
1051  ObjectAddressSet(address, DatabaseRelationId, db_id);
1052 
1053  /*
1054  * Close pg_database, but keep lock till commit.
1055  */
1056  heap_close(rel, NoLock);
1057 
1058  return address;
1059 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
Oid GetUserId(void)
Definition: miscinit.c:284
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1846
#define DatabaseRelationId
Definition: pg_database.h:29
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:216
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:1725
#define OidIsValid(objectId)
Definition: c.h:532
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
Oid MyDatabaseId
Definition: globals.c:77
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2009
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:168
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2890
#define elog
Definition: elog.h:219
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:1979