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)
 
bool have_createdb_privilege (void)
 
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 2267 of file dbcommands.c.

2268 {
2269  Relation rel;
2270  Oid dboid;
2271  HeapTuple tuple,
2272  newtuple;
2273  Form_pg_database datform;
2274  ScanKeyData scankey;
2275  SysScanDesc scan;
2276  ListCell *option;
2277  bool dbistemplate = false;
2278  bool dballowconnections = true;
2279  int dbconnlimit = DATCONNLIMIT_UNLIMITED;
2280  DefElem *distemplate = NULL;
2281  DefElem *dallowconnections = NULL;
2282  DefElem *dconnlimit = NULL;
2283  DefElem *dtablespace = NULL;
2284  Datum new_record[Natts_pg_database] = {0};
2285  bool new_record_nulls[Natts_pg_database] = {0};
2286  bool new_record_repl[Natts_pg_database] = {0};
2287 
2288  /* Extract options from the statement node tree */
2289  foreach(option, stmt->options)
2290  {
2291  DefElem *defel = (DefElem *) lfirst(option);
2292 
2293  if (strcmp(defel->defname, "is_template") == 0)
2294  {
2295  if (distemplate)
2296  errorConflictingDefElem(defel, pstate);
2297  distemplate = defel;
2298  }
2299  else if (strcmp(defel->defname, "allow_connections") == 0)
2300  {
2301  if (dallowconnections)
2302  errorConflictingDefElem(defel, pstate);
2303  dallowconnections = defel;
2304  }
2305  else if (strcmp(defel->defname, "connection_limit") == 0)
2306  {
2307  if (dconnlimit)
2308  errorConflictingDefElem(defel, pstate);
2309  dconnlimit = defel;
2310  }
2311  else if (strcmp(defel->defname, "tablespace") == 0)
2312  {
2313  if (dtablespace)
2314  errorConflictingDefElem(defel, pstate);
2315  dtablespace = defel;
2316  }
2317  else
2318  ereport(ERROR,
2319  (errcode(ERRCODE_SYNTAX_ERROR),
2320  errmsg("option \"%s\" not recognized", defel->defname),
2321  parser_errposition(pstate, defel->location)));
2322  }
2323 
2324  if (dtablespace)
2325  {
2326  /*
2327  * While the SET TABLESPACE syntax doesn't allow any other options,
2328  * somebody could write "WITH TABLESPACE ...". Forbid any other
2329  * options from being specified in that case.
2330  */
2331  if (list_length(stmt->options) != 1)
2332  ereport(ERROR,
2333  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2334  errmsg("option \"%s\" cannot be specified with other options",
2335  dtablespace->defname),
2336  parser_errposition(pstate, dtablespace->location)));
2337  /* this case isn't allowed within a transaction block */
2338  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2339  movedb(stmt->dbname, defGetString(dtablespace));
2340  return InvalidOid;
2341  }
2342 
2343  if (distemplate && distemplate->arg)
2344  dbistemplate = defGetBoolean(distemplate);
2345  if (dallowconnections && dallowconnections->arg)
2346  dballowconnections = defGetBoolean(dallowconnections);
2347  if (dconnlimit && dconnlimit->arg)
2348  {
2349  dbconnlimit = defGetInt32(dconnlimit);
2350  if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
2351  ereport(ERROR,
2352  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2353  errmsg("invalid connection limit: %d", dbconnlimit)));
2354  }
2355 
2356  /*
2357  * Get the old tuple. We don't need a lock on the database per se,
2358  * because we're not going to do anything that would mess up incoming
2359  * connections.
2360  */
2361  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2362  ScanKeyInit(&scankey,
2363  Anum_pg_database_datname,
2364  BTEqualStrategyNumber, F_NAMEEQ,
2365  CStringGetDatum(stmt->dbname));
2366  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2367  NULL, 1, &scankey);
2368  tuple = systable_getnext(scan);
2369  if (!HeapTupleIsValid(tuple))
2370  ereport(ERROR,
2371  (errcode(ERRCODE_UNDEFINED_DATABASE),
2372  errmsg("database \"%s\" does not exist", stmt->dbname)));
2373 
2374  datform = (Form_pg_database) GETSTRUCT(tuple);
2375  dboid = datform->oid;
2376 
2377  if (database_is_invalid_form(datform))
2378  {
2379  ereport(FATAL,
2380  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2381  errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2382  errhint("Use DROP DATABASE to drop invalid databases."));
2383  }
2384 
2385  if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2387  stmt->dbname);
2388 
2389  /*
2390  * In order to avoid getting locked out and having to go through
2391  * standalone mode, we refuse to disallow connections to the database
2392  * we're currently connected to. Lockout can still happen with concurrent
2393  * sessions but the likeliness of that is not high enough to worry about.
2394  */
2395  if (!dballowconnections && dboid == MyDatabaseId)
2396  ereport(ERROR,
2397  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2398  errmsg("cannot disallow connections for current database")));
2399 
2400  /*
2401  * Build an updated tuple, perusing the information just obtained
2402  */
2403  if (distemplate)
2404  {
2405  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2406  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2407  }
2408  if (dallowconnections)
2409  {
2410  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2411  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2412  }
2413  if (dconnlimit)
2414  {
2415  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2416  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2417  }
2418 
2419  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2420  new_record_nulls, new_record_repl);
2421  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2422 
2423  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2424 
2425  systable_endscan(scan);
2426 
2427  /* Close pg_database, but keep lock till commit */
2428  table_close(rel, NoLock);
2429 
2430  return dboid;
2431 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2701
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4132
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3113
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1905
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 errhint(const char *fmt,...)
Definition: elog.c:1322
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
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:90
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1210
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:515
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
@ OBJECT_DATABASE
Definition: parsenodes.h:2105
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
#define DATCONNLIMIT_UNLIMITED
Definition: pg_database.h:117
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:530
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:802
int location
Definition: parsenodes.h:806
Node * arg
Definition: parsenodes.h:803
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:3497

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), database_is_invalid_form(), DATCONNLIMIT_UNLIMITED, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), FATAL, GETSTRUCT, GetUserId(), heap_modify_tuple(), HeapTupleIsValid, Int32GetDatum(), InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), DefElem::location, movedb(), MyDatabaseId, NoLock, OBJECT_DATABASE, object_ownercheck(), parser_errposition(), PreventInTransactionBlock(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), stmt, 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 2547 of file dbcommands.c.

