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

2213 {
2214  Relation rel;
2215  Oid dboid;
2216  HeapTuple tuple,
2217  newtuple;
2218  Form_pg_database datform;
2219  ScanKeyData scankey;
2220  SysScanDesc scan;
2221  ListCell *option;
2222  bool dbistemplate = false;
2223  bool dballowconnections = true;
2224  int dbconnlimit = -1;
2225  DefElem *distemplate = NULL;
2226  DefElem *dallowconnections = NULL;
2227  DefElem *dconnlimit = NULL;
2228  DefElem *dtablespace = NULL;
2229  Datum new_record[Natts_pg_database] = {0};
2230  bool new_record_nulls[Natts_pg_database] = {0};
2231  bool new_record_repl[Natts_pg_database] = {0};
2232 
2233  /* Extract options from the statement node tree */
2234  foreach(option, stmt->options)
2235  {
2236  DefElem *defel = (DefElem *) lfirst(option);
2237 
2238  if (strcmp(defel->defname, "is_template") == 0)
2239  {
2240  if (distemplate)
2241  errorConflictingDefElem(defel, pstate);
2242  distemplate = defel;
2243  }
2244  else if (strcmp(defel->defname, "allow_connections") == 0)
2245  {
2246  if (dallowconnections)
2247  errorConflictingDefElem(defel, pstate);
2248  dallowconnections = defel;
2249  }
2250  else if (strcmp(defel->defname, "connection_limit") == 0)
2251  {
2252  if (dconnlimit)
2253  errorConflictingDefElem(defel, pstate);
2254  dconnlimit = defel;
2255  }
2256  else if (strcmp(defel->defname, "tablespace") == 0)
2257  {
2258  if (dtablespace)
2259  errorConflictingDefElem(defel, pstate);
2260  dtablespace = defel;
2261  }
2262  else
2263  ereport(ERROR,
2264  (errcode(ERRCODE_SYNTAX_ERROR),
2265  errmsg("option \"%s\" not recognized", defel->defname),
2266  parser_errposition(pstate, defel->location)));
2267  }
2268 
2269  if (dtablespace)
2270  {
2271  /*
2272  * While the SET TABLESPACE syntax doesn't allow any other options,
2273  * somebody could write "WITH TABLESPACE ...". Forbid any other
2274  * options from being specified in that case.
2275  */
2276  if (list_length(stmt->options) != 1)
2277  ereport(ERROR,
2278  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2279  errmsg("option \"%s\" cannot be specified with other options",
2280  dtablespace->defname),
2281  parser_errposition(pstate, dtablespace->location)));
2282  /* this case isn't allowed within a transaction block */
2283  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2284  movedb(stmt->dbname, defGetString(dtablespace));
2285  return InvalidOid;
2286  }
2287 
2288  if (distemplate && distemplate->arg)
2289  dbistemplate = defGetBoolean(distemplate);
2290  if (dallowconnections && dallowconnections->arg)
2291  dballowconnections = defGetBoolean(dallowconnections);
2292  if (dconnlimit && dconnlimit->arg)
2293  {
2294  dbconnlimit = defGetInt32(dconnlimit);
2295  if (dbconnlimit < -1)
2296  ereport(ERROR,
2297  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2298  errmsg("invalid connection limit: %d", dbconnlimit)));
2299  }
2300 
2301  /*
2302  * Get the old tuple. We don't need a lock on the database per se,
2303  * because we're not going to do anything that would mess up incoming
2304  * connections.
2305  */
2306  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2307  ScanKeyInit(&scankey,
2308  Anum_pg_database_datname,
2309  BTEqualStrategyNumber, F_NAMEEQ,
2310  CStringGetDatum(stmt->dbname));
2311  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2312  NULL, 1, &scankey);
2313  tuple = systable_getnext(scan);
2314  if (!HeapTupleIsValid(tuple))
2315  ereport(ERROR,
2316  (errcode(ERRCODE_UNDEFINED_DATABASE),
2317  errmsg("database \"%s\" does not exist", stmt->dbname)));
2318 
2319  datform = (Form_pg_database) GETSTRUCT(tuple);
2320  dboid = datform->oid;
2321 
2322  if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2324  stmt->dbname);
2325 
2326  /*
2327  * In order to avoid getting locked out and having to go through
2328  * standalone mode, we refuse to disallow connections to the database
2329  * we're currently connected to. Lockout can still happen with concurrent
2330  * sessions but the likeliness of that is not high enough to worry about.
2331  */
2332  if (!dballowconnections && dboid == MyDatabaseId)
2333  ereport(ERROR,
2334  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2335  errmsg("cannot disallow connections for current database")));
2336 
2337  /*
2338  * Build an updated tuple, perusing the information just obtained
2339  */
2340  if (distemplate)
2341  {
2342  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2343  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2344  }
2345  if (dallowconnections)
2346  {
2347  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2348  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2349  }
2350  if (dconnlimit)
2351  {
2352  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2353  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2354  }
2355 
2356  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2357  new_record_nulls, new_record_repl);
2358  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2359 
2360  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2361 
2362  systable_endscan(scan);
2363 
2364  /* Close pg_database, but keep lock till commit */
2365  table_close(rel, NoLock);
2366 
2367  return dboid;
2368 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2673
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3976
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1850
int32 defGetInt32(DefElem *def)
Definition: define.c:163
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#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:1113
#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:510
#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:2091
FormData_pg_database * Form_pg_database
Definition: pg_database.h:90
#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:529
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:810
int location
Definition: parsenodes.h:814
Node * arg
Definition: parsenodes.h:811
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:3482

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

