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

Go to the source code of this file.

Data Structures

struct  createdb_failure_params
 
struct  movedb_failure_params
 
struct  CreateDBRelInfo
 

Typedefs

typedef enum CreateDBStrategy CreateDBStrategy
 
typedef struct CreateDBRelInfo CreateDBRelInfo
 

Enumerations

enum  CreateDBStrategy { CREATEDB_WAL_LOG , CREATEDB_FILE_COPY }
 

Functions

static void createdb_failure_callback (int code, Datum arg)
 
static void movedb (const char *dbname, const char *tblspcname)
 
static void movedb_failure_callback (int code, Datum arg)
 
static bool get_db_info (const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbIculocale, char **dbIcurules, char *dbLocProvider, char **dbCollversion)
 
static void remove_dbtablespaces (Oid db_id)
 
static bool check_db_file_conflict (Oid db_id)
 
static int errdetail_busy_db (int notherbackends, int npreparedxacts)
 
static void CreateDatabaseUsingWalLog (Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
 
static ListScanSourceDatabasePgClass (Oid tbid, Oid dbid, char *srcpath)
 
static ListScanSourceDatabasePgClassPage (Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
 
static CreateDBRelInfoScanSourceDatabasePgClassTuple (HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
 
static void CreateDirAndVersionFile (char *dbpath, Oid dbid, Oid tsid, bool isRedo)
 
static void CreateDatabaseUsingFileCopy (Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
 
static void recovery_create_dbdir (char *path, bool only_tblspc)
 
Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 
void dropdb (const char *dbname, bool missing_ok, bool force)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterDatabaseRefreshColl (AlterDatabaseRefreshCollStmt *stmt)
 
Oid AlterDatabaseSet (AlterDatabaseSetStmt *stmt)
 
ObjectAddress AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
Datum pg_database_collation_actual_version (PG_FUNCTION_ARGS)
 
bool have_createdb_privilege (void)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
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 2212 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2484 of file dbcommands.c.

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

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)

Definition at line 2375 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2458 of file dbcommands.c.

2459 {
2460  Oid datid = get_database_oid(stmt->dbname, false);
2461 
2462  /*
2463  * Obtain a lock on the database and make sure it didn't go away in the
2464  * meantime.
2465  */
2466  shdepLockAndCheckObject(DatabaseRelationId, datid);
2467 
2468  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2470  stmt->dbname);
2471 
2472  AlterSetting(datid, InvalidOid, stmt->setstmt);
2473 
2474  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2475 
2476  return datid;
2477 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2981
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1067
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1166

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

Referenced by standard_ProcessUtility().

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 2908 of file dbcommands.c.

2909 {
2910  bool result = false;
2911  Relation rel;
2912  TableScanDesc scan;
2913  HeapTuple tuple;
2914 
2915  rel = table_open(TableSpaceRelationId, AccessShareLock);
2916  scan = table_beginscan_catalog(rel, 0, NULL);
2917  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2918  {
2919  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2920  Oid dsttablespace = spcform->oid;
2921  char *dstpath;
2922  struct stat st;
2923 
2924  /* Don't mess with the global tablespace */
2925  if (dsttablespace == GLOBALTABLESPACE_OID)
2926  continue;
2927 
2928  dstpath = GetDatabasePath(db_id, dsttablespace);
2929 
2930  if (lstat(dstpath, &st) == 0)
2931  {
2932  /* Found a conflicting file (or directory, whatever) */
2933  pfree(dstpath);
2934  result = true;
2935  break;
2936  }
2937 
2938  pfree(dstpath);
2939  }
2940 
2941  table_endscan(scan);
2943 
2944  return result;
2945 }
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1093
void pfree(void *pointer)
Definition: mcxt.c:1436
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1011
#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 1469 of file dbcommands.c.

1470 {
1471  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1472  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1473 
1474  if (!(ctype_encoding == encoding ||
1475  ctype_encoding == PG_SQL_ASCII ||
1476  ctype_encoding == -1 ||
1477 #ifdef WIN32
1478  encoding == PG_UTF8 ||
1479 #endif
1480  (encoding == PG_SQL_ASCII && superuser())))
1481  ereport(ERROR,
1482  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1483  errmsg("encoding \"%s\" does not match locale \"%s\"",
1485  ctype),
1486  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1487  pg_encoding_to_char(ctype_encoding))));
1488 
1489  if (!(collate_encoding == encoding ||
1490  collate_encoding == PG_SQL_ASCII ||
1491  collate_encoding == -1 ||
1492 #ifdef WIN32
1493  encoding == PG_UTF8 ||
1494 #endif
1495  (encoding == PG_SQL_ASCII && superuser())))
1496  ereport(ERROR,
1497  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1498  errmsg("encoding \"%s\" does not match locale \"%s\"",
1500  collate),
1501  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1502  pg_encoding_to_char(collate_encoding))));
1503 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
bool superuser(void)
Definition: superuser.c:46

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