2548 {
2549  Oid db_id;
2550  HeapTuple tuple;
2551  Relation rel;
2552  ScanKeyData scankey;
2553  SysScanDesc scan;
2554  Form_pg_database datForm;
2555  ObjectAddress address;
2556 
2557  /*
2558  * Get the old tuple. We don't need a lock on the database per se,
2559  * because we're not going to do anything that would mess up incoming
2560  * connections.
2561  */
2562  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2563  ScanKeyInit(&scankey,
2564  Anum_pg_database_datname,
2565  BTEqualStrategyNumber, F_NAMEEQ,
2567  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2568  NULL, 1, &scankey);
2569  tuple = systable_getnext(scan);
2570  if (!HeapTupleIsValid(tuple))
2571  ereport(ERROR,
2572  (errcode(ERRCODE_UNDEFINED_DATABASE),
2573  errmsg("database \"%s\" does not exist", dbname)));
2574 
2575  datForm = (Form_pg_database) GETSTRUCT(tuple);
2576  db_id = datForm->oid;
2577 
2578  /*
2579  * If the new owner is the same as the existing owner, consider the
2580  * command to have succeeded. This is to be consistent with other
2581  * objects.
2582  */
2583  if (datForm->datdba != newOwnerId)
2584  {
2585  Datum repl_val[Natts_pg_database];
2586  bool repl_null[Natts_pg_database] = {0};
2587  bool repl_repl[Natts_pg_database] = {0};
2588  Acl *newAcl;
2589  Datum aclDatum;
2590  bool isNull;
2591  HeapTuple newtuple;
2592 
2593  /* Otherwise, must be owner of the existing object */
2594  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2596  dbname);
2597 
2598  /* Must be able to become new owner */
2599  check_can_set_role(GetUserId(), newOwnerId);
2600 
2601  /*
2602  * must have createdb rights
2603  *
2604  * NOTE: This is different from other alter-owner checks in that the
2605  * current user is checked for createdb privileges instead of the
2606  * destination owner. This is consistent with the CREATE case for
2607  * databases. Because superusers will always have this right, we need
2608  * no special case for them.
2609  */
2610  if (!have_createdb_privilege())
2611  ereport(ERROR,
2612  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2613  errmsg("permission denied to change owner of database")));
2614 
2615  repl_repl[Anum_pg_database_datdba - 1] = true;
2616  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2617 
2618  /*
2619  * Determine the modified ACL for the new owner. This is only
2620  * necessary when the ACL is non-null.
2621  */
2622  aclDatum = heap_getattr(tuple,
2623  Anum_pg_database_datacl,
2624  RelationGetDescr(rel),
2625  &isNull);
2626  if (!isNull)
2627  {
2628  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2629  datForm->datdba, newOwnerId);
2630  repl_repl[Anum_pg_database_datacl - 1] = true;
2631  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2632  }
2633 
2634  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2635  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2636 
2637  heap_freetuple(newtuple);
2638 
2639  /* Update owner dependency reference */
2640  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2641  }
2642 
2643  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2644 
2645  ObjectAddressSet(address, DatabaseRelationId, db_id);
2646 
2647  systable_endscan(scan);
2648 
2649  /* Close pg_database, but keep lock till commit */
2650  table_close(rel, NoLock);
2651 
2652  return address;
2653 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1087
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5117
#define DatumGetAclP(X)
Definition: acl.h:120
bool have_createdb_privilege(void)
Definition: dbcommands.c:2854
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
#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:322
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
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 2438 of file dbcommands.c.

