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

Typedef Documentation

◆ CreateDBRelInfo

◆ CreateDBStrategy

Enumeration Type Documentation

◆ CreateDBStrategy

Enumerator
CREATEDB_WAL_LOG 
CREATEDB_FILE_COPY 

Definition at line 82 of file dbcommands.c.

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

Function Documentation

◆ AlterDatabase()

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

Definition at line 2315 of file dbcommands.c.

2316 {
2317  Relation rel;
2318  Oid dboid;
2319  HeapTuple tuple,
2320  newtuple;
2321  Form_pg_database datform;
2322  ScanKeyData scankey;
2323  SysScanDesc scan;
2324  ListCell *option;
2325  bool dbistemplate = false;
2326  bool dballowconnections = true;
2327  int dbconnlimit = DATCONNLIMIT_UNLIMITED;
2328  DefElem *distemplate = NULL;
2329  DefElem *dallowconnections = NULL;
2330  DefElem *dconnlimit = NULL;
2331  DefElem *dtablespace = NULL;
2332  Datum new_record[Natts_pg_database] = {0};
2333  bool new_record_nulls[Natts_pg_database] = {0};
2334  bool new_record_repl[Natts_pg_database] = {0};
2335 
2336  /* Extract options from the statement node tree */
2337  foreach(option, stmt->options)
2338  {
2339  DefElem *defel = (DefElem *) lfirst(option);
2340 
2341  if (strcmp(defel->defname, "is_template") == 0)
2342  {
2343  if (distemplate)
2344  errorConflictingDefElem(defel, pstate);
2345  distemplate = defel;
2346  }
2347  else if (strcmp(defel->defname, "allow_connections") == 0)
2348  {
2349  if (dallowconnections)
2350  errorConflictingDefElem(defel, pstate);
2351  dallowconnections = defel;
2352  }
2353  else if (strcmp(defel->defname, "connection_limit") == 0)
2354  {
2355  if (dconnlimit)
2356  errorConflictingDefElem(defel, pstate);
2357  dconnlimit = defel;
2358  }
2359  else if (strcmp(defel->defname, "tablespace") == 0)
2360  {
2361  if (dtablespace)
2362  errorConflictingDefElem(defel, pstate);
2363  dtablespace = defel;
2364  }
2365  else
2366  ereport(ERROR,
2367  (errcode(ERRCODE_SYNTAX_ERROR),
2368  errmsg("option \"%s\" not recognized", defel->defname),
2369  parser_errposition(pstate, defel->location)));
2370  }
2371 
2372  if (dtablespace)
2373  {
2374  /*
2375  * While the SET TABLESPACE syntax doesn't allow any other options,
2376  * somebody could write "WITH TABLESPACE ...". Forbid any other
2377  * options from being specified in that case.
2378  */
2379  if (list_length(stmt->options) != 1)
2380  ereport(ERROR,
2381  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2382  errmsg("option \"%s\" cannot be specified with other options",
2383  dtablespace->defname),
2384  parser_errposition(pstate, dtablespace->location)));
2385  /* this case isn't allowed within a transaction block */
2386  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2387  movedb(stmt->dbname, defGetString(dtablespace));
2388  return InvalidOid;
2389  }
2390 
2391  if (distemplate && distemplate->arg)
2392  dbistemplate = defGetBoolean(distemplate);
2393  if (dallowconnections && dallowconnections->arg)
2394  dballowconnections = defGetBoolean(dallowconnections);
2395  if (dconnlimit && dconnlimit->arg)
2396  {
2397  dbconnlimit = defGetInt32(dconnlimit);
2398  if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
2399  ereport(ERROR,
2400  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2401  errmsg("invalid connection limit: %d", dbconnlimit)));
2402  }
2403 
2404  /*
2405  * Get the old tuple. We don't need a lock on the database per se,
2406  * because we're not going to do anything that would mess up incoming
2407  * connections.
2408  */
2409  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2410  ScanKeyInit(&scankey,
2411  Anum_pg_database_datname,
2412  BTEqualStrategyNumber, F_NAMEEQ,
2413  CStringGetDatum(stmt->dbname));
2414  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2415  NULL, 1, &scankey);
2416  tuple = systable_getnext(scan);
2417  if (!HeapTupleIsValid(tuple))
2418  ereport(ERROR,
2419  (errcode(ERRCODE_UNDEFINED_DATABASE),
2420  errmsg("database \"%s\" does not exist", stmt->dbname)));
2421 
2422  datform = (Form_pg_database) GETSTRUCT(tuple);
2423  dboid = datform->oid;
2424 
2425  if (database_is_invalid_form(datform))
2426  {
2427  ereport(FATAL,
2428  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2429  errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2430  errhint("Use DROP DATABASE to drop invalid databases."));
2431  }
2432 
2433  if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2435  stmt->dbname);
2436 
2437  /*
2438  * In order to avoid getting locked out and having to go through
2439  * standalone mode, we refuse to disallow connections to the database
2440  * we're currently connected to. Lockout can still happen with concurrent
2441  * sessions but the likeliness of that is not high enough to worry about.
2442  */
2443  if (!dballowconnections && dboid == MyDatabaseId)
2444  ereport(ERROR,
2445  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2446  errmsg("cannot disallow connections for current database")));
2447 
2448  /*
2449  * Build an updated tuple, perusing the information just obtained
2450  */
2451  if (distemplate)
2452  {
2453  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2454  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2455  }
2456  if (dallowconnections)
2457  {
2458  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2459  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2460  }
2461  if (dconnlimit)
2462  {
2463  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2464  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2465  }
2466 
2467  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2468  new_record_nulls, new_record_repl);
2469  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2470 
2471  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2472 
2473  systable_endscan(scan);
2474 
2475  /* Close pg_database, but keep lock till commit */
2476  table_close(rel, NoLock);
2477 
2478  return dboid;
2479 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2688
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4130
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3177
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1953
int32 defGetInt32(DefElem *def)
Definition: define.c:162
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
Oid MyDatabaseId
Definition: globals.c:91
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
#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:514
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ OBJECT_DATABASE
Definition: parsenodes.h:2118
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
#define DATCONNLIMIT_UNLIMITED
Definition: pg_database.h:117
#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:531
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:811
int location
Definition: parsenodes.h:815
Node * arg
Definition: parsenodes.h:812
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:3557

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2606 of file dbcommands.c.

