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

2181 {
2182  Relation rel;
2183  Oid dboid;
2184  HeapTuple tuple,
2185  newtuple;
2186  Form_pg_database datform;
2187  ScanKeyData scankey;
2188  SysScanDesc scan;
2189  ListCell *option;
2190  bool dbistemplate = false;
2191  bool dballowconnections = true;
2192  int dbconnlimit = -1;
2193  DefElem *distemplate = NULL;
2194  DefElem *dallowconnections = NULL;
2195  DefElem *dconnlimit = NULL;
2196  DefElem *dtablespace = NULL;
2197  Datum new_record[Natts_pg_database];
2198  bool new_record_nulls[Natts_pg_database];
2199  bool new_record_repl[Natts_pg_database];
2200 
2201  /* Extract options from the statement node tree */
2202  foreach(option, stmt->options)
2203  {
2204  DefElem *defel = (DefElem *) lfirst(option);
2205 
2206  if (strcmp(defel->defname, "is_template") == 0)
2207  {
2208  if (distemplate)
2209  errorConflictingDefElem(defel, pstate);
2210  distemplate = defel;
2211  }
2212  else if (strcmp(defel->defname, "allow_connections") == 0)
2213  {
2214  if (dallowconnections)
2215  errorConflictingDefElem(defel, pstate);
2216  dallowconnections = defel;
2217  }
2218  else if (strcmp(defel->defname, "connection_limit") == 0)
2219  {
2220  if (dconnlimit)
2221  errorConflictingDefElem(defel, pstate);
2222  dconnlimit = defel;
2223  }
2224  else if (strcmp(defel->defname, "tablespace") == 0)
2225  {
2226  if (dtablespace)
2227  errorConflictingDefElem(defel, pstate);
2228  dtablespace = defel;
2229  }
2230  else
2231  ereport(ERROR,
2232  (errcode(ERRCODE_SYNTAX_ERROR),
2233  errmsg("option \"%s\" not recognized", defel->defname),
2234  parser_errposition(pstate, defel->location)));
2235  }
2236 
2237  if (dtablespace)
2238  {
2239  /*
2240  * While the SET TABLESPACE syntax doesn't allow any other options,
2241  * somebody could write "WITH TABLESPACE ...". Forbid any other
2242  * options from being specified in that case.
2243  */
2244  if (list_length(stmt->options) != 1)
2245  ereport(ERROR,
2246  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2247  errmsg("option \"%s\" cannot be specified with other options",
2248  dtablespace->defname),
2249  parser_errposition(pstate, dtablespace->location)));
2250  /* this case isn't allowed within a transaction block */
2251  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2252  movedb(stmt->dbname, defGetString(dtablespace));
2253  return InvalidOid;
2254  }
2255 
2256  if (distemplate && distemplate->arg)
2257  dbistemplate = defGetBoolean(distemplate);
2258  if (dallowconnections && dallowconnections->arg)
2259  dballowconnections = defGetBoolean(dallowconnections);
2260  if (dconnlimit && dconnlimit->arg)
2261  {
2262  dbconnlimit = defGetInt32(dconnlimit);
2263  if (dbconnlimit < -1)
2264  ereport(ERROR,
2265  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2266  errmsg("invalid connection limit: %d", dbconnlimit)));
2267  }
2268 
2269  /*
2270  * Get the old tuple. We don't need a lock on the database per se,
2271  * because we're not going to do anything that would mess up incoming
2272  * connections.
2273  */
2274  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2275  ScanKeyInit(&scankey,
2276  Anum_pg_database_datname,
2277  BTEqualStrategyNumber, F_NAMEEQ,
2278  CStringGetDatum(stmt->dbname));
2279  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2280  NULL, 1, &scankey);
2281  tuple = systable_getnext(scan);
2282  if (!HeapTupleIsValid(tuple))
2283  ereport(ERROR,
2284  (errcode(ERRCODE_UNDEFINED_DATABASE),
2285  errmsg("database \"%s\" does not exist", stmt->dbname)));
2286 
2287  datform = (Form_pg_database) GETSTRUCT(tuple);
2288  dboid = datform->oid;
2289 
2290  if (!pg_database_ownercheck(dboid, GetUserId()))
2292  stmt->dbname);
2293 
2294  /*
2295  * In order to avoid getting locked out and having to go through
2296  * standalone mode, we refuse to disallow connections to the database
2297  * we're currently connected to. Lockout can still happen with concurrent
2298  * sessions but the likeliness of that is not high enough to worry about.
2299  */
2300  if (!dballowconnections && dboid == MyDatabaseId)
2301  ereport(ERROR,
2302  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2303  errmsg("cannot disallow connections for current database")));
2304 
2305  /*
2306  * Build an updated tuple, perusing the information just obtained
2307  */
2308  MemSet(new_record, 0, sizeof(new_record));
2309  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
2310  MemSet(new_record_repl, false, sizeof(new_record_repl));
2311 
2312  if (distemplate)
2313  {
2314  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2315  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2316  }
2317  if (dallowconnections)
2318  {
2319  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2320  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2321  }
2322  if (dconnlimit)
2323  {
2324  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2325  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2326  }
2327 
2328  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2329  new_record_nulls, new_record_repl);
2330  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2331 
2332  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2333 
2334  systable_endscan(scan);
2335 
2336  /* Close pg_database, but keep lock till commit */
2337  table_close(rel, NoLock);
2338 
2339  return dboid;
2340 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5589
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
#define MemSet(start, val, len)
Definition: c.h:1008
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1815
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:352
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
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:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:492
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:195
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
@ OBJECT_DATABASE
Definition: parsenodes.h:2143
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define BoolGetDatum(X)
Definition: postgres.h:446
#define Int32GetDatum(X)
Definition: postgres.h:523
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:515
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:765
int location
Definition: parsenodes.h:769
Node * arg
Definition: parsenodes.h:766
ItemPointerData t_self
Definition: htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3462

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

