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 *dbLocProvider, char **dbCollversion)
 
static bool have_createdb_privilege (void)
 
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)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
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 2174 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2446 of file dbcommands.c.

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

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2420 of file dbcommands.c.

2421 {
2422  Oid datid = get_database_oid(stmt->dbname, false);
2423 
2424  /*
2425  * Obtain a lock on the database and make sure it didn't go away in the
2426  * meantime.
2427  */
2428  shdepLockAndCheckObject(DatabaseRelationId, datid);
2429 
2430  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2432  stmt->dbname);
2433 
2434  AlterSetting(datid, InvalidOid, stmt->setstmt);
2435 
2436  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2437 
2438  return datid;
2439 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2934
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
VariableSetStmt * setstmt
Definition: parsenodes.h:3427

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), AlterDatabaseSetStmt::dbname, get_database_oid(), GetUserId(), InvalidOid, OBJECT_DATABASE, object_ownercheck(), AlterDatabaseSetStmt::setstmt, shdepLockAndCheckObject(), and UnlockSharedObject().

Referenced by standard_ProcessUtility().

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 2861 of file dbcommands.c.

2862 {
2863  bool result = false;
2864  Relation rel;
2865  TableScanDesc scan;
2866  HeapTuple tuple;
2867 
2868  rel = table_open(TableSpaceRelationId, AccessShareLock);
2869  scan = table_beginscan_catalog(rel, 0, NULL);
2870  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2871  {
2872  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2873  Oid dsttablespace = spcform->oid;
2874  char *dstpath;
2875  struct stat st;
2876 
2877  /* Don't mess with the global tablespace */
2878  if (dsttablespace == GLOBALTABLESPACE_OID)
2879  continue;
2880 
2881  dstpath = GetDatabasePath(db_id, dsttablespace);
2882 
2883  if (lstat(dstpath, &st) == 0)
2884  {
2885  /* Found a conflicting file (or directory, whatever) */
2886  pfree(dstpath);
2887  result = true;
2888  break;
2889  }
2890 
2891  pfree(dstpath);
2892  }
2893 
2894  table_endscan(scan);
2896 
2897  return result;
2898 }
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1306
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:26
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
#define lstat(path, sb)
Definition: win32_port.h:287

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