2607 {
2608  Oid db_id;
2609  HeapTuple tuple;
2610  Relation rel;
2611  ScanKeyData scankey;
2612  SysScanDesc scan;
2613  Form_pg_database datForm;
2614  ObjectAddress address;
2615 
2616  /*
2617  * Get the old tuple. We don't need a lock on the database per se,
2618  * because we're not going to do anything that would mess up incoming
2619  * connections.
2620  */
2621  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2622  ScanKeyInit(&scankey,
2623  Anum_pg_database_datname,
2624  BTEqualStrategyNumber, F_NAMEEQ,
2626  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2627  NULL, 1, &scankey);
2628  tuple = systable_getnext(scan);
2629  if (!HeapTupleIsValid(tuple))
2630  ereport(ERROR,
2631  (errcode(ERRCODE_UNDEFINED_DATABASE),
2632  errmsg("database \"%s\" does not exist", dbname)));
2633 
2634  datForm = (Form_pg_database) GETSTRUCT(tuple);
2635  db_id = datForm->oid;
2636 
2637  /*
2638  * If the new owner is the same as the existing owner, consider the
2639  * command to have succeeded. This is to be consistent with other
2640  * objects.
2641  */
2642  if (datForm->datdba != newOwnerId)
2643  {
2644  Datum repl_val[Natts_pg_database];
2645  bool repl_null[Natts_pg_database] = {0};
2646  bool repl_repl[Natts_pg_database] = {0};
2647  Acl *newAcl;
2648  Datum aclDatum;
2649  bool isNull;
2650  HeapTuple newtuple;
2651 
2652  /* Otherwise, must be owner of the existing object */
2653  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2655  dbname);
2656 
2657  /* Must be able to become new owner */
2658  check_can_set_role(GetUserId(), newOwnerId);
2659 
2660  /*
2661  * must have createdb rights
2662  *
2663  * NOTE: This is different from other alter-owner checks in that the
2664  * current user is checked for createdb privileges instead of the
2665  * destination owner. This is consistent with the CREATE case for
2666  * databases. Because superusers will always have this right, we need
2667  * no special case for them.
2668  */
2669  if (!have_createdb_privilege())
2670  ereport(ERROR,
2671  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2672  errmsg("permission denied to change owner of database")));
2673 
2674  repl_repl[Anum_pg_database_datdba - 1] = true;
2675  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2676 
2677  /*
2678  * Determine the modified ACL for the new owner. This is only
2679  * necessary when the ACL is non-null.
2680  */
2681  aclDatum = heap_getattr(tuple,
2682  Anum_pg_database_datacl,
2683  RelationGetDescr(rel),
2684  &isNull);
2685  if (!isNull)
2686  {
2687  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2688  datForm->datdba, newOwnerId);
2689  repl_repl[Anum_pg_database_datacl - 1] = true;
2690  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2691  }
2692 
2693  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2694  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2695 
2696  heap_freetuple(newtuple);
2697 
2698  /* Update owner dependency reference */
2699  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2700  }
2701 
2702  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2703 
2704  ObjectAddressSet(address, DatabaseRelationId, db_id);
2705 
2706  systable_endscan(scan);
2707 
2708  /* Close pg_database, but keep lock till commit */
2709  table_close(rel, NoLock);
2710 
2711  return address;
2712 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1088
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5123
#define DatumGetAclP(X)
Definition: acl.h:120
bool have_createdb_privilege(void)
Definition: dbcommands.c:2918
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
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:308
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 2486 of file dbcommands.c.

2487 {
2488  Relation rel;
2489  ScanKeyData scankey;
2490  SysScanDesc scan;
2491  Oid db_id;
2492  HeapTuple tuple;
2493  Form_pg_database datForm;
2494  ObjectAddress address;
2495  Datum datum;
2496  bool isnull;
2497  char *oldversion;
2498  char *newversion;
2499 
2500  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2501  ScanKeyInit(&scankey,
2502  Anum_pg_database_datname,
2503  BTEqualStrategyNumber, F_NAMEEQ,
2504  CStringGetDatum(stmt->dbname));
2505  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2506  NULL, 1, &scankey);
2507  tuple = systable_getnext(scan);
2508  if (!HeapTupleIsValid(tuple))
2509  ereport(ERROR,
2510  (errcode(ERRCODE_UNDEFINED_DATABASE),
2511  errmsg("database \"%s\" does not exist", stmt->dbname)));
2512 
2513  datForm = (Form_pg_database) GETSTRUCT(tuple);
2514  db_id = datForm->oid;
2515 
2516  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2518  stmt->dbname);
2519 
2520  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2521  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2522 
2523  if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2524  {
2525  datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2526  if (isnull)
2527  elog(ERROR, "unexpected null in pg_database");
2528  }
2529  else
2530  {
2531  datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2532  if (isnull)
2533  elog(ERROR, "unexpected null in pg_database");
2534  }
2535 
2536  newversion = get_collation_actual_version(datForm->datlocprovider,
2537  TextDatumGetCString(datum));
2538 
2539  /* cannot change from NULL to non-NULL or vice versa */
2540  if ((!oldversion && newversion) || (oldversion && !newversion))
2541  elog(ERROR, "invalid collation version change");
2542  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2543  {
2544  bool nulls[Natts_pg_database] = {0};
2545  bool replaces[Natts_pg_database] = {0};
2546  Datum values[Natts_pg_database] = {0};
2547 
2548  ereport(NOTICE,
2549  (errmsg("changing version from %s to %s",
2550  oldversion, newversion)));
2551 
2552  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2553  replaces[Anum_pg_database_datcollversion - 1] = true;
2554 
2555  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2556  values, nulls, replaces);
2557  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2558  heap_freetuple(tuple);
2559  }
2560  else
2561  ereport(NOTICE,
2562  (errmsg("version has not changed")));
2563 
2564  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2565 
2566  ObjectAddressSet(address, DatabaseRelationId, db_id);
2567 
2568  systable_endscan(scan);
2569 
2570  table_close(rel, NoLock);
2571 
2572  return address;
2573 }
static Datum values[MAXATTR]
Definition: bootstrap.c:152
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define elog(elevel,...)
Definition: elog.h:224
#define NOTICE
Definition: elog.h:35
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1724

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