Referenced by createdb(), and DefineCollation().

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

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

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

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1507 of file dbcommands.c.

1508 {
1510 
1511  /*
1512  * If we were copying database at block levels then drop pages for the
1513  * destination database that are in the shared buffer cache. And tell
1514  * checkpointer to forget any pending fsync and unlink requests for files
1515  * in the database. The reasoning behind doing this is same as explained
1516  * in dropdb function. But unlike dropdb we don't need to call
1517  * pgstat_drop_database because this database is still not created so
1518  * there should not be any stat for this.
1519  */
1520  if (fparms->strategy == CREATEDB_WAL_LOG)
1521  {
1524 
1525  /* Release lock on the target database. */
1526  UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1527  AccessShareLock);
1528  }
1529 
1530  /*
1531  * Release lock on source database before doing recursive remove. This is
1532  * not essential but it seems desirable to release the lock as soon as
1533  * possible.
1534  */
1535  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1536 
1537  /* Throw away any successfully copied subdirectories */
1539 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3484
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2818
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1092
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312

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

Referenced by createdb().

◆ CreateDirAndVersionFile()

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

Definition at line 457 of file dbcommands.c.

458 {
459  int fd;
460  int nbytes;
461  char versionfile[MAXPGPATH];
462  char buf[16];
463 
464  /*
465  * Prepare version data before starting a critical section.
466  *
467  * Note that we don't have to copy this from the source database; there's
468  * only one legal value.
469  */
470  sprintf(buf, "%s\n", PG_MAJORVERSION);
471  nbytes = strlen(PG_MAJORVERSION) + 1;
472 
473  /* If we are not in WAL replay then write the WAL. */
474  if (!isRedo)
475  {
477  XLogRecPtr lsn;
478 
480 
481  xlrec.db_id = dbid;
482  xlrec.tablespace_id = tsid;
483 
484  XLogBeginInsert();
485  XLogRegisterData((char *) (&xlrec),
487 
488  lsn = XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
489 
490  /* As always, WAL must hit the disk before the data update does. */
491  XLogFlush(lsn);
492  }
493 
494  /* Create database directory. */
495  if (MakePGDirectory(dbpath) < 0)
496  {
497  /* Failure other than already exists or not in WAL replay? */
498  if (errno != EEXIST || !isRedo)
499  ereport(ERROR,
501  errmsg("could not create directory \"%s\": %m", dbpath)));
502  }
503 
504  /*
505  * Create PG_VERSION file in the database path. If the file already
506  * exists and we are in WAL replay then try again to open it in write
507  * mode.
508  */
509  snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
510 
511  fd = OpenTransientFile(versionfile, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY);
512  if (fd < 0 && errno == EEXIST && isRedo)
513  fd = OpenTransientFile(versionfile, O_WRONLY | O_TRUNC | PG_BINARY);
514 
515  if (fd < 0)
516  ereport(ERROR,
518  errmsg("could not create file \"%s\": %m", versionfile)));
519 
520  /* Write PG_MAJORVERSION in the PG_VERSION file. */
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:1260
#define XLOG_DBASE_CREATE_WAL_LOG
int errcode_for_file_access(void)
Definition: elog.c:881
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3714
int CloseTransientFile(int fd)
Definition: fd.c:2610
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2434
#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:225
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:271
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2514
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 3088 of file dbcommands.c.