1432 {
1433  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1434  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1435 
1436  if (!(ctype_encoding == encoding ||
1437  ctype_encoding == PG_SQL_ASCII ||
1438  ctype_encoding == -1 ||
1439 #ifdef WIN32
1440  encoding == PG_UTF8 ||
1441 #endif
1442  (encoding == PG_SQL_ASCII && superuser())))
1443  ereport(ERROR,
1444  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1445  errmsg("encoding \"%s\" does not match locale \"%s\"",
1447  ctype),
1448  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1449  pg_encoding_to_char(ctype_encoding))));
1450 
1451  if (!(collate_encoding == encoding ||
1452  collate_encoding == PG_SQL_ASCII ||
1453  collate_encoding == -1 ||
1454 #ifdef WIN32
1455  encoding == PG_UTF8 ||
1456 #endif
1457  (encoding == PG_SQL_ASCII && superuser())))
1458  ereport(ERROR,
1459  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1460  errmsg("encoding \"%s\" does not match locale \"%s\"",
1462  collate),
1463  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1464  pg_encoding_to_char(collate_encoding))));
1465 }
int errdetail(const char *fmt,...)
Definition: elog.c:1079
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:931
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
#define XLOG_DBASE_CREATE_FILE_COPY
#define stat
Definition: win32_port.h:286
#define S_ISDIR(m)
Definition: win32_port.h:327
#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:451
void XLogBeginInsert(void)
Definition: xloginsert.c:150
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71

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

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_icu_locale(), check_locale(), copyTemplateDependencies(), CountOtherDBBackends(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb_failure_callback(), CREATEDB_FILE_COPY, CREATEDB_WAL_LOG, CStringGetDatum(), CStringGetTextDatum, dbname, CreatedbStmt::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(), Int32GetDatum(), InvalidMultiXactId, InvalidOid, InvalidTransactionId, InvokeObjectPostCreateHook, is_encoding_supported_by_icu(), IsA, IsBinaryUpgrade, IsUnderPostmaster, lfirst, DefElem::location, LockSharedObject(), namein(), NoLock, object_aclcheck(), object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, CreatedbStmt::options, 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, 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 1469 of file dbcommands.c.

1470 {
1472 
1473  /*
1474  * If we were copying database at block levels then drop pages for the
1475  * destination database that are in the shared buffer cache. And tell
1476  * checkpointer to forget any pending fsync and unlink requests for files
1477  * in the database. The reasoning behind doing this is same as explained
1478  * in dropdb function. But unlike dropdb we don't need to call
1479  * pgstat_drop_database because this database is still not created so
1480  * there should not be any stat for this.
1481  */
1482  if (fparms->strategy == CREATEDB_WAL_LOG)
1483  {
1486 
1487  /* Release lock on the target database. */
1488  UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1489  AccessShareLock);
1490  }
1491 
1492  /*
1493  * Release lock on source database before doing recursive remove. This is
1494  * not essential but it seems desirable to release the lock as soon as
1495  * possible.
1496  */
1497  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1498 
1499  /* Throw away any successfully copied subdirectories */
1501 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3413
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2771
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1070
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660

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. */
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:1209
#define XLOG_DBASE_CREATE_WAL_LOG
int errcode_for_file_access(void)
Definition: elog.c:758
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3713
int CloseTransientFile(int fd)
Definition: fd.c:2609
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2433
#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
@ WAIT_EVENT_VERSION_FILE_WRITE
Definition: wait_event.h:222
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:268
static void pgstat_report_wait_end(void)
Definition: wait_event.h:284
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2512
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, WAIT_EVENT_VERSION_FILE_WRITE, write, XLOG_DBASE_CREATE_WAL_LOG, XLogBeginInsert(), XLogFlush(), XLogInsert(), and XLogRegisterData().

Referenced by CreateDatabaseUsingWalLog(), and dbase_redo().

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 3041 of file dbcommands.c.

3042 {
3043  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3044 
3045  /* Backup blocks are not used in dbase records */
3046  Assert(!XLogRecHasAnyBlockRefs(record));
3047 
3048  if (info == XLOG_DBASE_CREATE_FILE_COPY)
3049  {
3052  char *src_path;
3053  char *dst_path;
3054  char *parent_path;
3055  struct stat st;
3056 
3057  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3058  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3059 
3060  /*
3061  * Our theory for replaying a CREATE is to forcibly drop the target
3062  * subdirectory if present, then re-copy the source data. This may be
3063  * more work than needed, but it is simple to implement.
3064  */
3065  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3066  {
3067  if (!rmtree(dst_path, true))
3068  /* If this failed, copydir() below is going to error. */
3069  ereport(WARNING,
3070  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3071  dst_path)));
3072  }
3073 
3074  /*
3075  * If the parent of the target path doesn't exist, create it now. This
3076  * enables us to create the target underneath later.
3077  */
3078  parent_path = pstrdup(dst_path);
3079  get_parent_directory(parent_path);
3080  if (stat(parent_path, &st) < 0)
3081  {
3082  if (errno != ENOENT)
3083  ereport(FATAL,
3084  errmsg("could not stat directory \"%s\": %m",
3085  dst_path));
3086 
3087  /* create the parent directory if needed and valid */
3088  recovery_create_dbdir(parent_path, true);
3089  }
3090  pfree(parent_path);
3091 
3092  /*
3093  * There's a case where the copy source directory is missing for the
3094  * same reason above. Create the emtpy source directory so that
3095  * copydir below doesn't fail. The directory will be dropped soon by
3096  * recovery.
3097  */
3098  if (stat(src_path, &st) < 0 && errno == ENOENT)
3099  recovery_create_dbdir(src_path, false);
3100 
3101  /*
3102  * Force dirty buffers out to disk, to ensure source database is
3103  * up-to-date for the copy.
3104  */
3106 
3107  /* Close all sgmr fds in all backends. */
3109 
3110  /*
3111  * Copy this subdirectory to the new location
3112  *
3113  * We don't need to copy subdirectories
3114  */
3115  copydir(src_path, dst_path, false);
3116 
3117  pfree(src_path);
3118  pfree(dst_path);
3119  }
3120  else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3121  {
3124  char *dbpath;
3125  char *parent_path;
3126 
3127  dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3128 
3129  /* create the parent directory if needed and valid */
3130  parent_path = pstrdup(dbpath);
3131  get_parent_directory(parent_path);
3132  recovery_create_dbdir(parent_path, true);
3133 
3134  /* Create the database directory with the version file. */
3135  CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3136  true);
3137  pfree(dbpath);
3138  }
3139  else if (info == XLOG_DBASE_DROP)
3140  {
3141  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
3142  char *dst_path;
3143  int i;
3144 
3145  if (InHotStandby)
3146  {
3147  /*
3148  * Lock database while we resolve conflicts to ensure that
3149  * InitPostgres() cannot fully re-execute concurrently. This
3150  * avoids backends re-connecting automatically to same database,
3151  * which can happen in some cases.
3152  *
3153  * This will lock out walsenders trying to connect to db-specific
3154  * slots for logical decoding too, so it's safe for us to drop
3155  * slots.
3156  */
3157  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3159  }
3160 
3161  /* Drop any database-specific replication slots */
3163 
3164  /* Drop pages for this database that are in the shared buffer cache */
3165  DropDatabaseBuffers(xlrec->db_id);
3166 
3167  /* Also, clean out any fsync requests that might be pending in md.c */
3169 
3170  /* Clean out the xlog relcache too */
3171  XLogDropDatabase(xlrec->db_id);
3172 
3173  /* Close all sgmr fds in all backends. */
3175 
3176  for (i = 0; i < xlrec->ntablespaces; i++)
3177  {
3178  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3179 
3180  /* And remove the physical files */
3181  if (!rmtree(dst_path, true))
3182  ereport(WARNING,
3183  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3184  dst_path)));
3185  pfree(dst_path);
3186  }
3187 
3188  if (InHotStandby)
3189  {
3190  /*
3191  * Release locks prior to commit. XXX There is a race condition
3192  * here that may allow backends to reconnect, but the window for
3193  * this is small because the gap between here and commit is mostly
3194  * fairly small and it is unlikely that people will be dropping
3195  * databases that we are trying to connect to anyway.
3196  */
3197  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3198  }
3199  }
3200  else
3201  elog(PANIC, "dbase_redo: unknown op code %u", info);
3202 }
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3868
unsigned char uint8
Definition: c.h:440
static void recovery_create_dbdir(char *path, bool only_tblspc)
Definition: dbcommands.c:3012
#define XLOG_DBASE_DROP
#define FATAL
Definition: elog.h:37
#define PANIC
Definition: elog.h:38
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:1483
void get_parent_directory(char *path)
Definition: path.c:977
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:392
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:332
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:52
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1043
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:563
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:411
#define XLogRecGetData(decoder)
Definition: xlogreader.h:416
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:418
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:669
#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 2149 of file dbcommands.c.

