PostgreSQL Source Code  git master
dbcommands.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_database.h"
#include "catalog/pg_db_role_setting.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_tablespace.h"
#include "commands/comment.h"
#include "commands/dbcommands.h"
#include "commands/dbcommands_xlog.h"
#include "commands/defrem.h"
#include "commands/seclabel.h"
#include "commands/tablespace.h"
#include "common/file_perm.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgwriter.h"
#include "replication/slot.h"
#include "storage/copydir.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/md.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/pg_locale.h"
#include "utils/relmapper.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for dbcommands.c:

Go to the source code of this file.

Data Structures

struct  createdb_failure_params
 
struct  movedb_failure_params
 
struct  CreateDBRelInfo
 

Typedefs

typedef enum CreateDBStrategy CreateDBStrategy
 
typedef struct CreateDBRelInfo CreateDBRelInfo
 

Enumerations

enum  CreateDBStrategy { CREATEDB_WAL_LOG , CREATEDB_FILE_COPY }
 

Functions

static void createdb_failure_callback (int code, Datum arg)
 
static void movedb (const char *dbname, const char *tblspcname)
 
static void movedb_failure_callback (int code, Datum arg)
 
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)
 
static void remove_dbtablespaces (Oid db_id)
 
static bool check_db_file_conflict (Oid db_id)
 
static int errdetail_busy_db (int notherbackends, int npreparedxacts)
 
static void CreateDatabaseUsingWalLog (Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
 
static ListScanSourceDatabasePgClass (Oid tbid, Oid dbid, char *srcpath)
 
static ListScanSourceDatabasePgClassPage (Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
 
static CreateDBRelInfoScanSourceDatabasePgClassTuple (HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
 
static void CreateDirAndVersionFile (char *dbpath, Oid dbid, Oid tsid, bool isRedo)
 
static void CreateDatabaseUsingFileCopy (Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
 
static void recovery_create_dbdir (char *path, bool only_tblspc)
 
Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 
void dropdb (const char *dbname, bool missing_ok, bool force)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterDatabaseRefreshColl (AlterDatabaseRefreshCollStmt *stmt)
 
Oid AlterDatabaseSet (AlterDatabaseSetStmt *stmt)
 
ObjectAddress AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
Datum pg_database_collation_actual_version (PG_FUNCTION_ARGS)
 
bool have_createdb_privilege (void)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
bool database_is_invalid_form (Form_pg_database datform)
 
bool database_is_invalid_oid (Oid dboid)
 
void dbase_redo (XLogReaderState *record)
 

Typedef Documentation

◆ CreateDBRelInfo

◆ CreateDBStrategy

Enumeration Type Documentation

◆ CreateDBStrategy

Enumerator
CREATEDB_WAL_LOG 
CREATEDB_FILE_COPY 

Definition at line 83 of file dbcommands.c.

84 {
CreateDBStrategy
Definition: dbcommands.c:84
@ CREATEDB_FILE_COPY
Definition: dbcommands.c:86
@ CREATEDB_WAL_LOG
Definition: dbcommands.c:85

Function Documentation

◆ AlterDatabase()

Oid AlterDatabase ( ParseState pstate,
AlterDatabaseStmt stmt,
bool  isTopLevel 
)

Definition at line 2265 of file dbcommands.c.

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

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), database_is_invalid_form(), DATCONNLIMIT_UNLIMITED, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), FATAL, GETSTRUCT, GetUserId(), heap_modify_tuple(), HeapTupleIsValid, Int32GetDatum(), InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), DefElem::location, movedb(), MyDatabaseId, NoLock, OBJECT_DATABASE, object_ownercheck(), parser_errposition(), PreventInTransactionBlock(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), stmt, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2545 of file dbcommands.c.

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

References aclcheck_error(), ACLCHECK_NOT_OWNER, aclnewowner(), BTEqualStrategyNumber, CatalogTupleUpdate(), changeDependencyOnOwner(), check_can_set_role(), CStringGetDatum(), DatumGetAclP, dbname, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, GetUserId(), have_createdb_privilege(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, OBJECT_DATABASE, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), PointerGetDatum(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)

Definition at line 2436 of file dbcommands.c.

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

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), CStringGetTextDatum, elog(), ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), GETSTRUCT, GetUserId(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, NOTICE, OBJECT_DATABASE, object_ownercheck(), ObjectAddressSet, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), stmt, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, and values.

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2519 of file dbcommands.c.

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

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), get_database_oid(), GetUserId(), InvalidOid, OBJECT_DATABASE, object_ownercheck(), shdepLockAndCheckObject(), stmt, and UnlockSharedObject().

Referenced by standard_ProcessUtility().

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 2964 of file dbcommands.c.

2965 {
2966  bool result = false;
2967  Relation rel;
2968  TableScanDesc scan;
2969  HeapTuple tuple;
2970 
2971  rel = table_open(TableSpaceRelationId, AccessShareLock);
2972  scan = table_beginscan_catalog(rel, 0, NULL);
2973  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2974  {
2975  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2976  Oid dsttablespace = spcform->oid;
2977  char *dstpath;
2978  struct stat st;
2979 
2980  /* Don't mess with the global tablespace */
2981  if (dsttablespace == GLOBALTABLESPACE_OID)
2982  continue;
2983 
2984  dstpath = GetDatabasePath(db_id, dsttablespace);
2985 
2986  if (lstat(dstpath, &st) == 0)
2987  {
2988  /* Found a conflicting file (or directory, whatever) */
2989  pfree(dstpath);
2990  result = true;
2991  break;
2992  }
2993 
2994  pfree(dstpath);
2995  }
2996 
2997  table_endscan(scan);
2999 
3000  return result;
3001 }
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1086
void pfree(void *pointer)
Definition: mcxt.c:1456
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
#define lstat(path, sb)
Definition: win32_port.h:285