2581 {
2582  Oid datid = get_database_oid(stmt->dbname, false);
2583 
2584  /*
2585  * Obtain a lock on the database and make sure it didn't go away in the
2586  * meantime.
2587  */
2588  shdepLockAndCheckObject(DatabaseRelationId, datid);
2589 
2590  if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2592  stmt->dbname);
2593 
2594  AlterSetting(datid, InvalidOid, stmt->setstmt);
2595 
2596  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2597 
2598  return datid;
2599 }
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3106
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1104
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1161

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

3034 {
3035  bool result = false;
3036  Relation rel;
3037  TableScanDesc scan;
3038  HeapTuple tuple;
3039 
3040  rel = table_open(TableSpaceRelationId, AccessShareLock);
3041  scan = table_beginscan_catalog(rel, 0, NULL);
3042  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3043  {
3044  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
3045  Oid dsttablespace = spcform->oid;
3046  char *dstpath;
3047  struct stat st;
3048 
3049  /* Don't mess with the global tablespace */
3050  if (dsttablespace == GLOBALTABLESPACE_OID)
3051  continue;
3052 
3053  dstpath = GetDatabasePath(db_id, dsttablespace);
3054 
3055  if (lstat(dstpath, &st) == 0)
3056  {
3057  /* Found a conflicting file (or directory, whatever) */
3058  pfree(dstpath);
3059  result = true;
3060  break;
3061  }
3062 
3063  pfree(dstpath);
3064  }
3065 
3066  table_endscan(scan);
3068 
3069  return result;
3070 }
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1082
void pfree(void *pointer)
Definition: mcxt.c:1508
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009
#define lstat(path, sb)
Definition: win32_port.h:285

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

Referenced by createdb().

◆ check_encoding_locale_matches()

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

Definition at line 1556 of file dbcommands.c.

1557 {
1558  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1559  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1560 
1561  if (!(ctype_encoding == encoding ||
1562  ctype_encoding == PG_SQL_ASCII ||
1563  ctype_encoding == -1 ||
1564 #ifdef WIN32
1565  encoding == PG_UTF8 ||
1566 #endif
1567  (encoding == PG_SQL_ASCII && superuser())))
1568  ereport(ERROR,
1569  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1570  errmsg("encoding \"%s\" does not match locale \"%s\"",
1572  ctype),
1573  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1574  pg_encoding_to_char(ctype_encoding))));
1575 
1576  if (!(collate_encoding == encoding ||
1577  collate_encoding == PG_SQL_ASCII ||
1578  collate_encoding == -1 ||
1579 #ifdef WIN32
1580  encoding == PG_UTF8 ||
1581 #endif
1582  (encoding == PG_SQL_ASCII && superuser())))
1583  ereport(ERROR,
1584  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1585  errmsg("encoding \"%s\" does not match locale \"%s\"",
1587  collate),
1588  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1589  pg_encoding_to_char(collate_encoding))));
1590 }
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
#define pg_encoding_to_char
Definition: pg_wchar.h:569
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 550 of file dbcommands.c.

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

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

Referenced by createdb().

◆ CreateDatabaseUsingWalLog()

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

Definition at line 148 of file dbcommands.c.

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

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

Referenced by createdb().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 670 of file dbcommands.c.

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

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

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

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1594 of file dbcommands.c.

1595 {
1597 
1598  /*
1599  * If we were copying database at block levels then drop pages for the
1600  * destination database that are in the shared buffer cache. And tell
1601  * checkpointer to forget any pending fsync and unlink requests for files
1602  * in the database. The reasoning behind doing this is same as explained
1603  * in dropdb function. But unlike dropdb we don't need to call
1604  * pgstat_drop_database because this database is still not created so
1605  * there should not be any stat for this.
1606  */
1607  if (fparms->strategy == CREATEDB_WAL_LOG)
1608  {
1611 
1612  /* Release lock on the target database. */
1613  UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1614  AccessShareLock);
1615  }
1616 
1617  /*
1618  * Release lock on source database before doing recursive remove. This is
1619  * not essential but it seems desirable to release the lock as soon as
1620  * possible.
1621  */
1622  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1623 
1624  /* Throw away any successfully copied subdirectories */
1626 }
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4039
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2943
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1428
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 456 of file dbcommands.c.

457 {
458  int fd;
459  int nbytes;
460  char versionfile[MAXPGPATH];
461  char buf[16];
462 
463  /*
464  * Note that we don't have to copy version data from the source database;
465  * there's only one legal value.
466  */
467  sprintf(buf, "%s\n", PG_MAJORVERSION);
468  nbytes = strlen(PG_MAJORVERSION) + 1;
469 
470  /* Create database directory. */
471  if (MakePGDirectory(dbpath) < 0)
472  {
473  /* Failure other than already exists or not in WAL replay? */
474  if (errno != EEXIST || !isRedo)
475  ereport(ERROR,
477  errmsg("could not create directory \"%s\": %m", dbpath)));
478  }
479 
480  /*
481  * Create PG_VERSION file in the database path. If the file already
482  * exists and we are in WAL replay then try again to open it in write
483  * mode.
484  */
485  snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
486 
487  fd = OpenTransientFile(versionfile, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY);
488  if (fd < 0 && errno == EEXIST && isRedo)
489  fd = OpenTransientFile(versionfile, O_WRONLY | O_TRUNC | PG_BINARY);
490 
491  if (fd < 0)
492  ereport(ERROR,
494  errmsg("could not create file \"%s\": %m", versionfile)));
495 
496  /* Write PG_MAJORVERSION in the PG_VERSION file. */
497  pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_WRITE);
498  errno = 0;
499  if ((int) write(fd, buf, nbytes) != nbytes)
500  {
501  /* If write didn't set errno, assume problem is no disk space. */
502  if (errno == 0)
503  errno = ENOSPC;
504  ereport(ERROR,
506  errmsg("could not write to file \"%s\": %m", versionfile)));
507  }
509 
510  pgstat_report_wait_start(WAIT_EVENT_VERSION_FILE_SYNC);
511  if (pg_fsync(fd) != 0)
514  errmsg("could not fsync file \"%s\": %m", versionfile)));
515  fsync_fname(dbpath, true);
517 
518  /* Close the version file. */
520 
521  /* If we are not in WAL replay then write the WAL. */
522  if (!isRedo)
523  {
525 
527 
528  xlrec.db_id = dbid;
529  xlrec.tablespace_id = tsid;
530 
531  XLogBeginInsert();
532  XLogRegisterData((char *) (&xlrec),
534 
535  (void) XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
536 
538  }
539 }
#define PG_BINARY
Definition: c.h:1260
#define XLOG_DBASE_CREATE_WAL_LOG
int errcode_for_file_access(void)
Definition: elog.c:882
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3913
int CloseTransientFile(int fd)
Definition: fd.c:2809
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:756
int data_sync_elevel(int elevel)
Definition: fd.c:3936
int pg_fsync(int fd)
Definition: fd.c:386
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2633
#define write(a, b, c)
Definition: win32.h:14
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:73
#define sprintf
Definition: port.h:240
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104

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

