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

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

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

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

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

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

2594 {
2595  Oid datid = get_database_oid(stmt->dbname, false);
2596 
2597  /*
2598  * Obtain a lock on the database and make sure it didn't go away in the
2599  * meantime.
2600  */
2601  shdepLockAndCheckObject(DatabaseRelationId, datid);
2602 
2603  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2605  stmt->dbname);
2606 
2607  AlterSetting(datid, InvalidOid, stmt->setstmt);
2608 
2609  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2610 
2611  return datid;
2612 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3119
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1132
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1211

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

1570 {
1571  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1572  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1573 
1574  if (!(ctype_encoding == encoding ||
1575  ctype_encoding == PG_SQL_ASCII ||
1576  ctype_encoding == -1 ||
1577 #ifdef WIN32
1578  encoding == PG_UTF8 ||
1579 #endif
1580  (encoding == PG_SQL_ASCII && superuser())))
1581  ereport(ERROR,
1582  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1583  errmsg("encoding \"%s\" does not match locale \"%s\"",
1585  ctype),
1586  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1587  pg_encoding_to_char(ctype_encoding))));
1588 
1589  if (!(collate_encoding == encoding ||
1590  collate_encoding == PG_SQL_ASCII ||
1591  collate_encoding == -1 ||
1592 #ifdef WIN32
1593  encoding == PG_UTF8 ||
1594 #endif
1595  (encoding == PG_SQL_ASCII && superuser())))
1596  ereport(ERROR,
1597  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1598  errmsg("encoding \"%s\" does not match locale \"%s\"",
1600  collate),
1601  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1602  pg_encoding_to_char(collate_encoding))));
1603 }
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 682 of file dbcommands.c.

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

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

2304 {
2305  bool force = false;
2306  ListCell *lc;
2307 
2308  foreach(lc, stmt->options)
2309  {
2310  DefElem *opt = (DefElem *) lfirst(lc);
2311 
2312  if (strcmp(opt->defname, "force") == 0)
2313  force = true;
2314  else
2315  ereport(ERROR,
2316  (errcode(ERRCODE_SYNTAX_ERROR),
2317  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2318  parser_errposition(pstate, opt->location)));
2319  }
2320 
2321  dropdb(stmt->dbname, stmt->missing_ok, force);
2322 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1646

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

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

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

3167 {
3168  HeapTuple dbtuple;
3169  char *result;
3170 
3171  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3172  if (HeapTupleIsValid(dbtuple))
3173  {
3174  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3175  ReleaseSysCache(dbtuple);
3176  }
3177  else
3178  result = NULL;
3179 
3180  return result;
3181 }
#define NameStr(name)
Definition: c.h:746
char * pstrdup(const char *in)
Definition: mcxt.c:1696
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 3119 of file dbcommands.c.

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

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

2932 {
2933  bool result = false;
2934  HeapTuple utup;
2935 
2936  /* Superusers can always do everything */
2937  if (superuser())
2938  return true;
2939 
2940  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2941  if (HeapTupleIsValid(utup))
2942  {
2943  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2944  ReleaseSysCache(utup);
2945  }
2946  return result;
2947 }
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 1868 of file dbcommands.c.

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