References AccessShareLock, dstpath, ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), lstat, pfree(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by createdb().

◆ check_encoding_locale_matches()

void check_encoding_locale_matches ( int  encoding,
const char *  collate,
const char *  ctype 
)

Definition at line 1506 of file dbcommands.c.

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

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

Referenced by createdb(), and DefineCollation().

◆ CreateDatabaseUsingFileCopy()

static void CreateDatabaseUsingFileCopy ( Oid  src_dboid,
Oid  dst_dboid,
Oid  src_tsid,
Oid  dst_tsid 
)
static

Definition at line 551 of file dbcommands.c.

553 {
554  TableScanDesc scan;
555  Relation rel;
556  HeapTuple tuple;
557 
558  /*
559  * Force a checkpoint before starting the copy. This will force all dirty
560  * buffers, including those of unlogged tables, out to disk, to ensure
561  * source database is up-to-date on disk for the copy.
562  * FlushDatabaseBuffers() would suffice for that, but we also want to
563  * process any pending unlink requests. Otherwise, if a checkpoint
564  * happened while we're copying files, a file might be deleted just when
565  * we're about to copy it, causing the lstat() call in copydir() to fail
566  * with ENOENT.
567  */
570 
571  /*
572  * Iterate through all tablespaces of the template database, and copy each
573  * one to the new database.
574  */
575  rel = table_open(TableSpaceRelationId, AccessShareLock);
576  scan = table_beginscan_catalog(rel, 0, NULL);
577  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
578  {
579  Form_pg_tablespace spaceform = (Form_pg_tablespace) GETSTRUCT(tuple);
580  Oid srctablespace = spaceform->oid;
581  Oid dsttablespace;
582  char *srcpath;
583  char *dstpath;
584  struct stat st;
585 
586  /* No need to copy global tablespace */
587  if (srctablespace == GLOBALTABLESPACE_OID)
588  continue;
589 
590  srcpath = GetDatabasePath(src_dboid, srctablespace);
591 
592  if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
593  directory_is_empty(srcpath))
594  {
595  /* Assume we can ignore it */
596  pfree(srcpath);
597  continue;
598  }
599 
600  if (srctablespace == src_tsid)
601  dsttablespace = dst_tsid;
602  else
603  dsttablespace = srctablespace;
604 
605  dstpath = GetDatabasePath(dst_dboid, dsttablespace);
606 
607  /*
608  * Copy this subdirectory to the new location
609  *
610  * We don't need to copy subdirectories
611  */
612  copydir(srcpath, dstpath, false);
613 
614  /* Record the filesystem change in XLOG */
615  {
617 
618  xlrec.db_id = dst_dboid;
619  xlrec.tablespace_id = dsttablespace;
620  xlrec.src_db_id = src_dboid;
621  xlrec.src_tablespace_id = srctablespace;
622 
623  XLogBeginInsert();
624  XLogRegisterData((char *) &xlrec,
626 
627  (void) XLogInsert(RM_DBASE_ID,
629  }
630  pfree(srcpath);
631  pfree(dstpath);
632  }
633  table_endscan(scan);
635 
636  /*
637  * We force a checkpoint before committing. This effectively means that
638  * committed XLOG_DBASE_CREATE_FILE_COPY operations will never need to be
639  * replayed (at least not in ordinary crash recovery; we still have to
640  * make the XLOG entry for the benefit of PITR operations). This avoids
641  * two nasty scenarios:
642  *
643  * #1: When PITR is off, we don't XLOG the contents of newly created
644  * indexes; therefore the drop-and-recreate-whole-directory behavior of
645  * DBASE_CREATE replay would lose such indexes.
646  *
647  * #2: Since we have to recopy the source database during DBASE_CREATE
648  * replay, we run the risk of copying changes in it that were committed
649  * after the original CREATE DATABASE command but before the system crash
650  * that led to the replay. This is at least unexpected and at worst could
651  * lead to inconsistencies, eg duplicate table names.
652  *
653  * (Both of these were real bugs in releases 8.0 through 8.0.3.)
654  *
655  * In PITR replay, the first of these isn't an issue, and the second is
656  * only a risk if the CREATE DATABASE and subsequent template database
657  * change both occur while a base backup is being taken. There doesn't
658  * seem to be much we can do about that except document it as a
659  * limitation.
660  *
661  * See CreateDatabaseUsingWalLog() for a less cheesy CREATE DATABASE
662  * strategy that avoids these problems.
663  */
665 }
bool directory_is_empty(const char *path)
Definition: tablespace.c:859
void RequestCheckpoint(int flags)
Definition: checkpointer.c:930
void copydir(const char *fromdir, const char *todir, bool recurse)
Definition: copydir.c:37
#define XLOG_DBASE_CREATE_FILE_COPY
#define stat
Definition: win32_port.h:284
#define S_ISDIR(m)
Definition: win32_port.h:325
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:138
#define CHECKPOINT_FORCE
Definition: xlog.h:137
#define CHECKPOINT_WAIT
Definition: xlog.h:140
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:136
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:461
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:82

References AccessShareLock, CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, copydir(), xl_dbase_create_file_copy_rec::db_id, directory_is_empty(), dstpath, ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), pfree(), RequestCheckpoint(), S_ISDIR, xl_dbase_create_file_copy_rec::src_db_id, xl_dbase_create_file_copy_rec::src_tablespace_id, stat::st_mode, stat, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), xl_dbase_create_file_copy_rec::tablespace_id, XLOG_DBASE_CREATE_FILE_COPY, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by createdb().

◆ CreateDatabaseUsingWalLog()

static void CreateDatabaseUsingWalLog ( Oid  src_dboid,
Oid  dst_dboid,
Oid  src_tsid,
Oid  dst_tsid 
)
static

Definition at line 149 of file dbcommands.c.