2485 {
2486  Oid db_id;
2487  HeapTuple tuple;
2488  Relation rel;
2489  ScanKeyData scankey;
2490  SysScanDesc scan;
2491  Form_pg_database datForm;
2492  ObjectAddress address;
2493 
2494  /*
2495  * Get the old tuple. We don't need a lock on the database per se,
2496  * because we're not going to do anything that would mess up incoming
2497  * connections.
2498  */
2499  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2500  ScanKeyInit(&scankey,
2501  Anum_pg_database_datname,
2502  BTEqualStrategyNumber, F_NAMEEQ,
2504  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2505  NULL, 1, &scankey);
2506  tuple = systable_getnext(scan);
2507  if (!HeapTupleIsValid(tuple))
2508  ereport(ERROR,
2509  (errcode(ERRCODE_UNDEFINED_DATABASE),
2510  errmsg("database \"%s\" does not exist", dbname)));
2511 
2512  datForm = (Form_pg_database) GETSTRUCT(tuple);
2513  db_id = datForm->oid;
2514 
2515  /*
2516  * If the new owner is the same as the existing owner, consider the
2517  * command to have succeeded. This is to be consistent with other
2518  * objects.
2519  */
2520  if (datForm->datdba != newOwnerId)
2521  {
2522  Datum repl_val[Natts_pg_database];
2523  bool repl_null[Natts_pg_database] = {0};
2524  bool repl_repl[Natts_pg_database] = {0};
2525  Acl *newAcl;
2526  Datum aclDatum;
2527  bool isNull;
2528  HeapTuple newtuple;
2529 
2530  /* Otherwise, must be owner of the existing object */
2531  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2533  dbname);
2534 
2535  /* Must be able to become new owner */
2536  check_can_set_role(GetUserId(), newOwnerId);
2537 
2538  /*
2539  * must have createdb rights
2540  *
2541  * NOTE: This is different from other alter-owner checks in that the
2542  * current user is checked for createdb privileges instead of the
2543  * destination owner. This is consistent with the CREATE case for
2544  * databases. Because superusers will always have this right, we need
2545  * no special case for them.
2546  */
2547  if (!have_createdb_privilege())
2548  ereport(ERROR,
2549  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2550  errmsg("permission denied to change owner of database")));
2551 
2552  repl_repl[Anum_pg_database_datdba - 1] = true;
2553  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2554 
2555  /*
2556  * Determine the modified ACL for the new owner. This is only
2557  * necessary when the ACL is non-null.
2558  */
2559  aclDatum = heap_getattr(tuple,
2560  Anum_pg_database_datacl,
2561  RelationGetDescr(rel),
2562  &isNull);
2563  if (!isNull)
2564  {
2565  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2566  datForm->datdba, newOwnerId);
2567  repl_repl[Anum_pg_database_datacl - 1] = true;
2568  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2569  }
2570 
2571  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2572  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2573 
2574  heap_freetuple(newtuple);
2575 
2576  /* Update owner dependency reference */
2577  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2578  }
2579 
2580  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2581 
2582  ObjectAddressSet(address, DatabaseRelationId, db_id);
2583 
2584  systable_endscan(scan);
2585 
2586  /* Close pg_database, but keep lock till commit */
2587  table_close(rel, NoLock);
2588 
2589  return address;
2590 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1090
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5026
#define DatumGetAclP(X)
Definition: acl.h:120
bool have_createdb_privilege(void)
Definition: dbcommands.c:2788
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h: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 2375 of file dbcommands.c.

