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

Go to the source code of this file.

Functions

Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void dropdb (const char *dbname, bool missing_ok, bool force)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterDatabaseRefreshColl (AlterDatabaseRefreshCollStmt *stmt)
 
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 2174 of file dbcommands.c.

2175 {
2176  Relation rel;
2177  Oid dboid;
2178  HeapTuple tuple,
2179  newtuple;
2180  Form_pg_database datform;
2181  ScanKeyData scankey;
2182  SysScanDesc scan;
2183  ListCell *option;
2184  bool dbistemplate = false;
2185  bool dballowconnections = true;
2186  int dbconnlimit = -1;
2187  DefElem *distemplate = NULL;
2188  DefElem *dallowconnections = NULL;
2189  DefElem *dconnlimit = NULL;
2190  DefElem *dtablespace = NULL;
2191  Datum new_record[Natts_pg_database] = {0};
2192  bool new_record_nulls[Natts_pg_database] = {0};
2193  bool new_record_repl[Natts_pg_database] = {0};
2194 
2195  /* Extract options from the statement node tree */
2196  foreach(option, stmt->options)
2197  {
2198  DefElem *defel = (DefElem *) lfirst(option);
2199 
2200  if (strcmp(defel->defname, "is_template") == 0)
2201  {
2202  if (distemplate)
2203  errorConflictingDefElem(defel, pstate);
2204  distemplate = defel;
2205  }
2206  else if (strcmp(defel->defname, "allow_connections") == 0)
2207  {
2208  if (dallowconnections)
2209  errorConflictingDefElem(defel, pstate);
2210  dallowconnections = defel;
2211  }
2212  else if (strcmp(defel->defname, "connection_limit") == 0)
2213  {
2214  if (dconnlimit)
2215  errorConflictingDefElem(defel, pstate);
2216  dconnlimit = defel;
2217  }
2218  else if (strcmp(defel->defname, "tablespace") == 0)
2219  {
2220  if (dtablespace)
2221  errorConflictingDefElem(defel, pstate);
2222  dtablespace = defel;
2223  }
2224  else
2225  ereport(ERROR,
2226  (errcode(ERRCODE_SYNTAX_ERROR),
2227  errmsg("option \"%s\" not recognized", defel->defname),
2228  parser_errposition(pstate, defel->location)));
2229  }
2230 
2231  if (dtablespace)
2232  {
2233  /*
2234  * While the SET TABLESPACE syntax doesn't allow any other options,
2235  * somebody could write "WITH TABLESPACE ...". Forbid any other
2236  * options from being specified in that case.
2237  */
2238  if (list_length(stmt->options) != 1)
2239  ereport(ERROR,
2240  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2241  errmsg("option \"%s\" cannot be specified with other options",
2242  dtablespace->defname),
2243  parser_errposition(pstate, dtablespace->location)));
2244  /* this case isn't allowed within a transaction block */
2245  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2246  movedb(stmt->dbname, defGetString(dtablespace));
2247  return InvalidOid;
2248  }
2249 
2250  if (distemplate && distemplate->arg)
2251  dbistemplate = defGetBoolean(distemplate);
2252  if (dallowconnections && dallowconnections->arg)
2253  dballowconnections = defGetBoolean(dallowconnections);
2254  if (dconnlimit && dconnlimit->arg)
2255  {
2256  dbconnlimit = defGetInt32(dconnlimit);
2257  if (dbconnlimit < -1)
2258  ereport(ERROR,
2259  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2260  errmsg("invalid connection limit: %d", dbconnlimit)));
2261  }
2262 
2263  /*
2264  * Get the old tuple. We don't need a lock on the database per se,
2265  * because we're not going to do anything that would mess up incoming
2266  * connections.
2267  */
2268  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2269  ScanKeyInit(&scankey,
2270  Anum_pg_database_datname,
2271  BTEqualStrategyNumber, F_NAMEEQ,
2272  CStringGetDatum(stmt->dbname));
2273  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2274  NULL, 1, &scankey);
2275  tuple = systable_getnext(scan);
2276  if (!HeapTupleIsValid(tuple))
2277  ereport(ERROR,
2278  (errcode(ERRCODE_UNDEFINED_DATABASE),
2279  errmsg("database \"%s\" does not exist", stmt->dbname)));
2280 
2281  datform = (Form_pg_database) GETSTRUCT(tuple);
2282  dboid = datform->oid;
2283 
2284  if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2286  stmt->dbname);
2287 
2288  /*
2289  * In order to avoid getting locked out and having to go through
2290  * standalone mode, we refuse to disallow connections to the database
2291  * we're currently connected to. Lockout can still happen with concurrent
2292  * sessions but the likeliness of that is not high enough to worry about.
2293  */
2294  if (!dballowconnections && dboid == MyDatabaseId)
2295  ereport(ERROR,
2296  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2297  errmsg("cannot disallow connections for current database")));
2298 
2299  /*
2300  * Build an updated tuple, perusing the information just obtained
2301  */
2302  if (distemplate)
2303  {
2304  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2305  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2306  }
2307  if (dallowconnections)
2308  {
2309  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2310  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2311  }
2312  if (dconnlimit)
2313  {
2314  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2315  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2316  }
2317 
2318  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2319  new_record_nulls, new_record_repl);
2320  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2321 
2322  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2323 
2324  systable_endscan(scan);
2325 
2326  /* Close pg_database, but keep lock till commit */
2327  table_close(rel, NoLock);
2328 
2329  return dboid;
2330 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3485
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4799
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1812
int32 defGetInt32(DefElem *def)
Definition: define.c:163
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:497
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
@ OBJECT_DATABASE
Definition: parsenodes.h:1897
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
uintptr_t Datum
Definition: postgres.h:412
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:698
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:560
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:527
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char * defname
Definition: parsenodes.h:779
int location
Definition: parsenodes.h:783
Node * arg
Definition: parsenodes.h:780
ItemPointerData t_self
Definition: htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3469

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2446 of file dbcommands.c.

