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

2317 {
2318  Relation rel;
2319  Oid dboid;
2320  HeapTuple tuple,
2321  newtuple;
2322  Form_pg_database datform;
2323  ScanKeyData scankey;
2324  SysScanDesc scan;
2325  ListCell *option;
2326  bool dbistemplate = false;
2327  bool dballowconnections = true;
2328  int dbconnlimit = DATCONNLIMIT_UNLIMITED;
2329  DefElem *distemplate = NULL;
2330  DefElem *dallowconnections = NULL;
2331  DefElem *dconnlimit = NULL;
2332  DefElem *dtablespace = NULL;
2333  Datum new_record[Natts_pg_database] = {0};
2334  bool new_record_nulls[Natts_pg_database] = {0};
2335  bool new_record_repl[Natts_pg_database] = {0};
2336 
2337  /* Extract options from the statement node tree */
2338  foreach(option, stmt->options)
2339  {
2340  DefElem *defel = (DefElem *) lfirst(option);
2341 
2342  if (strcmp(defel->defname, "is_template") == 0)
2343  {
2344  if (distemplate)
2345  errorConflictingDefElem(defel, pstate);
2346  distemplate = defel;
2347  }
2348  else if (strcmp(defel->defname, "allow_connections") == 0)
2349  {
2350  if (dallowconnections)
2351  errorConflictingDefElem(defel, pstate);
2352  dallowconnections = defel;
2353  }
2354  else if (strcmp(defel->defname, "connection_limit") == 0)
2355  {
2356  if (dconnlimit)
2357  errorConflictingDefElem(defel, pstate);
2358  dconnlimit = defel;
2359  }
2360  else if (strcmp(defel->defname, "tablespace") == 0)
2361  {
2362  if (dtablespace)
2363  errorConflictingDefElem(defel, pstate);
2364  dtablespace = defel;
2365  }
2366  else
2367  ereport(ERROR,
2368  (errcode(ERRCODE_SYNTAX_ERROR),
2369  errmsg("option \"%s\" not recognized", defel->defname),
2370  parser_errposition(pstate, defel->location)));
2371  }
2372 
2373  if (dtablespace)
2374  {
2375  /*
2376  * While the SET TABLESPACE syntax doesn't allow any other options,
2377  * somebody could write "WITH TABLESPACE ...". Forbid any other
2378  * options from being specified in that case.
2379  */
2380  if (list_length(stmt->options) != 1)
2381  ereport(ERROR,
2382  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2383  errmsg("option \"%s\" cannot be specified with other options",
2384  dtablespace->defname),
2385  parser_errposition(pstate, dtablespace->location)));
2386  /* this case isn't allowed within a transaction block */
2387  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2388  movedb(stmt->dbname, defGetString(dtablespace));
2389  return InvalidOid;
2390  }
2391 
2392  if (distemplate && distemplate->arg)
2393  dbistemplate = defGetBoolean(distemplate);
2394  if (dallowconnections && dallowconnections->arg)
2395  dballowconnections = defGetBoolean(dallowconnections);
2396  if (dconnlimit && dconnlimit->arg)
2397  {
2398  dbconnlimit = defGetInt32(dconnlimit);
2399  if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
2400  ereport(ERROR,
2401  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2402  errmsg("invalid connection limit: %d", dbconnlimit)));
2403  }
2404 
2405  /*
2406  * Get the old tuple. We don't need a lock on the database per se,
2407  * because we're not going to do anything that would mess up incoming
2408  * connections.
2409  */
2410  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2411  ScanKeyInit(&scankey,
2412  Anum_pg_database_datname,
2413  BTEqualStrategyNumber, F_NAMEEQ,
2414  CStringGetDatum(stmt->dbname));
2415  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2416  NULL, 1, &scankey);
2417  tuple = systable_getnext(scan);
2418  if (!HeapTupleIsValid(tuple))
2419  ereport(ERROR,
2420  (errcode(ERRCODE_UNDEFINED_DATABASE),
2421  errmsg("database \"%s\" does not exist", stmt->dbname)));
2422 
2423  datform = (Form_pg_database) GETSTRUCT(tuple);
2424  dboid = datform->oid;
2425 
2426  if (database_is_invalid_form(datform))
2427  {
2428  ereport(FATAL,
2429  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2430  errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2431  errhint("Use DROP DATABASE to drop invalid databases."));
2432  }
2433 
2434  if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2436  stmt->dbname);
2437 
2438  /*
2439  * In order to avoid getting locked out and having to go through
2440  * standalone mode, we refuse to disallow connections to the database
2441  * we're currently connected to. Lockout can still happen with concurrent
2442  * sessions but the likeliness of that is not high enough to worry about.
2443  */
2444  if (!dballowconnections && dboid == MyDatabaseId)
2445  ereport(ERROR,
2446  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2447  errmsg("cannot disallow connections for current database")));
2448 
2449  /*
2450  * Build an updated tuple, perusing the information just obtained
2451  */
2452  if (distemplate)
2453  {
2454  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2455  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2456  }
2457  if (dallowconnections)
2458  {
2459  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2460  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2461  }
2462  if (dconnlimit)
2463  {
2464  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2465  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2466  }
2467 
2468  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2469  new_record_nulls, new_record_repl);
2470  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2471 
2472  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2473 
2474  systable_endscan(scan);
2475 
2476  /* Close pg_database, but keep lock till commit */
2477  table_close(rel, NoLock);
2478 
2479  return dboid;
2480 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2702
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4144
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3178
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1954
int32 defGetInt32(DefElem *def)
Definition: define.c:162
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#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:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
Oid MyDatabaseId
Definition: globals.c:91
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
#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:514
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ OBJECT_DATABASE
Definition: parsenodes.h:2270
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:531
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:815
ParseLoc location
Definition: parsenodes.h:819
Node * arg
Definition: parsenodes.h:816
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:3584

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