2150 {
2151  bool force = false;
2152  ListCell *lc;
2153 
2154  foreach(lc, stmt->options)
2155  {
2156  DefElem *opt = (DefElem *) lfirst(lc);
2157 
2158  if (strcmp(opt->defname, "force") == 0)
2159  force = true;
2160  else
2161  ereport(ERROR,
2162  (errcode(ERRCODE_SYNTAX_ERROR),
2163  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2164  parser_errposition(pstate, opt->location)));
2165  }
2166 
2167  dropdb(stmt->dbname, stmt->missing_ok, force);
2168 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1508
List * options
Definition: parsenodes.h:3439
char * dbname
Definition: parsenodes.h:3437
bool missing_ok
Definition: parsenodes.h:3438

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1508 of file dbcommands.c.

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

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

Referenced by DropDatabase().

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 2904 of file dbcommands.c.

2905 {
2906  if (notherbackends > 0 && npreparedxacts > 0)
2907 
2908  /*
2909  * We don't deal with singular versus plural here, since gettext
2910  * doesn't support multiple plurals in one string.
2911  */
2912  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2913  notherbackends, npreparedxacts);
2914  else if (notherbackends > 0)
2915  errdetail_plural("There is %d other session using the database.",
2916  "There are %d other sessions using the database.",
2917  notherbackends,
2918  notherbackends);
2919  else
2920  errdetail_plural("There is %d prepared transaction using the database.",
2921  "There are %d prepared transactions using the database.",
2922  npreparedxacts,
2923  npreparedxacts);
2924  return 0; /* just to keep ereport macro happy */
2925 }