151 {
152  char *srcpath;
153  char *dstpath;
154  List *rlocatorlist = NULL;
155  ListCell *cell;
156  LockRelId srcrelid;
157  LockRelId dstrelid;
158  RelFileLocator srcrlocator;
159  RelFileLocator dstrlocator;
160  CreateDBRelInfo *relinfo;
161 
162  /* Get source and destination database paths. */
163  srcpath = GetDatabasePath(src_dboid, src_tsid);
164  dstpath = GetDatabasePath(dst_dboid, dst_tsid);
165 
166  /* Create database directory and write PG_VERSION file. */
167  CreateDirAndVersionFile(dstpath, dst_dboid, dst_tsid, false);
168 
169  /* Copy relmap file from source database to the destination database. */
170  RelationMapCopy(dst_dboid, dst_tsid, srcpath, dstpath);
171 
172  /* Get list of relfilelocators to copy from the source database. */
173  rlocatorlist = ScanSourceDatabasePgClass(src_tsid, src_dboid, srcpath);
174  Assert(rlocatorlist != NIL);
175 
176  /*
177  * Database IDs will be the same for all relations so set them before
178  * entering the loop.
179  */
180  srcrelid.dbId = src_dboid;
181  dstrelid.dbId = dst_dboid;
182 
183  /* Loop over our list of relfilelocators and copy each one. */
184  foreach(cell, rlocatorlist)
185  {
186  relinfo = lfirst(cell);
187  srcrlocator = relinfo->rlocator;
188 
189  /*
190  * If the relation is from the source db's default tablespace then we
191  * need to create it in the destination db's default tablespace.
192  * Otherwise, we need to create in the same tablespace as it is in the
193  * source database.
194  */
195  if (srcrlocator.spcOid == src_tsid)
196  dstrlocator.spcOid = dst_tsid;
197  else
198  dstrlocator.spcOid = srcrlocator.spcOid;
199 
200  dstrlocator.dbOid = dst_dboid;
201  dstrlocator.relNumber = srcrlocator.relNumber;
202 
203  /*
204  * Acquire locks on source and target relations before copying.
205  *
206  * We typically do not read relation data into shared_buffers without
207  * holding a relation lock. It's unclear what could go wrong if we
208  * skipped it in this case, because nobody can be modifying either the
209  * source or destination database at this point, and we have locks on
210  * both databases, too, but let's take the conservative route.
211  */
212  dstrelid.relId = srcrelid.relId = relinfo->reloid;
213  LockRelationId(&srcrelid, AccessShareLock);
214  LockRelationId(&dstrelid, AccessShareLock);
215 
216  /* Copy relation storage from source to the destination. */
217  CreateAndCopyRelationData(srcrlocator, dstrlocator, relinfo->permanent);
218 
219  /* Release the relation locks. */
220  UnlockRelationId(&srcrelid, AccessShareLock);
221  UnlockRelationId(&dstrelid, AccessShareLock);
222  }
223 
224  pfree(srcpath);
225  pfree(dstpath);
226  list_free_deep(rlocatorlist);
227 }
void CreateAndCopyRelationData(RelFileLocator src_rlocator, RelFileLocator dst_rlocator, bool permanent)
Definition: bufmgr.c:4348
static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
Definition: dbcommands.c:457
static List * ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath)
Definition: dbcommands.c:251
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_free_deep(List *list)
Definition: list.c:1559
void UnlockRelationId(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:213
void LockRelationId(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:185
#define NIL
Definition: pg_list.h:68
void RelationMapCopy(Oid dbid, Oid tsid, char *srcdbpath, char *dstdbpath)
Definition: relmapper.c:293
RelFileLocator rlocator
Definition: dbcommands.c:107
Definition: pg_list.h:54
Definition: rel.h:39
Oid relId
Definition: rel.h:40
Oid dbId
Definition: rel.h:41
RelFileNumber relNumber

References AccessShareLock, Assert(), CreateAndCopyRelationData(), CreateDirAndVersionFile(), LockRelId::dbId, RelFileLocator::dbOid, dstpath, GetDatabasePath(), lfirst, list_free_deep(), LockRelationId(), NIL, CreateDBRelInfo::permanent, pfree(), RelationMapCopy(), LockRelId::relId, RelFileLocator::relNumber, CreateDBRelInfo::reloid, CreateDBRelInfo::rlocator, ScanSourceDatabasePgClass(), RelFileLocator::spcOid, and UnlockRelationId().

Referenced by createdb().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 671 of file dbcommands.c.

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

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, DefElem::arg, Assert(), BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_can_set_role(), check_db_file_conflict(), check_encoding_locale_matches(), check_locale(), copyTemplateDependencies(), CountOtherDBBackends(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb_failure_callback(), CREATEDB_FILE_COPY, CREATEDB_WAL_LOG, CStringGetDatum(), CStringGetTextDatum, database_is_invalid_oid(), DATCONNLIMIT_UNLIMITED, dbname, defGetBoolean(), defGetInt32(), defGetObjectId(), defGetString(), DefElem::defname, createdb_failure_params::dest_dboid, DirectFunctionCall1, directory_is_empty(), elog(), encoding, ereport, errcode(), errdetail(), errdetail_busy_db(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), FirstNormalObjectId, ForceSyncCommit(), get_collation_actual_version(), get_database_name(), get_database_oid(), get_db_info(), get_role_oid(), get_tablespace_oid(), GetDatabasePath(), GetNewOidWithIndex(), GetUserId(), have_createdb_privilege(), heap_form_tuple(), icu_language_tag(), icu_validate_locale(), icu_validation_level, Int32GetDatum(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, is_encoding_supported_by_icu(), IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), namein(), NoLock, NOTICE, object_aclcheck(), object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, parser_errposition(), pfree(), pg_encoding_to_char(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_strcasecmp(), PG_VALID_BE_ENCODING, pg_valid_server_encoding(), PointerGetDatum(), quote_identifier(), recordDependencyOnOwner(), RelationGetDescr, RowExclusiveLock, S_ISDIR, ShareLock, createdb_failure_params::src_dboid, stat::st_mode, stat, stmt, createdb_failure_params::strategy, table_close(), table_open(), TransactionIdGetDatum(), and WARNING.

Referenced by CreateRole(), main(), and standard_ProcessUtility().

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1544 of file dbcommands.c.

1545 {
1547 
1548  /*
1549  * If we were copying database at block levels then drop pages for the
1550  * destination database that are in the shared buffer cache. And tell
1551  * checkpointer to forget any pending fsync and unlink requests for files
1552  * in the database. The reasoning behind doing this is same as explained
1553  * in dropdb function. But unlike dropdb we don't need to call
1554  * pgstat_drop_database because this database is still not created so
1555  * there should not be any stat for this.
1556  */
1557  if (fparms->strategy == CREATEDB_WAL_LOG)
1558  {
1561 
1562  /* Release lock on the target database. */
1563  UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1564  AccessShareLock);
1565  }
1566 
1567  /*
1568  * Release lock on source database before doing recursive remove. This is
1569  * not essential but it seems desirable to release the lock as soon as
1570  * possible.
1571  */
1572  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1573 
1574  /* Throw away any successfully copied subdirectories */
1576 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3952
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2874
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1234
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312

References AccessShareLock, arg, CREATEDB_WAL_LOG, DatumGetPointer(), createdb_failure_params::dest_dboid, DropDatabaseBuffers(), ForgetDatabaseSyncRequests(), remove_dbtablespaces(), ShareLock, createdb_failure_params::src_dboid, createdb_failure_params::strategy, and UnlockSharedObject().

Referenced by createdb().

◆ CreateDirAndVersionFile()

static void CreateDirAndVersionFile ( char *  dbpath,
Oid  dbid,
Oid  tsid,
bool  isRedo 
)
static

Definition at line 457 of file dbcommands.c.

458 {
459  int fd;
460  int nbytes;
461  char versionfile[MAXPGPATH];
462  char buf[16];
463 
464  /*
465  * Prepare version data before starting a critical section.
466  *
467  * Note that we don't have to copy this from the source database; there's
468  * only one legal value.
469  */
470  sprintf(buf, "%s\n", PG_MAJORVERSION);
471  nbytes = strlen(PG_MAJORVERSION) + 1;
472 
473  /* If we are not in WAL replay then write the WAL. */
474  if (!isRedo)
475  {
477  XLogRecPtr lsn;
478 
480 
481  xlrec.db_id = dbid;
482  xlrec.tablespace_id = tsid;
483 
484  XLogBeginInsert();
485  XLogRegisterData((char *) (&xlrec),
487 
488  lsn = XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
489 
490  /* As always, WAL must hit the disk before the data update does. */
491  XLogFlush(lsn);
492  }
493 
494  /* Create database directory. */
495  if (MakePGDirectory(dbpath) < 0)
496  {
497  /* Failure other than already exists or not in WAL replay? */
498  if (errno != EEXIST || !isRedo)
499  ereport(ERROR,
501  errmsg("could not create directory \"%s\": %m", dbpath)));
502  }
503 
504  /*
505  * Create PG_VERSION file in the database path. If the file already
506  * exists and we are in WAL replay then try again to open it in write
507  * mode.
508  */
509  snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
510 
511  fd = OpenTransientFile(versionfile, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY);
512  if (fd < 0 && errno == EEXIST && isRedo)
513  fd = OpenTransientFile(versionfile, O_WRONLY | O_TRUNC | PG_BINARY);
514 
515  if (fd < 0)
516  ereport(ERROR,
518  errmsg("could not create file \"%s\": %m", versionfile)));
519 
520  /* Write PG_MAJORVERSION in the PG_VERSION file. */
521  pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_WRITE);
522  errno = 0;
523  if ((int) write(fd, buf, nbytes) != nbytes)
524  {
525  /* If write didn't set errno, assume problem is no disk space. */
526  if (errno == 0)
527  errno = ENOSPC;
528  ereport(ERROR,
530  errmsg("could not write to file \"%s\": %m", versionfile)));
531  }
533 
534  /* Close the version file. */
536 
537  /* Critical section done. */
538  if (!isRedo)
540 }
#define PG_BINARY
Definition: c.h:1283
#define XLOG_DBASE_CREATE_WAL_LOG
int errcode_for_file_access(void)
Definition: elog.c:881
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3858
int CloseTransientFile(int fd)
Definition: fd.c:2754
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2578
#define write(a, b, c)
Definition: win32.h:14
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:67
#define sprintf
Definition: port.h:240
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2535
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References buf, CloseTransientFile(), xl_dbase_create_wal_log_rec::db_id, END_CRIT_SECTION, ereport, errcode_for_file_access(), errmsg(), ERROR, fd(), MakePGDirectory(), MAXPGPATH, OpenTransientFile(), PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), snprintf, sprintf, START_CRIT_SECTION, xl_dbase_create_wal_log_rec::tablespace_id, write, XLOG_DBASE_CREATE_WAL_LOG, XLogBeginInsert(), XLogFlush(), XLogInsert(), and XLogRegisterData().

Referenced by CreateDatabaseUsingWalLog(), and dbase_redo().

◆ database_is_invalid_form()

bool database_is_invalid_form ( Form_pg_database  datform)

Definition at line 3108 of file dbcommands.c.

3109 {
3110  return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
3111 }
#define DATCONNLIMIT_INVALID_DB
Definition: pg_database.h:119

References DATCONNLIMIT_INVALID_DB.

Referenced by AlterDatabase(), database_is_invalid_oid(), get_database_list(), InitPostgres(), and vac_truncate_clog().

◆ database_is_invalid_oid()

bool database_is_invalid_oid ( Oid  dboid)

Definition at line 3118 of file dbcommands.c.

3119 {
3120  HeapTuple dbtup;
3121  Form_pg_database dbform;
3122  bool invalid;
3123 
3124  dbtup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dboid));
3125  if (!HeapTupleIsValid(dbtup))
3126  elog(ERROR, "cache lookup failed for database %u", dboid);
3127  dbform = (Form_pg_database) GETSTRUCT(dbtup);
3128 
3130 
3131  ReleaseSysCache(dbtup);
3132 
3133  return invalid;
3134 }
invalidindex index d is invalid
Definition: isn.c:134
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ DATABASEOID
Definition: syscache.h:55

References database_is_invalid_form(), DATABASEOID, elog(), ERROR, GETSTRUCT, HeapTupleIsValid, invalid, ObjectIdGetDatum(), ReleaseSysCache(), and SearchSysCache1().

Referenced by createdb().

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 3180 of file dbcommands.c.