2376 {
2377  Relation rel;
2378  ScanKeyData scankey;
2379  SysScanDesc scan;
2380  Oid db_id;
2381  HeapTuple tuple;
2382  Form_pg_database datForm;
2383  ObjectAddress address;
2384  Datum datum;
2385  bool isnull;
2386  char *oldversion;
2387  char *newversion;
2388 
2389  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2390  ScanKeyInit(&scankey,
2391  Anum_pg_database_datname,
2392  BTEqualStrategyNumber, F_NAMEEQ,
2393  CStringGetDatum(stmt->dbname));
2394  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2395  NULL, 1, &scankey);
2396  tuple = systable_getnext(scan);
2397  if (!HeapTupleIsValid(tuple))
2398  ereport(ERROR,
2399  (errcode(ERRCODE_UNDEFINED_DATABASE),
2400  errmsg("database \"%s\" does not exist", stmt->dbname)));
2401 
2402  datForm = (Form_pg_database) GETSTRUCT(tuple);
2403  db_id = datForm->oid;
2404 
2405  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2407  stmt->dbname);
2408 
2409  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2410  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2411 
2412  datum = heap_getattr(tuple, datForm->datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2413  if (isnull)
2414  elog(ERROR, "unexpected null in pg_database");
2415  newversion = get_collation_actual_version(datForm->datlocprovider, TextDatumGetCString(datum));
2416 
2417  /* cannot change from NULL to non-NULL or vice versa */
2418  if ((!oldversion && newversion) || (oldversion && !newversion))
2419  elog(ERROR, "invalid collation version change");
2420  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2421  {
2422  bool nulls[Natts_pg_database] = {0};
2423  bool replaces[Natts_pg_database] = {0};
2424  Datum values[Natts_pg_database] = {0};
2425 
2426  ereport(NOTICE,
2427  (errmsg("changing version from %s to %s",
2428  oldversion, newversion)));
2429 
2430  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2431  replaces[Anum_pg_database_datcollversion - 1] = true;
2432 
2433  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2434  values, nulls, replaces);
2435  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2436  heap_freetuple(tuple);
2437  }
2438  else
2439  ereport(NOTICE,
2440  (errmsg("version has not changed")));
2441 
2442  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2443 
2444  ObjectAddressSet(address, DatabaseRelationId, db_id);
2445 
2446  systable_endscan(scan);
2447 
2448  table_close(rel, NoLock);
2449 
2450  return address;
2451 }
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:1707

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

2459 {
2460  Oid datid = get_database_oid(stmt->dbname, false);
2461 
2462  /*
2463  * Obtain a lock on the database and make sure it didn't go away in the
2464  * meantime.
2465  */
2466  shdepLockAndCheckObject(DatabaseRelationId, datid);
2467 
2468  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2470  stmt->dbname);
2471 
2472  AlterSetting(datid, InvalidOid, stmt->setstmt);
2473 
2474  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2475 
2476  return datid;
2477 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2976
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 1469 of file dbcommands.c.