References errdetail(), and errdetail_plural().

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

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 2981 of file dbcommands.c.

2982 {
2983  HeapTuple dbtuple;
2984  char *result;
2985 
2986  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2987  if (HeapTupleIsValid(dbtuple))
2988  {
2989  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2990  ReleaseSysCache(dbtuple);
2991  }
2992  else
2993  result = NULL;
2994 
2995  return result;
2996 }
#define NameStr(name)
Definition: c.h:682
NameData datname
Definition: pg_database.h:35

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 2934 of file dbcommands.c.

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

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 *  dbLocProvider,
char **  dbCollversion 
)
static

Definition at line 2598 of file dbcommands.c.

2605 {
2606  bool result = false;
2607  Relation relation;
2608 
2609  Assert(name);
2610 
2611  /* Caller may wish to grab a better lock on pg_database beforehand... */
2612  relation = table_open(DatabaseRelationId, AccessShareLock);
2613 
2614  /*
2615  * Loop covers the rare case where the database is renamed before we can
2616  * lock it. We try again just in case we can find a new one of the same
2617  * name.
2618  */
2619  for (;;)
2620  {
2621  ScanKeyData scanKey;
2622  SysScanDesc scan;
2623  HeapTuple tuple;
2624  Oid dbOid;
2625 
2626  /*
2627  * there's no syscache for database-indexed-by-name, so must do it the
2628  * hard way
2629  */
2630  ScanKeyInit(&scanKey,
2631  Anum_pg_database_datname,
2632  BTEqualStrategyNumber, F_NAMEEQ,
2634 
2635  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2636  NULL, 1, &scanKey);
2637 
2638  tuple = systable_getnext(scan);
2639 
2640  if (!HeapTupleIsValid(tuple))
2641  {
2642  /* definitely no database of that name */
2643  systable_endscan(scan);
2644  break;
2645  }
2646 
2647  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2648 
2649  systable_endscan(scan);
2650 
2651  /*
2652  * Now that we have a database OID, we can try to lock the DB.
2653  */
2654  if (lockmode != NoLock)
2655  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2656 
2657  /*
2658  * And now, re-fetch the tuple by OID. If it's still there and still
2659  * the same name, we win; else, drop the lock and loop back to try
2660  * again.
2661  */
2662  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
2663  if (HeapTupleIsValid(tuple))
2664  {
2665  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
2666 
2667  if (strcmp(name, NameStr(dbform->datname)) == 0)
2668  {
2669  Datum datum;
2670  bool isnull;
2671 
2672  /* oid of the database */
2673  if (dbIdP)
2674  *dbIdP = dbOid;
2675  /* oid of the owner */
2676  if (ownerIdP)
2677  *ownerIdP = dbform->datdba;
2678  /* character encoding */
2679  if (encodingP)
2680  *encodingP = dbform->encoding;
2681  /* allowed as template? */
2682  if (dbIsTemplateP)
2683  *dbIsTemplateP = dbform->datistemplate;
2684  /* allowing connections? */
2685  if (dbAllowConnP)
2686  *dbAllowConnP = dbform->datallowconn;
2687  /* limit of frozen XIDs */
2688  if (dbFrozenXidP)
2689  *dbFrozenXidP = dbform->datfrozenxid;
2690  /* minimum MultiXactId */
2691  if (dbMinMultiP)
2692  *dbMinMultiP = dbform->datminmxid;
2693  /* default tablespace for this database */
2694  if (dbTablespace)
2695  *dbTablespace = dbform->dattablespace;
2696  /* default locale settings for this database */
2697  if (dbLocProvider)
2698  *dbLocProvider = dbform->datlocprovider;
2699  if (dbCollate)
2700  {
2701  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollate, &isnull);
2702  Assert(!isnull);
2703  *dbCollate = TextDatumGetCString(datum);
2704  }
2705  if (dbCtype)
2706  {
2707  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datctype, &isnull);
2708  Assert(!isnull);
2709  *dbCtype = TextDatumGetCString(datum);
2710  }
2711  if (dbIculocale)
2712  {
2713  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticulocale, &isnull);
2714  if (isnull)
2715  *dbIculocale = NULL;
2716  else
2717  *dbIculocale = TextDatumGetCString(datum);
2718  }
2719  if (dbCollversion)
2720  {
2721  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
2722  if (isnull)
2723  *dbCollversion = NULL;
2724  else
2725  *dbCollversion = TextDatumGetCString(datum);
2726  }
2727  ReleaseSysCache(tuple);
2728  result = true;
2729  break;
2730  }
2731  /* can only get here if it was just renamed */
2732  ReleaseSysCache(tuple);
2733  }
2734 
2735  if (lockmode != NoLock)
2736  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2737  }
2738 
2739  table_close(relation, AccessShareLock);
2740 
2741  return result;
2742 }
const char * name
Definition: encode.c:561
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434

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

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