3181 {
3182  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3183 
3184  /* Backup blocks are not used in dbase records */
3185  Assert(!XLogRecHasAnyBlockRefs(record));
3186 
3187  if (info == XLOG_DBASE_CREATE_FILE_COPY)
3188  {
3191  char *src_path;
3192  char *dst_path;
3193  char *parent_path;
3194  struct stat st;
3195 
3196  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3197  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3198 
3199  /*
3200  * Our theory for replaying a CREATE is to forcibly drop the target
3201  * subdirectory if present, then re-copy the source data. This may be
3202  * more work than needed, but it is simple to implement.
3203  */
3204  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3205  {
3206  if (!rmtree(dst_path, true))
3207  /* If this failed, copydir() below is going to error. */
3208  ereport(WARNING,
3209  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3210  dst_path)));
3211  }
3212 
3213  /*
3214  * If the parent of the target path doesn't exist, create it now. This
3215  * enables us to create the target underneath later.
3216  */
3217  parent_path = pstrdup(dst_path);
3218  get_parent_directory(parent_path);
3219  if (stat(parent_path, &st) < 0)
3220  {
3221  if (errno != ENOENT)
3222  ereport(FATAL,
3223  errmsg("could not stat directory \"%s\": %m",
3224  dst_path));
3225 
3226  /* create the parent directory if needed and valid */
3227  recovery_create_dbdir(parent_path, true);
3228  }
3229  pfree(parent_path);
3230 
3231  /*
3232  * There's a case where the copy source directory is missing for the
3233  * same reason above. Create the empty source directory so that
3234  * copydir below doesn't fail. The directory will be dropped soon by
3235  * recovery.
3236  */
3237  if (stat(src_path, &st) < 0 && errno == ENOENT)
3238  recovery_create_dbdir(src_path, false);
3239 
3240  /*
3241  * Force dirty buffers out to disk, to ensure source database is
3242  * up-to-date for the copy.
3243  */
3245 
3246  /* Close all sgmr fds in all backends. */
3248 
3249  /*
3250  * Copy this subdirectory to the new location
3251  *
3252  * We don't need to copy subdirectories
3253  */
3254  copydir(src_path, dst_path, false);
3255 
3256  pfree(src_path);
3257  pfree(dst_path);
3258  }
3259  else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3260  {
3263  char *dbpath;
3264  char *parent_path;
3265 
3266  dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3267 
3268  /* create the parent directory if needed and valid */
3269  parent_path = pstrdup(dbpath);
3270  get_parent_directory(parent_path);
3271  recovery_create_dbdir(parent_path, true);
3272 
3273  /* Create the database directory with the version file. */
3274  CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3275  true);
3276  pfree(dbpath);
3277  }
3278  else if (info == XLOG_DBASE_DROP)
3279  {
3280  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
3281  char *dst_path;
3282  int i;
3283 
3284  if (InHotStandby)
3285  {
3286  /*
3287  * Lock database while we resolve conflicts to ensure that
3288  * InitPostgres() cannot fully re-execute concurrently. This
3289  * avoids backends re-connecting automatically to same database,
3290  * which can happen in some cases.
3291  *
3292  * This will lock out walsenders trying to connect to db-specific
3293  * slots for logical decoding too, so it's safe for us to drop
3294  * slots.
3295  */
3296  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3298  }
3299 
3300  /* Drop any database-specific replication slots */
3302 
3303  /* Drop pages for this database that are in the shared buffer cache */
3304  DropDatabaseBuffers(xlrec->db_id);
3305 
3306  /* Also, clean out any fsync requests that might be pending in md.c */
3308 
3309  /* Clean out the xlog relcache too */
3310  XLogDropDatabase(xlrec->db_id);
3311 
3312  /* Close all sgmr fds in all backends. */
3314 
3315  for (i = 0; i < xlrec->ntablespaces; i++)
3316  {
3317  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3318 
3319  /* And remove the physical files */
3320  if (!rmtree(dst_path, true))
3321  ereport(WARNING,
3322  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3323  dst_path)));
3324  pfree(dst_path);
3325  }
3326 
3327  if (InHotStandby)
3328  {
3329  /*
3330  * Release locks prior to commit. XXX There is a race condition
3331  * here that may allow backends to reconnect, but the window for
3332  * this is small because the gap between here and commit is mostly
3333  * fairly small and it is unlikely that people will be dropping
3334  * databases that we are trying to connect to anyway.
3335  */
3336  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3337  }
3338  }
3339  else
3340  elog(PANIC, "dbase_redo: unknown op code %u", info);
3341 }
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4417
unsigned char uint8
Definition: c.h:493
static void recovery_create_dbdir(char *path, bool only_tblspc)
Definition: dbcommands.c:3151
#define XLOG_DBASE_DROP
#define PANIC
Definition: elog.h:42
int i
Definition: isn.c:73
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1106
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1088
#define AccessExclusiveLock
Definition: lockdefs.h:43
char * pstrdup(const char *in)
Definition: mcxt.c:1644
void get_parent_directory(char *path)
Definition: path.c:977
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:393
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:333
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:56
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1058
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:569
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:417
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:654
#define InHotStandby
Definition: xlogutils.h:57

References AccessExclusiveLock, Assert(), copydir(), CreateDirAndVersionFile(), xl_dbase_create_file_copy_rec::db_id, xl_dbase_create_wal_log_rec::db_id, xl_dbase_drop_rec::db_id, DropDatabaseBuffers(), elog(), EmitProcSignalBarrier(), ereport, errmsg(), FATAL, FlushDatabaseBuffers(), ForgetDatabaseSyncRequests(), get_parent_directory(), GetDatabasePath(), i, InHotStandby, LockSharedObjectForSession(), xl_dbase_drop_rec::ntablespaces, PANIC, pfree(), PROCSIGNAL_BARRIER_SMGRRELEASE, pstrdup(), recovery_create_dbdir(), ReplicationSlotsDropDBSlots(), ResolveRecoveryConflictWithDatabase(), rmtree(), S_ISDIR, xl_dbase_create_file_copy_rec::src_db_id, xl_dbase_create_file_copy_rec::src_tablespace_id, stat::st_mode, stat, xl_dbase_create_file_copy_rec::tablespace_id, xl_dbase_create_wal_log_rec::tablespace_id, xl_dbase_drop_rec::tablespace_ids, UnlockSharedObjectForSession(), WaitForProcSignalBarrier(), WARNING, XLOG_DBASE_CREATE_FILE_COPY, XLOG_DBASE_CREATE_WAL_LOG, XLOG_DBASE_DROP, XLogDropDatabase(), XLogRecGetData, XLogRecGetInfo, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 2240 of file dbcommands.c.

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

References DefElem::defname, dropdb(), ereport, errcode(), errmsg(), ERROR, lfirst, DefElem::location, parser_errposition(), and stmt.

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1583 of file dbcommands.c.

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

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

Referenced by DropDatabase().

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 3007 of file dbcommands.c.

3008 {
3009  if (notherbackends > 0 && npreparedxacts > 0)
3010 
3011  /*
3012  * We don't deal with singular versus plural here, since gettext
3013  * doesn't support multiple plurals in one string.
3014  */
3015  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3016  notherbackends, npreparedxacts);
3017  else if (notherbackends > 0)
3018  errdetail_plural("There is %d other session using the database.",
3019  "There are %d other sessions using the database.",
3020  notherbackends,
3021  notherbackends);
3022  else
3023  errdetail_plural("There is %d prepared transaction using the database.",
3024  "There are %d prepared transactions using the database.",
3025  npreparedxacts,
3026  npreparedxacts);
3027  return 0; /* just to keep ereport macro happy */
3028 }

References errdetail(), and errdetail_plural().

Referenced by createdb(), dropdb(), movedb(), and RenameDatabase().

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 3084 of file dbcommands.c.

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

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

Referenced by AfterTriggerSetState(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscriptionOwner_internal(), calculate_database_size(), createdb(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), exec_object_restorecon(), ExpandColumnRefStar(), GetNewMultiXactId(), GetNewTransactionId(), getObjectDescription(), getObjectIdentityParts(), heap_vacuum_rel(), IdentifySystem(), InitTempTableNamespace(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), perform_work_item(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), ReindexMultipleTables(), RenameSchema(), SetMultiXactIdLimit(), SetTransactionIdLimit(), shdepLockAndCheckObject(), TerminateOtherDBBackends(), and transformColumnRef().

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 3037 of file dbcommands.c.

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

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

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

◆ get_db_info()

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 
)
static

Definition at line 2694 of file dbcommands.c.