Referenced by CreateDatabaseUsingWalLog(), and dbase_redo().

◆ database_is_invalid_form()

bool database_is_invalid_form ( Form_pg_database  datform)

Definition at line 3177 of file dbcommands.c.

3178 {
3179  return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
3180 }
#define DATCONNLIMIT_INVALID_DB
Definition: pg_database.h:124

References DATCONNLIMIT_INVALID_DB.

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

◆ database_is_invalid_oid()

bool database_is_invalid_oid ( Oid  dboid)

Definition at line 3187 of file dbcommands.c.

3188 {
3189  HeapTuple dbtup;
3190  Form_pg_database dbform;
3191  bool invalid;
3192 
3193  dbtup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dboid));
3194  if (!HeapTupleIsValid(dbtup))
3195  elog(ERROR, "cache lookup failed for database %u", dboid);
3196  dbform = (Form_pg_database) GETSTRUCT(dbtup);
3197 
3199 
3200  ReleaseSysCache(dbtup);
3201 
3202  return invalid;
3203 }
invalidindex index d is invalid
Definition: isn.c:134
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218

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

Referenced by createdb().

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 3249 of file dbcommands.c.

3250 {
3251  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3252 
3253  /* Backup blocks are not used in dbase records */
3254  Assert(!XLogRecHasAnyBlockRefs(record));
3255 
3256  if (info == XLOG_DBASE_CREATE_FILE_COPY)
3257  {
3260  char *src_path;
3261  char *dst_path;
3262  char *parent_path;
3263  struct stat st;
3264 
3265  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3266  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3267 
3268  /*
3269  * Our theory for replaying a CREATE is to forcibly drop the target
3270  * subdirectory if present, then re-copy the source data. This may be
3271  * more work than needed, but it is simple to implement.
3272  */
3273  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3274  {
3275  if (!rmtree(dst_path, true))
3276  /* If this failed, copydir() below is going to error. */
3277  ereport(WARNING,
3278  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3279  dst_path)));
3280  }
3281 
3282  /*
3283  * If the parent of the target path doesn't exist, create it now. This
3284  * enables us to create the target underneath later.
3285  */
3286  parent_path = pstrdup(dst_path);
3287  get_parent_directory(parent_path);
3288  if (stat(parent_path, &st) < 0)
3289  {
3290  if (errno != ENOENT)
3291  ereport(FATAL,
3292  errmsg("could not stat directory \"%s\": %m",
3293  dst_path));
3294 
3295  /* create the parent directory if needed and valid */
3296  recovery_create_dbdir(parent_path, true);
3297  }
3298  pfree(parent_path);
3299 
3300  /*
3301  * There's a case where the copy source directory is missing for the
3302  * same reason above. Create the empty source directory so that
3303  * copydir below doesn't fail. The directory will be dropped soon by
3304  * recovery.
3305  */
3306  if (stat(src_path, &st) < 0 && errno == ENOENT)
3307  recovery_create_dbdir(src_path, false);
3308 
3309  /*
3310  * Force dirty buffers out to disk, to ensure source database is
3311  * up-to-date for the copy.
3312  */
3314 
3315  /* Close all sgmr fds in all backends. */
3317 
3318  /*
3319  * Copy this subdirectory to the new location
3320  *
3321  * We don't need to copy subdirectories
3322  */
3323  copydir(src_path, dst_path, false);
3324 
3325  pfree(src_path);
3326  pfree(dst_path);
3327  }
3328  else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3329  {
3332  char *dbpath;
3333  char *parent_path;
3334 
3335  dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3336 
3337  /* create the parent directory if needed and valid */
3338  parent_path = pstrdup(dbpath);
3339  get_parent_directory(parent_path);
3340  recovery_create_dbdir(parent_path, true);
3341 
3342  /* Create the database directory with the version file. */
3343  CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3344  true);
3345  pfree(dbpath);
3346  }
3347  else if (info == XLOG_DBASE_DROP)
3348  {
3349  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
3350  char *dst_path;
3351  int i;
3352 
3353  if (InHotStandby)
3354  {
3355  /*
3356  * Lock database while we resolve conflicts to ensure that
3357  * InitPostgres() cannot fully re-execute concurrently. This
3358  * avoids backends re-connecting automatically to same database,
3359  * which can happen in some cases.
3360  *
3361  * This will lock out walsenders trying to connect to db-specific
3362  * slots for logical decoding too, so it's safe for us to drop
3363  * slots.
3364  */
3365  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3367  }
3368 
3369  /* Drop any database-specific replication slots */
3371 
3372  /* Drop pages for this database that are in the shared buffer cache */
3373  DropDatabaseBuffers(xlrec->db_id);
3374 
3375  /* Also, clean out any fsync requests that might be pending in md.c */
3377 
3378  /* Clean out the xlog relcache too */
3379  XLogDropDatabase(xlrec->db_id);
3380 
3381  /* Close all sgmr fds in all backends. */
3383 
3384  for (i = 0; i < xlrec->ntablespaces; i++)
3385  {
3386  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3387 
3388  /* And remove the physical files */
3389  if (!rmtree(dst_path, true))
3390  ereport(WARNING,
3391  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3392  dst_path)));
3393  pfree(dst_path);
3394  }
3395 
3396  if (InHotStandby)
3397  {
3398  /*
3399  * Release locks prior to commit. XXX There is a race condition
3400  * here that may allow backends to reconnect, but the window for
3401  * this is small because the gap between here and commit is mostly
3402  * fairly small and it is unlikely that people will be dropping
3403  * databases that we are trying to connect to anyway.
3404  */
3405  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3406  }
3407  }
3408  else
3409  elog(PANIC, "dbase_redo: unknown op code %u", info);
3410 }
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4498
unsigned char uint8
Definition: c.h:491
static void recovery_create_dbdir(char *path, bool only_tblspc)
Definition: dbcommands.c:3220
#define XLOG_DBASE_DROP
#define PANIC
Definition: elog.h:42
int i
Definition: isn.c:73
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1143
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1125
#define AccessExclusiveLock
Definition: lockdefs.h:43
char * pstrdup(const char *in)
Definition: mcxt.c:1683
void get_parent_directory(char *path)
Definition: path.c:976
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:389
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:329
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:56
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1243
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:568
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:417
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:652
#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 2290 of file dbcommands.c.