3089 {
3090  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3091 
3092  /* Backup blocks are not used in dbase records */
3093  Assert(!XLogRecHasAnyBlockRefs(record));
3094 
3095  if (info == XLOG_DBASE_CREATE_FILE_COPY)
3096  {
3099  char *src_path;
3100  char *dst_path;
3101  char *parent_path;
3102  struct stat st;
3103 
3104  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3105  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3106 
3107  /*
3108  * Our theory for replaying a CREATE is to forcibly drop the target
3109  * subdirectory if present, then re-copy the source data. This may be
3110  * more work than needed, but it is simple to implement.
3111  */
3112  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3113  {
3114  if (!rmtree(dst_path, true))
3115  /* If this failed, copydir() below is going to error. */
3116  ereport(WARNING,
3117  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3118  dst_path)));
3119  }
3120 
3121  /*
3122  * If the parent of the target path doesn't exist, create it now. This
3123  * enables us to create the target underneath later.
3124  */
3125  parent_path = pstrdup(dst_path);
3126  get_parent_directory(parent_path);
3127  if (stat(parent_path, &st) < 0)
3128  {
3129  if (errno != ENOENT)
3130  ereport(FATAL,
3131  errmsg("could not stat directory \"%s\": %m",
3132  dst_path));
3133 
3134  /* create the parent directory if needed and valid */
3135  recovery_create_dbdir(parent_path, true);
3136  }
3137  pfree(parent_path);
3138 
3139  /*
3140  * There's a case where the copy source directory is missing for the
3141  * same reason above. Create the empty source directory so that
3142  * copydir below doesn't fail. The directory will be dropped soon by
3143  * recovery.
3144  */
3145  if (stat(src_path, &st) < 0 && errno == ENOENT)
3146  recovery_create_dbdir(src_path, false);
3147 
3148  /*
3149  * Force dirty buffers out to disk, to ensure source database is
3150  * up-to-date for the copy.
3151  */
3153 
3154  /* Close all sgmr fds in all backends. */
3156 
3157  /*
3158  * Copy this subdirectory to the new location
3159  *
3160  * We don't need to copy subdirectories
3161  */
3162  copydir(src_path, dst_path, false);
3163 
3164  pfree(src_path);
3165  pfree(dst_path);
3166  }
3167  else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3168  {
3171  char *dbpath;
3172  char *parent_path;
3173 
3174  dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3175 
3176  /* create the parent directory if needed and valid */
3177  parent_path = pstrdup(dbpath);
3178  get_parent_directory(parent_path);
3179  recovery_create_dbdir(parent_path, true);
3180 
3181  /* Create the database directory with the version file. */
3182  CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3183  true);
3184  pfree(dbpath);
3185  }
3186  else if (info == XLOG_DBASE_DROP)
3187  {
3188  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
3189  char *dst_path;
3190  int i;
3191 
3192  if (InHotStandby)
3193  {
3194  /*
3195  * Lock database while we resolve conflicts to ensure that
3196  * InitPostgres() cannot fully re-execute concurrently. This
3197  * avoids backends re-connecting automatically to same database,
3198  * which can happen in some cases.
3199  *
3200  * This will lock out walsenders trying to connect to db-specific
3201  * slots for logical decoding too, so it's safe for us to drop
3202  * slots.
3203  */
3204  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3206  }
3207 
3208  /* Drop any database-specific replication slots */
3210 
3211  /* Drop pages for this database that are in the shared buffer cache */
3212  DropDatabaseBuffers(xlrec->db_id);
3213 
3214  /* Also, clean out any fsync requests that might be pending in md.c */
3216 
3217  /* Clean out the xlog relcache too */
3218  XLogDropDatabase(xlrec->db_id);
3219 
3220  /* Close all sgmr fds in all backends. */
3222 
3223  for (i = 0; i < xlrec->ntablespaces; i++)
3224  {
3225  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3226 
3227  /* And remove the physical files */
3228  if (!rmtree(dst_path, true))
3229  ereport(WARNING,
3230  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3231  dst_path)));
3232  pfree(dst_path);
3233  }
3234 
3235  if (InHotStandby)
3236  {
3237  /*
3238  * Release locks prior to commit. XXX There is a race condition
3239  * here that may allow backends to reconnect, but the window for
3240  * this is small because the gap between here and commit is mostly
3241  * fairly small and it is unlikely that people will be dropping
3242  * databases that we are trying to connect to anyway.
3243  */
3244  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3245  }
3246  }
3247  else
3248  elog(PANIC, "dbase_redo: unknown op code %u", info);
3249 }
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3942
unsigned char uint8
Definition: c.h:488
static void recovery_create_dbdir(char *path, bool only_tblspc)
Definition: dbcommands.c:3059
#define XLOG_DBASE_DROP
#define FATAL
Definition: elog.h:41
#define PANIC
Definition: elog.h:42
int i
Definition: isn.c:73
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1106
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1088
#define AccessExclusiveLock
Definition: lockdefs.h:43
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void get_parent_directory(char *path)
Definition: path.c:977
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:393
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:333
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:53
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1043
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:555
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:409
#define XLogRecGetData(decoder)
Definition: xlogreader.h:414
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:416
#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 2187 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1546 of file dbcommands.c.

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