2608 {
2609  Oid db_id;
2610  HeapTuple tuple;
2611  Relation rel;
2612  ScanKeyData scankey;
2613  SysScanDesc scan;
2614  Form_pg_database datForm;
2615  ObjectAddress address;
2616 
2617  /*
2618  * Get the old tuple. We don't need a lock on the database per se,
2619  * because we're not going to do anything that would mess up incoming
2620  * connections.
2621  */
2622  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2623  ScanKeyInit(&scankey,
2624  Anum_pg_database_datname,
2625  BTEqualStrategyNumber, F_NAMEEQ,
2627  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2628  NULL, 1, &scankey);
2629  tuple = systable_getnext(scan);
2630  if (!HeapTupleIsValid(tuple))
2631  ereport(ERROR,
2632  (errcode(ERRCODE_UNDEFINED_DATABASE),
2633  errmsg("database \"%s\" does not exist", dbname)));
2634 
2635  datForm = (Form_pg_database) GETSTRUCT(tuple);
2636  db_id = datForm->oid;
2637 
2638  /*
2639  * If the new owner is the same as the existing owner, consider the
2640  * command to have succeeded. This is to be consistent with other
2641  * objects.
2642  */
2643  if (datForm->datdba != newOwnerId)
2644  {
2645  Datum repl_val[Natts_pg_database];
2646  bool repl_null[Natts_pg_database] = {0};
2647  bool repl_repl[Natts_pg_database] = {0};
2648  Acl *newAcl;
2649  Datum aclDatum;
2650  bool isNull;
2651  HeapTuple newtuple;
2652 
2653  /* Otherwise, must be owner of the existing object */
2654  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2656  dbname);
2657 
2658  /* Must be able to become new owner */
2659  check_can_set_role(GetUserId(), newOwnerId);
2660 
2661  /*
2662  * must have createdb rights
2663  *
2664  * NOTE: This is different from other alter-owner checks in that the
2665  * current user is checked for createdb privileges instead of the
2666  * destination owner. This is consistent with the CREATE case for
2667  * databases. Because superusers will always have this right, we need
2668  * no special case for them.
2669  */
2670  if (!have_createdb_privilege())
2671  ereport(ERROR,
2672  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2673  errmsg("permission denied to change owner of database")));
2674 
2675  repl_repl[Anum_pg_database_datdba - 1] = true;
2676  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2677 
2678  /*
2679  * Determine the modified ACL for the new owner. This is only
2680  * necessary when the ACL is non-null.
2681  */
2682  aclDatum = heap_getattr(tuple,
2683  Anum_pg_database_datacl,
2684  RelationGetDescr(rel),
2685  &isNull);
2686  if (!isNull)
2687  {
2688  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2689  datForm->datdba, newOwnerId);
2690  repl_repl[Anum_pg_database_datacl - 1] = true;
2691  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2692  }
2693 
2694  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2695  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2696 
2697  heap_freetuple(newtuple);
2698 
2699  /* Update owner dependency reference */
2700  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2701  }
2702 
2703  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2704 
2705  ObjectAddressSet(address, DatabaseRelationId, db_id);
2706 
2707  systable_endscan(scan);
2708 
2709  /* Close pg_database, but keep lock till commit */
2710  table_close(rel, NoLock);
2711 
2712  return address;
2713 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1096
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5185
#define DatumGetAclP(X)
Definition: acl.h:120
bool have_createdb_privilege(void)
Definition: dbcommands.c:2919
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
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:52

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