2457 {
2458  Oid db_id;
2459  HeapTuple tuple;
2460  Relation rel;
2461  ScanKeyData scankey;
2462  SysScanDesc scan;
2463  Form_pg_database datForm;
2464  ObjectAddress address;
2465 
2466  /*
2467  * Get the old tuple. We don't need a lock on the database per se,
2468  * because we're not going to do anything that would mess up incoming
2469  * connections.
2470  */
2471  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2472  ScanKeyInit(&scankey,
2473  Anum_pg_database_datname,
2474  BTEqualStrategyNumber, F_NAMEEQ,
2476  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2477  NULL, 1, &scankey);
2478  tuple = systable_getnext(scan);
2479  if (!HeapTupleIsValid(tuple))
2480  ereport(ERROR,
2481  (errcode(ERRCODE_UNDEFINED_DATABASE),
2482  errmsg("database \"%s\" does not exist", dbname)));
2483 
2484  datForm = (Form_pg_database) GETSTRUCT(tuple);
2485  db_id = datForm->oid;
2486 
2487  /*
2488  * If the new owner is the same as the existing owner, consider the
2489  * command to have succeeded. This is to be consistent with other
2490  * objects.
2491  */
2492  if (datForm->datdba != newOwnerId)
2493  {
2494  Datum repl_val[Natts_pg_database];
2495  bool repl_null[Natts_pg_database];
2496  bool repl_repl[Natts_pg_database];
2497  Acl *newAcl;
2498  Datum aclDatum;
2499  bool isNull;
2500  HeapTuple newtuple;
2501 
2502  /* Otherwise, must be owner of the existing object */
2503  if (!pg_database_ownercheck(db_id, GetUserId()))
2505  dbname);
2506 
2507  /* Must be able to become new owner */
2508  check_is_member_of_role(GetUserId(), newOwnerId);
2509 
2510  /*
2511  * must have createdb rights
2512  *
2513  * NOTE: This is different from other alter-owner checks in that the
2514  * current user is checked for createdb privileges instead of the
2515  * destination owner. This is consistent with the CREATE case for
2516  * databases. Because superusers will always have this right, we need
2517  * no special case for them.
2518  */
2519  if (!have_createdb_privilege())
2520  ereport(ERROR,
2521  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2522  errmsg("permission denied to change owner of database")));
2523 
2524  memset(repl_null, false, sizeof(repl_null));
2525  memset(repl_repl, false, sizeof(repl_repl));
2526 
2527  repl_repl[Anum_pg_database_datdba - 1] = true;
2528  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2529 
2530  /*
2531  * Determine the modified ACL for the new owner. This is only
2532  * necessary when the ACL is non-null.
2533  */
2534  aclDatum = heap_getattr(tuple,
2535  Anum_pg_database_datacl,
2536  RelationGetDescr(rel),
2537  &isNull);
2538  if (!isNull)
2539  {
2540  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2541  datForm->datdba, newOwnerId);
2542  repl_repl[Anum_pg_database_datacl - 1] = true;
2543  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2544  }
2545 
2546  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2547  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2548 
2549  heap_freetuple(newtuple);
2550 
2551  /* Update owner dependency reference */
2552  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2553  }
2554 
2555  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2556 
2557  ObjectAddressSet(address, DatabaseRelationId, db_id);
2558 
2559  systable_endscan(scan);
2560 
2561  /* Close pg_database, but keep lock till commit */
2562  table_close(rel, NoLock);
2563 
2564  return address;
2565 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1053
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:5003
#define DatumGetAclP(X)
Definition: acl.h:120
static bool have_createdb_privilege(void)
Definition: dbcommands.c:2759
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:788
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:312
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define PointerGetDatum(X)
Definition: postgres.h:600
char * dbname
Definition: streamutil.c:51

References aclcheck_error(), ACLCHECK_NOT_OWNER, aclnewowner(), BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependencyOnOwner(), check_is_member_of_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, ObjectAddressSet, ObjectIdGetDatum, pg_database_ownercheck(), 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 2347 of file dbcommands.c.

2348 {
2349  Relation rel;
2350  ScanKeyData scankey;
2351  SysScanDesc scan;
2352  Oid db_id;
2353  HeapTuple tuple;
2354  Form_pg_database datForm;
2355  ObjectAddress address;
2356  Datum datum;
2357  bool isnull;
2358  char *oldversion;
2359  char *newversion;
2360 
2361  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2362  ScanKeyInit(&scankey,
2363  Anum_pg_database_datname,
2364  BTEqualStrategyNumber, F_NAMEEQ,
2365  CStringGetDatum(stmt->dbname));
2366  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2367  NULL, 1, &scankey);
2368  tuple = systable_getnext(scan);
2369  if (!HeapTupleIsValid(tuple))
2370  ereport(ERROR,
2371  (errcode(ERRCODE_UNDEFINED_DATABASE),
2372  errmsg("database \"%s\" does not exist", stmt->dbname)));
2373 
2374  datForm = (Form_pg_database) GETSTRUCT(tuple);
2375  db_id = datForm->oid;
2376 
2377  if (!pg_database_ownercheck(db_id, GetUserId()))
2379  stmt->dbname);
2380 
2381  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2382  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2383 
2384  datum = heap_getattr(tuple, datForm->datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2385  if (isnull)
2386  elog(ERROR, "unexpected null in pg_database");
2387  newversion = get_collation_actual_version(datForm->datlocprovider, TextDatumGetCString(datum));
2388 
2389  /* cannot change from NULL to non-NULL or vice versa */
2390  if ((!oldversion && newversion) || (oldversion && !newversion))
2391  elog(ERROR, "invalid collation version change");
2392  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2393  {
2394  bool nulls[Natts_pg_database] = {0};
2395  bool replaces[Natts_pg_database] = {0};
2396  Datum values[Natts_pg_database] = {0};
2397 
2398  ereport(NOTICE,
2399  (errmsg("changing version from %s to %s",
2400  oldversion, newversion)));
2401 
2402  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2403  replaces[Anum_pg_database_datcollversion - 1] = true;
2404 
2405  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2406  values, nulls, replaces);
2407  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2408  heap_freetuple(tuple);
2409  }
2410  else
2411  ereport(NOTICE,
2412  (errmsg("version has not changed")));
2413 
2414  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2415 
2416  ObjectAddressSet(address, DatabaseRelationId, db_id);
2417 
2418  systable_endscan(scan);
2419 
2420  table_close(rel, NoLock);
2421 
2422  return address;
2423 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define elog(elevel,...)
Definition: elog.h:218
#define NOTICE
Definition: elog.h:29
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1684

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum, CStringGetTextDatum, AlterDatabaseRefreshCollStmt::dbname, elog, ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), GETSTRUCT, GetUserId(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, NOTICE, OBJECT_DATABASE, ObjectAddressSet, pg_database_ownercheck(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), 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 2430 of file dbcommands.c.

2431 {
2432  Oid datid = get_database_oid(stmt->dbname, false);
2433 
2434  /*
2435  * Obtain a lock on the database and make sure it didn't go away in the
2436  * meantime.
2437  */
2438  shdepLockAndCheckObject(DatabaseRelationId, datid);
2439 
2440  if (!pg_database_ownercheck(datid, GetUserId()))
2442  stmt->dbname);
2443 
2444  AlterSetting(datid, InvalidOid, stmt->setstmt);
2445 
2446  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2447 
2448  return datid;
2449 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2947
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:1165
VariableSetStmt * setstmt
Definition: parsenodes.h:3666

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), AlterDatabaseSetStmt::dbname, get_database_oid(), GetUserId(), InvalidOid, OBJECT_DATABASE, pg_database_ownercheck(), AlterDatabaseSetStmt::setstmt, shdepLockAndCheckObject(), 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 1434 of file dbcommands.c.