2952 {
2953  if (notherbackends > 0 && npreparedxacts > 0)
2954 
2955  /*
2956  * We don't deal with singular versus plural here, since gettext
2957  * doesn't support multiple plurals in one string.
2958  */
2959  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2960  notherbackends, npreparedxacts);
2961  else if (notherbackends > 0)
2962  errdetail_plural("There is %d other session using the database.",
2963  "There are %d other sessions using the database.",
2964  notherbackends,
2965  notherbackends);
2966  else
2967  errdetail_plural("There is %d prepared transaction using the database.",
2968  "There are %d prepared transactions using the database.",
2969  npreparedxacts,
2970  npreparedxacts);
2971  return 0; /* just to keep ereport macro happy */
2972 }

References errdetail(), and errdetail_plural().

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

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 3028 of file dbcommands.c.

3029 {
3030  HeapTuple dbtuple;
3031  char *result;
3032 
3033  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3034  if (HeapTupleIsValid(dbtuple))
3035  {
3036  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3037  ReleaseSysCache(dbtuple);
3038  }
3039  else
3040  result = NULL;
3041 
3042  return result;
3043 }
#define NameStr(name)
Definition: c.h:730
NameData datname
Definition: pg_database.h:35

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 2981 of file dbcommands.c.

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

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

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

◆ get_db_info()

static bool get_db_info ( const char *  name,
LOCKMODE  lockmode,
Oid dbIdP,
Oid ownerIdP,
int *  encodingP,
bool dbIsTemplateP,
bool dbAllowConnP,
TransactionId dbFrozenXidP,
MultiXactId dbMinMultiP,
Oid dbTablespace,
char **  dbCollate,
char **  dbCtype,
char **  dbIculocale,
char **  dbIcurules,
char *  dbLocProvider,
char **  dbCollversion 
)
static

Definition at line 2636 of file dbcommands.c.