2488 {
2489  Relation rel;
2490  ScanKeyData scankey;
2491  SysScanDesc scan;
2492  Oid db_id;
2493  HeapTuple tuple;
2494  Form_pg_database datForm;
2495  ObjectAddress address;
2496  Datum datum;
2497  bool isnull;
2498  char *oldversion;
2499  char *newversion;
2500 
2501  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2502  ScanKeyInit(&scankey,
2503  Anum_pg_database_datname,
2504  BTEqualStrategyNumber, F_NAMEEQ,
2505  CStringGetDatum(stmt->dbname));
2506  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2507  NULL, 1, &scankey);
2508  tuple = systable_getnext(scan);
2509  if (!HeapTupleIsValid(tuple))
2510  ereport(ERROR,
2511  (errcode(ERRCODE_UNDEFINED_DATABASE),
2512  errmsg("database \"%s\" does not exist", stmt->dbname)));
2513 
2514  datForm = (Form_pg_database) GETSTRUCT(tuple);
2515  db_id = datForm->oid;
2516 
2517  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2519  stmt->dbname);
2520 
2521  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2522  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2523 
2524  if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2525  {
2526  datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2527  if (isnull)
2528  elog(ERROR, "unexpected null in pg_database");
2529  }
2530  else
2531  {
2532  datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2533  if (isnull)
2534  elog(ERROR, "unexpected null in pg_database");
2535  }
2536 
2537  newversion = get_collation_actual_version(datForm->datlocprovider,
2538  TextDatumGetCString(datum));
2539 
2540  /* cannot change from NULL to non-NULL or vice versa */
2541  if ((!oldversion && newversion) || (oldversion && !newversion))
2542  elog(ERROR, "invalid collation version change");
2543  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2544  {
2545  bool nulls[Natts_pg_database] = {0};
2546  bool replaces[Natts_pg_database] = {0};
2547  Datum values[Natts_pg_database] = {0};
2548 
2549  ereport(NOTICE,
2550  (errmsg("changing version from %s to %s",
2551  oldversion, newversion)));
2552 
2553  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2554  replaces[Anum_pg_database_datcollversion - 1] = true;
2555 
2556  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2557  values, nulls, replaces);
2558  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2559  heap_freetuple(tuple);
2560  }
2561  else
2562  ereport(NOTICE,
2563  (errmsg("version has not changed")));
2564 
2565  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2566 
2567  ObjectAddressSet(address, DatabaseRelationId, db_id);
2568 
2569  systable_endscan(scan);
2570 
2571  table_close(rel, NoLock);
2572 
2573  return address;
2574 }
static Datum values[MAXATTR]
Definition: bootstrap.c:152
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define elog(elevel,...)
Definition: elog.h:224
#define NOTICE
Definition: elog.h:35
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1729

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

2582 {
2583  Oid datid = get_database_oid(stmt->dbname, false);
2584 
2585  /*
2586  * Obtain a lock on the database and make sure it didn't go away in the
2587  * meantime.
2588  */
2589  shdepLockAndCheckObject(DatabaseRelationId, datid);
2590 
2591  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2593  stmt->dbname);
2594 
2595  AlterSetting(datid, InvalidOid, stmt->setstmt);
2596 
2597  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2598 
2599  return datid;
2600 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3107
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1142
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1203

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

1558 {
1559  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1560  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1561 
1562  if (!(ctype_encoding == encoding ||
1563  ctype_encoding == PG_SQL_ASCII ||
1564  ctype_encoding == -1 ||
1565 #ifdef WIN32
1566  encoding == PG_UTF8 ||
1567 #endif
1568  (encoding == PG_SQL_ASCII && superuser())))
1569  ereport(ERROR,
1570  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1571  errmsg("encoding \"%s\" does not match locale \"%s\"",
1573  ctype),
1574  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1575  pg_encoding_to_char(ctype_encoding))));
1576 
1577  if (!(collate_encoding == encoding ||
1578  collate_encoding == PG_SQL_ASCII ||
1579  collate_encoding == -1 ||
1580 #ifdef WIN32
1581  encoding == PG_UTF8 ||
1582 #endif
1583  (encoding == PG_SQL_ASCII && superuser())))
1584  ereport(ERROR,
1585  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1586  errmsg("encoding \"%s\" does not match locale \"%s\"",
1588  collate),
1589  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1590  pg_encoding_to_char(collate_encoding))));
1591 }
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
#define pg_encoding_to_char
Definition: pg_wchar.h:630
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 670 of file dbcommands.c.

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

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, DefElem::arg, Assert, BoolGetDatum(), builtin_validate_locale(), 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, locale, 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 2291 of file dbcommands.c.