2439 {
2440  Relation rel;
2441  ScanKeyData scankey;
2442  SysScanDesc scan;
2443  Oid db_id;
2444  HeapTuple tuple;
2445  Form_pg_database datForm;
2446  ObjectAddress address;
2447  Datum datum;
2448  bool isnull;
2449  char *oldversion;
2450  char *newversion;
2451 
2452  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2453  ScanKeyInit(&scankey,
2454  Anum_pg_database_datname,
2455  BTEqualStrategyNumber, F_NAMEEQ,
2456  CStringGetDatum(stmt->dbname));
2457  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2458  NULL, 1, &scankey);
2459  tuple = systable_getnext(scan);
2460  if (!HeapTupleIsValid(tuple))
2461  ereport(ERROR,
2462  (errcode(ERRCODE_UNDEFINED_DATABASE),
2463  errmsg("database \"%s\" does not exist", stmt->dbname)));
2464 
2465  datForm = (Form_pg_database) GETSTRUCT(tuple);
2466  db_id = datForm->oid;
2467 
2468  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2470  stmt->dbname);
2471 
2472  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2473  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2474 
2475  datum = heap_getattr(tuple, datForm->datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2476  if (isnull)
2477  elog(ERROR, "unexpected null in pg_database");
2478  newversion = get_collation_actual_version(datForm->datlocprovider, TextDatumGetCString(datum));
2479 
2480  /* cannot change from NULL to non-NULL or vice versa */
2481  if ((!oldversion && newversion) || (oldversion && !newversion))
2482  elog(ERROR, "invalid collation version change");
2483  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2484  {
2485  bool nulls[Natts_pg_database] = {0};
2486  bool replaces[Natts_pg_database] = {0};
2487  Datum values[Natts_pg_database] = {0};
2488 
2489  ereport(NOTICE,
2490  (errmsg("changing version from %s to %s",
2491  oldversion, newversion)));
2492 
2493  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2494  replaces[Anum_pg_database_datcollversion - 1] = true;
2495 
2496  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2497  values, nulls, replaces);
2498  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2499  heap_freetuple(tuple);
2500  }
2501  else
2502  ereport(NOTICE,
2503  (errmsg("version has not changed")));
2504 
2505  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2506 
2507  ObjectAddressSet(address, DatabaseRelationId, db_id);
2508 
2509  systable_endscan(scan);
2510 
2511  table_close(rel, NoLock);
2512 
2513  return address;
2514 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NOTICE
Definition: elog.h:35
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1677

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), CStringGetTextDatum, 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(), stmt, 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 2521 of file dbcommands.c.