2644 {
2645  bool result = false;
2646  Relation relation;
2647 
2648  Assert(name);
2649 
2650  /* Caller may wish to grab a better lock on pg_database beforehand... */
2651  relation = table_open(DatabaseRelationId, AccessShareLock);
2652 
2653  /*
2654  * Loop covers the rare case where the database is renamed before we can
2655  * lock it. We try again just in case we can find a new one of the same
2656  * name.
2657  */
2658  for (;;)
2659  {
2660  ScanKeyData scanKey;
2661  SysScanDesc scan;
2662  HeapTuple tuple;
2663  Oid dbOid;
2664 
2665  /*
2666  * there's no syscache for database-indexed-by-name, so must do it the
2667  * hard way
2668  */
2669  ScanKeyInit(&scanKey,
2670  Anum_pg_database_datname,
2671  BTEqualStrategyNumber, F_NAMEEQ,
2673 
2674  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2675  NULL, 1, &scanKey);
2676 
2677  tuple = systable_getnext(scan);
2678 
2679  if (!HeapTupleIsValid(tuple))
2680  {
2681  /* definitely no database of that name */
2682  systable_endscan(scan);
2683  break;
2684  }
2685 
2686  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2687 
2688  systable_endscan(scan);
2689 
2690  /*
2691  * Now that we have a database OID, we can try to lock the DB.
2692  */
2693  if (lockmode != NoLock)
2694  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2695 
2696  /*
2697  * And now, re-fetch the tuple by OID. If it's still there and still
2698  * the same name, we win; else, drop the lock and loop back to try
2699  * again.
2700  */
2701  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
2702  if (HeapTupleIsValid(tuple))
2703  {
2704  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
2705 
2706  if (strcmp(name, NameStr(dbform->datname)) == 0)
2707  {
2708  Datum datum;
2709  bool isnull;
2710 
2711  /* oid of the database */
2712  if (dbIdP)
2713  *dbIdP = dbOid;
2714  /* oid of the owner */
2715  if (ownerIdP)
2716  *ownerIdP = dbform->datdba;
2717  /* character encoding */
2718  if (encodingP)
2719  *encodingP = dbform->encoding;
2720  /* allowed as template? */
2721  if (dbIsTemplateP)
2722  *dbIsTemplateP = dbform->datistemplate;
2723  /* allowing connections? */
2724  if (dbAllowConnP)
2725  *dbAllowConnP = dbform->datallowconn;
2726  /* limit of frozen XIDs */
2727  if (dbFrozenXidP)
2728  *dbFrozenXidP = dbform->datfrozenxid;
2729  /* minimum MultiXactId */
2730  if (dbMinMultiP)
2731  *dbMinMultiP = dbform->datminmxid;
2732  /* default tablespace for this database */
2733  if (dbTablespace)
2734  *dbTablespace = dbform->dattablespace;
2735  /* default locale settings for this database */
2736  if (dbLocProvider)
2737  *dbLocProvider = dbform->datlocprovider;
2738  if (dbCollate)
2739  {
2740  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollate, &isnull);
2741  Assert(!isnull);
2742  *dbCollate = TextDatumGetCString(datum);
2743  }
2744  if (dbCtype)
2745  {
2746  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datctype, &isnull);
2747  Assert(!isnull);
2748  *dbCtype = TextDatumGetCString(datum);
2749  }
2750  if (dbIculocale)
2751  {
2752  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticulocale, &isnull);
2753  if (isnull)
2754  *dbIculocale = NULL;
2755  else
2756  *dbIculocale = TextDatumGetCString(datum);
2757  }
2758  if (dbIcurules)
2759  {
2760  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticurules, &isnull);
2761  if (isnull)
2762  *dbIcurules = NULL;
2763  else
2764  *dbIcurules = TextDatumGetCString(datum);
2765  }
2766  if (dbCollversion)
2767  {
2768  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
2769  if (isnull)
2770  *dbCollversion = NULL;
2771  else
2772  *dbCollversion = TextDatumGetCString(datum);
2773  }
2774  ReleaseSysCache(tuple);
2775  result = true;
2776  break;
2777  }
2778  /* can only get here if it was just renamed */
2779  ReleaseSysCache(tuple);
2780  }
2781 
2782  if (lockmode != NoLock)
2783  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2784  }
2785 
2786  table_close(relation, AccessShareLock);
2787 
2788  return result;
2789 }
const char * name
Definition: encode.c:571
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1078

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

bool have_createdb_privilege ( void  )

Definition at line 2793 of file dbcommands.c.

2794 {
2795  bool result = false;
2796  HeapTuple utup;
2797 
2798  /* Superusers can always do everything */
2799  if (superuser())
2800  return true;
2801 
2803  if (HeapTupleIsValid(utup))
2804  {
2805  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2806  ReleaseSysCache(utup);
2807  }
2808  return result;
2809 }
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38
@ AUTHOID
Definition: syscache.h:45

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

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

◆ movedb()

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

Definition at line 1850 of file dbcommands.c.

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

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

2171 {
2173  char *dstpath;
2174 
2175  /* Get rid of anything we managed to copy to the target directory */
2176  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2177 
2178  (void) rmtree(dstpath, true);
2179 
2180  pfree(dstpath);
2181 }

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