1470 {
1471  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1472  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1473 
1474  if (!(ctype_encoding == encoding ||
1475  ctype_encoding == PG_SQL_ASCII ||
1476  ctype_encoding == -1 ||
1477 #ifdef WIN32
1478  encoding == PG_UTF8 ||
1479 #endif
1480  (encoding == PG_SQL_ASCII && superuser())))
1481  ereport(ERROR,
1482  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1483  errmsg("encoding \"%s\" does not match locale \"%s\"",
1485  ctype),
1486  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1487  pg_encoding_to_char(ctype_encoding))));
1488 
1489  if (!(collate_encoding == encoding ||
1490  collate_encoding == PG_SQL_ASCII ||
1491  collate_encoding == -1 ||
1492 #ifdef WIN32
1493  encoding == PG_UTF8 ||
1494 #endif
1495  (encoding == PG_SQL_ASCII && superuser())))
1496  ereport(ERROR,
1497  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1498  errmsg("encoding \"%s\" does not match locale \"%s\"",
1500  collate),
1501  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1502  pg_encoding_to_char(collate_encoding))));
1503 }
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 = -1;
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 < -1)
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  * Permission check: to copy a DB that's not marked datistemplate, you
982  * must be superuser or the owner thereof.
983  */
984  if (!src_istemplate)
985  {
986  if (!object_ownercheck(DatabaseRelationId, src_dboid, GetUserId()))
987  ereport(ERROR,
988  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
989  errmsg("permission denied to copy database \"%s\"",
990  dbtemplate)));
991  }
992 
993  /* Validate the database creation strategy. */
994  if (dstrategy && dstrategy->arg)
995  {
996  char *strategy;
997 
998  strategy = defGetString(dstrategy);
999  if (strcmp(strategy, "wal_log") == 0)
1000  dbstrategy = CREATEDB_WAL_LOG;
1001  else if (strcmp(strategy, "file_copy") == 0)
1002  dbstrategy = CREATEDB_FILE_COPY;
1003  else
1004  ereport(ERROR,
1005  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1006  errmsg("invalid create database strategy \"%s\"", strategy),
1007  errhint("Valid strategies are \"wal_log\", and \"file_copy\".")));
1008  }
1009 
1010  /* If encoding or locales are defaulted, use source's setting */
1011  if (encoding < 0)
1012  encoding = src_encoding;
1013  if (dbcollate == NULL)
1014  dbcollate = src_collate;
1015  if (dbctype == NULL)
1016  dbctype = src_ctype;
1017  if (dblocprovider == '\0')
1018  dblocprovider = src_locprovider;
1019  if (dbiculocale == NULL && dblocprovider == COLLPROVIDER_ICU)
1020  dbiculocale = src_iculocale;
1021  if (dbicurules == NULL && dblocprovider == COLLPROVIDER_ICU)
1022  dbicurules = src_icurules;
1023 
1024  /* Some encodings are client only */
1026  ereport(ERROR,
1027  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1028  errmsg("invalid server encoding %d", encoding)));
1029 
1030  /* Check that the chosen locales are valid, and get canonical spellings */
1031  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
1032  ereport(ERROR,
1033  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1034  errmsg("invalid locale name: \"%s\"", dbcollate)));
1035  dbcollate = canonname;
1036  if (!check_locale(LC_CTYPE, dbctype, &canonname))
1037  ereport(ERROR,
1038  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1039  errmsg("invalid locale name: \"%s\"", dbctype)));
1040  dbctype = canonname;
1041 
1042  check_encoding_locale_matches(encoding, dbcollate, dbctype);
1043 
1044  if (dblocprovider == COLLPROVIDER_ICU)
1045  {
1047  ereport(ERROR,
1048  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1049  errmsg("encoding \"%s\" is not supported with ICU provider",
1051 
1052  /*
1053  * This would happen if template0 uses the libc provider but the new
1054  * database uses icu.
1055  */
1056  if (!dbiculocale)
1057  ereport(ERROR,
1058  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1059  errmsg("ICU locale must be specified")));
1060 
1061  icu_validate_locale(dbiculocale);
1062  }
1063  else
1064  {
1065  if (dbiculocale)
1066  ereport(ERROR,
1067  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1068  errmsg("ICU locale cannot be specified unless locale provider is ICU")));
1069 
1070  if (dbicurules)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1073  errmsg("ICU rules cannot be specified unless locale provider is ICU")));
1074  }
1075 
1076  /*
1077  * Check that the new encoding and locale settings match the source
1078  * database. We insist on this because we simply copy the source data ---
1079  * any non-ASCII data would be wrongly encoded, and any indexes sorted
1080  * according to the source locale would be wrong.
1081  *
1082  * However, we assume that template0 doesn't contain any non-ASCII data
1083  * nor any indexes that depend on collation or ctype, so template0 can be
1084  * used as template for creating a database with any encoding or locale.
1085  */
1086  if (strcmp(dbtemplate, "template0") != 0)
1087  {
1088  if (encoding != src_encoding)
1089  ereport(ERROR,
1090  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1091  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1093  pg_encoding_to_char(src_encoding)),
1094  errhint("Use the same encoding as in the template database, or use template0 as template.")));
1095 
1096  if (strcmp(dbcollate, src_collate) != 0)
1097  ereport(ERROR,
1098  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1099  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1100  dbcollate, src_collate),
1101  errhint("Use the same collation as in the template database, or use template0 as template.")));
1102 
1103  if (strcmp(dbctype, src_ctype) != 0)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1106  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1107  dbctype, src_ctype),
1108  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1109 
1110  if (dblocprovider != src_locprovider)
1111  ereport(ERROR,
1112  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1113  errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1114  collprovider_name(dblocprovider), collprovider_name(src_locprovider)),
1115  errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1116 
1117  if (dblocprovider == COLLPROVIDER_ICU)
1118  {
1119  char *val1;
1120  char *val2;
1121 
1122  Assert(dbiculocale);
1123  Assert(src_iculocale);
1124  if (strcmp(dbiculocale, src_iculocale) != 0)
1125  ereport(ERROR,
1126  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1127  errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1128  dbiculocale, src_iculocale),
1129  errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1130 
1131  val1 = dbicurules;
1132  if (!val1)
1133  val1 = "";
1134  val2 = src_icurules;
1135  if (!val2)
1136  val2 = "";
1137  if (strcmp(val1, val2) != 0)
1138  ereport(ERROR,
1139  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1140  errmsg("new ICU collation rules (%s) are incompatible with the ICU collation rules of the template database (%s)",
1141  val1, val2),
1142  errhint("Use the same ICU collation rules as in the template database, or use template0 as template.")));
1143  }
1144  }
1145 
1146  /*
1147  * If we got a collation version for the template database, check that it
1148  * matches the actual OS collation version. Otherwise error; the user
1149  * needs to fix the template database first. Don't complain if a
1150  * collation version was specified explicitly as a statement option; that
1151  * is used by pg_upgrade to reproduce the old state exactly.
1152  *
1153  * (If the template database has no collation version, then either the
1154  * platform/provider does not support collation versioning, or it's
1155  * template0, for which we stipulate that it does not contain
1156  * collation-using objects.)
1157  */
1158  if (src_collversion && !dcollversion)
1159  {
1160  char *actual_versionstr;
1161 
1162  actual_versionstr = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1163  if (!actual_versionstr)
1164  ereport(ERROR,
1165  (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1166  dbtemplate)));
1167 
1168  if (strcmp(actual_versionstr, src_collversion) != 0)
1169  ereport(ERROR,
1170  (errmsg("template database \"%s\" has a collation version mismatch",
1171  dbtemplate),
1172  errdetail("The template database was created using collation version %s, "
1173  "but the operating system provides version %s.",
1174  src_collversion, actual_versionstr),
1175  errhint("Rebuild all objects in the template database that use the default collation and run "
1176  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1177  "or build PostgreSQL with the right library version.",
1178  quote_identifier(dbtemplate))));
1179  }
1180 
1181  if (dbcollversion == NULL)
1182  dbcollversion = src_collversion;
1183 
1184  /*
1185  * Normally, we copy the collation version from the template database.
1186  * This last resort only applies if the template database does not have a
1187  * collation version, which is normally only the case for template0.
1188  */
1189  if (dbcollversion == NULL)
1190  dbcollversion = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1191 
1192  /* Resolve default tablespace for new database */
1193  if (dtablespacename && dtablespacename->arg)
1194  {
1195  char *tablespacename;
1196  AclResult aclresult;
1197 
1198  tablespacename = defGetString(dtablespacename);
1199  dst_deftablespace = get_tablespace_oid(tablespacename, false);
1200  /* check permissions */
1201  aclresult = object_aclcheck(TableSpaceRelationId, dst_deftablespace, GetUserId(),
1202  ACL_CREATE);
1203  if (aclresult != ACLCHECK_OK)
1204  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1205  tablespacename);
1206 
1207  /* pg_global must never be the default tablespace */
1208  if (dst_deftablespace == GLOBALTABLESPACE_OID)
1209  ereport(ERROR,
1210  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1211  errmsg("pg_global cannot be used as default tablespace")));
1212 
1213  /*
1214  * If we are trying to change the default tablespace of the template,
1215  * we require that the template not have any files in the new default
1216  * tablespace. This is necessary because otherwise the copied
1217  * database would contain pg_class rows that refer to its default
1218  * tablespace both explicitly (by OID) and implicitly (as zero), which
1219  * would cause problems. For example another CREATE DATABASE using
1220  * the copied database as template, and trying to change its default
1221  * tablespace again, would yield outright incorrect results (it would
1222  * improperly move tables to the new default tablespace that should
1223  * stay in the same tablespace).
1224  */
1225  if (dst_deftablespace != src_deftablespace)
1226  {
1227  char *srcpath;
1228  struct stat st;
1229 
1230  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
1231 
1232  if (stat(srcpath, &st) == 0 &&
1233  S_ISDIR(st.st_mode) &&
1234  !directory_is_empty(srcpath))
1235  ereport(ERROR,
1236  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1237  errmsg("cannot assign new default tablespace \"%s\"",
1238  tablespacename),
1239  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1240  dbtemplate)));
1241  pfree(srcpath);
1242  }
1243  }
1244  else
1245  {
1246  /* Use template database's default tablespace */
1247  dst_deftablespace = src_deftablespace;
1248  /* Note there is no additional permission check in this path */
1249  }
1250 
1251  /*
1252  * If built with appropriate switch, whine when regression-testing
1253  * conventions for database names are violated. But don't complain during
1254  * initdb.
1255  */
1256 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1257  if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1258  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1259 #endif
1260 
1261  /*
1262  * Check for db name conflict. This is just to give a more friendly error
1263  * message than "unique index violation". There's a race condition but
1264  * we're willing to accept the less friendly message in that case.
1265  */
1266  if (OidIsValid(get_database_oid(dbname, true)))
1267  ereport(ERROR,
1268  (errcode(ERRCODE_DUPLICATE_DATABASE),
1269  errmsg("database \"%s\" already exists", dbname)));
1270 
1271  /*
1272  * The source DB can't have any active backends, except this one
1273  * (exception is to allow CREATE DB while connected to template1).
1274  * Otherwise we might copy inconsistent data.
1275  *
1276  * This should be last among the basic error checks, because it involves
1277  * potential waiting; we may as well throw an error first if we're gonna
1278  * throw one.
1279  */
1280  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
1281  ereport(ERROR,
1282  (errcode(ERRCODE_OBJECT_IN_USE),
1283  errmsg("source database \"%s\" is being accessed by other users",
1284  dbtemplate),
1285  errdetail_busy_db(notherbackends, npreparedxacts)));
1286 
1287  /*
1288  * Select an OID for the new database, checking that it doesn't have a
1289  * filename conflict with anything already existing in the tablespace
1290  * directories.
1291  */
1292  pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
1293 
1294  /*
1295  * If database OID is configured, check if the OID is already in use or
1296  * data directory already exists.
1297  */
1298  if (OidIsValid(dboid))
1299  {
1300  char *existing_dbname = get_database_name(dboid);
1301 
1302  if (existing_dbname != NULL)
1303  ereport(ERROR,
1304  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1305  errmsg("database OID %u is already in use by database \"%s\"",
1306  dboid, existing_dbname));
1307 
1308  if (check_db_file_conflict(dboid))
1309  ereport(ERROR,
1310  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1311  errmsg("data directory with the specified OID %u already exists", dboid));
1312  }
1313  else
1314  {
1315  /* Select an OID for the new database if is not explicitly configured. */
1316  do
1317  {
1318  dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
1319  Anum_pg_database_oid);
1320  } while (check_db_file_conflict(dboid));
1321  }
1322 
1323  /*
1324  * Insert a new tuple into pg_database. This establishes our ownership of
1325  * the new database name (anyone else trying to insert the same name will
1326  * block on the unique index, and fail after we commit).
1327  */
1328 
1329  Assert((dblocprovider == COLLPROVIDER_ICU && dbiculocale) ||
1330  (dblocprovider != COLLPROVIDER_ICU && !dbiculocale));
1331 
1332  /* Form tuple */
1333  new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
1334  new_record[Anum_pg_database_datname - 1] =
1336  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
1337  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
1338  new_record[Anum_pg_database_datlocprovider - 1] = CharGetDatum(dblocprovider);
1339  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1340  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1341  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1342  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
1343  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
1344  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
1345  new_record[Anum_pg_database_datcollate - 1] = CStringGetTextDatum(dbcollate);
1346  new_record[Anum_pg_database_datctype - 1] = CStringGetTextDatum(dbctype);
1347  if (dbiculocale)
1348  new_record[Anum_pg_database_daticulocale - 1] = CStringGetTextDatum(dbiculocale);
1349  else
1350  new_record_nulls[Anum_pg_database_daticulocale - 1] = true;
1351  if (dbicurules)
1352  new_record[Anum_pg_database_daticurules - 1] = CStringGetTextDatum(dbicurules);
1353  else
1354  new_record_nulls[Anum_pg_database_daticurules - 1] = true;
1355  if (dbcollversion)
1356  new_record[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(dbcollversion);
1357  else
1358  new_record_nulls[Anum_pg_database_datcollversion - 1] = true;
1359 
1360  /*
1361  * We deliberately set datacl to default (NULL), rather than copying it
1362  * from the template database. Copying it would be a bad idea when the
1363  * owner is not the same as the template's owner.
1364  */
1365  new_record_nulls[Anum_pg_database_datacl - 1] = true;
1366 
1367  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
1368  new_record, new_record_nulls);
1369 
1370  CatalogTupleInsert(pg_database_rel, tuple);
1371 
1372  /*
1373  * Now generate additional catalog entries associated with the new DB
1374  */
1375 
1376  /* Register owner dependency */
1377  recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
1378 
1379  /* Create pg_shdepend entries for objects within database */
1380  copyTemplateDependencies(src_dboid, dboid);
1381 
1382  /* Post creation hook for new database */
1383  InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
1384 
1385  /*
1386  * If we're going to be reading data for the to-be-created database into
1387  * shared_buffers, take a lock on it. Nobody should know that this
1388  * database exists yet, but it's good to maintain the invariant that an
1389  * AccessExclusiveLock on the database is sufficient to drop all
1390  * of its buffers without worrying about more being read later.
1391  *
1392  * Note that we need to do this before entering the
1393  * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1394  * expects this lock to be held already.
1395  */
1396  if (dbstrategy == CREATEDB_WAL_LOG)
1397  LockSharedObject(DatabaseRelationId, dboid, 0, AccessShareLock);
1398 
1399  /*
1400  * Once we start copying subdirectories, we need to be able to clean 'em
1401  * up if we fail. Use an ENSURE block to make sure this happens. (This
1402  * is not a 100% solution, because of the possibility of failure during
1403  * transaction commit after we leave this routine, but it should handle
1404  * most scenarios.)
1405  */
1406  fparms.src_dboid = src_dboid;
1407  fparms.dest_dboid = dboid;
1408  fparms.strategy = dbstrategy;
1409 
1411  PointerGetDatum(&fparms));
1412  {
1413  /*
1414  * If the user has asked to create a database with WAL_LOG strategy
1415  * then call CreateDatabaseUsingWalLog, which will copy the database
1416  * at the block level and it will WAL log each copied block.
1417  * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1418  * database file by file.
1419  */
1420  if (dbstrategy == CREATEDB_WAL_LOG)
1421  CreateDatabaseUsingWalLog(src_dboid, dboid, src_deftablespace,
1422  dst_deftablespace);
1423  else
1424  CreateDatabaseUsingFileCopy(src_dboid, dboid, src_deftablespace,
1425  dst_deftablespace);
1426 
1427  /*
1428  * Close pg_database, but keep lock till commit.
1429  */
1430  table_close(pg_database_rel, NoLock);
1431 
1432  /*
1433  * Force synchronous commit, thus minimizing the window between
1434  * creation of the database files and committal of the transaction. If
1435  * we crash before committing, we'll have a DB that's taking up disk
1436  * space but is not in pg_database, which is not good.
1437  */
1438  ForceSyncCommit();
1439  }
1441  PointerGetDatum(&fparms));
1442 
1443  return dboid;
1444 }
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5255
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:3775
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:646
uint32 TransactionId
Definition: c.h:636
#define OidIsValid(objectId)
Definition: c.h:759
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3023
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:2633
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:1469
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2946
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:2903
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:1507
Oid defGetObjectId(DefElem *def)
Definition: define.c:220
int errhint(const char *fmt,...)
Definition: elog.c:1316
#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:1020
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:1436
#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:2124
#define ACL_CREATE
Definition: parsenodes.h:92
void icu_validate_locale(const char *loc_str)
Definition: pg_locale.c:2833
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:275
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:3739
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11751
Definition: value.h:29
CreateDBStrategy strategy
Definition: dbcommands.c:93
#define InvalidTransactionId
Definition: transam.h:31
#define FirstNormalObjectId
Definition: transam.h:197
#define stat
Definition: win32_port.h:286
#define S_ISDIR(m)
Definition: win32_port.h:327
void ForceSyncCommit(void)
Definition: xact.c: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, 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_validate_locale(), Int32GetDatum(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, is_encoding_supported_by_icu(), IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), namein(), NoLock, object_aclcheck(), object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, 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 2187 of file dbcommands.c.

