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

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

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

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

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

2520 {
2521  Oid datid = get_database_oid(stmt->dbname, false);
2522 
2523  /*
2524  * Obtain a lock on the database and make sure it didn't go away in the
2525  * meantime.
2526  */
2527  shdepLockAndCheckObject(DatabaseRelationId, datid);
2528 
2529  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2531  stmt->dbname);
2532 
2533  AlterSetting(datid, InvalidOid, stmt->setstmt);
2534 
2535  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2536 
2537  return datid;
2538 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3037
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1067
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1166

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

1507 {
1508  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1509  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1510 
1511  if (!(ctype_encoding == encoding ||
1512  ctype_encoding == PG_SQL_ASCII ||
1513  ctype_encoding == -1 ||
1514 #ifdef WIN32
1515  encoding == PG_UTF8 ||
1516 #endif
1517  (encoding == PG_SQL_ASCII && superuser())))
1518  ereport(ERROR,
1519  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1520  errmsg("encoding \"%s\" does not match locale \"%s\"",
1522  ctype),
1523  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1524  pg_encoding_to_char(ctype_encoding))));
1525 
1526  if (!(collate_encoding == encoding ||
1527  collate_encoding == PG_SQL_ASCII ||
1528  collate_encoding == -1 ||
1529 #ifdef WIN32
1530  encoding == PG_UTF8 ||
1531 #endif
1532  (encoding == PG_SQL_ASCII && superuser())))
1533  ereport(ERROR,
1534  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1535  errmsg("encoding \"%s\" does not match locale \"%s\"",
1537  collate),
1538  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1539  pg_encoding_to_char(collate_encoding))));
1540 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
bool superuser(void)
Definition: superuser.c:46

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

Referenced by createdb(), and DefineCollation().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 671 of file dbcommands.c.

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

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

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

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

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleDelete(), CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, CountDBSubscriptions(), CountOtherDBBackends(), DATABASEOID, 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 3084 of file dbcommands.c.

3085 {
3086  HeapTuple dbtuple;
3087  char *result;
3088 
3089  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3090  if (HeapTupleIsValid(dbtuple))
3091  {
3092  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3093  ReleaseSysCache(dbtuple);
3094  }
3095  else
3096  result = NULL;
3097 
3098  return result;
3099 }
#define NameStr(name)
Definition: c.h:735
char * pstrdup(const char *in)
Definition: mcxt.c:1644
NameData datname
Definition: pg_database.h:35
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820

References DATABASEOID, 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 3037 of file dbcommands.c.

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

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

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

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2849 of file dbcommands.c.

2850 {
2851  bool result = false;
2852  HeapTuple utup;
2853 
2854  /* Superusers can always do everything */
2855  if (superuser())
2856  return true;
2857 
2859  if (HeapTupleIsValid(utup))
2860  {
2861  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2862  ReleaseSysCache(utup);
2863  }
2864  return result;
2865 }
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38
@ AUTHOID
Definition: syscache.h:45

References AUTHOID, 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 1805 of file dbcommands.c.

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

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

Referenced by ExecRenameStmt().