2291 {
2292  bool force = false;
2293  ListCell *lc;
2294 
2295  foreach(lc, stmt->options)
2296  {
2297  DefElem *opt = (DefElem *) lfirst(lc);
2298 
2299  if (strcmp(opt->defname, "force") == 0)
2300  force = true;
2301  else
2302  ereport(ERROR,
2303  (errcode(ERRCODE_SYNTAX_ERROR),
2304  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2305  parser_errposition(pstate, opt->location)));
2306  }
2307 
2308  dropdb(stmt->dbname, stmt->missing_ok, force);
2309 }
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1633

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

1634 {
1635  Oid db_id;
1636  bool db_istemplate;
1637  Relation pgdbrel;
1638  HeapTuple tup;
1639  Form_pg_database datform;
1640  int notherbackends;
1641  int npreparedxacts;
1642  int nslots,
1643  nslots_active;
1644  int nsubscriptions;
1645 
1646  /*
1647  * Look up the target database's OID, and get exclusive lock on it. We
1648  * need this to ensure that no new backend starts up in the target
1649  * database while we are deleting it (see postinit.c), and that no one is
1650  * using it as a CREATE DATABASE template or trying to delete it for
1651  * themselves.
1652  */
1653  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1654 
1655  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1656  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1657  {
1658  if (!missing_ok)
1659  {
1660  ereport(ERROR,
1661  (errcode(ERRCODE_UNDEFINED_DATABASE),
1662  errmsg("database \"%s\" does not exist", dbname)));
1663  }
1664  else
1665  {
1666  /* Close pg_database, release the lock, since we changed nothing */
1667  table_close(pgdbrel, RowExclusiveLock);
1668  ereport(NOTICE,
1669  (errmsg("database \"%s\" does not exist, skipping",
1670  dbname)));
1671  return;
1672  }
1673  }
1674 
1675  /*
1676  * Permission checks
1677  */
1678  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1680  dbname);
1681 
1682  /* DROP hook for the database being removed */
1683  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1684 
1685  /*
1686  * Disallow dropping a DB that is marked istemplate. This is just to
1687  * prevent people from accidentally dropping template0 or template1; they
1688  * can do so if they're really determined ...
1689  */
1690  if (db_istemplate)
1691  ereport(ERROR,
1692  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1693  errmsg("cannot drop a template database")));
1694 
1695  /* Obviously can't drop my own database */
1696  if (db_id == MyDatabaseId)
1697  ereport(ERROR,
1698  (errcode(ERRCODE_OBJECT_IN_USE),
1699  errmsg("cannot drop the currently open database")));
1700 
1701  /*
1702  * Check whether there are active logical slots that refer to the
1703  * to-be-dropped database. The database lock we are holding prevents the
1704  * creation of new slots using the database or existing slots becoming
1705  * active.
1706  */
1707  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1708  if (nslots_active)
1709  {
1710  ereport(ERROR,
1711  (errcode(ERRCODE_OBJECT_IN_USE),
1712  errmsg("database \"%s\" is used by an active logical replication slot",
1713  dbname),
1714  errdetail_plural("There is %d active slot.",
1715  "There are %d active slots.",
1716  nslots_active, nslots_active)));
1717  }
1718 
1719  /*
1720  * Check if there are subscriptions defined in the target database.
1721  *
1722  * We can't drop them automatically because they might be holding
1723  * resources in other databases/instances.
1724  */
1725  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1726  ereport(ERROR,
1727  (errcode(ERRCODE_OBJECT_IN_USE),
1728  errmsg("database \"%s\" is being used by logical replication subscription",
1729  dbname),
1730  errdetail_plural("There is %d subscription.",
1731  "There are %d subscriptions.",
1732  nsubscriptions, nsubscriptions)));
1733 
1734 
1735  /*
1736  * Attempt to terminate all existing connections to the target database if
1737  * the user has requested to do so.
1738  */
1739  if (force)
1740  TerminateOtherDBBackends(db_id);
1741 
1742  /*
1743  * Check for other backends in the target database. (Because we hold the
1744  * database lock, no new ones can start after this.)
1745  *
1746  * As in CREATE DATABASE, check this after other error conditions.
1747  */
1748  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1749  ereport(ERROR,
1750  (errcode(ERRCODE_OBJECT_IN_USE),
1751  errmsg("database \"%s\" is being accessed by other users",
1752  dbname),
1753  errdetail_busy_db(notherbackends, npreparedxacts)));
1754 
1755  /*
1756  * Delete any comments or security labels associated with the database.
1757  */
1758  DeleteSharedComments(db_id, DatabaseRelationId);
1759  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1760 
1761  /*
1762  * Remove settings associated with this database
1763  */
1764  DropSetting(db_id, InvalidOid);
1765 
1766  /*
1767  * Remove shared dependency references for the database.
1768  */
1769  dropDatabaseDependencies(db_id);
1770 
1771  /*
1772  * Tell the cumulative stats system to forget it immediately, too.
1773  */
1774  pgstat_drop_database(db_id);
1775 
1776  tup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1777  if (!HeapTupleIsValid(tup))
1778  elog(ERROR, "cache lookup failed for database %u", db_id);
1779  datform = (Form_pg_database) GETSTRUCT(tup);
1780 
1781  /*
1782  * Except for the deletion of the catalog row, subsequent actions are not
1783  * transactional (consider DropDatabaseBuffers() discarding modified
1784  * buffers). But we might crash or get interrupted below. To prevent
1785  * accesses to a database with invalid contents, mark the database as
1786  * invalid using an in-place update.
1787  *
1788  * We need to flush the WAL before continuing, to guarantee the
1789  * modification is durable before performing irreversible filesystem
1790  * operations.
1791  */
1792  datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1793  heap_inplace_update(pgdbrel, tup);
1795 
1796  /*
1797  * Also delete the tuple - transactionally. If this transaction commits,
1798  * the row will be gone, but if we fail, dropdb() can be invoked again.
1799  */
1800  CatalogTupleDelete(pgdbrel, &tup->t_self);
1801 
1802  /*
1803  * Drop db-specific replication slots.
1804  */
1806 
1807  /*
1808  * Drop pages for this database that are in the shared buffer cache. This
1809  * is important to ensure that no remaining backend tries to write out a
1810  * dirty buffer to the dead database later...
1811  */
1812  DropDatabaseBuffers(db_id);
1813 
1814  /*
1815  * Tell checkpointer to forget any pending fsync and unlink requests for
1816  * files in the database; else the fsyncs will fail at next checkpoint, or
1817  * worse, it will delete files that belong to a newly created database
1818  * with the same OID.
1819  */
1821 
1822  /*
1823  * Force a checkpoint to make sure the checkpointer has received the
1824  * message sent by ForgetDatabaseSyncRequests.
1825  */
1827 
1828  /* Close all smgr fds in all backends. */
1830 
1831  /*
1832  * Remove all tablespace subdirs belonging to the database.
1833  */
1834  remove_dbtablespaces(db_id);
1835 
1836  /*
1837  * Close pg_database, but keep lock till commit.
1838  */
1839  table_close(pgdbrel, NoLock);
1840 
1841  /*
1842  * Force synchronous commit, thus minimizing the window between removal of
1843  * the database files and committal of the transaction. If we crash before
1844  * committing, we'll have a DB that's gone on disk but still there
1845  * according to pg_database, which is not good.
1846  */
1847  ForceSyncCommit();
1848 }
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:1297
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5889
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:949
int CountDBSubscriptions(Oid dbid)
void pgstat_drop_database(Oid databaseid)
void TerminateOtherDBBackends(Oid databaseId)
Definition: procarray.c:3815
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:1185
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
XLogRecPtr XactLastRecEnd
Definition: xlog.c:254
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2728

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