2595 {
2596  Oid dbid = PG_GETARG_OID(0);
2597  HeapTuple tp;
2598  char datlocprovider;
2599  Datum datum;
2600  bool isnull;
2601  char *version;
2602 
2604  if (!HeapTupleIsValid(tp))
2605  ereport(ERROR,
2606  (errcode(ERRCODE_UNDEFINED_OBJECT),
2607  errmsg("database with OID %u does not exist", dbid)));
2608 
2610 
2611  datum = SysCacheGetAttr(DATABASEOID, tp, datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, &isnull);
2612  if (isnull)
2613  elog(ERROR, "unexpected null in pg_database");
2615 
2616  ReleaseSysCache(tp);
2617 
2618  if (version)
2620  else
2621  PG_RETURN_NULL();
2622 }
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
char datlocprovider
Definition: pg_database.h:44
text * cstring_to_text(const char *s)
Definition: varlena.c:182

References cstring_to_text(), DATABASEOID, datlocprovider, 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 3059 of file dbcommands.c.

3060 {
3061  struct stat st;
3062 
3064 
3065  if (stat(path, &st) == 0)
3066  return;
3067 
3068  if (only_tblspc && strstr(path, "pg_tblspc/") == NULL)
3069  elog(PANIC, "requested to created invalid directory: %s", path);
3070 
3072  ereport(PANIC,
3073  errmsg("missing directory \"%s\"", path));
3074 
3076  "creating missing directory: %s", path);
3077 
3078  if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3079  ereport(PANIC,
3080  errmsg("could not create missing directory \"%s\": %m", path));
3081 }
bool allow_in_place_tablespaces
Definition: tablespace.c:91
#define DEBUG1
Definition: elog.h:30
int pg_dir_create_mode
Definition: file_perm.c:18
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
bool RecoveryInProgress(void)
Definition: xlog.c:5908
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 2818 of file dbcommands.c.

2819 {
2820  Relation rel;
2821  TableScanDesc scan;
2822  HeapTuple tuple;
2823  List *ltblspc = NIL;
2824  ListCell *cell;
2825  int ntblspc;
2826  int i;
2827  Oid *tablespace_ids;
2828 
2829  rel = table_open(TableSpaceRelationId, AccessShareLock);
2830  scan = table_beginscan_catalog(rel, 0, NULL);
2831  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2832  {
2833  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2834  Oid dsttablespace = spcform->oid;
2835  char *dstpath;
2836  struct stat st;
2837 
2838  /* Don't mess with the global tablespace */
2839  if (dsttablespace == GLOBALTABLESPACE_OID)
2840  continue;
2841 
2842  dstpath = GetDatabasePath(db_id, dsttablespace);
2843 
2844  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
2845  {
2846  /* Assume we can ignore it */
2847  pfree(dstpath);
2848  continue;
2849  }
2850 
2851  if (!rmtree(dstpath, true))
2852  ereport(WARNING,
2853  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2854  dstpath)));
2855 
2856  ltblspc = lappend_oid(ltblspc, dsttablespace);
2857  pfree(dstpath);
2858  }
2859 
2860  ntblspc = list_length(ltblspc);
2861  if (ntblspc == 0)
2862  {
2863  table_endscan(scan);
2865  return;
2866  }
2867 
2868  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
2869  i = 0;
2870  foreach(cell, ltblspc)
2871  tablespace_ids[i++] = lfirst_oid(cell);
2872 
2873  /* Record the filesystem change in XLOG */
2874  {
2875  xl_dbase_drop_rec xlrec;
2876 
2877  xlrec.db_id = db_id;
2878  xlrec.ntablespaces = ntblspc;
2879 
2880  XLogBeginInsert();
2881  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
2882  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
2883 
2884  (void) XLogInsert(RM_DBASE_ID,
2886  }
2887 
2888  list_free(ltblspc);
2889  pfree(tablespace_ids);
2890 
2891  table_endscan(scan);
2893 }
#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:1210
#define lfirst_oid(lc)
Definition: pg_list.h:174

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

Referenced by createdb_failure_callback(), and dropdb().