2292 {
2293  bool force = false;
2294  ListCell *lc;
2295 
2296  foreach(lc, stmt->options)
2297  {
2298  DefElem *opt = (DefElem *) lfirst(lc);
2299 
2300  if (strcmp(opt->defname, "force") == 0)
2301  force = true;
2302  else
2303  ereport(ERROR,
2304  (errcode(ERRCODE_SYNTAX_ERROR),
2305  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2306  parser_errposition(pstate, opt->location)));
2307  }
2308 
2309  dropdb(stmt->dbname, stmt->missing_ok, force);
2310 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1634

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

1635 {
1636  Oid db_id;
1637  bool db_istemplate;
1638  Relation pgdbrel;
1639  HeapTuple tup;
1640  Form_pg_database datform;
1641  int notherbackends;
1642  int npreparedxacts;
1643  int nslots,
1644  nslots_active;
1645  int nsubscriptions;
1646 
1647  /*
1648  * Look up the target database's OID, and get exclusive lock on it. We
1649  * need this to ensure that no new backend starts up in the target
1650  * database while we are deleting it (see postinit.c), and that no one is
1651  * using it as a CREATE DATABASE template or trying to delete it for
1652  * themselves.
1653  */
1654  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1655 
1656  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1657  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1658  {
1659  if (!missing_ok)
1660  {
1661  ereport(ERROR,
1662  (errcode(ERRCODE_UNDEFINED_DATABASE),
1663  errmsg("database \"%s\" does not exist", dbname)));
1664  }
1665  else
1666  {
1667  /* Close pg_database, release the lock, since we changed nothing */
1668  table_close(pgdbrel, RowExclusiveLock);
1669  ereport(NOTICE,
1670  (errmsg("database \"%s\" does not exist, skipping",
1671  dbname)));
1672  return;
1673  }
1674  }
1675 
1676  /*
1677  * Permission checks
1678  */
1679  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1681  dbname);
1682 
1683  /* DROP hook for the database being removed */
1684  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1685 
1686  /*
1687  * Disallow dropping a DB that is marked istemplate. This is just to
1688  * prevent people from accidentally dropping template0 or template1; they
1689  * can do so if they're really determined ...
1690  */
1691  if (db_istemplate)
1692  ereport(ERROR,
1693  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1694  errmsg("cannot drop a template database")));
1695 
1696  /* Obviously can't drop my own database */
1697  if (db_id == MyDatabaseId)
1698  ereport(ERROR,
1699  (errcode(ERRCODE_OBJECT_IN_USE),
1700  errmsg("cannot drop the currently open database")));
1701 
1702  /*
1703  * Check whether there are active logical slots that refer to the
1704  * to-be-dropped database. The database lock we are holding prevents the
1705  * creation of new slots using the database or existing slots becoming
1706  * active.
1707  */
1708  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1709  if (nslots_active)
1710  {
1711  ereport(ERROR,
1712  (errcode(ERRCODE_OBJECT_IN_USE),
1713  errmsg("database \"%s\" is used by an active logical replication slot",
1714  dbname),
1715  errdetail_plural("There is %d active slot.",
1716  "There are %d active slots.",
1717  nslots_active, nslots_active)));
1718  }
1719 
1720  /*
1721  * Check if there are subscriptions defined in the target database.
1722  *
1723  * We can't drop them automatically because they might be holding
1724  * resources in other databases/instances.
1725  */
1726  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1727  ereport(ERROR,
1728  (errcode(ERRCODE_OBJECT_IN_USE),
1729  errmsg("database \"%s\" is being used by logical replication subscription",
1730  dbname),
1731  errdetail_plural("There is %d subscription.",
1732  "There are %d subscriptions.",
1733  nsubscriptions, nsubscriptions)));
1734 
1735 
1736  /*
1737  * Attempt to terminate all existing connections to the target database if
1738  * the user has requested to do so.
1739  */
1740  if (force)
1741  TerminateOtherDBBackends(db_id);
1742 
1743  /*
1744  * Check for other backends in the target database. (Because we hold the
1745  * database lock, no new ones can start after this.)
1746  *
1747  * As in CREATE DATABASE, check this after other error conditions.
1748  */
1749  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1750  ereport(ERROR,
1751  (errcode(ERRCODE_OBJECT_IN_USE),
1752  errmsg("database \"%s\" is being accessed by other users",
1753  dbname),
1754  errdetail_busy_db(notherbackends, npreparedxacts)));
1755 
1756  /*
1757  * Delete any comments or security labels associated with the database.
1758  */
1759  DeleteSharedComments(db_id, DatabaseRelationId);
1760  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1761 
1762  /*
1763  * Remove settings associated with this database
1764  */
1765  DropSetting(db_id, InvalidOid);
1766 
1767  /*
1768  * Remove shared dependency references for the database.
1769  */
1770  dropDatabaseDependencies(db_id);
1771 
1772  /*
1773  * Tell the cumulative stats system to forget it immediately, too.
1774  */
1775  pgstat_drop_database(db_id);
1776 
1777  tup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1778  if (!HeapTupleIsValid(tup))
1779  elog(ERROR, "cache lookup failed for database %u", db_id);
1780  datform = (Form_pg_database) GETSTRUCT(tup);
1781 
1782  /*
1783  * Except for the deletion of the catalog row, subsequent actions are not
1784  * transactional (consider DropDatabaseBuffers() discarding modified
1785  * buffers). But we might crash or get interrupted below. To prevent
1786  * accesses to a database with invalid contents, mark the database as
1787  * invalid using an in-place update.
1788  *
1789  * We need to flush the WAL before continuing, to guarantee the
1790  * modification is durable before performing irreversible filesystem
1791  * operations.
1792  */
1793  datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1794  heap_inplace_update(pgdbrel, tup);
1796 
1797  /*
1798  * Also delete the tuple - transactionally. If this transaction commits,
1799  * the row will be gone, but if we fail, dropdb() can be invoked again.
1800  */
1801  CatalogTupleDelete(pgdbrel, &tup->t_self);
1802 
1803  /*
1804  * Drop db-specific replication slots.
1805  */
1807 
1808  /*
1809  * Drop pages for this database that are in the shared buffer cache. This
1810  * is important to ensure that no remaining backend tries to write out a
1811  * dirty buffer to the dead database later...
1812  */
1813  DropDatabaseBuffers(db_id);
1814 
1815  /*
1816  * Tell checkpointer to forget any pending fsync and unlink requests for
1817  * files in the database; else the fsyncs will fail at next checkpoint, or
1818  * worse, it will delete files that belong to a newly created database
1819  * with the same OID.
1820  */
1822 
1823  /*
1824  * Force a checkpoint to make sure the checkpointer has received the
1825  * message sent by ForgetDatabaseSyncRequests.
1826  */
1828 
1829  /* Close all smgr fds in all backends. */
1831 
1832  /*
1833  * Remove all tablespace subdirs belonging to the database.
1834  */
1835  remove_dbtablespaces(db_id);
1836 
1837  /*
1838  * Close pg_database, but keep lock till commit.
1839  */
1840  table_close(pgdbrel, NoLock);
1841 
1842  /*
1843  * Force synchronous commit, thus minimizing the window between removal of
1844  * the database files and committal of the transaction. If we crash before
1845  * committing, we'll have a DB that's gone on disk but still there
1846  * according to pg_database, which is not good.
1847  */
1848  ForceSyncCommit();
1849 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4329
void RequestCheckpoint(int flags)
Definition: checkpointer.c:941
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2944
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1295
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6062
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
#define AccessExclusiveLock
Definition: lockdefs.h:43
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1428
#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:991
int CountDBSubscriptions(Oid dbid)
void pgstat_drop_database(Oid databaseid)
void TerminateOtherDBBackends(Oid databaseId)
Definition: procarray.c:3815
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:389
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:329
@ 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:1212
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1270
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
XLogRecPtr XactLastRecEnd
Definition: xlog.c:254
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2791
#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 3154 of file dbcommands.c.