2188 {
2189  bool force = false;
2190  ListCell *lc;
2191 
2192  foreach(lc, stmt->options)
2193  {
2194  DefElem *opt = (DefElem *) lfirst(lc);
2195 
2196  if (strcmp(opt->defname, "force") == 0)
2197  force = true;
2198  else
2199  ereport(ERROR,
2200  (errcode(ERRCODE_SYNTAX_ERROR),
2201  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2202  parser_errposition(pstate, opt->location)));
2203  }
2204 
2205  dropdb(stmt->dbname, stmt->missing_ok, force);
2206 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1546

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

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

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

Referenced by DropDatabase().

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 3023 of file dbcommands.c.

3024 {
3025  HeapTuple dbtuple;
3026  char *result;
3027 
3028  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3029  if (HeapTupleIsValid(dbtuple))
3030  {
3031  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3032  ReleaseSysCache(dbtuple);
3033  }
3034  else
3035  result = NULL;
3036 
3037  return result;
3038 }
#define NameStr(name)
Definition: c.h:730
char * pstrdup(const char *in)
Definition: mcxt.c:1624
NameData datname
Definition: pg_database.h:35

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

Referenced by AfterTriggerSetState(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), calculate_database_size(), createdb(), CreatePublication(), CreateSchemaCommand(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), exec_object_restorecon(), ExpandColumnRefStar(), GetNewMultiXactId(), GetNewTransactionId(), getObjectDescription(), getObjectIdentityParts(), heap_vacuum_rel(), IdentifySystem(), InitTempTableNamespace(), 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 2976 of file dbcommands.c.

2977 {
2978  Relation pg_database;
2979  ScanKeyData entry[1];
2980  SysScanDesc scan;
2981  HeapTuple dbtuple;
2982  Oid oid;
2983 
2984  /*
2985  * There's no syscache for pg_database indexed by name, so we must look
2986  * the hard way.
2987  */
2988  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2989  ScanKeyInit(&entry[0],
2990  Anum_pg_database_datname,
2991  BTEqualStrategyNumber, F_NAMEEQ,
2993  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2994  NULL, 1, entry);
2995 
2996  dbtuple = systable_getnext(scan);
2997 
2998  /* We assume that there can be at most one matching tuple */
2999  if (HeapTupleIsValid(dbtuple))
3000  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3001  else
3002  oid = InvalidOid;
3003 
3004  systable_endscan(scan);
3005  table_close(pg_database, AccessShareLock);
3006 
3007  if (!OidIsValid(oid) && !missing_ok)
3008  ereport(ERROR,
3009  (errcode(ERRCODE_UNDEFINED_DATABASE),
3010  errmsg("database \"%s\" does not exist",
3011  dbname)));
3012 
3013  return oid;
3014 }

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

2789 {
2790  bool result = false;
2791  HeapTuple utup;
2792 
2793  /* Superusers can always do everything */
2794  if (superuser())
2795  return true;
2796 
2798  if (HeapTupleIsValid(utup))
2799  {
2800  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2801  ReleaseSysCache(utup);
2802  }
2803  return result;
2804 }
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 1752 of file dbcommands.c.

1753 {
1754  Oid db_id;
1755  HeapTuple newtup;
1756  Relation rel;
1757  int notherbackends;
1758  int npreparedxacts;
1759  ObjectAddress address;
1760 
1761  /*
1762  * Look up the target database's OID, and get exclusive lock on it. We
1763  * need this for the same reasons as DROP DATABASE.
1764  */
1765  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1766 
1767  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1768  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1769  ereport(ERROR,
1770  (errcode(ERRCODE_UNDEFINED_DATABASE),
1771  errmsg("database \"%s\" does not exist", oldname)));
1772 
1773  /* must be owner */
1774  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1776  oldname);
1777 
1778  /* must have createdb rights */
1779  if (!have_createdb_privilege())
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1782  errmsg("permission denied to rename database")));
1783 
1784  /*
1785  * If built with appropriate switch, whine when regression-testing
1786  * conventions for database names are violated.
1787  */
1788 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1789  if (strstr(newname, "regression") == NULL)
1790  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1791 #endif
1792 
1793  /*
1794  * Make sure the new name doesn't exist. See notes for same error in
1795  * CREATE DATABASE.
1796  */
1797  if (OidIsValid(get_database_oid(newname, true)))
1798  ereport(ERROR,
1799  (errcode(ERRCODE_DUPLICATE_DATABASE),
1800  errmsg("database \"%s\" already exists", newname)));
1801 
1802  /*
1803  * XXX Client applications probably store the current database somewhere,
1804  * so renaming it could cause confusion. On the other hand, there may not
1805  * be an actual problem besides a little confusion, so think about this
1806  * and decide.
1807  */
1808  if (db_id == MyDatabaseId)
1809  ereport(ERROR,
1810  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1811  errmsg("current database cannot be renamed")));
1812 
1813  /*
1814  * Make sure the database does not have active sessions. This is the same
1815  * concern as above, but applied to other sessions.
1816  *
1817  * As in CREATE DATABASE, check this after other error conditions.
1818  */
1819  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1820  ereport(ERROR,
1821  (errcode(ERRCODE_OBJECT_IN_USE),
1822  errmsg("database \"%s\" is being accessed by other users",
1823  oldname),
1824  errdetail_busy_db(notherbackends, npreparedxacts)));
1825 
1826  /* rename */
1828  if (!HeapTupleIsValid(newtup))
1829  elog(ERROR, "cache lookup failed for database %u", db_id);
1830  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1831  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1832 
1833  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1834 
1835  ObjectAddressSet(address, DatabaseRelationId, db_id);
1836 
1837  /*
1838  * Close pg_database, but keep lock till commit.
1839  */
1840  table_close(rel, NoLock);
1841 
1842  return address;
1843 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:182

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().