Referenced by DropDatabase().

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 3076 of file dbcommands.c.

3077 {
3078  if (notherbackends > 0 && npreparedxacts > 0)
3079 
3080  /*
3081  * We don't deal with singular versus plural here, since gettext
3082  * doesn't support multiple plurals in one string.
3083  */
3084  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3085  notherbackends, npreparedxacts);
3086  else if (notherbackends > 0)
3087  errdetail_plural("There is %d other session using the database.",
3088  "There are %d other sessions using the database.",
3089  notherbackends,
3090  notherbackends);
3091  else
3092  errdetail_plural("There is %d prepared transaction using the database.",
3093  "There are %d prepared transactions using the database.",
3094  npreparedxacts,
3095  npreparedxacts);
3096  return 0; /* just to keep ereport macro happy */
3097 }

References errdetail(), and errdetail_plural().

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

◆ get_database_name()

char* get_database_name ( Oid  dbid)

Definition at line 3153 of file dbcommands.c.

3154 {
3155  HeapTuple dbtuple;
3156  char *result;
3157 
3158  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3159  if (HeapTupleIsValid(dbtuple))
3160  {
3161  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3162  ReleaseSysCache(dbtuple);
3163  }
3164  else
3165  result = NULL;
3166 
3167  return result;
3168 }
#define NameStr(name)
Definition: c.h:733
NameData datname
Definition: pg_database.h:35

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 3106 of file dbcommands.c.

3107 {
3108  Relation pg_database;
3109  ScanKeyData entry[1];
3110  SysScanDesc scan;
3111  HeapTuple dbtuple;
3112  Oid oid;
3113 
3114  /*
3115  * There's no syscache for pg_database indexed by name, so we must look
3116  * the hard way.
3117  */
3118  pg_database = table_open(DatabaseRelationId, AccessShareLock);
3119  ScanKeyInit(&entry[0],
3120  Anum_pg_database_datname,
3121  BTEqualStrategyNumber, F_NAMEEQ,
3123  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
3124  NULL, 1, entry);
3125 
3126  dbtuple = systable_getnext(scan);
3127 
3128  /* We assume that there can be at most one matching tuple */
3129  if (HeapTupleIsValid(dbtuple))
3130  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3131  else
3132  oid = InvalidOid;
3133 
3134  systable_endscan(scan);
3135  table_close(pg_database, AccessShareLock);
3136 
3137  if (!OidIsValid(oid) && !missing_ok)
3138  ereport(ERROR,
3139  (errcode(ERRCODE_UNDEFINED_DATABASE),
3140  errmsg("database \"%s\" does not exist",
3141  dbname)));
3142 
3143  return oid;
3144 }

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(), sepgsql_database_post_create(), synchronize_slots(), and worker_spi_launch().

◆ get_db_info()

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

Definition at line 2760 of file dbcommands.c.