2702 {
2703  bool result = false;
2704  Relation relation;
2705 
2706  Assert(name);
2707 
2708  /* Caller may wish to grab a better lock on pg_database beforehand... */
2709  relation = table_open(DatabaseRelationId, AccessShareLock);
2710 
2711  /*
2712  * Loop covers the rare case where the database is renamed before we can
2713  * lock it. We try again just in case we can find a new one of the same
2714  * name.
2715  */
2716  for (;;)
2717  {
2718  ScanKeyData scanKey;
2719  SysScanDesc scan;
2720  HeapTuple tuple;
2721  Oid dbOid;
2722 
2723  /*
2724  * there's no syscache for database-indexed-by-name, so must do it the
2725  * hard way
2726  */
2727  ScanKeyInit(&scanKey,
2728  Anum_pg_database_datname,
2729  BTEqualStrategyNumber, F_NAMEEQ,
2731 
2732  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2733  NULL, 1, &scanKey);
2734 
2735  tuple = systable_getnext(scan);
2736 
2737  if (!HeapTupleIsValid(tuple))
2738  {
2739  /* definitely no database of that name */
2740  systable_endscan(scan);
2741  break;
2742  }
2743 
2744  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2745 
2746  systable_endscan(scan);
2747 
2748  /*
2749  * Now that we have a database OID, we can try to lock the DB.
2750  */
2751  if (lockmode != NoLock)
2752  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2753 
2754  /*
2755  * And now, re-fetch the tuple by OID. If it's still there and still
2756  * the same name, we win; else, drop the lock and loop back to try
2757  * again.
2758  */
2759  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
2760  if (HeapTupleIsValid(tuple))
2761  {
2762  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
2763 
2764  if (strcmp(name, NameStr(dbform->datname)) == 0)
2765  {
2766  Datum datum;
2767  bool isnull;
2768 
2769  /* oid of the database */
2770  if (dbIdP)
2771  *dbIdP = dbOid;
2772  /* oid of the owner */
2773  if (ownerIdP)
2774  *ownerIdP = dbform->datdba;
2775  /* character encoding */
2776  if (encodingP)
2777  *encodingP = dbform->encoding;
2778  /* allowed as template? */
2779  if (dbIsTemplateP)
2780  *dbIsTemplateP = dbform->datistemplate;
2781  /* allowing connections? */
2782  if (dbAllowConnP)
2783  *dbAllowConnP = dbform->datallowconn;
2784  /* limit of frozen XIDs */
2785  if (dbFrozenXidP)
2786  *dbFrozenXidP = dbform->datfrozenxid;
2787  /* minimum MultiXactId */
2788  if (dbMinMultiP)
2789  *dbMinMultiP = dbform->datminmxid;
2790  /* default tablespace for this database */
2791  if (dbTablespace)
2792  *dbTablespace = dbform->dattablespace;
2793  /* default locale settings for this database */
2794  if (dbLocProvider)
2795  *dbLocProvider = dbform->datlocprovider;
2796  if (dbCollate)
2797  {
2798  datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datcollate);
2799  *dbCollate = TextDatumGetCString(datum);
2800  }
2801  if (dbCtype)
2802  {
2803  datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datctype);
2804  *dbCtype = TextDatumGetCString(datum);
2805  }
2806  if (dbIculocale)
2807  {
2808  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticulocale, &isnull);
2809  if (isnull)
2810  *dbIculocale = NULL;
2811  else
2812  *dbIculocale = TextDatumGetCString(datum);
2813  }
2814  if (dbIcurules)
2815  {
2816  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticurules, &isnull);
2817  if (isnull)
2818  *dbIcurules = NULL;
2819  else
2820  *dbIcurules = TextDatumGetCString(datum);
2821  }
2822  if (dbCollversion)
2823  {
2824  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
2825  if (isnull)
2826  *dbCollversion = NULL;
2827  else
2828  *dbCollversion = TextDatumGetCString(datum);
2829  }
2830  ReleaseSysCache(tuple);
2831  result = true;
2832  break;
2833  }
2834  /* can only get here if it was just renamed */
2835  ReleaseSysCache(tuple);
2836  }
2837 
2838  if (lockmode != NoLock)
2839  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2840  }
2841 
2842  table_close(relation, AccessShareLock);
2843 
2844  return result;
2845 }
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1081
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:1112
const char * name