◆ RenameDatabase()

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

Definition at line 1752 of file dbcommands.c.

1753 {
1754  Oid db_id;
1755  HeapTuple newtup;
1756  Relation rel;
1757  int notherbackends;
1758  int npreparedxacts;
1759  ObjectAddress address;
1760 
1761  /*
1762  * Look up the target database's OID, and get exclusive lock on it. We
1763  * need this for the same reasons as DROP DATABASE.
1764  */
1765  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1766 
1767  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1768  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1769  ereport(ERROR,
1770  (errcode(ERRCODE_UNDEFINED_DATABASE),
1771  errmsg("database \"%s\" does not exist", oldname)));
1772 
1773  /* must be owner */
1774  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1776  oldname);
1777 
1778  /* must have createdb rights */
1779  if (!have_createdb_privilege())
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1782  errmsg("permission denied to rename database")));
1783 
1784  /*
1785  * If built with appropriate switch, whine when regression-testing
1786  * conventions for database names are violated.
1787  */
1788 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1789  if (strstr(newname, "regression") == NULL)
1790  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1791 #endif
1792 
1793  /*
1794  * Make sure the new name doesn't exist. See notes for same error in
1795  * CREATE DATABASE.
1796  */
1797  if (OidIsValid(get_database_oid(newname, true)))
1798  ereport(ERROR,
1799  (errcode(ERRCODE_DUPLICATE_DATABASE),
1800  errmsg("database \"%s\" already exists", newname)));
1801 
1802  /*
1803  * XXX Client applications probably store the current database somewhere,
1804  * so renaming it could cause confusion. On the other hand, there may not
1805  * be an actual problem besides a little confusion, so think about this
1806  * and decide.
1807  */
1808  if (db_id == MyDatabaseId)
1809  ereport(ERROR,
1810  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1811  errmsg("current database cannot be renamed")));
1812 
1813  /*
1814  * Make sure the database does not have active sessions. This is the same
1815  * concern as above, but applied to other sessions.
1816  *
1817  * As in CREATE DATABASE, check this after other error conditions.
1818  */
1819  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1820  ereport(ERROR,
1821  (errcode(ERRCODE_OBJECT_IN_USE),
1822  errmsg("database \"%s\" is being accessed by other users",
1823  oldname),
1824  errdetail_busy_db(notherbackends, npreparedxacts)));
1825 
1826  /* rename */
1828  if (!HeapTupleIsValid(newtup))
1829  elog(ERROR, "cache lookup failed for database %u", db_id);
1830  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1831  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1832 
1833  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1834 
1835  ObjectAddressSet(address, DatabaseRelationId, db_id);
1836 
1837  /*
1838  * Close pg_database, but keep lock till commit.
1839  */
1840  table_close(rel, NoLock);
1841 
1842  return address;
1843 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h: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, true);
301 
303  page = BufferGetPage(buf);
304  if (PageIsNew(page) || PageIsEmpty(page))
305  {
307  continue;
308  }
309 
310  /* Append relevant pg_class tuples for current page to rlocatorlist. */
311  rlocatorlist = ScanSourceDatabasePgClassPage(page, buf, tbid, dbid,
312  srcpath, rlocatorlist,
313  snapshot);
314 
316  }
317 
318  /* Release relation lock. */
320 
321  return rlocatorlist;
322 }
#define InvalidBackendId
Definition: backendid.h:23
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4028
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4246
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition: bufmgr.c:791
@ BAS_BULKREAD
Definition: bufmgr.h:35
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:111
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:285
@ RBM_NORMAL
Definition: bufmgr.h:44
static bool PageIsEmpty(Page page)
Definition: bufpage.h:220
Pointer Page
Definition: bufpage.h:78
static bool PageIsNew(Page page)
Definition: bufpage.h:230
static List * ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
Definition: dbcommands.c:329
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
RelFileNumber RelationMapOidToFilenumberForDatabase(char *dbpath, Oid relationId)
Definition: relmapper.c:266
Oid RelFileNumber
Definition: relpath.h:25
@ MAIN_FORKNUM
Definition: relpath.h:50
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c: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:2811
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().