◆ have_createdb_privilege()

static bool have_createdb_privilege ( void  )
static

Definition at line 2746 of file dbcommands.c.

2747 {
2748  bool result = false;
2749  HeapTuple utup;
2750 
2751  /* Superusers can always do everything */
2752  if (superuser())
2753  return true;
2754 
2756  if (HeapTupleIsValid(utup))
2757  {
2758  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2759  ReleaseSysCache(utup);
2760  }
2761  return result;
2762 }
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(), createdb(), and RenameDatabase().

◆ movedb()

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

Definition at line 1812 of file dbcommands.c.

1813 {
1814  Oid db_id;
1815  Relation pgdbrel;
1816  int notherbackends;
1817  int npreparedxacts;
1818  HeapTuple oldtuple,
1819  newtuple;
1820  Oid src_tblspcoid,
1821  dst_tblspcoid;
1822  ScanKeyData scankey;
1823  SysScanDesc sysscan;
1824  AclResult aclresult;
1825  char *src_dbpath;
1826  char *dst_dbpath;
1827  DIR *dstdir;
1828  struct dirent *xlde;
1829  movedb_failure_params fparms;
1830 
1831  /*
1832  * Look up the target database's OID, and get exclusive lock on it. We
1833  * need this to ensure that no new backend starts up in the database while
1834  * we are moving it, and that no one is using it as a CREATE DATABASE
1835  * template or trying to delete it.
1836  */
1837  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1838 
1839  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1840  NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL, NULL, NULL, NULL))
1841  ereport(ERROR,
1842  (errcode(ERRCODE_UNDEFINED_DATABASE),
1843  errmsg("database \"%s\" does not exist", dbname)));
1844 
1845  /*
1846  * We actually need a session lock, so that the lock will persist across
1847  * the commit/restart below. (We could almost get away with letting the
1848  * lock be released at commit, except that someone could try to move
1849  * relations of the DB back into the old directory while we rmtree() it.)
1850  */
1851  LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1853 
1854  /*
1855  * Permission checks
1856  */
1857  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1859  dbname);
1860 
1861  /*
1862  * Obviously can't move the tables of my own database
1863  */
1864  if (db_id == MyDatabaseId)
1865  ereport(ERROR,
1866  (errcode(ERRCODE_OBJECT_IN_USE),
1867  errmsg("cannot change the tablespace of the currently open database")));
1868 
1869  /*
1870  * Get tablespace's oid
1871  */
1872  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1873 
1874  /*
1875  * Permission checks
1876  */
1877  aclresult = object_aclcheck(TableSpaceRelationId, dst_tblspcoid, GetUserId(),
1878  ACL_CREATE);
1879  if (aclresult != ACLCHECK_OK)
1880  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1881  tblspcname);
1882 
1883  /*
1884  * pg_global must never be the default tablespace
1885  */
1886  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1887  ereport(ERROR,
1888  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1889  errmsg("pg_global cannot be used as default tablespace")));
1890 
1891  /*
1892  * No-op if same tablespace
1893  */
1894  if (src_tblspcoid == dst_tblspcoid)
1895  {
1896  table_close(pgdbrel, NoLock);
1897  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1899  return;
1900  }
1901 
1902  /*
1903  * Check for other backends in the target database. (Because we hold the
1904  * database lock, no new ones can start after this.)
1905  *
1906  * As in CREATE DATABASE, check this after other error conditions.
1907  */
1908  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1909  ereport(ERROR,
1910  (errcode(ERRCODE_OBJECT_IN_USE),
1911  errmsg("database \"%s\" is being accessed by other users",
1912  dbname),
1913  errdetail_busy_db(notherbackends, npreparedxacts)));
1914 
1915  /*
1916  * Get old and new database paths
1917  */
1918  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1919  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1920 
1921  /*
1922  * Force a checkpoint before proceeding. This will force all dirty
1923  * buffers, including those of unlogged tables, out to disk, to ensure
1924  * source database is up-to-date on disk for the copy.
1925  * FlushDatabaseBuffers() would suffice for that, but we also want to
1926  * process any pending unlink requests. Otherwise, the check for existing
1927  * files in the target directory might fail unnecessarily, not to mention
1928  * that the copy might fail due to source files getting deleted under it.
1929  * On Windows, this also ensures that background procs don't hold any open
1930  * files, which would cause rmdir() to fail.
1931  */
1934 
1935  /* Close all smgr fds in all backends. */
1937 
1938  /*
1939  * Now drop all buffers holding data of the target database; they should
1940  * no longer be dirty so DropDatabaseBuffers is safe.
1941  *
1942  * It might seem that we could just let these buffers age out of shared
1943  * buffers naturally, since they should not get referenced anymore. The
1944  * problem with that is that if the user later moves the database back to
1945  * its original tablespace, any still-surviving buffers would appear to
1946  * contain valid data again --- but they'd be missing any changes made in
1947  * the database while it was in the new tablespace. In any case, freeing
1948  * buffers that should never be used again seems worth the cycles.
1949  *
1950  * Note: it'd be sufficient to get rid of buffers matching db_id and
1951  * src_tblspcoid, but bufmgr.c presently provides no API for that.
1952  */
1953  DropDatabaseBuffers(db_id);
1954 
1955  /*
1956  * Check for existence of files in the target directory, i.e., objects of
1957  * this database that are already in the target tablespace. We can't
1958  * allow the move in such a case, because we would need to change those
1959  * relations' pg_class.reltablespace entries to zero, and we don't have
1960  * access to the DB's pg_class to do so.
1961  */
1962  dstdir = AllocateDir(dst_dbpath);
1963  if (dstdir != NULL)
1964  {
1965  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1966  {
1967  if (strcmp(xlde->d_name, ".") == 0 ||
1968  strcmp(xlde->d_name, "..") == 0)
1969  continue;
1970 
1971  ereport(ERROR,
1972  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1973  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1974  dbname, tblspcname),
1975  errhint("You must move them back to the database's default tablespace before using this command.")));
1976  }
1977 
1978  FreeDir(dstdir);
1979 
1980  /*
1981  * The directory exists but is empty. We must remove it before using
1982  * the copydir function.
1983  */
1984  if (rmdir(dst_dbpath) != 0)
1985  elog(ERROR, "could not remove directory \"%s\": %m",
1986  dst_dbpath);
1987  }
1988 
1989  /*
1990  * Use an ENSURE block to make sure we remove the debris if the copy fails
1991  * (eg, due to out-of-disk-space). This is not a 100% solution, because
1992  * of the possibility of failure during transaction commit, but it should
1993  * handle most scenarios.
1994  */
1995  fparms.dest_dboid = db_id;
1996  fparms.dest_tsoid = dst_tblspcoid;
1998  PointerGetDatum(&fparms));
1999  {
2000  Datum new_record[Natts_pg_database] = {0};
2001  bool new_record_nulls[Natts_pg_database] = {0};
2002  bool new_record_repl[Natts_pg_database] = {0};
2003 
2004  /*
2005  * Copy files from the old tablespace to the new one
2006  */
2007  copydir(src_dbpath, dst_dbpath, false);
2008 
2009  /*
2010  * Record the filesystem change in XLOG
2011  */
2012  {
2014 
2015  xlrec.db_id = db_id;
2016  xlrec.tablespace_id = dst_tblspcoid;
2017  xlrec.src_db_id = db_id;
2018  xlrec.src_tablespace_id = src_tblspcoid;
2019 
2020  XLogBeginInsert();
2021  XLogRegisterData((char *) &xlrec,
2023 
2024  (void) XLogInsert(RM_DBASE_ID,
2026  }
2027 
2028  /*
2029  * Update the database's pg_database tuple
2030  */
2031  ScanKeyInit(&scankey,
2032  Anum_pg_database_datname,
2033  BTEqualStrategyNumber, F_NAMEEQ,
2035  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
2036  NULL, 1, &scankey);
2037  oldtuple = systable_getnext(sysscan);
2038  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2039  ereport(ERROR,
2040  (errcode(ERRCODE_UNDEFINED_DATABASE),
2041  errmsg("database \"%s\" does not exist", dbname)));
2042 
2043  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
2044  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
2045 
2046  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2047  new_record,
2048  new_record_nulls, new_record_repl);
2049  CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2050 
2051  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2052 
2053  systable_endscan(sysscan);
2054 
2055  /*
2056  * Force another checkpoint here. As in CREATE DATABASE, this is to
2057  * ensure that we don't have to replay a committed
2058  * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2059  * any unlogged operations done in the new DB tablespace before the
2060  * next checkpoint.
2061  */
2063 
2064  /*
2065  * Force synchronous commit, thus minimizing the window between
2066  * copying the database files and committal of the transaction. If we
2067  * crash before committing, we'll leave an orphaned set of files on
2068  * disk, which is not fatal but not good either.
2069  */
2070  ForceSyncCommit();
2071 
2072  /*
2073  * Close pg_database, but keep lock till commit.
2074  */
2075  table_close(pgdbrel, NoLock);
2076  }
2078  PointerGetDatum(&fparms));
2079 
2080  /*
2081  * Commit the transaction so that the pg_database update is committed. If
2082  * we crash while removing files, the database won't be corrupt, we'll
2083  * just leave some orphaned files in the old directory.
2084  *
2085  * (This is OK because we know we aren't inside a transaction block.)
2086  *
2087  * XXX would it be safe/better to do this inside the ensure block? Not
2088  * convinced it's a good idea; consider elog just after the transaction
2089  * really commits.
2090  */
2093 
2094  /* Start new transaction for the remaining work; don't need a snapshot */
2096 
2097  /*
2098  * Remove files from the old tablespace
2099  */
2100  if (!rmtree(src_dbpath, true))
2101  ereport(WARNING,
2102  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2103  src_dbpath)));
2104 
2105  /*
2106  * Record the filesystem change in XLOG
2107  */
2108  {
2109  xl_dbase_drop_rec xlrec;
2110 
2111  xlrec.db_id = db_id;
2112  xlrec.ntablespaces = 1;
2113 
2114  XLogBeginInsert();
2115  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
2116  XLogRegisterData((char *) &src_tblspcoid, sizeof(Oid));
2117 
2118  (void) XLogInsert(RM_DBASE_ID,
2120  }
2121 
2122  /* Now it's safe to release the database lock */
2123  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
2125 
2126  pfree(src_dbpath);
2127  pfree(dst_dbpath);
2128 }
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:2132
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2709
int FreeDir(DIR *dir)
Definition: fd.c:2761
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2643
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
void StartTransactionCommand(void)
Definition: xact.c:2925
void CommitTransactionCommand(void)
Definition: xact.c:3022

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