3155 {
3156  HeapTuple dbtuple;
3157  char *result;
3158 
3159  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3160  if (HeapTupleIsValid(dbtuple))
3161  {
3162  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3163  ReleaseSysCache(dbtuple);
3164  }
3165  else
3166  result = NULL;
3167 
3168  return result;
3169 }
#define NameStr(name)
Definition: c.h:746
char * pstrdup(const char *in)
Definition: mcxt.c:1695
NameData datname
Definition: pg_database.h:35
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

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

3108 {
3109  Relation pg_database;
3110  ScanKeyData entry[1];
3111  SysScanDesc scan;
3112  HeapTuple dbtuple;
3113  Oid oid;
3114 
3115  /*
3116  * There's no syscache for pg_database indexed by name, so we must look
3117  * the hard way.
3118  */
3119  pg_database = table_open(DatabaseRelationId, AccessShareLock);
3120  ScanKeyInit(&entry[0],
3121  Anum_pg_database_datname,
3122  BTEqualStrategyNumber, F_NAMEEQ,
3124  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
3125  NULL, 1, entry);
3126 
3127  dbtuple = systable_getnext(scan);
3128 
3129  /* We assume that there can be at most one matching tuple */
3130  if (HeapTupleIsValid(dbtuple))
3131  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3132  else
3133  oid = InvalidOid;
3134 
3135  systable_endscan(scan);
3136  table_close(pg_database, AccessShareLock);
3137 
3138  if (!OidIsValid(oid) && !missing_ok)
3139  ereport(ERROR,
3140  (errcode(ERRCODE_UNDEFINED_DATABASE),
3141  errmsg("database \"%s\" does not exist",
3142  dbname)));
3143 
3144  return oid;
3145 }

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