References AccessShareLock, Assert(), BTEqualStrategyNumber, CStringGetDatum(), DATABASEOID, GETSTRUCT, HeapTupleIsValid, LockSharedObject(), name, NameStr, NoLock, ObjectIdGetDatum(), ReleaseSysCache(), ScanKeyInit(), SearchSysCache1(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TextDatumGetCString, and UnlockSharedObject().

Referenced by createdb(), dropdb(), movedb(), and RenameDatabase().

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2849 of file dbcommands.c.

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

References AUTHOID, GETSTRUCT, GetUserId(), HeapTupleIsValid, ObjectIdGetDatum(), ReleaseSysCache(), rolcreatedb, SearchSysCache1(), and superuser().

Referenced by AlterDatabaseOwner(), AlterRole(), createdb(), CreateRole(), and RenameDatabase().

◆ movedb()

static void movedb ( const char *  dbname,
const char *  tblspcname 
)
static

Definition at line 1903 of file dbcommands.c.

1904 {
1905  Oid db_id;
1906  Relation pgdbrel;
1907  int notherbackends;
1908  int npreparedxacts;
1909  HeapTuple oldtuple,
1910  newtuple;
1911  Oid src_tblspcoid,
1912  dst_tblspcoid;
1913  ScanKeyData scankey;
1914  SysScanDesc sysscan;
1915  AclResult aclresult;
1916  char *src_dbpath;
1917  char *dst_dbpath;
1918  DIR *dstdir;
1919  struct dirent *xlde;
1920  movedb_failure_params fparms;
1921 
1922  /*
1923  * Look up the target database's OID, and get exclusive lock on it. We
1924  * need this to ensure that no new backend starts up in the database while
1925  * we are moving it, and that no one is using it as a CREATE DATABASE
1926  * template or trying to delete it.
1927  */
1928  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1929 
1930  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1931  NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL, NULL, NULL, NULL, NULL))
1932  ereport(ERROR,
1933  (errcode(ERRCODE_UNDEFINED_DATABASE),
1934  errmsg("database \"%s\" does not exist", dbname)));
1935 
1936  /*
1937  * We actually need a session lock, so that the lock will persist across
1938  * the commit/restart below. (We could almost get away with letting the
1939  * lock be released at commit, except that someone could try to move
1940  * relations of the DB back into the old directory while we rmtree() it.)
1941  */
1942  LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1944 
1945  /*
1946  * Permission checks
1947  */
1948  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1950  dbname);
1951 
1952  /*
1953  * Obviously can't move the tables of my own database
1954  */
1955  if (db_id == MyDatabaseId)
1956  ereport(ERROR,
1957  (errcode(ERRCODE_OBJECT_IN_USE),
1958  errmsg("cannot change the tablespace of the currently open database")));
1959 
1960  /*
1961  * Get tablespace's oid
1962  */
1963  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1964 
1965  /*
1966  * Permission checks
1967  */
1968  aclresult = object_aclcheck(TableSpaceRelationId, dst_tblspcoid, GetUserId(),
1969  ACL_CREATE);
1970  if (aclresult != ACLCHECK_OK)
1971  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1972  tblspcname);
1973 
1974  /*
1975  * pg_global must never be the default tablespace
1976  */
1977  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1978  ereport(ERROR,
1979  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1980  errmsg("pg_global cannot be used as default tablespace")));
1981 
1982  /*
1983  * No-op if same tablespace
1984  */
1985  if (src_tblspcoid == dst_tblspcoid)
1986  {
1987  table_close(pgdbrel, NoLock);
1988  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1990  return;
1991  }
1992 
1993  /*
1994  * Check for other backends in the target database. (Because we hold the
1995  * database lock, no new ones can start after this.)
1996  *
1997  * As in CREATE DATABASE, check this after other error conditions.
1998  */
1999  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
2000  ereport(ERROR,
2001  (errcode(ERRCODE_OBJECT_IN_USE),
2002  errmsg("database \"%s\" is being accessed by other users",
2003  dbname),
2004  errdetail_busy_db(notherbackends, npreparedxacts)));
2005 
2006  /*
2007  * Get old and new database paths
2008  */
2009  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
2010  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
2011 
2012  /*
2013  * Force a checkpoint before proceeding. This will force all dirty
2014  * buffers, including those of unlogged tables, out to disk, to ensure
2015  * source database is up-to-date on disk for the copy.
2016  * FlushDatabaseBuffers() would suffice for that, but we also want to
2017  * process any pending unlink requests. Otherwise, the check for existing
2018  * files in the target directory might fail unnecessarily, not to mention
2019  * that the copy might fail due to source files getting deleted under it.
2020  * On Windows, this also ensures that background procs don't hold any open
2021  * files, which would cause rmdir() to fail.
2022  */
2025 
2026  /* Close all smgr fds in all backends. */
2028 
2029  /*
2030  * Now drop all buffers holding data of the target database; they should
2031  * no longer be dirty so DropDatabaseBuffers is safe.
2032  *
2033  * It might seem that we could just let these buffers age out of shared
2034  * buffers naturally, since they should not get referenced anymore. The
2035  * problem with that is that if the user later moves the database back to
2036  * its original tablespace, any still-surviving buffers would appear to
2037  * contain valid data again --- but they'd be missing any changes made in
2038  * the database while it was in the new tablespace. In any case, freeing
2039  * buffers that should never be used again seems worth the cycles.
2040  *
2041  * Note: it'd be sufficient to get rid of buffers matching db_id and
2042  * src_tblspcoid, but bufmgr.c presently provides no API for that.
2043  */
2044  DropDatabaseBuffers(db_id);
2045 
2046  /*
2047  * Check for existence of files in the target directory, i.e., objects of
2048  * this database that are already in the target tablespace. We can't
2049  * allow the move in such a case, because we would need to change those
2050  * relations' pg_class.reltablespace entries to zero, and we don't have
2051  * access to the DB's pg_class to do so.
2052  */
2053  dstdir = AllocateDir(dst_dbpath);
2054  if (dstdir != NULL)
2055  {
2056  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
2057  {
2058  if (strcmp(xlde->d_name, ".") == 0 ||
2059  strcmp(xlde->d_name, "..") == 0)
2060  continue;
2061 
2062  ereport(ERROR,
2063  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2064  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
2065  dbname, tblspcname),
2066  errhint("You must move them back to the database's default tablespace before using this command.")));
2067  }
2068 
2069  FreeDir(dstdir);
2070 
2071  /*
2072  * The directory exists but is empty. We must remove it before using
2073  * the copydir function.
2074  */
2075  if (rmdir(dst_dbpath) != 0)
2076  elog(ERROR, "could not remove directory \"%s\": %m",
2077  dst_dbpath);
2078  }
2079 
2080  /*
2081  * Use an ENSURE block to make sure we remove the debris if the copy fails
2082  * (eg, due to out-of-disk-space). This is not a 100% solution, because
2083  * of the possibility of failure during transaction commit, but it should
2084  * handle most scenarios.
2085  */
2086  fparms.dest_dboid = db_id;
2087  fparms.dest_tsoid = dst_tblspcoid;
2089  PointerGetDatum(&fparms));
2090  {
2091  Datum new_record[Natts_pg_database] = {0};
2092  bool new_record_nulls[Natts_pg_database] = {0};
2093  bool new_record_repl[Natts_pg_database] = {0};
2094 
2095  /*
2096  * Copy files from the old tablespace to the new one
2097  */
2098  copydir(src_dbpath, dst_dbpath, false);
2099 
2100  /*
2101  * Record the filesystem change in XLOG
2102  */
2103  {
2105 
2106  xlrec.db_id = db_id;
2107  xlrec.tablespace_id = dst_tblspcoid;
2108  xlrec.src_db_id = db_id;
2109  xlrec.src_tablespace_id = src_tblspcoid;
2110 
2111  XLogBeginInsert();
2112  XLogRegisterData((char *) &xlrec,
2114 
2115  (void) XLogInsert(RM_DBASE_ID,
2117  }
2118 
2119  /*
2120  * Update the database's pg_database tuple
2121  */
2122  ScanKeyInit(&scankey,
2123  Anum_pg_database_datname,
2124  BTEqualStrategyNumber, F_NAMEEQ,
2126  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
2127  NULL, 1, &scankey);
2128  oldtuple = systable_getnext(sysscan);
2129  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2130  ereport(ERROR,
2131  (errcode(ERRCODE_UNDEFINED_DATABASE),
2132  errmsg("database \"%s\" does not exist", dbname)));
2133 
2134  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
2135  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
2136 
2137  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2138  new_record,
2139  new_record_nulls, new_record_repl);
2140  CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2141 
2142  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2143 
2144  systable_endscan(sysscan);
2145 
2146  /*
2147  * Force another checkpoint here. As in CREATE DATABASE, this is to
2148  * ensure that we don't have to replay a committed
2149  * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2150  * any unlogged operations done in the new DB tablespace before the
2151  * next checkpoint.
2152  */
2154 
2155  /*
2156  * Force synchronous commit, thus minimizing the window between
2157  * copying the database files and committal of the transaction. If we
2158  * crash before committing, we'll leave an orphaned set of files on
2159  * disk, which is not fatal but not good either.
2160  */
2161  ForceSyncCommit();
2162 
2163  /*
2164  * Close pg_database, but keep lock till commit.
2165  */
2166  table_close(pgdbrel, NoLock);
2167  }
2169  PointerGetDatum(&fparms));
2170 
2171  /*
2172  * Commit the transaction so that the pg_database update is committed. If
2173  * we crash while removing files, the database won't be corrupt, we'll
2174  * just leave some orphaned files in the old directory.
2175  *
2176  * (This is OK because we know we aren't inside a transaction block.)
2177  *
2178  * XXX would it be safe/better to do this inside the ensure block? Not
2179  * convinced it's a good idea; consider elog just after the transaction
2180  * really commits.
2181  */
2184 
2185  /* Start new transaction for the remaining work; don't need a snapshot */
2187 
2188  /*
2189  * Remove files from the old tablespace
2190  */
2191  if (!rmtree(src_dbpath, true))
2192  ereport(WARNING,
2193  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2194  src_dbpath)));
2195 
2196  /*
2197  * Record the filesystem change in XLOG
2198  */
2199  {
2200  xl_dbase_drop_rec xlrec;
2201 
2202  xlrec.db_id = db_id;
2203  xlrec.ntablespaces = 1;
2204 
2205  XLogBeginInsert();
2206  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
2207  XLogRegisterData((char *) &src_tblspcoid, sizeof(Oid));
2208 
2209  (void) XLogInsert(RM_DBASE_ID,
2211  }
2212 
2213  /* Now it's safe to release the database lock */
2214  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
2216 
2217  pfree(src_dbpath);
2218  pfree(dst_dbpath);
2219 }
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:2223
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2854
int FreeDir(DIR *dir)
Definition: fd.c:2906
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2788
void PopActiveSnapshot(void)
Definition: snapmgr.c:724
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
void StartTransactionCommand(void)
Definition: xact.c:2937
void CommitTransactionCommand(void)
Definition: xact.c:3034

References AccessExclusiveLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AllocateDir(), BTEqualStrategyNumber, CatalogTupleUpdate(), CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, CommitTransactionCommand(), copydir(), CountOtherDBBackends(), CStringGetDatum(), dirent::d_name, xl_dbase_create_file_copy_rec::db_id, xl_dbase_drop_rec::db_id, dbname, movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, DropDatabaseBuffers(), elog(), EmitProcSignalBarrier(), ereport, errcode(), errdetail_busy_db(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FreeDir(), get_db_info(), get_tablespace_oid(), GetDatabasePath(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, LockSharedObjectForSession(), movedb_failure_callback(), MyDatabaseId, NoLock, xl_dbase_drop_rec::ntablespaces, object_aclcheck(), OBJECT_DATABASE, object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), pfree(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, PointerGetDatum(), PopActiveSnapshot(), PROCSIGNAL_BARRIER_SMGRRELEASE, ReadDir(), RelationGetDescr, RequestCheckpoint(), rmtree(), RowExclusiveLock, ScanKeyInit(), xl_dbase_create_file_copy_rec::src_db_id, xl_dbase_create_file_copy_rec::src_tablespace_id, StartTransactionCommand(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), xl_dbase_create_file_copy_rec::tablespace_id, UnlockSharedObjectForSession(), WaitForProcSignalBarrier(), WARNING, XLOG_DBASE_CREATE_FILE_COPY, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by AlterDatabase().

◆ movedb_failure_callback()

static void movedb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 2223 of file dbcommands.c.

2224 {
2226  char *dstpath;
2227 
2228  /* Get rid of anything we managed to copy to the target directory */
2229  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2230 
2231  (void) rmtree(dstpath, true);
2232 
2233  pfree(dstpath);
2234 }

References arg, DatumGetPointer(), movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, dstpath, GetDatabasePath(), pfree(), and rmtree().

Referenced by movedb().

◆ pg_database_collation_actual_version()

Datum pg_database_collation_actual_version ( PG_FUNCTION_ARGS  )

Definition at line 2655 of file dbcommands.c.

2656 {
2657  Oid dbid = PG_GETARG_OID(0);
2658  HeapTuple tp;
2659  char datlocprovider;
2660  Datum datum;
2661  char *version;
2662 
2664  if (!HeapTupleIsValid(tp))
2665  ereport(ERROR,
2666  (errcode(ERRCODE_UNDEFINED_OBJECT),
2667  errmsg("database with OID %u does not exist", dbid)));
2668 
2670 
2671  datum = SysCacheGetAttrNotNull(DATABASEOID, tp, datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate);
2673 
2674  ReleaseSysCache(tp);
2675 
2676  if (version)
2678  else
2679  PG_RETURN_NULL();
2680 }
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
char datlocprovider
Definition: pg_database.h:44
text * cstring_to_text(const char *s)
Definition: varlena.c:182

References cstring_to_text(), DATABASEOID, datlocprovider, ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum(), PG_GETARG_OID, PG_RETURN_NULL, PG_RETURN_TEXT_P, ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

◆ recovery_create_dbdir()

static void recovery_create_dbdir ( char *  path,
bool  only_tblspc 
)
static

Definition at line 3151 of file dbcommands.c.

3152 {
3153  struct stat st;
3154 
3156 
3157  if (stat(path, &st) == 0)
3158  return;
3159 
3160  if (only_tblspc && strstr(path, "pg_tblspc/") == NULL)
3161  elog(PANIC, "requested to created invalid directory: %s", path);
3162 
3164  ereport(PANIC,
3165  errmsg("missing directory \"%s\"", path));
3166 
3168  "creating missing directory: %s", path);
3169 
3170  if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3171  ereport(PANIC,
3172  errmsg("could not create missing directory \"%s\": %m", path));
3173 }
bool allow_in_place_tablespaces
Definition: tablespace.c:91
#define DEBUG1
Definition: elog.h:30
int pg_dir_create_mode
Definition: file_perm.c:18
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
bool RecoveryInProgress(void)
Definition: xlog.c:5948
bool reachedConsistency
Definition: xlogrecovery.c:294

References allow_in_place_tablespaces, Assert(), DEBUG1, elog(), ereport, errmsg(), PANIC, pg_dir_create_mode, pg_mkdir_p(), reachedConsistency, RecoveryInProgress(), stat, and WARNING.

Referenced by dbase_redo().

◆ remove_dbtablespaces()

static void remove_dbtablespaces ( Oid  db_id)
static

Definition at line 2874 of file dbcommands.c.

2875 {
2876  Relation rel;
2877  TableScanDesc scan;
2878  HeapTuple tuple;
2879  List *ltblspc = NIL;
2880  ListCell *cell;
2881  int ntblspc;
2882  int i;
2883  Oid *tablespace_ids;
2884 
2885  rel = table_open(TableSpaceRelationId, AccessShareLock);
2886  scan = table_beginscan_catalog(rel, 0, NULL);
2887  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2888  {
2889  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2890  Oid dsttablespace = spcform->oid;
2891  char *dstpath;
2892  struct stat st;
2893 
2894  /* Don't mess with the global tablespace */
2895  if (dsttablespace == GLOBALTABLESPACE_OID)
2896  continue;
2897 
2898  dstpath = GetDatabasePath(db_id, dsttablespace);
2899 
2900  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
2901  {
2902  /* Assume we can ignore it */
2903  pfree(dstpath);
2904  continue;
2905  }
2906 
2907  if (!rmtree(dstpath, true))
2908  ereport(WARNING,
2909  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2910  dstpath)));
2911 
2912  ltblspc = lappend_oid(ltblspc, dsttablespace);
2913  pfree(dstpath);
2914  }
2915 
2916  ntblspc = list_length(ltblspc);
2917  if (ntblspc == 0)
2918  {
2919  table_endscan(scan);
2921  return;
2922  }
2923 
2924  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
2925  i = 0;
2926  foreach(cell, ltblspc)
2927  tablespace_ids[i++] = lfirst_oid(cell);
2928 
2929  /* Record the filesystem change in XLOG */
2930  {
2931  xl_dbase_drop_rec xlrec;
2932 
2933  xlrec.db_id = db_id;
2934  xlrec.ntablespaces = ntblspc;
2935 
2936  XLogBeginInsert();
2937  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
2938  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
2939 
2940  (void) XLogInsert(RM_DBASE_ID,
2942  }
2943 
2944  list_free(ltblspc);
2945  pfree(tablespace_ids);
2946 
2947  table_endscan(scan);
2949 }
#define MinSizeOfDbaseDropRec
List * lappend_oid(List *list, Oid datum)
Definition: list.c:374
void list_free(List *list)
Definition: list.c:1545
void * palloc(Size size)
Definition: mcxt.c:1226
#define lfirst_oid(lc)
Definition: pg_list.h:174

References AccessShareLock, xl_dbase_drop_rec::db_id, dstpath, ereport, errmsg(), ForwardScanDirection, GetDatabasePath(), GETSTRUCT, heap_getnext(), i, lappend_oid(), lfirst_oid, list_free(), list_length(), lstat, MinSizeOfDbaseDropRec, NIL, xl_dbase_drop_rec::ntablespaces, palloc(), pfree(), rmtree(), S_ISDIR, stat::st_mode, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), WARNING, XLOG_DBASE_DROP, XLogBeginInsert(), XLogInsert(), XLogRegisterData(), and XLR_SPECIAL_REL_UPDATE.

Referenced by createdb_failure_callback(), and dropdb().

◆ RenameDatabase()

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

Definition at line 1805 of file dbcommands.c.

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

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

Referenced by ExecRenameStmt().

◆ ScanSourceDatabasePgClass()

static List * ScanSourceDatabasePgClass ( Oid  tbid,
Oid  dbid,
char *  srcpath 
)
static

Definition at line 251 of file dbcommands.c.

252 {
253  RelFileLocator rlocator;
254  BlockNumber nblocks;
255  BlockNumber blkno;
256  Buffer buf;
257  RelFileNumber relfilenumber;
258  Page page;
259  List *rlocatorlist = NIL;
260  LockRelId relid;
261  Snapshot snapshot;
262  SMgrRelation smgr;
263  BufferAccessStrategy bstrategy;
264 
265  /* Get pg_class relfilenumber. */
266  relfilenumber = RelationMapOidToFilenumberForDatabase(srcpath,
267  RelationRelationId);
268 
269  /* Don't read data into shared_buffers without holding a relation lock. */
270  relid.dbId = dbid;
271  relid.relId = RelationRelationId;
273 
274  /* Prepare a RelFileLocator for the pg_class relation. */
275  rlocator.spcOid = tbid;
276  rlocator.dbOid = dbid;
277  rlocator.relNumber = relfilenumber;
278 
279  smgr = smgropen(rlocator, InvalidBackendId);
280  nblocks = smgrnblocks(smgr, MAIN_FORKNUM);
281  smgrclose(smgr);
282 
283  /* Use a buffer access strategy since this is a bulk read operation. */
284  bstrategy = GetAccessStrategy(BAS_BULKREAD);
285 
286  /*
287  * As explained in the function header comments, we need a snapshot that
288  * will see all committed transactions as committed, and our transaction
289  * snapshot - or the active snapshot - might not be new enough for that,
290  * but the return value of GetLatestSnapshot() should work fine.
291  */
292  snapshot = GetLatestSnapshot();
293 
294  /* Process the relation block by block. */
295  for (blkno = 0; blkno < nblocks; blkno++)
296  {
298 
299  buf = ReadBufferWithoutRelcache(rlocator, MAIN_FORKNUM, blkno,
300  RBM_NORMAL, bstrategy, true);
301 
303  page = BufferGetPage(buf);
304  if (PageIsNew(page) || PageIsEmpty(page))
305  {
307  continue;
308  }
309 
310  /* Append relevant pg_class tuples for current page to rlocatorlist. */
311  rlocatorlist = ScanSourceDatabasePgClassPage(page, buf, tbid, dbid,
312  srcpath, rlocatorlist,
313  snapshot);
314 
316  }
317 
318  /* Release relation lock. */
320 
321  return rlocatorlist;
322 }
#define InvalidBackendId
Definition: backendid.h:23
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4497
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4715
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition: bufmgr.c:795
@ BAS_BULKREAD
Definition: bufmgr.h:35
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:158
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:350
@ RBM_NORMAL
Definition: bufmgr.h:44
static bool PageIsEmpty(Page page)
Definition: bufpage.h:220
Pointer Page
Definition: bufpage.h:78
static bool PageIsNew(Page page)
Definition: bufpage.h:230
static List * ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
Definition: dbcommands.c:329
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
RelFileNumber RelationMapOidToFilenumberForDatabase(char *dbpath, Oid relationId)
Definition: relmapper.c:266
Oid RelFileNumber
Definition: relpath.h:25
@ MAIN_FORKNUM
Definition: relpath.h:50
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:609
void smgrclose(SMgrRelation reln)
Definition: smgr.c:260
SMgrRelation smgropen(RelFileLocator rlocator, BackendId backend)
Definition: smgr.c:150
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:272