2522 {
2523  Oid datid = get_database_oid(stmt->dbname, false);
2524 
2525  /*
2526  * Obtain a lock on the database and make sure it didn't go away in the
2527  * meantime.
2528  */
2529  shdepLockAndCheckObject(DatabaseRelationId, datid);
2530 
2531  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2533  stmt->dbname);
2534 
2535  AlterSetting(datid, InvalidOid, stmt->setstmt);
2536 
2537  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2538 
2539  return datid;
2540 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3042
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1105
#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

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), get_database_oid(), GetUserId(), InvalidOid, OBJECT_DATABASE, object_ownercheck(), shdepLockAndCheckObject(), stmt, 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 1508 of file dbcommands.c.

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

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_locale(), copyTemplateDependencies(), CountOtherDBBackends(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb_failure_callback(), CREATEDB_FILE_COPY, CREATEDB_WAL_LOG, CStringGetDatum(), CStringGetTextDatum, database_is_invalid_oid(), DATCONNLIMIT_UNLIMITED, 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(), icu_language_tag(), icu_validate_locale(), icu_validation_level, Int32GetDatum(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, is_encoding_supported_by_icu(), IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), namein(), NoLock, NOTICE, object_aclcheck(), object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, 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, stmt, 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 2242 of file dbcommands.c.

2243 {
2244  bool force = false;
2245  ListCell *lc;
2246 
2247  foreach(lc, stmt->options)
2248  {
2249  DefElem *opt = (DefElem *) lfirst(lc);
2250 
2251  if (strcmp(opt->defname, "force") == 0)
2252  force = true;
2253  else
2254  ereport(ERROR,
2255  (errcode(ERRCODE_SYNTAX_ERROR),
2256  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2257  parser_errposition(pstate, opt->location)));
2258  }
2259 
2260  dropdb(stmt->dbname, stmt->missing_ok, force);
2261 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1585

References DefElem::defname, dropdb(), ereport, errcode(), errmsg(), ERROR, lfirst, DefElem::location, parser_errposition(), and stmt.

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1585 of file dbcommands.c.

1586 {
1587  Oid db_id;
1588  bool db_istemplate;
1589  Relation pgdbrel;
1590  HeapTuple tup;
1591  Form_pg_database datform;
1592  int notherbackends;
1593  int npreparedxacts;
1594  int nslots,
1595  nslots_active;
1596  int nsubscriptions;
1597 
1598  /*
1599  * Look up the target database's OID, and get exclusive lock on it. We
1600  * need this to ensure that no new backend starts up in the target
1601  * database while we are deleting it (see postinit.c), and that no one is
1602  * using it as a CREATE DATABASE template or trying to delete it for
1603  * themselves.
1604  */
1605  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1606 
1607  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1608  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1609  {
1610  if (!missing_ok)
1611  {
1612  ereport(ERROR,
1613  (errcode(ERRCODE_UNDEFINED_DATABASE),
1614  errmsg("database \"%s\" does not exist", dbname)));
1615  }
1616  else
1617  {
1618  /* Close pg_database, release the lock, since we changed nothing */
1619  table_close(pgdbrel, RowExclusiveLock);
1620  ereport(NOTICE,
1621  (errmsg("database \"%s\" does not exist, skipping",
1622  dbname)));
1623  return;
1624  }
1625  }
1626 
1627  /*
1628  * Permission checks
1629  */
1630  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1632  dbname);
1633 
1634  /* DROP hook for the database being removed */
1635  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1636 
1637  /*
1638  * Disallow dropping a DB that is marked istemplate. This is just to
1639  * prevent people from accidentally dropping template0 or template1; they
1640  * can do so if they're really determined ...
1641  */
1642  if (db_istemplate)
1643  ereport(ERROR,
1644  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1645  errmsg("cannot drop a template database")));
1646 
1647  /* Obviously can't drop my own database */
1648  if (db_id == MyDatabaseId)
1649  ereport(ERROR,
1650  (errcode(ERRCODE_OBJECT_IN_USE),
1651  errmsg("cannot drop the currently open database")));
1652 
1653  /*
1654  * Check whether there are active logical slots that refer to the
1655  * to-be-dropped database. The database lock we are holding prevents the
1656  * creation of new slots using the database or existing slots becoming
1657  * active.
1658  */
1659  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1660  if (nslots_active)
1661  {
1662  ereport(ERROR,
1663  (errcode(ERRCODE_OBJECT_IN_USE),
1664  errmsg("database \"%s\" is used by an active logical replication slot",
1665  dbname),
1666  errdetail_plural("There is %d active slot.",
1667  "There are %d active slots.",
1668  nslots_active, nslots_active)));
1669  }
1670 
1671  /*
1672  * Check if there are subscriptions defined in the target database.
1673  *
1674  * We can't drop them automatically because they might be holding
1675  * resources in other databases/instances.
1676  */
1677  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1678  ereport(ERROR,
1679  (errcode(ERRCODE_OBJECT_IN_USE),
1680  errmsg("database \"%s\" is being used by logical replication subscription",
1681  dbname),
1682  errdetail_plural("There is %d subscription.",
1683  "There are %d subscriptions.",
1684  nsubscriptions, nsubscriptions)));
1685 
1686 
1687  /*
1688  * Attempt to terminate all existing connections to the target database if
1689  * the user has requested to do so.
1690  */
1691  if (force)
1692  TerminateOtherDBBackends(db_id);
1693 
1694  /*
1695  * Check for other backends in the target database. (Because we hold the
1696  * database lock, no new ones can start after this.)
1697  *
1698  * As in CREATE DATABASE, check this after other error conditions.
1699  */
1700  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1701  ereport(ERROR,
1702  (errcode(ERRCODE_OBJECT_IN_USE),
1703  errmsg("database \"%s\" is being accessed by other users",
1704  dbname),
1705  errdetail_busy_db(notherbackends, npreparedxacts)));
1706 
1707  /*
1708  * Delete any comments or security labels associated with the database.
1709  */
1710  DeleteSharedComments(db_id, DatabaseRelationId);
1711  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1712 
1713  /*
1714  * Remove settings associated with this database
1715  */
1716  DropSetting(db_id, InvalidOid);
1717 
1718  /*
1719  * Remove shared dependency references for the database.
1720  */
1721  dropDatabaseDependencies(db_id);
1722 
1723  /*
1724  * Tell the cumulative stats system to forget it immediately, too.
1725  */
1726  pgstat_drop_database(db_id);
1727 
1728  tup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1729  if (!HeapTupleIsValid(tup))
1730  elog(ERROR, "cache lookup failed for database %u", db_id);
1731  datform = (Form_pg_database) GETSTRUCT(tup);
1732 
1733  /*
1734  * Except for the deletion of the catalog row, subsequent actions are not
1735  * transactional (consider DropDatabaseBuffers() discarding modified
1736  * buffers). But we might crash or get interrupted below. To prevent
1737  * accesses to a database with invalid contents, mark the database as
1738  * invalid using an in-place update.
1739  *
1740  * We need to flush the WAL before continuing, to guarantee the
1741  * modification is durable before performing irreversible filesystem
1742  * operations.
1743  */
1744  datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1745  heap_inplace_update(pgdbrel, tup);
1747 
1748  /*
1749  * Also delete the tuple - transactionally. If this transaction commits,
1750  * the row will be gone, but if we fail, dropdb() can be invoked again.
1751  */
1752  CatalogTupleDelete(pgdbrel, &tup->t_self);
1753 
1754  /*
1755  * Drop db-specific replication slots.
1756  */
1758 
1759  /*
1760  * Drop pages for this database that are in the shared buffer cache. This
1761  * is important to ensure that no remaining backend tries to write out a
1762  * dirty buffer to the dead database later...
1763  */
1764  DropDatabaseBuffers(db_id);
1765 
1766  /*
1767  * Tell checkpointer to forget any pending fsync and unlink requests for
1768  * files in the database; else the fsyncs will fail at next checkpoint, or
1769  * worse, it will delete files that belong to a newly created database
1770  * with the same OID.
1771  */
1773 
1774  /*
1775  * Force a checkpoint to make sure the checkpointer has received the
1776  * message sent by ForgetDatabaseSyncRequests.
1777  */
1779 
1780  /* Close all smgr fds in all backends. */
1782 
1783  /*
1784  * Remove all tablespace subdirs belonging to the database.
1785  */
1786  remove_dbtablespaces(db_id);
1787 
1788  /*
1789  * Close pg_database, but keep lock till commit.
1790  */
1791  table_close(pgdbrel, NoLock);
1792 
1793  /*
1794  * Force synchronous commit, thus minimizing the window between removal of
1795  * the database files and committal of the transaction. If we crash before
1796  * committing, we'll have a DB that's gone on disk but still there
1797  * according to pg_database, which is not good.
1798  */
1799  ForceSyncCommit();
1800 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4040
void RequestCheckpoint(int flags)
Definition: checkpointer.c:935
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2879
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1300
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5893
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
#define AccessExclusiveLock
Definition: lockdefs.h:43
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1388
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
#define DATCONNLIMIT_INVALID_DB
Definition: pg_database.h:124
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:3742
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:393
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:333
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:56
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:1148
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1206
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
XLogRecPtr XactLastRecEnd
Definition: xlog.c:258
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2733
#define CHECKPOINT_FORCE
Definition: xlog.h:140
#define CHECKPOINT_WAIT
Definition: xlog.h:143
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:139

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

Referenced by DropDatabase().

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 3089 of file dbcommands.c.

3090 {
3091  HeapTuple dbtuple;
3092  char *result;
3093 
3094  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3095  if (HeapTupleIsValid(dbtuple))
3096  {
3097  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3098  ReleaseSysCache(dbtuple);
3099  }
3100  else
3101  result = NULL;
3102 
3103  return result;
3104 }
#define NameStr(name)
Definition: c.h:735
char * pstrdup(const char *in)
Definition: mcxt.c:1619
NameData datname
Definition: pg_database.h:35
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 3042 of file dbcommands.c.

3043 {
3044  Relation pg_database;
3045  ScanKeyData entry[1];
3046  SysScanDesc scan;
3047  HeapTuple dbtuple;
3048  Oid oid;
3049 
3050  /*
3051  * There's no syscache for pg_database indexed by name, so we must look
3052  * the hard way.
3053  */
3054  pg_database = table_open(DatabaseRelationId, AccessShareLock);
3055  ScanKeyInit(&entry[0],
3056  Anum_pg_database_datname,
3057  BTEqualStrategyNumber, F_NAMEEQ,
3059  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
3060  NULL, 1, entry);
3061 
3062  dbtuple = systable_getnext(scan);
3063 
3064  /* We assume that there can be at most one matching tuple */
3065  if (HeapTupleIsValid(dbtuple))
3066  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3067  else
3068  oid = InvalidOid;
3069 
3070  systable_endscan(scan);
3071  table_close(pg_database, AccessShareLock);
3072 
3073  if (!OidIsValid(oid) && !missing_ok)
3074  ereport(ERROR,
3075  (errcode(ERRCODE_UNDEFINED_DATABASE),
3076  errmsg("database \"%s\" does not exist",
3077  dbname)));
3078 
3079  return oid;
3080 }

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(), sepgsql_database_post_create(), synchronize_slots(), and worker_spi_launch().

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2854 of file dbcommands.c.

2855 {
2856  bool result = false;
2857  HeapTuple utup;
2858 
2859  /* Superusers can always do everything */
2860  if (superuser())
2861  return true;
2862 
2863  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2864  if (HeapTupleIsValid(utup))
2865  {
2866  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2867  ReleaseSysCache(utup);
2868  }
2869  return result;
2870 }
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38

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

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

◆ RenameDatabase()

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

Definition at line 1807 of file dbcommands.c.

1808 {
1809  Oid db_id;
1810  HeapTuple newtup;
1811  Relation rel;
1812  int notherbackends;
1813  int npreparedxacts;
1814  ObjectAddress address;
1815 
1816  /*
1817  * Look up the target database's OID, and get exclusive lock on it. We
1818  * need this for the same reasons as DROP DATABASE.
1819  */
1820  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1821 
1822  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL, NULL,
1823  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1824  ereport(ERROR,
1825  (errcode(ERRCODE_UNDEFINED_DATABASE),
1826  errmsg("database \"%s\" does not exist", oldname)));
1827 
1828  /* must be owner */
1829  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1831  oldname);
1832 
1833  /* must have createdb rights */
1834  if (!have_createdb_privilege())
1835  ereport(ERROR,
1836  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1837  errmsg("permission denied to rename database")));
1838 
1839  /*
1840  * If built with appropriate switch, whine when regression-testing
1841  * conventions for database names are violated.
1842  */
1843 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1844  if (strstr(newname, "regression") == NULL)
1845  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1846 #endif
1847 
1848  /*
1849  * Make sure the new name doesn't exist. See notes for same error in
1850  * CREATE DATABASE.
1851  */
1852  if (OidIsValid(get_database_oid(newname, true)))
1853  ereport(ERROR,
1854  (errcode(ERRCODE_DUPLICATE_DATABASE),
1855  errmsg("database \"%s\" already exists", newname)));
1856 
1857  /*
1858  * XXX Client applications probably store the current database somewhere,
1859  * so renaming it could cause confusion. On the other hand, there may not
1860  * be an actual problem besides a little confusion, so think about this
1861  * and decide.
1862  */
1863  if (db_id == MyDatabaseId)
1864  ereport(ERROR,
1865  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1866  errmsg("current database cannot be renamed")));
1867 
1868  /*
1869  * Make sure the database does not have active sessions. This is the same
1870  * concern as above, but applied to other sessions.
1871  *
1872  * As in CREATE DATABASE, check this after other error conditions.
1873  */
1874  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1875  ereport(ERROR,
1876  (errcode(ERRCODE_OBJECT_IN_USE),
1877  errmsg("database \"%s\" is being accessed by other users",
1878  oldname),
1879  errdetail_busy_db(notherbackends, npreparedxacts)));
1880 
1881  /* rename */
1882  newtup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1883  if (!HeapTupleIsValid(newtup))
1884  elog(ERROR, "cache lookup failed for database %u", db_id);
1885  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1886  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1887 
1888  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1889 
1890  ObjectAddressSet(address, DatabaseRelationId, db_id);
1891 
1892  /*
1893  * Close pg_database, but keep lock till commit.
1894  */
1895  table_close(rel, NoLock);
1896 
1897  return address;
1898 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), CountOtherDBBackends(), 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().