1435 {
1436  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1437  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1438 
1439  if (!(ctype_encoding == encoding ||
1440  ctype_encoding == PG_SQL_ASCII ||
1441  ctype_encoding == -1 ||
1442 #ifdef WIN32
1443  encoding == PG_UTF8 ||
1444 #endif
1445  (encoding == PG_SQL_ASCII && superuser())))
1446  ereport(ERROR,
1447  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1448  errmsg("encoding \"%s\" does not match locale \"%s\"",
1450  ctype),
1451  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1452  pg_encoding_to_char(ctype_encoding))));
1453 
1454  if (!(collate_encoding == encoding ||
1455  collate_encoding == PG_SQL_ASCII ||
1456  collate_encoding == -1 ||
1457 #ifdef WIN32
1458  encoding == PG_UTF8 ||
1459 #endif
1460  (encoding == PG_SQL_ASCII && superuser())))
1461  ereport(ERROR,
1462  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1463  errmsg("encoding \"%s\" does not match locale \"%s\"",
1465  collate),
1466  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1467  pg_encoding_to_char(collate_encoding))));
1468 }
int errdetail(const char *fmt,...)
Definition: elog.c:1037
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:224
@ PG_UTF8
Definition: pg_wchar.h:230
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:451
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 674 of file dbcommands.c.