2133 {
2135  char *dstpath;
2136 
2137  /* Get rid of anything we managed to copy to the target directory */
2138  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2139 
2140  (void) rmtree(dstpath, true);
2141 
2142  pfree(dstpath);
2143 }

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

2557 {
2558  Oid dbid = PG_GETARG_OID(0);
2559  HeapTuple tp;
2560  char datlocprovider;
2561  Datum datum;
2562  bool isnull;
2563  char *version;
2564 
2566  if (!HeapTupleIsValid(tp))
2567  ereport(ERROR,
2568  (errcode(ERRCODE_UNDEFINED_OBJECT),
2569  errmsg("database with OID %u does not exist", dbid)));
2570 
2572 
2573  datum = SysCacheGetAttr(DATABASEOID, tp, datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, &isnull);
2574  if (isnull)
2575  elog(ERROR, "unexpected null in pg_database");
2577 
2578  ReleaseSysCache(tp);
2579 
2580  if (version)
2582  else
2583  PG_RETURN_NULL();
2584 }
#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:189

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

◆ recovery_create_dbdir()

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

Definition at line 3012 of file dbcommands.c.

3013 {
3014  struct stat st;
3015 
3017 
3018  if (stat(path, &st) == 0)
3019  return;
3020 
3021  if (only_tblspc && strstr(path, "pg_tblspc/") == NULL)
3022  elog(PANIC, "requested to created invalid directory: %s", path);
3023 
3025  ereport(PANIC,
3026  errmsg("missing directory \"%s\"", path));
3027 
3029  "creating missing directory: %s", path);
3030 
3031  if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3032  ereport(PANIC,
3033  errmsg("could not create missing directory \"%s\": %m", path));
3034 }
bool allow_in_place_tablespaces
Definition: tablespace.c:91
#define DEBUG1
Definition: elog.h:26
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:5912
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 2771 of file dbcommands.c.