2920 {
2921  bool result = false;
2922  HeapTuple utup;
2923 
2924  /* Superusers can always do everything */
2925  if (superuser())
2926  return true;
2927 
2928  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2929  if (HeapTupleIsValid(utup))
2930  {
2931  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2932  ReleaseSysCache(utup);
2933  }
2934  return result;
2935 }
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 1856 of file dbcommands.c.

1857 {
1858  Oid db_id;
1859  HeapTuple newtup;
1860  Relation rel;
1861  int notherbackends;
1862  int npreparedxacts;
1863  ObjectAddress address;
1864 
1865  /*
1866  * Look up the target database's OID, and get exclusive lock on it. We
1867  * need this for the same reasons as DROP DATABASE.
1868  */
1869  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1870 
1871  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL, NULL,
1872  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1873  ereport(ERROR,
1874  (errcode(ERRCODE_UNDEFINED_DATABASE),
1875  errmsg("database \"%s\" does not exist", oldname)));
1876 
1877  /* must be owner */
1878  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1880  oldname);
1881 
1882  /* must have createdb rights */
1883  if (!have_createdb_privilege())
1884  ereport(ERROR,
1885  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1886  errmsg("permission denied to rename database")));
1887 
1888  /*
1889  * If built with appropriate switch, whine when regression-testing
1890  * conventions for database names are violated.
1891  */
1892 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1893  if (strstr(newname, "regression") == NULL)
1894  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1895 #endif
1896 
1897  /*
1898  * Make sure the new name doesn't exist. See notes for same error in
1899  * CREATE DATABASE.
1900  */
1901  if (OidIsValid(get_database_oid(newname, true)))
1902  ereport(ERROR,
1903  (errcode(ERRCODE_DUPLICATE_DATABASE),
1904  errmsg("database \"%s\" already exists", newname)));
1905 
1906  /*
1907  * XXX Client applications probably store the current database somewhere,
1908  * so renaming it could cause confusion. On the other hand, there may not
1909  * be an actual problem besides a little confusion, so think about this
1910  * and decide.
1911  */
1912  if (db_id == MyDatabaseId)
1913  ereport(ERROR,
1914  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1915  errmsg("current database cannot be renamed")));
1916 
1917  /*
1918  * Make sure the database does not have active sessions. This is the same
1919  * concern as above, but applied to other sessions.
1920  *
1921  * As in CREATE DATABASE, check this after other error conditions.
1922  */
1923  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1924  ereport(ERROR,
1925  (errcode(ERRCODE_OBJECT_IN_USE),
1926  errmsg("database \"%s\" is being accessed by other users",
1927  oldname),
1928  errdetail_busy_db(notherbackends, npreparedxacts)));
1929 
1930  /* rename */
1931  newtup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1932  if (!HeapTupleIsValid(newtup))
1933  elog(ERROR, "cache lookup failed for database %u", db_id);
1934  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1935  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1936 
1937  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1938 
1939  ObjectAddressSet(address, DatabaseRelationId, db_id);
1940 
1941  /*
1942  * Close pg_database, but keep lock till commit.
1943  */
1944  table_close(rel, NoLock);
1945 
1946  return address;
1947 }
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().