References AccessShareLock, BAS_BULKREAD, buf, BUFFER_LOCK_SHARE, BufferGetPage(), CHECK_FOR_INTERRUPTS, LockRelId::dbId, RelFileLocator::dbOid, GetAccessStrategy(), GetLatestSnapshot(), InvalidBackendId, LockBuffer(), LockRelationId(), MAIN_FORKNUM, NIL, PageIsEmpty(), PageIsNew(), RBM_NORMAL, ReadBufferWithoutRelcache(), RelationMapOidToFilenumberForDatabase(), LockRelId::relId, RelFileLocator::relNumber, ScanSourceDatabasePgClassPage(), smgrclose(), smgrnblocks(), smgropen(), RelFileLocator::spcOid, UnlockRelationId(), and UnlockReleaseBuffer().

Referenced by CreateDatabaseUsingWalLog().

◆ ScanSourceDatabasePgClassPage()

static List * ScanSourceDatabasePgClassPage ( Page  page,
Buffer  buf,
Oid  tbid,
Oid  dbid,
char *  srcpath,
List rlocatorlist,
Snapshot  snapshot 
)
static

Definition at line 329 of file dbcommands.c.

332 {
334  OffsetNumber offnum;
335  OffsetNumber maxoff;
336  HeapTupleData tuple;
337 
338  maxoff = PageGetMaxOffsetNumber(page);
339 
340  /* Loop over offsets. */
341  for (offnum = FirstOffsetNumber;
342  offnum <= maxoff;
343  offnum = OffsetNumberNext(offnum))
344  {
345  ItemId itemid;
346 
347  itemid = PageGetItemId(page, offnum);
348 
349  /* Nothing to do if slot is empty or already dead. */
350  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
351  ItemIdIsRedirected(itemid))
352  continue;
353 
354  Assert(ItemIdIsNormal(itemid));
355  ItemPointerSet(&(tuple.t_self), blkno, offnum);
356 
357  /* Initialize a HeapTupleData structure. */
358  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
359  tuple.t_len = ItemIdGetLength(itemid);
360  tuple.t_tableOid = RelationRelationId;
361 
362  /* Skip tuples that are not visible to this snapshot. */
363  if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
364  {
365  CreateDBRelInfo *relinfo;
366 
367  /*
368  * ScanSourceDatabasePgClassTuple is in charge of constructing a
369  * CreateDBRelInfo object for this tuple, but can also decide that
370  * this tuple isn't something we need to copy. If we do need to
371  * copy the relation, add it to the list.
372  */
373  relinfo = ScanSourceDatabasePgClassTuple(&tuple, tbid, dbid,
374  srcpath);
375  if (relinfo != NULL)
376  rlocatorlist = lappend(rlocatorlist, relinfo);
377  }
378  }
379 
380  return rlocatorlist;
381 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:3290
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
static CreateDBRelInfo * ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
Definition: dbcommands.c:392
bool HeapTupleSatisfiesVisibility(HeapTuple htup, Snapshot snapshot, Buffer buffer)
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition: itemptr.h:135
List * lappend(List *list, void *datum)
Definition: list.c:338
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66

References Assert(), buf, BufferGetBlockNumber(), FirstOffsetNumber, HeapTupleSatisfiesVisibility(), ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet(), lappend(), OffsetNumberNext, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), ScanSourceDatabasePgClassTuple(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by ScanSourceDatabasePgClass().

◆ ScanSourceDatabasePgClassTuple()

CreateDBRelInfo * ScanSourceDatabasePgClassTuple ( HeapTupleData tuple,
Oid  tbid,
Oid  dbid,
char *  srcpath 
)
static

Definition at line 392 of file dbcommands.c.

394 {
395  CreateDBRelInfo *relinfo;
396  Form_pg_class classForm;
397  RelFileNumber relfilenumber = InvalidRelFileNumber;
398 
399  classForm = (Form_pg_class) GETSTRUCT(tuple);
400 
401  /*
402  * Return NULL if this object does not need to be copied.
403  *
404  * Shared objects don't need to be copied, because they are shared.
405  * Objects without storage can't be copied, because there's nothing to
406  * copy. Temporary relations don't need to be copied either, because they
407  * are inaccessible outside of the session that created them, which must
408  * be gone already, and couldn't connect to a different database if it
409  * still existed. autovacuum will eventually remove the pg_class entries
410  * as well.
411  */
412  if (classForm->reltablespace == GLOBALTABLESPACE_OID ||
413  !RELKIND_HAS_STORAGE(classForm->relkind) ||
414  classForm->relpersistence == RELPERSISTENCE_TEMP)
415  return NULL;
416 
417  /*
418  * If relfilenumber is valid then directly use it. Otherwise, consult the
419  * relmap.
420  */
421  if (RelFileNumberIsValid(classForm->relfilenode))
422  relfilenumber = classForm->relfilenode;
423  else
424  relfilenumber = RelationMapOidToFilenumberForDatabase(srcpath,
425  classForm->oid);
426 
427  /* We must have a valid relfilenumber. */
428  if (!RelFileNumberIsValid(relfilenumber))
429  elog(ERROR, "relation with OID %u does not have a valid relfilenumber",
430  classForm->oid);
431 
432  /* Prepare a rel info element and add it to the list. */
433  relinfo = (CreateDBRelInfo *) palloc(sizeof(CreateDBRelInfo));
434  if (OidIsValid(classForm->reltablespace))
435  relinfo->rlocator.spcOid = classForm->reltablespace;
436  else
437  relinfo->rlocator.spcOid = tbid;
438 
439  relinfo->rlocator.dbOid = dbid;
440  relinfo->rlocator.relNumber = relfilenumber;
441  relinfo->reloid = classForm->oid;
442 
443  /* Temporary relations were rejected above. */
444  Assert(classForm->relpersistence != RELPERSISTENCE_TEMP);
445  relinfo->permanent =
446  (classForm->relpersistence == RELPERSISTENCE_PERMANENT) ? true : false;
447 
448  return relinfo;
449 }
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define InvalidRelFileNumber
Definition: relpath.h:26
#define RelFileNumberIsValid(relnumber)
Definition: relpath.h:27

References Assert(), RelFileLocator::dbOid, elog(), ERROR, GETSTRUCT, InvalidRelFileNumber, OidIsValid, palloc(), CreateDBRelInfo::permanent, RelationMapOidToFilenumberForDatabase(), RelFileNumberIsValid, RelFileLocator::relNumber, CreateDBRelInfo::reloid, CreateDBRelInfo::rlocator, and RelFileLocator::spcOid.

Referenced by ScanSourceDatabasePgClassPage().