2772 {
2773  Relation rel;
2774  TableScanDesc scan;
2775  HeapTuple tuple;
2776  List *ltblspc = NIL;
2777  ListCell *cell;
2778  int ntblspc;
2779  int i;
2780  Oid *tablespace_ids;
2781 
2782  rel = table_open(TableSpaceRelationId, AccessShareLock);
2783  scan = table_beginscan_catalog(rel, 0, NULL);
2784  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2785  {
2786  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2787  Oid dsttablespace = spcform->oid;
2788  char *dstpath;
2789  struct stat st;
2790 
2791  /* Don't mess with the global tablespace */
2792  if (dsttablespace == GLOBALTABLESPACE_OID)
2793  continue;
2794 
2795  dstpath = GetDatabasePath(db_id, dsttablespace);
2796 
2797  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
2798  {
2799  /* Assume we can ignore it */
2800  pfree(dstpath);
2801  continue;
2802  }
2803 
2804  if (!rmtree(dstpath, true))
2805  ereport(WARNING,
2806  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2807  dstpath)));
2808 
2809  ltblspc = lappend_oid(ltblspc, dsttablespace);
2810  pfree(dstpath);
2811  }
2812 
2813  ntblspc = list_length(ltblspc);
2814  if (ntblspc == 0)
2815  {
2816  table_endscan(scan);
2818  return;
2819  }
2820 
2821  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
2822  i = 0;
2823  foreach(cell, ltblspc)
2824  tablespace_ids[i++] = lfirst_oid(cell);
2825 
2826  /* Record the filesystem change in XLOG */
2827  {
2828  xl_dbase_drop_rec xlrec;
2829 
2830  xlrec.db_id = db_id;
2831  xlrec.ntablespaces = ntblspc;
2832 
2833  XLogBeginInsert();
2834  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
2835  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
2836 
2837  (void) XLogInsert(RM_DBASE_ID,
2839  }
2840 
2841  list_free(ltblspc);
2842  pfree(tablespace_ids);
2843 
2844  table_endscan(scan);
2846 }
#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:1199
#define lfirst_oid(lc)
Definition: pg_list.h:172

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

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

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), CountOtherDBBackends(), DATABASEOID, datname, elog(), ereport, errcode(), errdetail_busy_db(), errmsg(), ERROR, get_database_oid(), get_db_info(), GETSTRUCT, GetUserId(), have_createdb_privilege(), HeapTupleIsValid, InvokeObjectPostAlterHook, MyDatabaseId, namestrcpy(), NoLock, OBJECT_DATABASE, 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, false);
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:3954
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4172
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition: bufmgr.c:799
@ BAS_BULKREAD
Definition: bufmgr.h:30
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:106
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:280
@ RBM_NORMAL
Definition: bufmgr.h:39
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:579
void smgrclose(SMgrRelation reln)
Definition: smgr.c:256
SMgrRelation smgropen(RelFileLocator rlocator, BackendId backend)
Definition: smgr.c:146
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:326

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