675 {
676  Oid src_dboid;
677  Oid src_owner;
678  int src_encoding = -1;
679  char *src_collate = NULL;
680  char *src_ctype = NULL;
681  char *src_iculocale = NULL;
682  char src_locprovider = '\0';
683  char *src_collversion = NULL;
684  bool src_istemplate;
685  bool src_allowconn;
686  TransactionId src_frozenxid = InvalidTransactionId;
687  MultiXactId src_minmxid = InvalidMultiXactId;
688  Oid src_deftablespace;
689  volatile Oid dst_deftablespace;
690  Relation pg_database_rel;
691  HeapTuple tuple;
692  Datum new_record[Natts_pg_database];
693  bool new_record_nulls[Natts_pg_database];
694  Oid dboid = InvalidOid;
695  Oid datdba;
696  ListCell *option;
697  DefElem *dtablespacename = NULL;
698  DefElem *downer = NULL;
699  DefElem *dtemplate = NULL;
700  DefElem *dencoding = NULL;
701  DefElem *dlocale = NULL;
702  DefElem *dcollate = NULL;
703  DefElem *dctype = NULL;
704  DefElem *diculocale = NULL;
705  DefElem *dlocprovider = NULL;
706  DefElem *distemplate = NULL;
707  DefElem *dallowconnections = NULL;
708  DefElem *dconnlimit = NULL;
709  DefElem *dcollversion = NULL;
710  DefElem *dstrategy = NULL;
711  char *dbname = stmt->dbname;
712  char *dbowner = NULL;
713  const char *dbtemplate = NULL;
714  char *dbcollate = NULL;
715  char *dbctype = NULL;
716  char *dbiculocale = NULL;
717  char 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, "locale_provider") == 0)
783  {
784  if (dlocprovider)
785  errorConflictingDefElem(defel, pstate);
786  dlocprovider = defel;
787  }
788  else if (strcmp(defel->defname, "is_template") == 0)
789  {
790  if (distemplate)
791  errorConflictingDefElem(defel, pstate);
792  distemplate = defel;
793  }
794  else if (strcmp(defel->defname, "allow_connections") == 0)
795  {
796  if (dallowconnections)
797  errorConflictingDefElem(defel, pstate);
798  dallowconnections = defel;
799  }
800  else if (strcmp(defel->defname, "connection_limit") == 0)
801  {
802  if (dconnlimit)
803  errorConflictingDefElem(defel, pstate);
804  dconnlimit = defel;
805  }
806  else if (strcmp(defel->defname, "collation_version") == 0)
807  {
808  if (dcollversion)
809  errorConflictingDefElem(defel, pstate);
810  dcollversion = defel;
811  }
812  else if (strcmp(defel->defname, "location") == 0)
813  {
815  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
816  errmsg("LOCATION is not supported anymore"),
817  errhint("Consider using tablespaces instead."),
818  parser_errposition(pstate, defel->location)));
819  }
820  else if (strcmp(defel->defname, "oid") == 0)
821  {
822  dboid = defGetInt32(defel);
823 
824  /*
825  * We don't normally permit new databases to be created with
826  * system-assigned OIDs. pg_upgrade tries to preserve database
827  * OIDs, so we can't allow any database to be created with an OID
828  * that might be in use in a freshly-initialized cluster created
829  * by some future version. We assume all such OIDs will be from
830  * the system-managed OID range.
831  *
832  * As an exception, however, we permit any OID to be assigned when
833  * allow_system_table_mods=on (so that initdb can assign system
834  * OIDs to template0 and postgres) or when performing a binary
835  * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
836  * in the source cluster).
837  */
838  if (dboid < FirstNormalObjectId &&
840  ereport(ERROR,
841  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
842  errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
843  }
844  else if (strcmp(defel->defname, "strategy") == 0)
845  {
846  if (dstrategy)
847  errorConflictingDefElem(defel, pstate);
848  dstrategy = defel;
849  }
850  else
851  ereport(ERROR,
852  (errcode(ERRCODE_SYNTAX_ERROR),
853  errmsg("option \"%s\" not recognized", defel->defname),
854  parser_errposition(pstate, defel->location)));
855  }
856 
857  if (downer && downer->arg)
858  dbowner = defGetString(downer);
859  if (dtemplate && dtemplate->arg)
860  dbtemplate = defGetString(dtemplate);
861  if (dencoding && dencoding->arg)
862  {
863  const char *encoding_name;
864 
865  if (IsA(dencoding->arg, Integer))
866  {
867  encoding = defGetInt32(dencoding);
868  encoding_name = pg_encoding_to_char(encoding);
869  if (strcmp(encoding_name, "") == 0 ||
870  pg_valid_server_encoding(encoding_name) < 0)
871  ereport(ERROR,
872  (errcode(ERRCODE_UNDEFINED_OBJECT),
873  errmsg("%d is not a valid encoding code",
874  encoding),
875  parser_errposition(pstate, dencoding->location)));
876  }
877  else
878  {
879  encoding_name = defGetString(dencoding);
880  encoding = pg_valid_server_encoding(encoding_name);
881  if (encoding < 0)
882  ereport(ERROR,
883  (errcode(ERRCODE_UNDEFINED_OBJECT),
884  errmsg("%s is not a valid encoding name",
885  encoding_name),
886  parser_errposition(pstate, dencoding->location)));
887  }
888  }
889  if (dlocale && dlocale->arg)
890  {
891  dbcollate = defGetString(dlocale);
892  dbctype = defGetString(dlocale);
893  }
894  if (dcollate && dcollate->arg)
895  dbcollate = defGetString(dcollate);
896  if (dctype && dctype->arg)
897  dbctype = defGetString(dctype);
898  if (diculocale && diculocale->arg)
899  dbiculocale = defGetString(diculocale);
900  if (dlocprovider && dlocprovider->arg)
901  {
902  char *locproviderstr = defGetString(dlocprovider);
903 
904  if (pg_strcasecmp(locproviderstr, "icu") == 0)
905  dblocprovider = COLLPROVIDER_ICU;
906  else if (pg_strcasecmp(locproviderstr, "libc") == 0)
907  dblocprovider = COLLPROVIDER_LIBC;
908  else
909  ereport(ERROR,
910  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
911  errmsg("unrecognized locale provider: %s",
912  locproviderstr)));
913  }
914  if (diculocale && dblocprovider != COLLPROVIDER_ICU)
915  ereport(ERROR,
916  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
917  errmsg("ICU locale cannot be specified unless locale provider is ICU")));
918  if (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)
919  {
920  if (dlocale && dlocale->arg)
921  dbiculocale = defGetString(dlocale);
922  }
923  if (distemplate && distemplate->arg)
924  dbistemplate = defGetBoolean(distemplate);
925  if (dallowconnections && dallowconnections->arg)
926  dballowconnections = defGetBoolean(dallowconnections);
927  if (dconnlimit && dconnlimit->arg)
928  {
929  dbconnlimit = defGetInt32(dconnlimit);
930  if (dbconnlimit < -1)
931  ereport(ERROR,
932  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
933  errmsg("invalid connection limit: %d", dbconnlimit)));
934  }
935  if (dcollversion)
936  dbcollversion = defGetString(dcollversion);
937 
938  /* obtain OID of proposed owner */
939  if (dbowner)
940  datdba = get_role_oid(dbowner, false);
941  else
942  datdba = GetUserId();
943 
944  /*
945  * To create a database, must have createdb privilege and must be able to
946  * become the target role (this does not imply that the target role itself
947  * must have createdb privilege). The latter provision guards against
948  * "giveaway" attacks. Note that a superuser will always have both of
949  * these privileges a fortiori.
950  */
952  ereport(ERROR,
953  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
954  errmsg("permission denied to create database")));
955 
957 
958  /*
959  * Lookup database (template) to be cloned, and obtain share lock on it.
960  * ShareLock allows two CREATE DATABASEs to work from the same template
961  * concurrently, while ensuring no one is busy dropping it in parallel
962  * (which would be Very Bad since we'd likely get an incomplete copy
963  * without knowing it). This also prevents any new connections from being
964  * made to the source until we finish copying it, so we can be sure it
965  * won't change underneath us.
966  */
967  if (!dbtemplate)
968  dbtemplate = "template1"; /* Default template database name */
969 
970  if (!get_db_info(dbtemplate, ShareLock,
971  &src_dboid, &src_owner, &src_encoding,
972  &src_istemplate, &src_allowconn,
973  &src_frozenxid, &src_minmxid, &src_deftablespace,
974  &src_collate, &src_ctype, &src_iculocale, &src_locprovider,
975  &src_collversion))
976  ereport(ERROR,
977  (errcode(ERRCODE_UNDEFINED_DATABASE),
978  errmsg("template database \"%s\" does not exist",
979  dbtemplate)));
980 
981  /*
982  * Permission check: to copy a DB that's not marked datistemplate, you
983  * must be superuser or the owner thereof.
984  */
985  if (!src_istemplate)
986  {
987  if (!pg_database_ownercheck(src_dboid, GetUserId()))
988  ereport(ERROR,
989  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
990  errmsg("permission denied to copy database \"%s\"",
991  dbtemplate)));
992  }
993 
994  /* Validate the database creation strategy. */
995  if (dstrategy && dstrategy->arg)
996  {
997  char *strategy;
998 
999  strategy = defGetString(dstrategy);
1000  if (strcmp(strategy, "wal_log") == 0)
1001  dbstrategy = CREATEDB_WAL_LOG;
1002  else if (strcmp(strategy, "file_copy") == 0)
1003  dbstrategy = CREATEDB_FILE_COPY;
1004  else
1005  ereport(ERROR,
1006  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1007  errmsg("invalid create database strategy %s", strategy),
1008  errhint("Valid strategies are \"wal_log\", and \"file_copy\".")));
1009  }
1010 
1011  /* If encoding or locales are defaulted, use source's setting */
1012  if (encoding < 0)
1013  encoding = src_encoding;
1014  if (dbcollate == NULL)
1015  dbcollate = src_collate;
1016  if (dbctype == NULL)
1017  dbctype = src_ctype;
1018  if (dbiculocale == NULL)
1019  dbiculocale = src_iculocale;
1020  if (dblocprovider == '\0')
1021  dblocprovider = src_locprovider;
1022 
1023  /* Some encodings are client only */
1025  ereport(ERROR,
1026  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1027  errmsg("invalid server encoding %d", encoding)));
1028 
1029  /* Check that the chosen locales are valid, and get canonical spellings */
1030  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
1031  ereport(ERROR,
1032  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1033  errmsg("invalid locale name: \"%s\"", dbcollate)));
1034  dbcollate = canonname;
1035  if (!check_locale(LC_CTYPE, dbctype, &canonname))
1036  ereport(ERROR,
1037  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1038  errmsg("invalid locale name: \"%s\"", dbctype)));
1039  dbctype = canonname;
1040 
1041  check_encoding_locale_matches(encoding, dbcollate, dbctype);
1042 
1043  if (dblocprovider == COLLPROVIDER_ICU)
1044  {
1045  /*
1046  * This would happen if template0 uses the libc provider but the new
1047  * database uses icu.
1048  */
1049  if (!dbiculocale)
1050  ereport(ERROR,
1051  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1052  errmsg("ICU locale must be specified")));
1053  }
1054 
1055  if (dblocprovider == COLLPROVIDER_ICU)
1056  check_icu_locale(dbiculocale);
1057 
1058  /*
1059  * Check that the new encoding and locale settings match the source
1060  * database. We insist on this because we simply copy the source data ---
1061  * any non-ASCII data would be wrongly encoded, and any indexes sorted
1062  * according to the source locale would be wrong.
1063  *
1064  * However, we assume that template0 doesn't contain any non-ASCII data
1065  * nor any indexes that depend on collation or ctype, so template0 can be
1066  * used as template for creating a database with any encoding or locale.
1067  */
1068  if (strcmp(dbtemplate, "template0") != 0)
1069  {
1070  if (encoding != src_encoding)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1073  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1075  pg_encoding_to_char(src_encoding)),
1076  errhint("Use the same encoding as in the template database, or use template0 as template.")));
1077 
1078  if (strcmp(dbcollate, src_collate) != 0)
1079  ereport(ERROR,
1080  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1081  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1082  dbcollate, src_collate),
1083  errhint("Use the same collation as in the template database, or use template0 as template.")));
1084 
1085  if (strcmp(dbctype, src_ctype) != 0)
1086  ereport(ERROR,
1087  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1088  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1089  dbctype, src_ctype),
1090  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1091 
1092  if (dblocprovider != src_locprovider)
1093  ereport(ERROR,
1094  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1095  errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1096  collprovider_name(dblocprovider), collprovider_name(src_locprovider)),
1097  errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1098 
1099  if (dblocprovider == COLLPROVIDER_ICU)
1100  {
1101  Assert(dbiculocale);
1102  Assert(src_iculocale);
1103  if (strcmp(dbiculocale, src_iculocale) != 0)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1106  errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1107  dbiculocale, src_iculocale),
1108  errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1109  }
1110  }
1111 
1112  /*
1113  * If we got a collation version for the template database, check that it
1114  * matches the actual OS collation version. Otherwise error; the user
1115  * needs to fix the template database first. Don't complain if a
1116  * collation version was specified explicitly as a statement option; that
1117  * is used by pg_upgrade to reproduce the old state exactly.
1118  *
1119  * (If the template database has no collation version, then either the
1120  * platform/provider does not support collation versioning, or it's
1121  * template0, for which we stipulate that it does not contain
1122  * collation-using objects.)
1123  */
1124  if (src_collversion && !dcollversion)
1125  {
1126  char *actual_versionstr;
1127 
1128  actual_versionstr = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1129  if (!actual_versionstr)
1130  ereport(ERROR,
1131  (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1132  dbtemplate)));
1133 
1134  if (strcmp(actual_versionstr, src_collversion) != 0)
1135  ereport(ERROR,
1136  (errmsg("template database \"%s\" has a collation version mismatch",
1137  dbtemplate),
1138  errdetail("The template database was created using collation version %s, "
1139  "but the operating system provides version %s.",
1140  src_collversion, actual_versionstr),
1141  errhint("Rebuild all objects in the template database that use the default collation and run "
1142  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1143  "or build PostgreSQL with the right library version.",
1144  quote_identifier(dbtemplate))));
1145  }
1146 
1147  if (dbcollversion == NULL)
1148  dbcollversion = src_collversion;
1149 
1150  /*
1151  * Normally, we copy the collation version from the template database.
1152  * This last resort only applies if the template database does not have a
1153  * collation version, which is normally only the case for template0.
1154  */
1155  if (dbcollversion == NULL)
1156  dbcollversion = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1157 
1158  /* Resolve default tablespace for new database */
1159  if (dtablespacename && dtablespacename->arg)
1160  {
1161  char *tablespacename;
1162  AclResult aclresult;
1163 
1164  tablespacename = defGetString(dtablespacename);
1165  dst_deftablespace = get_tablespace_oid(tablespacename, false);
1166  /* check permissions */
1167  aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
1168  ACL_CREATE);
1169  if (aclresult != ACLCHECK_OK)
1170  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1171  tablespacename);
1172 
1173  /* pg_global must never be the default tablespace */
1174  if (dst_deftablespace == GLOBALTABLESPACE_OID)
1175  ereport(ERROR,
1176  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1177  errmsg("pg_global cannot be used as default tablespace")));
1178 
1179  /*
1180  * If we are trying to change the default tablespace of the template,
1181  * we require that the template not have any files in the new default
1182  * tablespace. This is necessary because otherwise the copied
1183  * database would contain pg_class rows that refer to its default
1184  * tablespace both explicitly (by OID) and implicitly (as zero), which
1185  * would cause problems. For example another CREATE DATABASE using
1186  * the copied database as template, and trying to change its default
1187  * tablespace again, would yield outright incorrect results (it would
1188  * improperly move tables to the new default tablespace that should
1189  * stay in the same tablespace).
1190  */
1191  if (dst_deftablespace != src_deftablespace)
1192  {
1193  char *srcpath;
1194  struct stat st;
1195 
1196  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
1197 
1198  if (stat(srcpath, &st) == 0 &&
1199  S_ISDIR(st.st_mode) &&
1200  !directory_is_empty(srcpath))
1201  ereport(ERROR,
1202  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1203  errmsg("cannot assign new default tablespace \"%s\"",
1204  tablespacename),
1205  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1206  dbtemplate)));
1207  pfree(srcpath);
1208  }
1209  }
1210  else
1211  {
1212  /* Use template database's default tablespace */
1213  dst_deftablespace = src_deftablespace;
1214  /* Note there is no additional permission check in this path */
1215  }
1216 
1217  /*
1218  * If built with appropriate switch, whine when regression-testing
1219  * conventions for database names are violated. But don't complain during
1220  * initdb.
1221  */
1222 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1223  if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1224  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1225 #endif
1226 
1227  /*
1228  * Check for db name conflict. This is just to give a more friendly error
1229  * message than "unique index violation". There's a race condition but
1230  * we're willing to accept the less friendly message in that case.
1231  */
1232  if (OidIsValid(get_database_oid(dbname, true)))
1233  ereport(ERROR,
1234  (errcode(ERRCODE_DUPLICATE_DATABASE),
1235  errmsg("database \"%s\" already exists", dbname)));
1236 
1237  /*
1238  * The source DB can't have any active backends, except this one
1239  * (exception is to allow CREATE DB while connected to template1).
1240  * Otherwise we might copy inconsistent data.
1241  *
1242  * This should be last among the basic error checks, because it involves
1243  * potential waiting; we may as well throw an error first if we're gonna
1244  * throw one.
1245  */
1246  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
1247  ereport(ERROR,
1248  (errcode(ERRCODE_OBJECT_IN_USE),
1249  errmsg("source database \"%s\" is being accessed by other users",
1250  dbtemplate),
1251  errdetail_busy_db(notherbackends, npreparedxacts)));
1252 
1253  /*
1254  * Select an OID for the new database, checking that it doesn't have a
1255  * filename conflict with anything already existing in the tablespace
1256  * directories.
1257  */
1258  pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
1259 
1260  /*
1261  * If database OID is configured, check if the OID is already in use or
1262  * data directory already exists.
1263  */
1264  if (OidIsValid(dboid))
1265  {
1266  char *existing_dbname = get_database_name(dboid);
1267 
1268  if (existing_dbname != NULL)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1271  errmsg("database OID %u is already in use by database \"%s\"",
1272  dboid, existing_dbname));
1273 
1274  if (check_db_file_conflict(dboid))
1275  ereport(ERROR,
1276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1277  errmsg("data directory with the specified OID %u already exists", dboid));
1278  }
1279  else
1280  {
1281  /* Select an OID for the new database if is not explicitly configured. */
1282  do
1283  {
1284  dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
1285  Anum_pg_database_oid);
1286  } while (check_db_file_conflict(dboid));
1287  }
1288 
1289  /*
1290  * Insert a new tuple into pg_database. This establishes our ownership of
1291  * the new database name (anyone else trying to insert the same name will
1292  * block on the unique index, and fail after we commit).
1293  */
1294 
1295  Assert((dblocprovider == COLLPROVIDER_ICU && dbiculocale) ||
1296  (dblocprovider != COLLPROVIDER_ICU && !dbiculocale));
1297 
1298  /* Form tuple */
1299  MemSet(new_record, 0, sizeof(new_record));
1300  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1301 
1302  new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
1303  new_record[Anum_pg_database_datname - 1] =
1305  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
1306  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
1307  new_record[Anum_pg_database_datlocprovider - 1] = CharGetDatum(dblocprovider);
1308  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1309  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1310  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1311  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
1312  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
1313  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
1314  new_record[Anum_pg_database_datcollate - 1] = CStringGetTextDatum(dbcollate);
1315  new_record[Anum_pg_database_datctype - 1] = CStringGetTextDatum(dbctype);
1316  if (dbiculocale)
1317  new_record[Anum_pg_database_daticulocale - 1] = CStringGetTextDatum(dbiculocale);
1318  else
1319  new_record_nulls[Anum_pg_database_daticulocale - 1] = true;
1320  if (dbcollversion)
1321  new_record[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(dbcollversion);
1322  else
1323  new_record_nulls[Anum_pg_database_datcollversion - 1] = true;
1324 
1325  /*
1326  * We deliberately set datacl to default (NULL), rather than copying it
1327  * from the template database. Copying it would be a bad idea when the
1328  * owner is not the same as the template's owner.
1329  */
1330  new_record_nulls[Anum_pg_database_datacl - 1] = true;
1331 
1332  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
1333  new_record, new_record_nulls);
1334 
1335  CatalogTupleInsert(pg_database_rel, tuple);
1336 
1337  /*
1338  * Now generate additional catalog entries associated with the new DB
1339  */
1340 
1341  /* Register owner dependency */
1342  recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
1343 
1344  /* Create pg_shdepend entries for objects within database */
1345  copyTemplateDependencies(src_dboid, dboid);
1346 
1347  /* Post creation hook for new database */
1348  InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
1349 
1350  /*
1351  * If we're going to be reading data for the to-be-created database into
1352  * shared_buffers, take a lock on it. Nobody should know that this
1353  * database exists yet, but it's good to maintain the invariant that a
1354  * lock an AccessExclusiveLock on the database is sufficient to drop all
1355  * of its buffers without worrying about more being read later.
1356  *
1357  * Note that we need to do this before entering the
1358  * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1359  * expects this lock to be held already.
1360  */
1361  if (dbstrategy == CREATEDB_WAL_LOG)
1362  LockSharedObject(DatabaseRelationId, dboid, 0, AccessShareLock);
1363 
1364  /*
1365  * Once we start copying subdirectories, we need to be able to clean 'em
1366  * up if we fail. Use an ENSURE block to make sure this happens. (This
1367  * is not a 100% solution, because of the possibility of failure during
1368  * transaction commit after we leave this routine, but it should handle
1369  * most scenarios.)
1370  */
1371  fparms.src_dboid = src_dboid;
1372  fparms.dest_dboid = dboid;
1373  fparms.strategy = dbstrategy;
1374 
1376  PointerGetDatum(&fparms));
1377  {
1378  /*
1379  * If the user has asked to create a database with WAL_LOG strategy
1380  * then call CreateDatabaseUsingWalLog, which will copy the database
1381  * at the block level and it will WAL log each copied block.
1382  * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1383  * database file by file.
1384  */
1385  if (dbstrategy == CREATEDB_WAL_LOG)
1386  CreateDatabaseUsingWalLog(src_dboid, dboid, src_deftablespace,
1387  dst_deftablespace);
1388  else
1389  CreateDatabaseUsingFileCopy(src_dboid, dboid, src_deftablespace,
1390  dst_deftablespace);
1391 
1392  /*
1393  * Close pg_database, but keep lock till commit.
1394  */
1395  table_close(pg_database_rel, NoLock);
1396 
1397  /*
1398  * Force synchronous commit, thus minimizing the window between
1399  * creation of the database files and committal of the transaction. If
1400  * we crash before committing, we'll have a DB that's taking up disk
1401  * space but is not in pg_database, which is not good.
1402  */
1403  ForceSyncCommit();
1404  }
1406  PointerGetDatum(&fparms));
1407 
1408  return dboid;
1409 }
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5177
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5121
bool directory_is_empty(const char *path)
Definition: tablespace.c:899
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1474
TransactionId MultiXactId
Definition: c.h:597
uint32 TransactionId
Definition: c.h:587
#define OidIsValid(objectId)
Definition: c.h:710
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:391
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 *dbLocProvider, char **dbCollversion)
Definition: dbcommands.c:2611
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2994
CreateDBStrategy
Definition: dbcommands.c:81
@ CREATEDB_FILE_COPY
Definition: dbcommands.c:83
@ CREATEDB_WAL_LOG
Definition: dbcommands.c:82
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Definition: dbcommands.c:1434
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2917
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:2874
static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:554
static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:145
static void createdb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1472
int errhint(const char *fmt,...)
Definition: elog.c:1151
#define WARNING
Definition: elog.h:30
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
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:221
#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:1175
#define InvalidMultiXactId
Definition: multixact.h:24
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:171
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2176
#define ACL_CREATE
Definition: parsenodes.h:91
void check_icu_locale(const char *icu_locale)
Definition: pg_locale.c:1991
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:246
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
Definition: pg_shdepend.c:849
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:279
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define TransactionIdGetDatum(X)
Definition: postgres.h:565
#define CharGetDatum(X)
Definition: postgres.h:460
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:3719
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12163
List * options
Definition: parsenodes.h:3642
char * dbname
Definition: parsenodes.h:3641
Definition: value.h:29
CreateDBStrategy strategy
Definition: dbcommands.c:90
#define InvalidTransactionId
Definition: transam.h:31
#define FirstNormalObjectId
Definition: transam.h:197
#define stat
Definition: win32_port.h:283
#define S_ISDIR(m)
Definition: win32_port.h:324
void ForceSyncCommit(void)
Definition: xact.c:1124

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, DefElem::arg, Assert(), BoolGetDatum, CatalogTupleInsert(), CharGetDatum, check_db_file_conflict(), check_encoding_locale_matches(), check_icu_locale(), check_is_member_of_role(), check_locale(), copyTemplateDependencies(), CountOtherDBBackends(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb_failure_callback(), CREATEDB_FILE_COPY, CREATEDB_WAL_LOG, CStringGetDatum, CStringGetTextDatum, dbname, CreatedbStmt::dbname, defGetBoolean(), defGetInt32(), 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(), Int32GetDatum, InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), MemSet, namein(), NoLock, OBJECT_TABLESPACE, ObjectIdGetDatum, OidIsValid, CreatedbStmt::options, parser_errposition(), pfree(), pg_database_ownercheck(), pg_encoding_to_char(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_strcasecmp(), pg_tablespace_aclcheck(), 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, 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 2155 of file dbcommands.c.

2156 {
2157  bool force = false;
2158  ListCell *lc;
2159 
2160  foreach(lc, stmt->options)
2161  {
2162  DefElem *opt = (DefElem *) lfirst(lc);
2163 
2164  if (strcmp(opt->defname, "force") == 0)
2165  force = true;
2166  else
2167  ereport(ERROR,
2168  (errcode(ERRCODE_SYNTAX_ERROR),
2169  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2170  parser_errposition(pstate, opt->location)));
2171  }
2172 
2173  dropdb(stmt->dbname, stmt->missing_ok, force);
2174 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1511
List * options
Definition: parsenodes.h:3678
char * dbname
Definition: parsenodes.h:3676
bool missing_ok
Definition: parsenodes.h:3677

References DropdbStmt::dbname, DefElem::defname, dropdb(), ereport, errcode(), errmsg(), ERROR, lfirst, DefElem::location, DropdbStmt::missing_ok, DropdbStmt::options, and parser_errposition().

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1511 of file dbcommands.c.

1512 {
1513  Oid db_id;
1514  bool db_istemplate;
1515  Relation pgdbrel;
1516  HeapTuple tup;
1517  int notherbackends;
1518  int npreparedxacts;
1519  int nslots,
1520  nslots_active;
1521  int nsubscriptions;
1522 
1523  /*
1524  * Look up the target database's OID, and get exclusive lock on it. We
1525  * need this to ensure that no new backend starts up in the target
1526  * database while we are deleting it (see postinit.c), and that no one is
1527  * using it as a CREATE DATABASE template or trying to delete it for
1528  * themselves.
1529  */
1530  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1531 
1532  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1533  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1534  {
1535  if (!missing_ok)
1536  {
1537  ereport(ERROR,
1538  (errcode(ERRCODE_UNDEFINED_DATABASE),
1539  errmsg("database \"%s\" does not exist", dbname)));
1540  }
1541  else
1542  {
1543  /* Close pg_database, release the lock, since we changed nothing */
1544  table_close(pgdbrel, RowExclusiveLock);
1545  ereport(NOTICE,
1546  (errmsg("database \"%s\" does not exist, skipping",
1547  dbname)));
1548  return;
1549  }
1550  }
1551 
1552  /*
1553  * Permission checks
1554  */
1555  if (!pg_database_ownercheck(db_id, GetUserId()))
1557  dbname);
1558 
1559  /* DROP hook for the database being removed */
1560  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1561 
1562  /*
1563  * Disallow dropping a DB that is marked istemplate. This is just to
1564  * prevent people from accidentally dropping template0 or template1; they
1565  * can do so if they're really determined ...
1566  */
1567  if (db_istemplate)
1568  ereport(ERROR,
1569  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1570  errmsg("cannot drop a template database")));
1571 
1572  /* Obviously can't drop my own database */
1573  if (db_id == MyDatabaseId)
1574  ereport(ERROR,
1575  (errcode(ERRCODE_OBJECT_IN_USE),
1576  errmsg("cannot drop the currently open database")));
1577 
1578  /*
1579  * Check whether there are active logical slots that refer to the
1580  * to-be-dropped database. The database lock we are holding prevents the
1581  * creation of new slots using the database or existing slots becoming
1582  * active.
1583  */
1584  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1585  if (nslots_active)
1586  {
1587  ereport(ERROR,
1588  (errcode(ERRCODE_OBJECT_IN_USE),
1589  errmsg("database \"%s\" is used by an active logical replication slot",
1590  dbname),
1591  errdetail_plural("There is %d active slot.",
1592  "There are %d active slots.",
1593  nslots_active, nslots_active)));
1594  }
1595 
1596  /*
1597  * Check if there are subscriptions defined in the target database.
1598  *
1599  * We can't drop them automatically because they might be holding
1600  * resources in other databases/instances.
1601  */
1602  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1603  ereport(ERROR,
1604  (errcode(ERRCODE_OBJECT_IN_USE),
1605  errmsg("database \"%s\" is being used by logical replication subscription",
1606  dbname),
1607  errdetail_plural("There is %d subscription.",
1608  "There are %d subscriptions.",
1609  nsubscriptions, nsubscriptions)));
1610 
1611 
1612  /*
1613  * Attempt to terminate all existing connections to the target database if
1614  * the user has requested to do so.
1615  */
1616  if (force)
1617  TerminateOtherDBBackends(db_id);
1618 
1619  /*
1620  * Check for other backends in the target database. (Because we hold the
1621  * database lock, no new ones can start after this.)
1622  *
1623  * As in CREATE DATABASE, check this after other error conditions.
1624  */
1625  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1626  ereport(ERROR,
1627  (errcode(ERRCODE_OBJECT_IN_USE),
1628  errmsg("database \"%s\" is being accessed by other users",
1629  dbname),
1630  errdetail_busy_db(notherbackends, npreparedxacts)));
1631 
1632  /*
1633  * Remove the database's tuple from pg_database.
1634  */
1636  if (!HeapTupleIsValid(tup))
1637  elog(ERROR, "cache lookup failed for database %u", db_id);
1638 
1639  CatalogTupleDelete(pgdbrel, &tup->t_self);
1640 
1641  ReleaseSysCache(tup);
1642 
1643  /*
1644  * Delete any comments or security labels associated with the database.
1645  */
1646  DeleteSharedComments(db_id, DatabaseRelationId);
1647  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1648 
1649  /*
1650  * Remove settings associated with this database
1651  */
1652  DropSetting(db_id, InvalidOid);
1653 
1654  /*
1655  * Remove shared dependency references for the database.
1656  */
1657  dropDatabaseDependencies(db_id);
1658 
1659  /*
1660  * Drop db-specific replication slots.
1661  */
1663 
1664  /*
1665  * Drop pages for this database that are in the shared buffer cache. This
1666  * is important to ensure that no remaining backend tries to write out a
1667  * dirty buffer to the dead database later...
1668  */
1669  DropDatabaseBuffers(db_id);
1670 
1671  /*
1672  * Tell the cumulative stats system to forget it immediately, too.
1673  */
1674  pgstat_drop_database(db_id);
1675 
1676  /*
1677  * Tell checkpointer to forget any pending fsync and unlink requests for
1678  * files in the database; else the fsyncs will fail at next checkpoint, or
1679  * worse, it will delete files that belong to a newly created database
1680  * with the same OID.
1681  */
1683 
1684  /*
1685  * Force a checkpoint to make sure the checkpointer has received the
1686  * message sent by ForgetDatabaseSyncRequests.
1687  */
1689 
1690  /* Close all smgr fds in all backends. */
1692 
1693  /*
1694  * Remove all tablespace subdirs belonging to the database.
1695  */
1696  remove_dbtablespaces(db_id);
1697 
1698  /*
1699  * Close pg_database, but keep lock till commit.
1700  */
1701  table_close(pgdbrel, NoLock);
1702 
1703  /*
1704  * Force synchronous commit, thus minimizing the window between removal of
1705  * the database files and committal of the transaction. If we crash before
1706  * committing, we'll have a DB that's gone on disk but still there
1707  * according to pg_database, which is not good.
1708  */
1709  ForceSyncCommit();
1710 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3404
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:2784
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1129
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#define AccessExclusiveLock
Definition: lockdefs.h:43
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1039
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:180
void DropSetting(Oid databaseid, Oid roleid)
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:953
int CountDBSubscriptions(Oid dbid)
void pgstat_drop_database(Oid databaseid)
void TerminateOtherDBBackends(Oid databaseId)
Definition: procarray.c:3797
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:392
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:332
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:52
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:982
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1038
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ 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, ObjectIdGetDatum, pg_database_ownercheck(), 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 2994 of file dbcommands.c.

2995 {
2996  HeapTuple dbtuple;
2997  char *result;
2998 
2999  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3000  if (HeapTupleIsValid(dbtuple))
3001  {
3002  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3003  ReleaseSysCache(dbtuple);
3004  }
3005  else
3006  result = NULL;
3007 
3008  return result;
3009 }
#define NameStr(name)
Definition: c.h:681
char * pstrdup(const char *in)
Definition: mcxt.c:1305
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(), lazy_check_wraparound_failsafe(), 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 2947 of file dbcommands.c.

2948 {
2949  Relation pg_database;
2950  ScanKeyData entry[1];
2951  SysScanDesc scan;
2952  HeapTuple dbtuple;
2953  Oid oid;
2954 
2955  /*
2956  * There's no syscache for pg_database indexed by name, so we must look
2957  * the hard way.
2958  */
2959  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2960  ScanKeyInit(&entry[0],
2961  Anum_pg_database_datname,
2962  BTEqualStrategyNumber, F_NAMEEQ,
2964  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2965  NULL, 1, entry);
2966 
2967  dbtuple = systable_getnext(scan);
2968 
2969  /* We assume that there can be at most one matching tuple */
2970  if (HeapTupleIsValid(dbtuple))
2971  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2972  else
2973  oid = InvalidOid;
2974 
2975  systable_endscan(scan);
2976  table_close(pg_database, AccessShareLock);
2977 
2978  if (!OidIsValid(oid) && !missing_ok)
2979  ereport(ERROR,
2980  (errcode(ERRCODE_UNDEFINED_DATABASE),
2981  errmsg("database \"%s\" does not exist",
2982  dbname)));
2983 
2984  return oid;
2985 }

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

◆ RenameDatabase()

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

Definition at line 1717 of file dbcommands.c.

1718 {
1719  Oid db_id;
1720  HeapTuple newtup;
1721  Relation rel;
1722  int notherbackends;
1723  int npreparedxacts;
1724  ObjectAddress address;
1725 
1726  /*
1727  * Look up the target database's OID, and get exclusive lock on it. We
1728  * need this for the same reasons as DROP DATABASE.
1729  */
1730  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1731 
1732  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1733  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1734  ereport(ERROR,
1735  (errcode(ERRCODE_UNDEFINED_DATABASE),
1736  errmsg("database \"%s\" does not exist", oldname)));
1737 
1738  /* must be owner */
1739  if (!pg_database_ownercheck(db_id, GetUserId()))
1741  oldname);
1742 
1743  /* must have createdb rights */
1744  if (!have_createdb_privilege())
1745  ereport(ERROR,
1746  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1747  errmsg("permission denied to rename database")));
1748 
1749  /*
1750  * If built with appropriate switch, whine when regression-testing
1751  * conventions for database names are violated.
1752  */
1753 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1754  if (strstr(newname, "regression") == NULL)
1755  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1756 #endif
1757 
1758  /*
1759  * Make sure the new name doesn't exist. See notes for same error in
1760  * CREATE DATABASE.
1761  */
1762  if (OidIsValid(get_database_oid(newname, true)))
1763  ereport(ERROR,
1764  (errcode(ERRCODE_DUPLICATE_DATABASE),
1765  errmsg("database \"%s\" already exists", newname)));
1766 
1767  /*
1768  * XXX Client applications probably store the current database somewhere,
1769  * so renaming it could cause confusion. On the other hand, there may not
1770  * be an actual problem besides a little confusion, so think about this
1771  * and decide.
1772  */
1773  if (db_id == MyDatabaseId)
1774  ereport(ERROR,
1775  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1776  errmsg("current database cannot be renamed")));
1777 
1778  /*
1779  * Make sure the database does not have active sessions. This is the same
1780  * concern as above, but applied to other sessions.
1781  *
1782  * As in CREATE DATABASE, check this after other error conditions.
1783  */
1784  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1785  ereport(ERROR,
1786  (errcode(ERRCODE_OBJECT_IN_USE),
1787  errmsg("database \"%s\" is being accessed by other users",
1788  oldname),
1789  errdetail_busy_db(notherbackends, npreparedxacts)));
1790 
1791  /* rename */
1793  if (!HeapTupleIsValid(newtup))
1794  elog(ERROR, "cache lookup failed for database %u", db_id);
1795  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1796  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1797 
1798  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1799 
1800  ObjectAddressSet(address, DatabaseRelationId, db_id);
1801 
1802  /*
1803  * Close pg_database, but keep lock till commit.
1804  */
1805  table_close(rel, NoLock);
1806 
1807  return address;
1808 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179

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, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, pg_database_ownercheck(), RowExclusiveLock, SearchSysCacheCopy1, HeapTupleData::t_self, table_close(), table_open(), and WARNING.

Referenced by ExecRenameStmt().