2447 {
2448  Oid db_id;
2449  HeapTuple tuple;
2450  Relation rel;
2451  ScanKeyData scankey;
2452  SysScanDesc scan;
2453  Form_pg_database datForm;
2454  ObjectAddress address;
2455 
2456  /*
2457  * Get the old tuple. We don't need a lock on the database per se,
2458  * because we're not going to do anything that would mess up incoming
2459  * connections.
2460  */
2461  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2462  ScanKeyInit(&scankey,
2463  Anum_pg_database_datname,
2464  BTEqualStrategyNumber, F_NAMEEQ,
2466  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2467  NULL, 1, &scankey);
2468  tuple = systable_getnext(scan);
2469  if (!HeapTupleIsValid(tuple))
2470  ereport(ERROR,
2471  (errcode(ERRCODE_UNDEFINED_DATABASE),
2472  errmsg("database \"%s\" does not exist", dbname)));
2473 
2474  datForm = (Form_pg_database) GETSTRUCT(tuple);
2475  db_id = datForm->oid;
2476 
2477  /*
2478  * If the new owner is the same as the existing owner, consider the
2479  * command to have succeeded. This is to be consistent with other
2480  * objects.
2481  */
2482  if (datForm->datdba != newOwnerId)
2483  {
2484  Datum repl_val[Natts_pg_database];
2485  bool repl_null[Natts_pg_database] = {0};
2486  bool repl_repl[Natts_pg_database] = {0};
2487  Acl *newAcl;
2488  Datum aclDatum;
2489  bool isNull;
2490  HeapTuple newtuple;
2491 
2492  /* Otherwise, must be owner of the existing object */
2493  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2495  dbname);
2496 
2497  /* Must be able to become new owner */
2498  check_can_set_role(GetUserId(), newOwnerId);
2499 
2500  /*
2501  * must have createdb rights
2502  *
2503  * NOTE: This is different from other alter-owner checks in that the
2504  * current user is checked for createdb privileges instead of the
2505  * destination owner. This is consistent with the CREATE case for
2506  * databases. Because superusers will always have this right, we need
2507  * no special case for them.
2508  */
2509  if (!have_createdb_privilege())
2510  ereport(ERROR,
2511  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2512  errmsg("permission denied to change owner of database")));
2513 
2514  repl_repl[Anum_pg_database_datdba - 1] = true;
2515  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2516 
2517  /*
2518  * Determine the modified ACL for the new owner. This is only
2519  * necessary when the ACL is non-null.
2520  */
2521  aclDatum = heap_getattr(tuple,
2522  Anum_pg_database_datacl,
2523  RelationGetDescr(rel),
2524  &isNull);
2525  if (!isNull)
2526  {
2527  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2528  datForm->datdba, newOwnerId);
2529  repl_repl[Anum_pg_database_datacl - 1] = true;
2530  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2531  }
2532 
2533  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2534  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2535 
2536  heap_freetuple(newtuple);
2537 
2538  /* Update owner dependency reference */
2539  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2540  }
2541 
2542  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2543 
2544  ObjectAddressSet(address, DatabaseRelationId, db_id);
2545 
2546  systable_endscan(scan);
2547 
2548  /* Close pg_database, but keep lock till commit */
2549  table_close(rel, NoLock);
2550 
2551  return address;
2552 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1065
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5006
#define DatumGetAclP(X)
Definition: acl.h:120
static bool have_createdb_privilege(void)
Definition: dbcommands.c:2746
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:788
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
char * dbname
Definition: streamutil.c:51

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)

Definition at line 2337 of file dbcommands.c.

2338 {
2339  Relation rel;
2340  ScanKeyData scankey;
2341  SysScanDesc scan;
2342  Oid db_id;
2343  HeapTuple tuple;
2344  Form_pg_database datForm;
2345  ObjectAddress address;
2346  Datum datum;
2347  bool isnull;
2348  char *oldversion;
2349  char *newversion;
2350 
2351  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2352  ScanKeyInit(&scankey,
2353  Anum_pg_database_datname,
2354  BTEqualStrategyNumber, F_NAMEEQ,
2355  CStringGetDatum(stmt->dbname));
2356  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2357  NULL, 1, &scankey);
2358  tuple = systable_getnext(scan);
2359  if (!HeapTupleIsValid(tuple))
2360  ereport(ERROR,
2361  (errcode(ERRCODE_UNDEFINED_DATABASE),
2362  errmsg("database \"%s\" does not exist", stmt->dbname)));
2363 
2364  datForm = (Form_pg_database) GETSTRUCT(tuple);
2365  db_id = datForm->oid;
2366 
2367  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2369  stmt->dbname);
2370 
2371  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2372  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2373 
2374  datum = heap_getattr(tuple, datForm->datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2375  if (isnull)
2376  elog(ERROR, "unexpected null in pg_database");
2377  newversion = get_collation_actual_version(datForm->datlocprovider, TextDatumGetCString(datum));
2378 
2379  /* cannot change from NULL to non-NULL or vice versa */
2380  if ((!oldversion && newversion) || (oldversion && !newversion))
2381  elog(ERROR, "invalid collation version change");
2382  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2383  {
2384  bool nulls[Natts_pg_database] = {0};
2385  bool replaces[Natts_pg_database] = {0};
2386  Datum values[Natts_pg_database] = {0};
2387 
2388  ereport(NOTICE,
2389  (errmsg("changing version from %s to %s",
2390  oldversion, newversion)));
2391 
2392  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2393  replaces[Anum_pg_database_datcollversion - 1] = true;
2394 
2395  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2396  values, nulls, replaces);
2397  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2398  heap_freetuple(tuple);
2399  }
2400  else
2401  ereport(NOTICE,
2402  (errmsg("version has not changed")));
2403 
2404  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2405 
2406  ObjectAddressSet(address, DatabaseRelationId, db_id);
2407 
2408  systable_endscan(scan);
2409 
2410  table_close(rel, NoLock);
2411 
2412  return address;
2413 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NOTICE
Definition: elog.h:31
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1647

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), CStringGetTextDatum, AlterDatabaseRefreshCollStmt::dbname, elog(), ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), GETSTRUCT, GetUserId(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, NOTICE, OBJECT_DATABASE, object_ownercheck(), ObjectAddressSet, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, and values.

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2420 of file dbcommands.c.

2421 {
2422  Oid datid = get_database_oid(stmt->dbname, false);
2423 
2424  /*
2425  * Obtain a lock on the database and make sure it didn't go away in the
2426  * meantime.
2427  */
2428  shdepLockAndCheckObject(DatabaseRelationId, datid);
2429 
2430  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2432  stmt->dbname);
2433 
2434  AlterSetting(datid, InvalidOid, stmt->setstmt);
2435 
2436  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2437 
2438  return datid;
2439 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2934
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1067
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1166
VariableSetStmt * setstmt
Definition: parsenodes.h:3427

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

Referenced by standard_ProcessUtility().

◆ check_encoding_locale_matches()

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

Definition at line 1431 of file dbcommands.c.

1432 {
1433  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1434  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1435 
1436  if (!(ctype_encoding == encoding ||
1437  ctype_encoding == PG_SQL_ASCII ||
1438  ctype_encoding == -1 ||
1439 #ifdef WIN32
1440  encoding == PG_UTF8 ||
1441 #endif
1442  (encoding == PG_SQL_ASCII && superuser())))
1443  ereport(ERROR,
1444  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1445  errmsg("encoding \"%s\" does not match locale \"%s\"",
1447  ctype),
1448  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1449  pg_encoding_to_char(ctype_encoding))));
1450 
1451  if (!(collate_encoding == encoding ||
1452  collate_encoding == PG_SQL_ASCII ||
1453  collate_encoding == -1 ||
1454 #ifdef WIN32
1455  encoding == PG_UTF8 ||
1456 #endif
1457  (encoding == PG_SQL_ASCII && superuser())))
1458  ereport(ERROR,
1459  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1460  errmsg("encoding \"%s\" does not match locale \"%s\"",
1462  collate),
1463  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1464  pg_encoding_to_char(collate_encoding))));
1465 }
int errdetail(const char *fmt,...)
Definition: elog.c:1039
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
bool superuser(void)
Definition: superuser.c:46