2768 {
2769  bool result = false;
2770  Relation relation;
2771 
2772  Assert(name);
2773 
2774  /* Caller may wish to grab a better lock on pg_database beforehand... */
2775  relation = table_open(DatabaseRelationId, AccessShareLock);
2776 
2777  /*
2778  * Loop covers the rare case where the database is renamed before we can
2779  * lock it. We try again just in case we can find a new one of the same
2780  * name.
2781  */
2782  for (;;)
2783  {
2784  ScanKeyData scanKey;
2785  SysScanDesc scan;
2786  HeapTuple tuple;
2787  Oid dbOid;
2788 
2789  /*
2790  * there's no syscache for database-indexed-by-name, so must do it the
2791  * hard way
2792  */
2793  ScanKeyInit(&scanKey,
2794  Anum_pg_database_datname,
2795  BTEqualStrategyNumber, F_NAMEEQ,
2797 
2798  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2799  NULL, 1, &scanKey);
2800 
2801  tuple = systable_getnext(scan);
2802 
2803  if (!HeapTupleIsValid(tuple))
2804  {
2805  /* definitely no database of that name */
2806  systable_endscan(scan);
2807  break;
2808  }
2809 
2810  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2811 
2812  systable_endscan(scan);
2813 
2814  /*
2815  * Now that we have a database OID, we can try to lock the DB.
2816  */
2817  if (lockmode != NoLock)
2818  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2819 
2820  /*
2821  * And now, re-fetch the tuple by OID. If it's still there and still
2822  * the same name, we win; else, drop the lock and loop back to try
2823  * again.
2824  */
2825  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
2826  if (HeapTupleIsValid(tuple))
2827  {
2828  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
2829 
2830  if (strcmp(name, NameStr(dbform->datname)) == 0)
2831  {
2832  Datum datum;
2833  bool isnull;
2834 
2835  /* oid of the database */
2836  if (dbIdP)
2837  *dbIdP = dbOid;
2838  /* oid of the owner */
2839  if (ownerIdP)
2840  *ownerIdP = dbform->datdba;
2841  /* character encoding */
2842  if (encodingP)
2843  *encodingP = dbform->encoding;
2844  /* allowed as template? */
2845  if (dbIsTemplateP)
2846  *dbIsTemplateP = dbform->datistemplate;
2847  /* Has on login event trigger? */
2848  if (dbHasLoginEvtP)
2849  *dbHasLoginEvtP = dbform->dathasloginevt;
2850  /* allowing connections? */
2851  if (dbAllowConnP)
2852  *dbAllowConnP = dbform->datallowconn;
2853  /* limit of frozen XIDs */
2854  if (dbFrozenXidP)
2855  *dbFrozenXidP = dbform->datfrozenxid;
2856  /* minimum MultiXactId */
2857  if (dbMinMultiP)
2858  *dbMinMultiP = dbform->datminmxid;
2859  /* default tablespace for this database */
2860  if (dbTablespace)
2861  *dbTablespace = dbform->dattablespace;
2862  /* default locale settings for this database */
2863  if (dbLocProvider)
2864  *dbLocProvider = dbform->datlocprovider;
2865  if (dbCollate)
2866  {
2867  datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datcollate);
2868  *dbCollate = TextDatumGetCString(datum);
2869  }
2870  if (dbCtype)
2871  {
2872  datum = SysCacheGetAttrNotNull(DATABASEOID, tuple, Anum_pg_database_datctype);
2873  *dbCtype = TextDatumGetCString(datum);
2874  }
2875  if (dbLocale)
2876  {
2877  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datlocale, &isnull);
2878  if (isnull)
2879  *dbLocale = NULL;
2880  else
2881  *dbLocale = TextDatumGetCString(datum);
2882  }
2883  if (dbIcurules)
2884  {
2885  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticurules, &isnull);
2886  if (isnull)
2887  *dbIcurules = NULL;
2888  else
2889  *dbIcurules = TextDatumGetCString(datum);
2890  }
2891  if (dbCollversion)
2892  {
2893  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
2894  if (isnull)
2895  *dbCollversion = NULL;
2896  else
2897  *dbCollversion = TextDatumGetCString(datum);
2898  }
2899  ReleaseSysCache(tuple);
2900  result = true;
2901  break;
2902  }
2903  /* can only get here if it was just renamed */
2904  ReleaseSysCache(tuple);
2905  }
2906 
2907  if (lockmode != NoLock)
2908  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2909  }
2910 
2911  table_close(relation, AccessShareLock);
2912 
2913  return result;
2914 }
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510
const char * name

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

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

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2918 of file dbcommands.c.

2919 {
2920  bool result = false;
2921  HeapTuple utup;
2922 
2923  /* Superusers can always do everything */
2924  if (superuser())
2925  return true;
2926 
2927  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2928  if (HeapTupleIsValid(utup))
2929  {
2930  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2931  ReleaseSysCache(utup);
2932  }
2933  return result;
2934 }
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38

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

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

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

2274 {
2276  char *dstpath;
2277 
2278  /* Get rid of anything we managed to copy to the target directory */
2279  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2280 
2281  (void) rmtree(dstpath, true);
2282 
2283  pfree(dstpath);
2284 }

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

2717 {
2718  Oid dbid = PG_GETARG_OID(0);
2719  HeapTuple tp;
2720  char datlocprovider;
2721  Datum datum;
2722  char *version;
2723 
2724  tp = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2725  if (!HeapTupleIsValid(tp))
2726  ereport(ERROR,
2727  (errcode(ERRCODE_UNDEFINED_OBJECT),
2728  errmsg("database with OID %u does not exist", dbid)));
2729 
2731 
2732  if (datlocprovider == COLLPROVIDER_LIBC)
2733  datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datcollate);
2734  else
2735  datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datlocale);
2736 
2738  TextDatumGetCString(datum));
2739 
2740  ReleaseSysCache(tp);
2741 
2742  if (version)
2744  else
2745  PG_RETURN_NULL();
2746 }
#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:184

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

◆ recovery_create_dbdir()

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

Definition at line 3220 of file dbcommands.c.

3221 {
3222  struct stat st;
3223 
3225 
3226  if (stat(path, &st) == 0)
3227  return;
3228 
3229  if (only_tblspc && strstr(path, "pg_tblspc/") == NULL)
3230  elog(PANIC, "requested to created invalid directory: %s", path);
3231 
3233  ereport(PANIC,
3234  errmsg("missing directory \"%s\"", path));
3235 
3237  "creating missing directory: %s", path);
3238 
3239  if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3240  ereport(PANIC,
3241  errmsg("could not create missing directory \"%s\": %m", path));
3242 }
bool allow_in_place_tablespaces
Definition: tablespace.c:85
#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:6201
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 2943 of file dbcommands.c.

2944 {
2945  Relation rel;
2946  TableScanDesc scan;
2947  HeapTuple tuple;
2948  List *ltblspc = NIL;
2949  ListCell *cell;
2950  int ntblspc;
2951  int i;
2952  Oid *tablespace_ids;
2953 
2954  rel = table_open(TableSpaceRelationId, AccessShareLock);
2955  scan = table_beginscan_catalog(rel, 0, NULL);
2956  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2957  {
2958  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2959  Oid dsttablespace = spcform->oid;
2960  char *dstpath;
2961  struct stat st;
2962 
2963  /* Don't mess with the global tablespace */
2964  if (dsttablespace == GLOBALTABLESPACE_OID)
2965  continue;
2966 
2967  dstpath = GetDatabasePath(db_id, dsttablespace);
2968 
2969  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
2970  {
2971  /* Assume we can ignore it */
2972  pfree(dstpath);
2973  continue;
2974  }
2975 
2976  if (!rmtree(dstpath, true))
2977  ereport(WARNING,
2978  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2979  dstpath)));
2980 
2981  ltblspc = lappend_oid(ltblspc, dsttablespace);
2982  pfree(dstpath);
2983  }
2984 
2985  ntblspc = list_length(ltblspc);
2986  if (ntblspc == 0)
2987  {
2988  table_endscan(scan);
2990  return;
2991  }
2992 
2993  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
2994  i = 0;
2995  foreach(cell, ltblspc)
2996  tablespace_ids[i++] = lfirst_oid(cell);
2997 
2998  /* Record the filesystem change in XLOG */
2999  {
3000  xl_dbase_drop_rec xlrec;
3001 
3002  xlrec.db_id = db_id;
3003  xlrec.ntablespaces = ntblspc;
3004 
3005  XLogBeginInsert();
3006  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
3007  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
3008 
3009  (void) XLogInsert(RM_DBASE_ID,
3011  }
3012 
3013  list_free(ltblspc);
3014  pfree(tablespace_ids);
3015 
3016  table_endscan(scan);
3018 }
#define MinSizeOfDbaseDropRec
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
void list_free(List *list)
Definition: list.c:1546
void * palloc(Size size)
Definition: mcxt.c:1304
#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 1855 of file dbcommands.c.

1856 {
1857  Oid db_id;
1858  HeapTuple newtup;
1859  Relation rel;
1860  int notherbackends;
1861  int npreparedxacts;
1862  ObjectAddress address;
1863 
1864  /*
1865  * Look up the target database's OID, and get exclusive lock on it. We
1866  * need this for the same reasons as DROP DATABASE.
1867  */
1868  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1869 
1870  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL, NULL,
1871  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1872  ereport(ERROR,
1873  (errcode(ERRCODE_UNDEFINED_DATABASE),
1874  errmsg("database \"%s\" does not exist", oldname)));
1875 
1876  /* must be owner */
1877  if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
1879  oldname);
1880 
1881  /* must have createdb rights */
1882  if (!have_createdb_privilege())
1883  ereport(ERROR,
1884  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1885  errmsg("permission denied to rename database")));
1886 
1887  /*
1888  * If built with appropriate switch, whine when regression-testing
1889  * conventions for database names are violated.
1890  */
1891 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1892  if (strstr(newname, "regression") == NULL)
1893  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1894 #endif
1895 
1896  /*
1897  * Make sure the new name doesn't exist. See notes for same error in
1898  * CREATE DATABASE.
1899  */
1900  if (OidIsValid(get_database_oid(newname, true)))
1901  ereport(ERROR,
1902  (errcode(ERRCODE_DUPLICATE_DATABASE),
1903  errmsg("database \"%s\" already exists", newname)));
1904 
1905  /*
1906  * XXX Client applications probably store the current database somewhere,
1907  * so renaming it could cause confusion. On the other hand, there may not
1908  * be an actual problem besides a little confusion, so think about this
1909  * and decide.
1910  */
1911  if (db_id == MyDatabaseId)
1912  ereport(ERROR,
1913  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1914  errmsg("current database cannot be renamed")));
1915 
1916  /*
1917  * Make sure the database does not have active sessions. This is the same
1918  * concern as above, but applied to other sessions.
1919  *
1920  * As in CREATE DATABASE, check this after other error conditions.
1921  */
1922  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1923  ereport(ERROR,
1924  (errcode(ERRCODE_OBJECT_IN_USE),
1925  errmsg("database \"%s\" is being accessed by other users",
1926  oldname),
1927  errdetail_busy_db(notherbackends, npreparedxacts)));
1928 
1929  /* rename */
1930  newtup = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(db_id));
1931  if (!HeapTupleIsValid(newtup))
1932  elog(ERROR, "cache lookup failed for database %u", db_id);
1933  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1934  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1935 
1936  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1937 
1938  ObjectAddressSet(address, DatabaseRelationId, db_id);
1939 
1940  /*
1941  * Close pg_database, but keep lock till commit.
1942  */
1943  table_close(rel, NoLock);
1944 
1945  return address;
1946 }
void namestrcpy(Name name, const char *str)
Definition: name.c:233

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), CountOtherDBBackends(), 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 250 of file dbcommands.c.

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

References AccessShareLock, BAS_BULKREAD, buf, BUFFER_LOCK_SHARE, BufferGetPage(), CHECK_FOR_INTERRUPTS, LockRelId::dbId, RelFileLocator::dbOid, GetAccessStrategy(), GetLatestSnapshot(), INVALID_PROC_NUMBER, 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 328 of file dbcommands.c.

331 {
333  OffsetNumber offnum;
334  OffsetNumber maxoff;
335  HeapTupleData tuple;
336 
337  maxoff = PageGetMaxOffsetNumber(page);
338 
339  /* Loop over offsets. */
340  for (offnum = FirstOffsetNumber;
341  offnum <= maxoff;
342  offnum = OffsetNumberNext(offnum))
343  {
344  ItemId itemid;
345 
346  itemid = PageGetItemId(page, offnum);
347 
348  /* Nothing to do if slot is empty or already dead. */
349  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
350  ItemIdIsRedirected(itemid))
351  continue;
352 
353  Assert(ItemIdIsNormal(itemid));
354  ItemPointerSet(&(tuple.t_self), blkno, offnum);
355 
356  /* Initialize a HeapTupleData structure. */
357  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
358  tuple.t_len = ItemIdGetLength(itemid);
359  tuple.t_tableOid = RelationRelationId;
360 
361  /* Skip tuples that are not visible to this snapshot. */
362  if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
363  {
364  CreateDBRelInfo *relinfo;
365 
366  /*
367  * ScanSourceDatabasePgClassTuple is in charge of constructing a
368  * CreateDBRelInfo object for this tuple, but can also decide that
369  * this tuple isn't something we need to copy. If we do need to
370  * copy the relation, add it to the list.
371  */
372  relinfo = ScanSourceDatabasePgClassTuple(&tuple, tbid, dbid,
373  srcpath);
374  if (relinfo != NULL)
375  rlocatorlist = lappend(rlocatorlist, relinfo);
376  }
377  }
378 
379  return rlocatorlist;
380 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:3377
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:391
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:339
#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 391 of file dbcommands.c.

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