References encoding, 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().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 671 of file dbcommands.c.

672 {
673  Oid src_dboid;
674  Oid src_owner;
675  int src_encoding = -1;
676  char *src_collate = NULL;
677  char *src_ctype = NULL;
678  char *src_iculocale = NULL;
679  char src_locprovider = '\0';
680  char *src_collversion = NULL;
681  bool src_istemplate;
682  bool src_allowconn;
683  TransactionId src_frozenxid = InvalidTransactionId;
684  MultiXactId src_minmxid = InvalidMultiXactId;
685  Oid src_deftablespace;
686  volatile Oid dst_deftablespace;
687  Relation pg_database_rel;
688  HeapTuple tuple;
689  Datum new_record[Natts_pg_database] = {0};
690  bool new_record_nulls[Natts_pg_database] = {0};
691  Oid dboid = InvalidOid;
692  Oid datdba;
693  ListCell *option;
694  DefElem *dtablespacename = NULL;
695  DefElem *downer = NULL;
696  DefElem *dtemplate = NULL;
697  DefElem *dencoding = NULL;
698  DefElem *dlocale = NULL;
699  DefElem *dcollate = NULL;
700  DefElem *dctype = NULL;
701  DefElem *diculocale = NULL;
702  DefElem *dlocprovider = NULL;
703  DefElem *distemplate = NULL;
704  DefElem *dallowconnections = NULL;
705  DefElem *dconnlimit = NULL;
706  DefElem *dcollversion = NULL;
707  DefElem *dstrategy = NULL;
708  char *dbname = stmt->dbname;
709  char *dbowner = NULL;
710  const char *dbtemplate = NULL;
711  char *dbcollate = NULL;
712  char *dbctype = NULL;
713  char *dbiculocale = NULL;
714  char dblocprovider = '\0';
715  char *canonname;
716  int encoding = -1;
717  bool dbistemplate = false;
718  bool dballowconnections = true;
719  int dbconnlimit = -1;
720  char *dbcollversion = NULL;
721  int notherbackends;
722  int npreparedxacts;
723  CreateDBStrategy dbstrategy = CREATEDB_WAL_LOG;
725 
726  /* Extract options from the statement node tree */
727  foreach(option, stmt->options)
728  {
729  DefElem *defel = (DefElem *) lfirst(option);
730 
731  if (strcmp(defel->defname, "tablespace") == 0)
732  {
733  if (dtablespacename)
734  errorConflictingDefElem(defel, pstate);
735  dtablespacename = defel;
736  }
737  else if (strcmp(defel->defname, "owner") == 0)
738  {
739  if (downer)
740  errorConflictingDefElem(defel, pstate);
741  downer = defel;
742  }
743  else if (strcmp(defel->defname, "template") == 0)
744  {
745  if (dtemplate)
746  errorConflictingDefElem(defel, pstate);
747  dtemplate = defel;
748  }
749  else if (strcmp(defel->defname, "encoding") == 0)
750  {
751  if (dencoding)
752  errorConflictingDefElem(defel, pstate);
753  dencoding = defel;
754  }
755  else if (strcmp(defel->defname, "locale") == 0)
756  {
757  if (dlocale)
758  errorConflictingDefElem(defel, pstate);
759  dlocale = defel;
760  }
761  else if (strcmp(defel->defname, "lc_collate") == 0)
762  {
763  if (dcollate)
764  errorConflictingDefElem(defel, pstate);
765  dcollate = defel;
766  }
767  else if (strcmp(defel->defname, "lc_ctype") == 0)
768  {
769  if (dctype)
770  errorConflictingDefElem(defel, pstate);
771  dctype = defel;
772  }
773  else if (strcmp(defel->defname, "icu_locale") == 0)
774  {
775  if (diculocale)
776  errorConflictingDefElem(defel, pstate);
777  diculocale = defel;
778  }
779  else if (strcmp(defel->defname, "locale_provider") == 0)
780  {
781  if (dlocprovider)
782  errorConflictingDefElem(defel, pstate);
783  dlocprovider = defel;
784  }
785  else if (strcmp(defel->defname, "is_template") == 0)
786  {
787  if (distemplate)
788  errorConflictingDefElem(defel, pstate);
789  distemplate = defel;
790  }
791  else if (strcmp(defel->defname, "allow_connections") == 0)
792  {
793  if (dallowconnections)
794  errorConflictingDefElem(defel, pstate);
795  dallowconnections = defel;
796  }
797  else if (strcmp(defel->defname, "connection_limit") == 0)
798  {
799  if (dconnlimit)
800  errorConflictingDefElem(defel, pstate);
801  dconnlimit = defel;
802  }
803  else if (strcmp(defel->defname, "collation_version") == 0)
804  {
805  if (dcollversion)
806  errorConflictingDefElem(defel, pstate);
807  dcollversion = defel;
808  }
809  else if (strcmp(defel->defname, "location") == 0)
810  {
812  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
813  errmsg("LOCATION is not supported anymore"),
814  errhint("Consider using tablespaces instead."),
815  parser_errposition(pstate, defel->location)));
816  }
817  else if (strcmp(defel->defname, "oid") == 0)
818  {
819  dboid = defGetObjectId(defel);
820 
821  /*
822  * We don't normally permit new databases to be created with
823  * system-assigned OIDs. pg_upgrade tries to preserve database
824  * OIDs, so we can't allow any database to be created with an OID
825  * that might be in use in a freshly-initialized cluster created
826  * by some future version. We assume all such OIDs will be from
827  * the system-managed OID range.
828  *
829  * As an exception, however, we permit any OID to be assigned when
830  * allow_system_table_mods=on (so that initdb can assign system
831  * OIDs to template0 and postgres) or when performing a binary
832  * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
833  * in the source cluster).
834  */
835  if (dboid < FirstNormalObjectId &&
837  ereport(ERROR,
838  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
839  errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
840  }
841  else if (strcmp(defel->defname, "strategy") == 0)
842  {
843  if (dstrategy)
844  errorConflictingDefElem(defel, pstate);
845  dstrategy = defel;
846  }
847  else
848  ereport(ERROR,
849  (errcode(ERRCODE_SYNTAX_ERROR),
850  errmsg("option \"%s\" not recognized", defel->defname),
851  parser_errposition(pstate, defel->location)));
852  }
853 
854  if (downer && downer->arg)
855  dbowner = defGetString(downer);
856  if (dtemplate && dtemplate->arg)
857  dbtemplate = defGetString(dtemplate);
858  if (dencoding && dencoding->arg)
859  {
860  const char *encoding_name;
861 
862  if (IsA(dencoding->arg, Integer))
863  {
864  encoding = defGetInt32(dencoding);
865  encoding_name = pg_encoding_to_char(encoding);
866  if (strcmp(encoding_name, "") == 0 ||
867  pg_valid_server_encoding(encoding_name) < 0)
868  ereport(ERROR,
869  (errcode(ERRCODE_UNDEFINED_OBJECT),
870  errmsg("%d is not a valid encoding code",
871  encoding),
872  parser_errposition(pstate, dencoding->location)));
873  }
874  else
875  {
876  encoding_name = defGetString(dencoding);
877  encoding = pg_valid_server_encoding(encoding_name);
878  if (encoding < 0)
879  ereport(ERROR,
880  (errcode(ERRCODE_UNDEFINED_OBJECT),
881  errmsg("%s is not a valid encoding name",
882  encoding_name),
883  parser_errposition(pstate, dencoding->location)));
884  }
885  }
886  if (dlocale && dlocale->arg)
887  {
888  dbcollate = defGetString(dlocale);
889  dbctype = defGetString(dlocale);
890  }
891  if (dcollate && dcollate->arg)
892  dbcollate = defGetString(dcollate);
893  if (dctype && dctype->arg)
894  dbctype = defGetString(dctype);
895  if (diculocale && diculocale->arg)
896  dbiculocale = defGetString(diculocale);
897  if (dlocprovider && dlocprovider->arg)
898  {
899  char *locproviderstr = defGetString(dlocprovider);
900 
901  if (pg_strcasecmp(locproviderstr, "icu") == 0)
902  dblocprovider = COLLPROVIDER_ICU;
903  else if (pg_strcasecmp(locproviderstr, "libc") == 0)
904  dblocprovider = COLLPROVIDER_LIBC;
905  else
906  ereport(ERROR,
907  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
908  errmsg("unrecognized locale provider: %s",
909  locproviderstr)));
910  }
911  if (distemplate && distemplate->arg)
912  dbistemplate = defGetBoolean(distemplate);
913  if (dallowconnections && dallowconnections->arg)
914  dballowconnections = defGetBoolean(dallowconnections);
915  if (dconnlimit && dconnlimit->arg)
916  {
917  dbconnlimit = defGetInt32(dconnlimit);
918  if (dbconnlimit < -1)
919  ereport(ERROR,
920  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
921  errmsg("invalid connection limit: %d", dbconnlimit)));
922  }
923  if (dcollversion)
924  dbcollversion = defGetString(dcollversion);
925 
926  /* obtain OID of proposed owner */
927  if (dbowner)
928  datdba = get_role_oid(dbowner, false);
929  else
930  datdba = GetUserId();
931 
932  /*
933  * To create a database, must have createdb privilege and must be able to
934  * become the target role (this does not imply that the target role itself
935  * must have createdb privilege). The latter provision guards against
936  * "giveaway" attacks. Note that a superuser will always have both of
937  * these privileges a fortiori.
938  */
940  ereport(ERROR,
941  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
942  errmsg("permission denied to create database")));
943 
944  check_can_set_role(GetUserId(), datdba);
945 
946  /*
947  * Lookup database (template) to be cloned, and obtain share lock on it.
948  * ShareLock allows two CREATE DATABASEs to work from the same template
949  * concurrently, while ensuring no one is busy dropping it in parallel
950  * (which would be Very Bad since we'd likely get an incomplete copy
951  * without knowing it). This also prevents any new connections from being
952  * made to the source until we finish copying it, so we can be sure it
953  * won't change underneath us.
954  */
955  if (!dbtemplate)
956  dbtemplate = "template1"; /* Default template database name */
957 
958  if (!get_db_info(dbtemplate, ShareLock,
959  &src_dboid, &src_owner, &src_encoding,
960  &src_istemplate, &src_allowconn,
961  &src_frozenxid, &src_minmxid, &src_deftablespace,
962  &src_collate, &src_ctype, &src_iculocale, &src_locprovider,
963  &src_collversion))
964  ereport(ERROR,
965  (errcode(ERRCODE_UNDEFINED_DATABASE),
966  errmsg("template database \"%s\" does not exist",
967  dbtemplate)));
968 
969  /*
970  * Permission check: to copy a DB that's not marked datistemplate, you
971  * must be superuser or the owner thereof.
972  */
973  if (!src_istemplate)
974  {
975  if (!object_ownercheck(DatabaseRelationId, src_dboid, GetUserId()))
976  ereport(ERROR,
977  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
978  errmsg("permission denied to copy database \"%s\"",
979  dbtemplate)));
980  }
981 
982  /* Validate the database creation strategy. */
983  if (dstrategy && dstrategy->arg)
984  {
985  char *strategy;
986 
987  strategy = defGetString(dstrategy);
988  if (strcmp(strategy, "wal_log") == 0)
989  dbstrategy = CREATEDB_WAL_LOG;
990  else if (strcmp(strategy, "file_copy") == 0)
991  dbstrategy = CREATEDB_FILE_COPY;
992  else
993  ereport(ERROR,
994  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
995  errmsg("invalid create database strategy \"%s\"", strategy),
996  errhint("Valid strategies are \"wal_log\", and \"file_copy\".")));
997  }
998 
999  /* If encoding or locales are defaulted, use source's setting */
1000  if (encoding < 0)
1001  encoding = src_encoding;
1002  if (dbcollate == NULL)
1003  dbcollate = src_collate;
1004  if (dbctype == NULL)
1005  dbctype = src_ctype;
1006  if (dblocprovider == '\0')
1007  dblocprovider = src_locprovider;
1008  if (dbiculocale == NULL && dblocprovider == COLLPROVIDER_ICU)
1009  dbiculocale = src_iculocale;
1010 
1011  /* Some encodings are client only */
1013  ereport(ERROR,
1014  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1015  errmsg("invalid server encoding %d", encoding)));
1016 
1017  /* Check that the chosen locales are valid, and get canonical spellings */
1018  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
1019  ereport(ERROR,
1020  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1021  errmsg("invalid locale name: \"%s\"", dbcollate)));
1022  dbcollate = canonname;
1023  if (!check_locale(LC_CTYPE, dbctype, &canonname))
1024  ereport(ERROR,
1025  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1026  errmsg("invalid locale name: \"%s\"", dbctype)));
1027  dbctype = canonname;
1028 
1029  check_encoding_locale_matches(encoding, dbcollate, dbctype);
1030 
1031  if (dblocprovider == COLLPROVIDER_ICU)
1032  {
1034  ereport(ERROR,
1035  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1036  errmsg("encoding \"%s\" is not supported with ICU provider",
1038 
1039  /*
1040  * This would happen if template0 uses the libc provider but the new
1041  * database uses icu.
1042  */
1043  if (!dbiculocale)
1044  ereport(ERROR,
1045  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1046  errmsg("ICU locale must be specified")));
1047 
1048  check_icu_locale(dbiculocale);
1049  }
1050  else
1051  {
1052  if (dbiculocale)
1053  ereport(ERROR,
1054  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1055  errmsg("ICU locale cannot be specified unless locale provider is ICU")));
1056  }
1057 
1058  /*
1059  * Check that the new encoding and locale settings match the source
1060  * database. We insist on this because we simply copy the source data ---
1061  * any non-ASCII data would be wrongly encoded, and any indexes sorted
1062  * according to the source locale would be wrong.
1063  *
1064  * However, we assume that template0 doesn't contain any non-ASCII data
1065  * nor any indexes that depend on collation or ctype, so template0 can be
1066  * used as template for creating a database with any encoding or locale.
1067  */
1068  if (strcmp(dbtemplate, "template0") != 0)
1069  {
1070  if (encoding != src_encoding)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1073  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1075  pg_encoding_to_char(src_encoding)),
1076  errhint("Use the same encoding as in the template database, or use template0 as template.")));
1077 
1078  if (strcmp(dbcollate, src_collate) != 0)
1079  ereport(ERROR,
1080  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1081  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1082  dbcollate, src_collate),
1083  errhint("Use the same collation as in the template database, or use template0 as template.")));
1084 
1085  if (strcmp(dbctype, src_ctype) != 0)
1086  ereport(ERROR,
1087  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1088  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1089  dbctype, src_ctype),
1090  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1091 
1092  if (dblocprovider != src_locprovider)
1093  ereport(ERROR,
1094  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1095  errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1096  collprovider_name(dblocprovider), collprovider_name(src_locprovider)),
1097  errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1098 
1099  if (dblocprovider == COLLPROVIDER_ICU)
1100  {
1101  Assert(dbiculocale);
1102  Assert(src_iculocale);
1103  if (strcmp(dbiculocale, src_iculocale) != 0)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1106  errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1107  dbiculocale, src_iculocale),
1108  errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1109  }
1110  }
1111 
1112  /*
1113  * If we got a collation version for the template database, check that it
1114  * matches the actual OS collation version. Otherwise error; the user
1115  * needs to fix the template database first. Don't complain if a
1116  * collation version was specified explicitly as a statement option; that
1117  * is used by pg_upgrade to reproduce the old state exactly.
1118  *
1119  * (If the template database has no collation version, then either the
1120  * platform/provider does not support collation versioning, or it's
1121  * template0, for which we stipulate that it does not contain
1122  * collation-using objects.)
1123  */
1124  if (src_collversion && !dcollversion)
1125  {
1126  char *actual_versionstr;
1127 
1128  actual_versionstr = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1129  if (!actual_versionstr)
1130  ereport(ERROR,
1131  (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1132  dbtemplate)));
1133 
1134  if (strcmp(actual_versionstr, src_collversion) != 0)
1135  ereport(ERROR,
1136  (errmsg("template database \"%s\" has a collation version mismatch",
1137  dbtemplate),
1138  errdetail("The template database was created using collation version %s, "
1139  "but the operating system provides version %s.",
1140  src_collversion, actual_versionstr),
1141  errhint("Rebuild all objects in the template database that use the default collation and run "
1142  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1143  "or build PostgreSQL with the right library version.",
1144  quote_identifier(dbtemplate))));
1145  }
1146 
1147  if (dbcollversion == NULL)
1148  dbcollversion = src_collversion;
1149 
1150  /*
1151  * Normally, we copy the collation version from the template database.
1152  * This last resort only applies if the template database does not have a
1153  * collation version, which is normally only the case for template0.
1154  */
1155  if (dbcollversion == NULL)
1156  dbcollversion = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1157 
1158  /* Resolve default tablespace for new database */
1159  if (dtablespacename && dtablespacename->arg)
1160  {
1161  char *tablespacename;
1162  AclResult aclresult;
1163 
1164  tablespacename = defGetString(dtablespacename);
1165  dst_deftablespace = get_tablespace_oid(tablespacename, false);
1166  /* check permissions */
1167  aclresult = object_aclcheck(TableSpaceRelationId, dst_deftablespace, GetUserId(),
1168  ACL_CREATE);
1169  if (aclresult != ACLCHECK_OK)
1170  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1171  tablespacename);
1172 
1173  /* pg_global must never be the default tablespace */
1174  if (dst_deftablespace == GLOBALTABLESPACE_OID)
1175  ereport(ERROR,
1176  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1177  errmsg("pg_global cannot be used as default tablespace")));
1178 
1179  /*
1180  * If we are trying to change the default tablespace of the template,
1181  * we require that the template not have any files in the new default
1182  * tablespace. This is necessary because otherwise the copied
1183  * database would contain pg_class rows that refer to its default
1184  * tablespace both explicitly (by OID) and implicitly (as zero), which
1185  * would cause problems. For example another CREATE DATABASE using
1186  * the copied database as template, and trying to change its default
1187  * tablespace again, would yield outright incorrect results (it would
1188  * improperly move tables to the new default tablespace that should
1189  * stay in the same tablespace).
1190  */
1191  if (dst_deftablespace != src_deftablespace)
1192  {
1193  char *srcpath;
1194  struct stat st;
1195 
1196  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
1197 
1198  if (stat(srcpath, &st) == 0 &&
1199  S_ISDIR(st.st_mode) &&
1200  !directory_is_empty(srcpath))
1201  ereport(ERROR,
1202  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1203  errmsg("cannot assign new default tablespace \"%s\"",
1204  tablespacename),
1205  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1206  dbtemplate)));
1207  pfree(srcpath);
1208  }
1209  }
1210  else
1211  {
1212  /* Use template database's default tablespace */
1213  dst_deftablespace = src_deftablespace;
1214  /* Note there is no additional permission check in this path */
1215  }
1216 
1217  /*
1218  * If built with appropriate switch, whine when regression-testing
1219  * conventions for database names are violated. But don't complain during
1220  * initdb.
1221  */
1222 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1223  if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1224  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1225 #endif
1226 
1227  /*
1228  * Check for db name conflict. This is just to give a more friendly error
1229  * message than "unique index violation". There's a race condition but
1230  * we're willing to accept the less friendly message in that case.
1231  */
1232  if (OidIsValid(get_database_oid(dbname, true)))
1233  ereport(ERROR,
1234  (errcode(ERRCODE_DUPLICATE_DATABASE),
1235  errmsg("database \"%s\" already exists", dbname)));
1236 
1237  /*
1238  * The source DB can't have any active backends, except this one
1239  * (exception is to allow CREATE DB while connected to template1).
1240  * Otherwise we might copy inconsistent data.
1241  *
1242  * This should be last among the basic error checks, because it involves
1243  * potential waiting; we may as well throw an error first if we're gonna
1244  * throw one.
1245  */
1246  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
1247  ereport(ERROR,
1248  (errcode(ERRCODE_OBJECT_IN_USE),
1249  errmsg("source database \"%s\" is being accessed by other users",
1250  dbtemplate),
1251  errdetail_busy_db(notherbackends, npreparedxacts)));
1252 
1253  /*
1254  * Select an OID for the new database, checking that it doesn't have a
1255  * filename conflict with anything already existing in the tablespace
1256  * directories.
1257  */
1258  pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
1259 
1260  /*
1261  * If database OID is configured, check if the OID is already in use or
1262  * data directory already exists.
1263  */
1264  if (OidIsValid(dboid))
1265  {
1266  char *existing_dbname = get_database_name(dboid);
1267 
1268  if (existing_dbname != NULL)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1271  errmsg("database OID %u is already in use by database \"%s\"",
1272  dboid, existing_dbname));
1273 
1274  if (check_db_file_conflict(dboid))
1275  ereport(ERROR,
1276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1277  errmsg("data directory with the specified OID %u already exists", dboid));
1278  }
1279  else
1280  {
1281  /* Select an OID for the new database if is not explicitly configured. */
1282  do
1283  {
1284  dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
1285  Anum_pg_database_oid);
1286  } while (check_db_file_conflict(dboid));
1287  }
1288 
1289  /*
1290  * Insert a new tuple into pg_database. This establishes our ownership of
1291  * the new database name (anyone else trying to insert the same name will
1292  * block on the unique index, and fail after we commit).
1293  */
1294 
1295  Assert((dblocprovider == COLLPROVIDER_ICU && dbiculocale) ||
1296  (dblocprovider != COLLPROVIDER_ICU && !dbiculocale));
1297 
1298  /* Form tuple */
1299  new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
1300  new_record[Anum_pg_database_datname - 1] =
1302  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
1303  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
1304  new_record[Anum_pg_database_datlocprovider - 1] = CharGetDatum(dblocprovider);
1305  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1306  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1307  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1308  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
1309  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
1310  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
1311  new_record[Anum_pg_database_datcollate - 1] = CStringGetTextDatum(dbcollate);
1312  new_record[Anum_pg_database_datctype - 1] = CStringGetTextDatum(dbctype);
1313  if (dbiculocale)
1314  new_record[Anum_pg_database_daticulocale - 1] = CStringGetTextDatum(dbiculocale);
1315  else
1316  new_record_nulls[Anum_pg_database_daticulocale - 1] = true;
1317  if (dbcollversion)
1318  new_record[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(dbcollversion);
1319  else
1320  new_record_nulls[Anum_pg_database_datcollversion - 1] = true;
1321 
1322  /*
1323  * We deliberately set datacl to default (NULL), rather than copying it
1324  * from the template database. Copying it would be a bad idea when the
1325  * owner is not the same as the template's owner.
1326  */
1327  new_record_nulls[Anum_pg_database_datacl - 1] = true;
1328 
1329  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
1330  new_record, new_record_nulls);
1331 
1332  CatalogTupleInsert(pg_database_rel, tuple);
1333 
1334  /*
1335  * Now generate additional catalog entries associated with the new DB
1336  */
1337 
1338  /* Register owner dependency */
1339  recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
1340 
1341  /* Create pg_shdepend entries for objects within database */
1342  copyTemplateDependencies(src_dboid, dboid);
1343 
1344  /* Post creation hook for new database */
1345  InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
1346 
1347  /*
1348  * If we're going to be reading data for the to-be-created database into
1349  * shared_buffers, take a lock on it. Nobody should know that this
1350  * database exists yet, but it's good to maintain the invariant that an
1351  * AccessExclusiveLock on the database is sufficient to drop all
1352  * of its buffers without worrying about more being read later.
1353  *
1354  * Note that we need to do this before entering the
1355  * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1356  * expects this lock to be held already.
1357  */
1358  if (dbstrategy == CREATEDB_WAL_LOG)
1359  LockSharedObject(DatabaseRelationId, dboid, 0, AccessShareLock);
1360 
1361  /*
1362  * Once we start copying subdirectories, we need to be able to clean 'em
1363  * up if we fail. Use an ENSURE block to make sure this happens. (This
1364  * is not a 100% solution, because of the possibility of failure during
1365  * transaction commit after we leave this routine, but it should handle
1366  * most scenarios.)
1367  */
1368  fparms.src_dboid = src_dboid;
1369  fparms.dest_dboid = dboid;
1370  fparms.strategy = dbstrategy;
1371 
1373  PointerGetDatum(&fparms));
1374  {
1375  /*
1376  * If the user has asked to create a database with WAL_LOG strategy
1377  * then call CreateDatabaseUsingWalLog, which will copy the database
1378  * at the block level and it will WAL log each copied block.
1379  * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1380  * database file by file.
1381  */
1382  if (dbstrategy == CREATEDB_WAL_LOG)
1383  CreateDatabaseUsingWalLog(src_dboid, dboid, src_deftablespace,
1384  dst_deftablespace);
1385  else
1386  CreateDatabaseUsingFileCopy(src_dboid, dboid, src_deftablespace,
1387  dst_deftablespace);
1388 
1389  /*
1390  * Close pg_database, but keep lock till commit.
1391  */
1392  table_close(pg_database_rel, NoLock);
1393 
1394  /*
1395  * Force synchronous commit, thus minimizing the window between
1396  * creation of the database files and committal of the transaction. If
1397  * we crash before committing, we'll have a DB that's taking up disk
1398  * space but is not in pg_database, which is not good.
1399  */
1400  ForceSyncCommit();
1401  }
1403  PointerGetDatum(&fparms));
1404 
1405  return dboid;
1406 }
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5235
AclResult
Definition: acl.h:183
@ ACLCHECK_OK
Definition: acl.h:184
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:4598
bool directory_is_empty(const char *path)
Definition: tablespace.c:859
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1432
TransactionId MultiXactId
Definition: c.h:598
uint32 TransactionId
Definition: c.h:588
#define OidIsValid(objectId)
Definition: c.h:711
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbIculocale, char *dbLocProvider, char **dbCollversion)
Definition: dbcommands.c:2598
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2981
CreateDBStrategy
Definition: dbcommands.c:84
@ CREATEDB_FILE_COPY
Definition: dbcommands.c:86
@ CREATEDB_WAL_LOG
Definition: dbcommands.c:85
static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:149
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Definition: dbcommands.c:1431
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2904
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:2861
static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:551
static void createdb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1469
Oid defGetObjectId(DefElem *def)
Definition: define.c:220
int errhint(const char *fmt,...)
Definition: elog.c:1153
#define WARNING
Definition: elog.h:32
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
bool is_encoding_supported_by_icu(int encoding)
Definition: encnames.c:459
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
bool IsBinaryUpgrade
Definition: globals.c:114
bool IsUnderPostmaster
Definition: globals.c:113
bool allowSystemTableMods
Definition: globals.c:124
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define ShareLock
Definition: lockdefs.h:40
void pfree(void *pointer)
Definition: mcxt.c:1306
#define InvalidMultiXactId
Definition: multixact.h:24
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
@ OBJECT_TABLESPACE
Definition: parsenodes.h:1930
#define ACL_CREATE
Definition: parsenodes.h:92
void check_icu_locale(const char *icu_locale)
Definition: pg_locale.c:1954
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:247
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
Definition: pg_shdepend.c:850
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:281
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:620
static Datum CharGetDatum(char X)
Definition: postgres.h:470
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:3716
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11529
List * options
Definition: parsenodes.h:3403
char * dbname
Definition: parsenodes.h:3402
Definition: value.h:29
CreateDBStrategy strategy
Definition: dbcommands.c:93
#define InvalidTransactionId
Definition: transam.h:31
#define FirstNormalObjectId
Definition: transam.h:197
#define stat
Definition: win32_port.h:286
#define S_ISDIR(m)
Definition: win32_port.h:327
void ForceSyncCommit(void)
Definition: xact.c:1127

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, DefElem::arg, Assert(), BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_can_set_role(), check_db_file_conflict(), check_encoding_locale_matches(), check_icu_locale(), check_locale(), copyTemplateDependencies(), CountOtherDBBackends(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb_failure_callback(), CREATEDB_FILE_COPY, CREATEDB_WAL_LOG, CStringGetDatum(), CStringGetTextDatum, dbname, CreatedbStmt::dbname, defGetBoolean(), defGetInt32(), defGetObjectId(), defGetString(), DefElem::defname, createdb_failure_params::dest_dboid, DirectFunctionCall1, directory_is_empty(), elog(), encoding, ereport, errcode(), errdetail(), errdetail_busy_db(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), FirstNormalObjectId, ForceSyncCommit(), get_collation_actual_version(), get_database_name(), get_database_oid(), get_db_info(), get_role_oid(), get_tablespace_oid(), GetDatabasePath(), GetNewOidWithIndex(), GetUserId(), have_createdb_privilege(), heap_form_tuple(), Int32GetDatum(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, is_encoding_supported_by_icu(), IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), namein(), NoLock, object_aclcheck(), object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, CreatedbStmt::options, parser_errposition(), pfree(), pg_encoding_to_char(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_strcasecmp(), PG_VALID_BE_ENCODING, pg_valid_server_encoding(), PointerGetDatum(), quote_identifier(), recordDependencyOnOwner(), RelationGetDescr, RowExclusiveLock, S_ISDIR, ShareLock, createdb_failure_params::src_dboid, stat::st_mode, stat, createdb_failure_params::strategy, table_close(), table_open(), TransactionIdGetDatum(), and WARNING.

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 2149 of file dbcommands.c.

2150 {
2151  bool force = false;
2152  ListCell *lc;
2153 
2154  foreach(lc, stmt->options)
2155  {
2156  DefElem *opt = (DefElem *) lfirst(lc);
2157 
2158  if (strcmp(opt->defname, "force") == 0)
2159  force = true;
2160  else
2161  ereport(ERROR,
2162  (errcode(ERRCODE_SYNTAX_ERROR),
2163  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2164  parser_errposition(pstate, opt->location)));
2165  }
2166 
2167  dropdb(stmt->dbname, stmt->missing_ok, force);
2168 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1508
List * options
Definition: parsenodes.h:3439
char * dbname
Definition: parsenodes.h:3437
bool missing_ok
Definition: parsenodes.h:3438

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1508 of file dbcommands.c.

1509 {
1510  Oid db_id;
1511  bool db_istemplate;
1512  Relation pgdbrel;
1513  HeapTuple tup;
1514  int notherbackends;
1515  int npreparedxacts;
1516  int nslots,
1517  nslots_active;
1518  int nsubscriptions;
1519 
1520  /*
1521  * Look up the target database's OID, and get exclusive lock on it. We
1522  * need this to ensure that no new backend starts up in the target
1523  * database while we are deleting it (see postinit.c), and that no one is
1524  * using it as a CREATE DATABASE template or trying to delete it for
1525  * themselves.
1526  */
1527  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1528 
1529  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1530  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1531  {
1532  if (!missing_ok)
1533  {
1534  ereport(ERROR,
1535  (errcode(ERRCODE_UNDEFINED_DATABASE),
1536  errmsg("database \"%s\" does not exist", dbname)));
1537  }
1538  else
1539  {
1540  /* Close pg_database, release the lock, since we changed nothing */
1541  table_close(pgdbrel, RowExclusiveLock);
1542  ereport(NOTICE,
1543  (errmsg("database \"%s\" does not exist, skipping",
1544  dbname)));
1545  return;
1546  }
1547  }
1548 
1549  /*
1550  * Permission checks
1551  */
1552  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1554  dbname);
1555 
1556  /* DROP hook for the database being removed */
1557  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1558 
1559  /*
1560  * Disallow dropping a DB that is marked istemplate. This is just to
1561  * prevent people from accidentally dropping template0 or template1; they
1562  * can do so if they're really determined ...
1563  */
1564  if (db_istemplate)
1565  ereport(ERROR,
1566  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1567  errmsg("cannot drop a template database")));
1568 
1569  /* Obviously can't drop my own database */
1570  if (db_id == MyDatabaseId)
1571  ereport(ERROR,
1572  (errcode(ERRCODE_OBJECT_IN_USE),
1573  errmsg("cannot drop the currently open database")));
1574 
1575  /*
1576  * Check whether there are active logical slots that refer to the
1577  * to-be-dropped database. The database lock we are holding prevents the
1578  * creation of new slots using the database or existing slots becoming
1579  * active.
1580  */
1581  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1582  if (nslots_active)
1583  {
1584  ereport(ERROR,
1585  (errcode(ERRCODE_OBJECT_IN_USE),
1586  errmsg("database \"%s\" is used by an active logical replication slot",
1587  dbname),
1588  errdetail_plural("There is %d active slot.",
1589  "There are %d active slots.",
1590  nslots_active, nslots_active)));
1591  }
1592 
1593  /*
1594  * Check if there are subscriptions defined in the target database.
1595  *
1596  * We can't drop them automatically because they might be holding
1597  * resources in other databases/instances.
1598  */
1599  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1600  ereport(ERROR,
1601  (errcode(ERRCODE_OBJECT_IN_USE),
1602  errmsg("database \"%s\" is being used by logical replication subscription",
1603  dbname),
1604  errdetail_plural("There is %d subscription.",
1605  "There are %d subscriptions.",
1606  nsubscriptions, nsubscriptions)));
1607 
1608 
1609  /*
1610  * Attempt to terminate all existing connections to the target database if
1611  * the user has requested to do so.
1612  */
1613  if (force)
1614  TerminateOtherDBBackends(db_id);
1615 
1616  /*
1617  * Check for other backends in the target database. (Because we hold the
1618  * database lock, no new ones can start after this.)
1619  *
1620  * As in CREATE DATABASE, check this after other error conditions.
1621  */
1622  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1623  ereport(ERROR,
1624  (errcode(ERRCODE_OBJECT_IN_USE),
1625  errmsg("database \"%s\" is being accessed by other users",
1626  dbname),
1627  errdetail_busy_db(notherbackends, npreparedxacts)));
1628 
1629  /*
1630  * Remove the database's tuple from pg_database.
1631  */
1633  if (!HeapTupleIsValid(tup))
1634  elog(ERROR, "cache lookup failed for database %u", db_id);
1635 
1636  CatalogTupleDelete(pgdbrel, &tup->t_self);
1637 
1638  ReleaseSysCache(tup);
1639 
1640  /*
1641  * Delete any comments or security labels associated with the database.
1642  */
1643  DeleteSharedComments(db_id, DatabaseRelationId);
1644  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1645 
1646  /*
1647  * Remove settings associated with this database
1648  */
1649  DropSetting(db_id, InvalidOid);
1650 
1651  /*
1652  * Remove shared dependency references for the database.
1653  */
1654  dropDatabaseDependencies(db_id);
1655 
1656  /*
1657  * Drop db-specific replication slots.
1658  */
1660 
1661  /*
1662  * Drop pages for this database that are in the shared buffer cache. This
1663  * is important to ensure that no remaining backend tries to write out a
1664  * dirty buffer to the dead database later...
1665  */
1666  DropDatabaseBuffers(db_id);
1667 
1668  /*
1669  * Tell the cumulative stats system to forget it immediately, too.
1670  */
1671  pgstat_drop_database(db_id);
1672 
1673  /*
1674  * Tell checkpointer to forget any pending fsync and unlink requests for
1675  * files in the database; else the fsyncs will fail at next checkpoint, or
1676  * worse, it will delete files that belong to a newly created database
1677  * with the same OID.
1678  */
1680 
1681  /*
1682  * Force a checkpoint to make sure the checkpointer has received the
1683  * message sent by ForgetDatabaseSyncRequests.
1684  */
1686 
1687  /* Close all smgr fds in all backends. */
1689 
1690  /*
1691  * Remove all tablespace subdirs belonging to the database.
1692  */
1693  remove_dbtablespaces(db_id);
1694 
1695  /*
1696  * Close pg_database, but keep lock till commit.
1697  */
1698  table_close(pgdbrel, NoLock);
1699 
1700  /*
1701  * Force synchronous commit, thus minimizing the window between removal of
1702  * the database files and committal of the transaction. If we crash before
1703  * committing, we'll have a DB that's gone on disk but still there
1704  * according to pg_database, which is not good.
1705  */
1706  ForceSyncCommit();
1707 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3413
void RequestCheckpoint(int flags)
Definition: checkpointer.c:931
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2771
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1131
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#define AccessExclusiveLock
Definition: lockdefs.h:43
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1070
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
void DropSetting(Oid databaseid, Oid roleid)
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:954
int CountDBSubscriptions(Oid dbid)
void pgstat_drop_database(Oid databaseid)
void TerminateOtherDBBackends(Oid databaseId)
Definition: procarray.c:3794
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:392
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:332
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:52
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:987
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1043
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ DATABASEOID
Definition: syscache.h:55
#define CHECKPOINT_FORCE
Definition: xlog.h:137
#define CHECKPOINT_WAIT
Definition: xlog.h:140
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:136

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

Referenced by DropDatabase().

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 2981 of file dbcommands.c.

2982 {
2983  HeapTuple dbtuple;
2984  char *result;
2985 
2986  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2987  if (HeapTupleIsValid(dbtuple))
2988  {
2989  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2990  ReleaseSysCache(dbtuple);
2991  }
2992  else
2993  result = NULL;
2994 
2995  return result;
2996 }
#define NameStr(name)
Definition: c.h:682
char * pstrdup(const char *in)
Definition: mcxt.c:1483
NameData datname
Definition: pg_database.h:35

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

Referenced by AfterTriggerSetState(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), calculate_database_size(), createdb(), 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(), lazy_check_wraparound_failsafe(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), perform_work_item(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RenameSchema(), SetMultiXactIdLimit(), SetTransactionIdLimit(), shdepLockAndCheckObject(), TerminateOtherDBBackends(), and transformColumnRef().

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 2934 of file dbcommands.c.

2935 {
2936  Relation pg_database;
2937  ScanKeyData entry[1];
2938  SysScanDesc scan;
2939  HeapTuple dbtuple;
2940  Oid oid;
2941 
2942  /*
2943  * There's no syscache for pg_database indexed by name, so we must look
2944  * the hard way.
2945  */
2946  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2947  ScanKeyInit(&entry[0],
2948  Anum_pg_database_datname,
2949  BTEqualStrategyNumber, F_NAMEEQ,
2951  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2952  NULL, 1, entry);
2953 
2954  dbtuple = systable_getnext(scan);
2955 
2956  /* We assume that there can be at most one matching tuple */
2957  if (HeapTupleIsValid(dbtuple))
2958  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2959  else
2960  oid = InvalidOid;
2961 
2962  systable_endscan(scan);
2963  table_close(pg_database, AccessShareLock);
2964 
2965  if (!OidIsValid(oid) && !missing_ok)
2966  ereport(ERROR,
2967  (errcode(ERRCODE_UNDEFINED_DATABASE),
2968  errmsg("database \"%s\" does not exist",
2969  dbname)));
2970 
2971  return oid;
2972 }

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum(), dbname, 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().

◆ RenameDatabase()

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

Definition at line 1714 of file dbcommands.c.

1715 {
1716  Oid db_id;
1717  HeapTuple newtup;
1718  Relation rel;
1719  int notherbackends;
1720  int npreparedxacts;
1721  ObjectAddress address;
1722 
1723  /*
1724  * Look up the target database's OID, and get exclusive lock on it. We
1725  * need this for the same reasons as DROP DATABASE.
1726  */
1727  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1728 
1729  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1730  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1731  ereport(ERROR,
1732  (errcode(ERRCODE_UNDEFINED_DATABASE),
1733  errmsg("database \"%s\" does not exist", oldname)));
1734 
1735  /* must be owner */
1736  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1738  oldname);
1739 
1740  /* must have createdb rights */
1741  if (!have_createdb_privilege())
1742  ereport(ERROR,
1743  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1744  errmsg("permission denied to rename database")));
1745 
1746  /*
1747  * If built with appropriate switch, whine when regression-testing
1748  * conventions for database names are violated.
1749  */
1750 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1751  if (strstr(newname, "regression") == NULL)
1752  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1753 #endif
1754 
1755  /*
1756  * Make sure the new name doesn't exist. See notes for same error in
1757  * CREATE DATABASE.
1758  */
1759  if (OidIsValid(get_database_oid(newname, true)))
1760  ereport(ERROR,
1761  (errcode(ERRCODE_DUPLICATE_DATABASE),
1762  errmsg("database \"%s\" already exists", newname)));
1763 
1764  /*
1765  * XXX Client applications probably store the current database somewhere,
1766  * so renaming it could cause confusion. On the other hand, there may not
1767  * be an actual problem besides a little confusion, so think about this
1768  * and decide.
1769  */
1770  if (db_id == MyDatabaseId)
1771  ereport(ERROR,
1772  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1773  errmsg("current database cannot be renamed")));
1774 
1775  /*
1776  * Make sure the database does not have active sessions. This is the same
1777  * concern as above, but applied to other sessions.
1778  *
1779  * As in CREATE DATABASE, check this after other error conditions.
1780  */
1781  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1782  ereport(ERROR,
1783  (errcode(ERRCODE_OBJECT_IN_USE),
1784  errmsg("database \"%s\" is being accessed by other users",
1785  oldname),
1786  errdetail_busy_db(notherbackends, npreparedxacts)));
1787 
1788  /* rename */
1790  if (!HeapTupleIsValid(newtup))
1791  elog(ERROR, "cache lookup failed for database %u", db_id);
1792  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1793  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1794 
1795  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1796 
1797  ObjectAddressSet(address, DatabaseRelationId, db_id);
1798 
1799  /*
1800  * Close pg_database, but keep lock till commit.
1801  */
1802  table_close(rel, NoLock);
1803 
1804  return address;
1805 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179

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, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), table_open(), and WARNING.

Referenced by ExecRenameStmt().