PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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/procsignal.h"
#include "storage/smgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/pg_locale.h"
#include "utils/relmapper.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/wait_event.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)
 
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 85 of file dbcommands.c.

86{
CreateDBStrategy
Definition dbcommands.c:86
@ CREATEDB_FILE_COPY
Definition dbcommands.c:88
@ CREATEDB_WAL_LOG
Definition dbcommands.c:87

Function Documentation

◆ AlterDatabase()

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

Definition at line 2390 of file dbcommands.c.

2391{
2392 Relation rel;
2393 Oid dboid;
2394 HeapTuple tuple,
2395 newtuple;
2398 SysScanDesc scan;
2400 bool dbistemplate = false;
2401 bool dballowconnections = true;
2410
2411 /* Extract options from the statement node tree */
2412 foreach(option, stmt->options)
2413 {
2415
2416 if (strcmp(defel->defname, "is_template") == 0)
2417 {
2418 if (distemplate)
2421 }
2422 else if (strcmp(defel->defname, "allow_connections") == 0)
2423 {
2427 }
2428 else if (strcmp(defel->defname, "connection_limit") == 0)
2429 {
2430 if (dconnlimit)
2432 dconnlimit = defel;
2433 }
2434 else if (strcmp(defel->defname, "tablespace") == 0)
2435 {
2436 if (dtablespace)
2439 }
2440 else
2441 ereport(ERROR,
2443 errmsg("option \"%s\" not recognized", defel->defname),
2444 parser_errposition(pstate, defel->location)));
2445 }
2446
2447 if (dtablespace)
2448 {
2449 /*
2450 * While the SET TABLESPACE syntax doesn't allow any other options,
2451 * somebody could write "WITH TABLESPACE ...". Forbid any other
2452 * options from being specified in that case.
2453 */
2454 if (list_length(stmt->options) != 1)
2455 ereport(ERROR,
2457 errmsg("option \"%s\" cannot be specified with other options",
2458 dtablespace->defname),
2459 parser_errposition(pstate, dtablespace->location)));
2460 /* this case isn't allowed within a transaction block */
2461 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2463 return InvalidOid;
2464 }
2465
2466 if (distemplate && distemplate->arg)
2470 if (dconnlimit && dconnlimit->arg)
2471 {
2474 ereport(ERROR,
2476 errmsg("invalid connection limit: %d", dbconnlimit)));
2477 }
2478
2479 /*
2480 * Get the old tuple. We don't need a lock on the database per se,
2481 * because we're not going to do anything that would mess up incoming
2482 * connections.
2483 */
2488 CStringGetDatum(stmt->dbname));
2489 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2490 NULL, 1, &scankey);
2491 tuple = systable_getnext(scan);
2492 if (!HeapTupleIsValid(tuple))
2493 ereport(ERROR,
2495 errmsg("database \"%s\" does not exist", stmt->dbname)));
2497
2499 dboid = datform->oid;
2500
2502 {
2503 ereport(FATAL,
2505 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2506 errhint("Use DROP DATABASE to drop invalid databases."));
2507 }
2508
2511 stmt->dbname);
2512
2513 /*
2514 * In order to avoid getting locked out and having to go through
2515 * standalone mode, we refuse to disallow connections to the database
2516 * we're currently connected to. Lockout can still happen with concurrent
2517 * sessions but the likeliness of that is not high enough to worry about.
2518 */
2519 if (!dballowconnections && dboid == MyDatabaseId)
2520 ereport(ERROR,
2522 errmsg("cannot disallow connections for current database")));
2523
2524 /*
2525 * Build an updated tuple, perusing the information just obtained
2526 */
2527 if (distemplate)
2528 {
2531 }
2533 {
2536 }
2537 if (dconnlimit)
2538 {
2541 }
2542
2543 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2545 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2547
2549
2550 systable_endscan(scan);
2551
2552 /* Close pg_database, but keep lock till commit */
2553 table_close(rel, NoLock);
2554
2555 return dboid;
2556}
@ ACLCHECK_NOT_OWNER
Definition acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
bool database_is_invalid_form(Form_pg_database datform)
static void movedb(const char *dbname, const char *tblspcname)
int32 defGetInt32(DefElem *def)
Definition define.c:148
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:42
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:612
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:523
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
Oid MyDatabaseId
Definition globals.c:96
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
void LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:562
#define NoLock
Definition lockdefs.h:34
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
#define RowExclusiveLock
Definition lockdefs.h:38
Oid GetUserId(void)
Definition miscinit.c:470
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
@ OBJECT_DATABASE
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
#define DATCONNLIMIT_UNLIMITED
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
uint64_t Datum
Definition postgres.h:70
static Datum CStringGetDatum(const char *X)
Definition postgres.h:370
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
#define InvalidOid
unsigned int Oid
static int fb(int x)
#define RelationGetDescr(relation)
Definition rel.h:542
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
#define BTEqualStrategyNumber
Definition stratnum.h:31
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:3698

References aclcheck_error(), ACLCHECK_NOT_OWNER, BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), database_is_invalid_form(), DATCONNLIMIT_UNLIMITED, defGetBoolean(), defGetInt32(), defGetString(), ereport, errcode(), errhint(), errmsg, ERROR, errorConflictingDefElem(), FATAL, fb(), Form_pg_database, GETSTRUCT(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InplaceUpdateTupleLock, Int32GetDatum(), InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), LockTuple(), 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(), table_open(), and UnlockTuple().

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char dbname,
Oid  newOwnerId 
)

Definition at line 2686 of file dbcommands.c.

2687{
2688 Oid db_id;
2689 HeapTuple tuple;
2690 Relation rel;
2692 SysScanDesc scan;
2694 ObjectAddress address;
2695
2696 /*
2697 * Get the old tuple. We don't need a lock on the database per se,
2698 * because we're not going to do anything that would mess up incoming
2699 * connections.
2700 */
2706 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2707 NULL, 1, &scankey);
2708 tuple = systable_getnext(scan);
2709 if (!HeapTupleIsValid(tuple))
2710 ereport(ERROR,
2712 errmsg("database \"%s\" does not exist", dbname)));
2713
2715 db_id = datForm->oid;
2716
2717 /*
2718 * If the new owner is the same as the existing owner, consider the
2719 * command to have succeeded. This is to be consistent with other
2720 * objects.
2721 */
2722 if (datForm->datdba != newOwnerId)
2723 {
2725 bool repl_null[Natts_pg_database] = {0};
2726 bool repl_repl[Natts_pg_database] = {0};
2727 Acl *newAcl;
2729 bool isNull;
2730 HeapTuple newtuple;
2731
2732 /* Otherwise, must be owner of the existing object */
2735 dbname);
2736
2737 /* Must be able to become new owner */
2739
2740 /*
2741 * must have createdb rights
2742 *
2743 * NOTE: This is different from other alter-owner checks in that the
2744 * current user is checked for createdb privileges instead of the
2745 * destination owner. This is consistent with the CREATE case for
2746 * databases. Because superusers will always have this right, we need
2747 * no special case for them.
2748 */
2750 ereport(ERROR,
2752 errmsg("permission denied to change owner of database")));
2753
2755
2758
2759 /*
2760 * Determine the modified ACL for the new owner. This is only
2761 * necessary when the ACL is non-null.
2762 */
2763 aclDatum = heap_getattr(tuple,
2765 RelationGetDescr(rel),
2766 &isNull);
2767 if (!isNull)
2768 {
2770 datForm->datdba, newOwnerId);
2773 }
2774
2776 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2778
2779 heap_freetuple(newtuple);
2780
2781 /* Update owner dependency reference */
2783 }
2784
2786
2787 ObjectAddressSet(address, DatabaseRelationId, db_id);
2788
2789 systable_endscan(scan);
2790
2791 /* Close pg_database, but keep lock till commit */
2792 table_close(rel, NoLock);
2793
2794 return address;
2795}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition acl.c:1147
void check_can_set_role(Oid member, Oid role)
Definition acl.c:5371
#define DatumGetAclP(X)
Definition acl.h:120
bool have_createdb_privilege(void)
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
#define ObjectAddressSet(addr, class_id, object_id)
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
static Datum PointerGetDatum(const void *X)
Definition postgres.h:342
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
char * dbname
Definition streamutil.c:49

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)

Definition at line 2563 of file dbcommands.c.

2564{
2565 Relation rel;
2567 SysScanDesc scan;
2568 Oid db_id;
2569 HeapTuple tuple;
2571 ObjectAddress address;
2572 Datum datum;
2573 bool isnull;
2574 char *oldversion;
2575 char *newversion;
2576
2581 CStringGetDatum(stmt->dbname));
2582 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2583 NULL, 1, &scankey);
2584 tuple = systable_getnext(scan);
2585 if (!HeapTupleIsValid(tuple))
2586 ereport(ERROR,
2588 errmsg("database \"%s\" does not exist", stmt->dbname)));
2589
2591 db_id = datForm->oid;
2592
2595 stmt->dbname);
2597
2598 datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2599 oldversion = isnull ? NULL : TextDatumGetCString(datum);
2600
2601 if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2602 {
2603 datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2604 if (isnull)
2605 elog(ERROR, "unexpected null in pg_database");
2606 }
2607 else
2608 {
2609 datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2610 if (isnull)
2611 elog(ERROR, "unexpected null in pg_database");
2612 }
2613
2615 TextDatumGetCString(datum));
2616
2617 /* cannot change from NULL to non-NULL or vice versa */
2618 if ((!oldversion && newversion) || (oldversion && !newversion))
2619 elog(ERROR, "invalid collation version change");
2620 else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2621 {
2622 bool nulls[Natts_pg_database] = {0};
2623 bool replaces[Natts_pg_database] = {0};
2625 HeapTuple newtuple;
2626
2628 (errmsg("changing version from %s to %s",
2630
2633
2634 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2635 values, nulls, replaces);
2636 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2637 heap_freetuple(newtuple);
2638 }
2639 else
2641 (errmsg("version has not changed")));
2643
2645
2646 ObjectAddressSet(address, DatabaseRelationId, db_id);
2647
2648 systable_endscan(scan);
2649
2650 table_close(rel, NoLock);
2651
2652 return address;
2653}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define TextDatumGetCString(d)
Definition builtins.h:99
#define elog(elevel,...)
Definition elog.h:228
#define NOTICE
Definition elog.h:36
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition pg_locale.c:1247

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), CStringGetTextDatum, elog, ereport, errcode(), errmsg, ERROR, fb(), Form_pg_database, get_collation_actual_version(), GETSTRUCT(), GetUserId(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvokeObjectPostAlterHook, LockTuple(), 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, UnlockTuple(), and values.

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2660 of file dbcommands.c.

2661{
2662 Oid datid = get_database_oid(stmt->dbname, false);
2663
2664 /*
2665 * Obtain a lock on the database and make sure it didn't go away in the
2666 * meantime.
2667 */
2669
2672 stmt->dbname);
2673
2674 AlterSetting(datid, InvalidOid, stmt->setstmt);
2675
2677
2678 return datid;
2679}
Oid get_database_oid(const char *dbname, bool missing_ok)
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1148
#define AccessShareLock
Definition lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)

References AccessShareLock, aclcheck_error(), ACLCHECK_NOT_OWNER, AlterSetting(), fb(), 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 3116 of file dbcommands.c.

3117{
3118 bool result = false;
3119 Relation rel;
3120 TableScanDesc scan;
3121 HeapTuple tuple;
3122
3124 scan = table_beginscan_catalog(rel, 0, NULL);
3125 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3126 {
3128 Oid dsttablespace = spcform->oid;
3129 char *dstpath;
3130 struct stat st;
3131
3132 /* Don't mess with the global tablespace */
3134 continue;
3135
3137
3138 if (lstat(dstpath, &st) == 0)
3139 {
3140 /* Found a conflicting file (or directory, whatever) */
3141 pfree(dstpath);
3142 result = true;
3143 break;
3144 }
3145
3146 pfree(dstpath);
3147 }
3148
3149 table_endscan(scan);
3151
3152 return result;
3153}
uint32 result
static char dstpath[MAXPGPATH]
Definition file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1435
void pfree(void *pointer)
Definition mcxt.c:1616
END_CATALOG_STRUCT typedef FormData_pg_tablespace * Form_pg_tablespace
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition relpath.c:110
@ ForwardScanDirection
Definition sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1061
#define lstat(path, sb)
Definition win32_port.h:275

References AccessShareLock, dstpath, fb(), Form_pg_tablespace, ForwardScanDirection, GetDatabasePath(), GETSTRUCT(), heap_getnext(), lstat, pfree(), result, 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 1612 of file dbcommands.c.

1613{
1615 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1616
1617 if (!(ctype_encoding == encoding ||
1619 ctype_encoding == -1 ||
1620#ifdef WIN32
1621 encoding == PG_UTF8 ||
1622#endif
1623 (encoding == PG_SQL_ASCII && superuser())))
1624 ereport(ERROR,
1626 errmsg("encoding \"%s\" does not match locale \"%s\"",
1628 ctype),
1629 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1631
1632 if (!(collate_encoding == encoding ||
1634 collate_encoding == -1 ||
1635#ifdef WIN32
1636 encoding == PG_UTF8 ||
1637#endif
1638 (encoding == PG_SQL_ASCII && superuser())))
1639 ereport(ERROR,
1641 errmsg("encoding \"%s\" does not match locale \"%s\"",
1643 collate),
1644 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1646}
int errdetail(const char *fmt,...) pg_attribute_printf(1
static char * encoding
Definition initdb.c:139
#define PG_UTF8
Definition mbprint.c:43
@ PG_SQL_ASCII
Definition pg_wchar.h:76
#define pg_encoding_to_char
Definition pg_wchar.h:483
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition chklocale.c:301
bool superuser(void)
Definition superuser.c:47

References encoding, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), 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 554 of file dbcommands.c.

556{
557 TableScanDesc scan;
558 Relation rel;
559 HeapTuple tuple;
560
561 /*
562 * Force a checkpoint before starting the copy. This will force all dirty
563 * buffers, including those of unlogged tables, out to disk, to ensure
564 * source database is up-to-date on disk for the copy.
565 * FlushDatabaseBuffers() would suffice for that, but we also want to
566 * process any pending unlink requests. Otherwise, if a checkpoint
567 * happened while we're copying files, a file might be deleted just when
568 * we're about to copy it, causing the lstat() call in copydir() to fail
569 * with ENOENT.
570 *
571 * In binary upgrade mode, we can skip this checkpoint because pg_upgrade
572 * is careful to ensure that template0 is fully written to disk prior to
573 * any CREATE DATABASE commands.
574 */
575 if (!IsBinaryUpgrade)
578
579 /*
580 * Iterate through all tablespaces of the template database, and copy each
581 * one to the new database.
582 */
584 scan = table_beginscan_catalog(rel, 0, NULL);
585 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
586 {
590 char *srcpath;
591 char *dstpath;
592 struct stat st;
593
594 /* No need to copy global tablespace */
596 continue;
597
599
600 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
602 {
603 /* Assume we can ignore it */
604 pfree(srcpath);
605 continue;
606 }
607
608 if (srctablespace == src_tsid)
610 else
612
614
615 /*
616 * Copy this subdirectory to the new location
617 *
618 * We don't need to copy subdirectories
619 */
620 copydir(srcpath, dstpath, false);
621
622 /* Record the filesystem change in XLOG */
623 {
625
627 xlrec.tablespace_id = dsttablespace;
628 xlrec.src_db_id = src_dboid;
629 xlrec.src_tablespace_id = srctablespace;
630
634
637 }
638 pfree(srcpath);
639 pfree(dstpath);
640 }
641 table_endscan(scan);
643
644 /*
645 * We force a checkpoint before committing. This effectively means that
646 * committed XLOG_DBASE_CREATE_FILE_COPY operations will never need to be
647 * replayed (at least not in ordinary crash recovery; we still have to
648 * make the XLOG entry for the benefit of PITR operations). This avoids
649 * two nasty scenarios:
650 *
651 * #1: At wal_level=minimal, we don't XLOG the contents of newly created
652 * relfilenodes; therefore the drop-and-recreate-whole-directory behavior
653 * of DBASE_CREATE replay would lose such files created in the new
654 * database between our commit and the next checkpoint.
655 *
656 * #2: Since we have to recopy the source database during DBASE_CREATE
657 * replay, we run the risk of copying changes in it that were committed
658 * after the original CREATE DATABASE command but before the system crash
659 * that led to the replay. This is at least unexpected and at worst could
660 * lead to inconsistencies, eg duplicate table names.
661 *
662 * (Both of these were real bugs in releases 8.0 through 8.0.3.)
663 *
664 * In PITR replay, the first of these isn't an issue, and the second is
665 * only a risk if the CREATE DATABASE and subsequent template database
666 * change both occur while a base backup is being taken. There doesn't
667 * seem to be much we can do about that except document it as a
668 * limitation.
669 *
670 * In binary upgrade mode, we can skip this checkpoint because neither of
671 * these problems applies: we don't ever replay the WAL generated during
672 * pg_upgrade, and we don't support taking base backups during pg_upgrade
673 * (not to mention that we don't concurrently modify template0, either).
674 *
675 * See CreateDatabaseUsingWalLog() for a less cheesy CREATE DATABASE
676 * strategy that avoids these problems.
677 */
678 if (!IsBinaryUpgrade)
681}
bool directory_is_empty(const char *path)
Definition tablespace.c:861
void RequestCheckpoint(int flags)
void copydir(const char *fromdir, const char *todir, bool recurse)
Definition copydir.c:49
#define XLOG_DBASE_CREATE_FILE_COPY
bool IsBinaryUpgrade
Definition globals.c:123
#define stat
Definition win32_port.h:74
#define S_ISDIR(m)
Definition win32_port.h:315
#define CHECKPOINT_FLUSH_UNLOGGED
Definition xlog.h:155
#define CHECKPOINT_FORCE
Definition xlog.h:154
#define CHECKPOINT_WAIT
Definition xlog.h:157
#define CHECKPOINT_FAST
Definition xlog.h:153
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:482
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:372
void XLogBeginInsert(void)
Definition xloginsert.c:153
#define XLR_SPECIAL_REL_UPDATE
Definition xlogrecord.h:82

References AccessShareLock, CHECKPOINT_FAST, CHECKPOINT_FLUSH_UNLOGGED, CHECKPOINT_FORCE, CHECKPOINT_WAIT, copydir(), xl_dbase_create_file_copy_rec::db_id, directory_is_empty(), dstpath, fb(), Form_pg_tablespace, ForwardScanDirection, GetDatabasePath(), GETSTRUCT(), heap_getnext(), IsBinaryUpgrade, pfree(), RequestCheckpoint(), S_ISDIR, stat::st_mode, stat, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), 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 151 of file dbcommands.c.

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

References AccessShareLock, Assert, CreateAndCopyRelationData(), CreateDirAndVersionFile(), LockRelId::dbId, dstpath, fb(), GetDatabasePath(), lfirst, list_free_deep(), LockRelationId(), NIL, pfree(), RelationMapCopy(), LockRelId::relId, ScanSourceDatabasePgClass(), and UnlockRelationId().

Referenced by createdb().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 687 of file dbcommands.c.

688{
689 Oid src_dboid;
691 int src_encoding = -1;
692 char *src_collate = NULL;
693 char *src_ctype = NULL;
694 char *src_locale = NULL;
695 char *src_icurules = NULL;
696 char src_locprovider = '\0';
697 char *src_collversion = NULL;
698 bool src_istemplate;
699 bool src_hasloginevt = false;
700 bool src_allowconn;
704 volatile Oid dst_deftablespace;
706 HeapTuple tuple;
709 Oid dboid = InvalidOid;
710 Oid datdba;
728 char *dbname = stmt->dbname;
729 char *dbowner = NULL;
730 const char *dbtemplate = NULL;
731 char *dbcollate = NULL;
732 char *dbctype = NULL;
733 const char *dblocale = NULL;
734 char *dbicurules = NULL;
735 char dblocprovider = '\0';
736 char *canonname;
737 int encoding = -1;
738 bool dbistemplate = false;
739 bool dballowconnections = true;
741 char *dbcollversion = NULL;
742 int notherbackends;
743 int npreparedxacts;
746
747 /* Report error if name has \n or \r character. */
748 if (strpbrk(dbname, "\n\r"))
751 errmsg("database name \"%s\" contains a newline or carriage return character", dbname)));
752
753 /* Extract options from the statement node tree */
754 foreach(option, stmt->options)
755 {
757
758 if (strcmp(defel->defname, "tablespace") == 0)
759 {
763 }
764 else if (strcmp(defel->defname, "owner") == 0)
765 {
766 if (ownerEl)
768 ownerEl = defel;
769 }
770 else if (strcmp(defel->defname, "template") == 0)
771 {
772 if (templateEl)
775 }
776 else if (strcmp(defel->defname, "encoding") == 0)
777 {
778 if (encodingEl)
781 }
782 else if (strcmp(defel->defname, "locale") == 0)
783 {
784 if (localeEl)
786 localeEl = defel;
787 }
788 else if (strcmp(defel->defname, "builtin_locale") == 0)
789 {
790 if (builtinlocaleEl)
793 }
794 else if (strcmp(defel->defname, "lc_collate") == 0)
795 {
796 if (collateEl)
799 }
800 else if (strcmp(defel->defname, "lc_ctype") == 0)
801 {
802 if (ctypeEl)
804 ctypeEl = defel;
805 }
806 else if (strcmp(defel->defname, "icu_locale") == 0)
807 {
808 if (iculocaleEl)
811 }
812 else if (strcmp(defel->defname, "icu_rules") == 0)
813 {
814 if (icurulesEl)
817 }
818 else if (strcmp(defel->defname, "locale_provider") == 0)
819 {
820 if (locproviderEl)
823 }
824 else if (strcmp(defel->defname, "is_template") == 0)
825 {
826 if (istemplateEl)
829 }
830 else if (strcmp(defel->defname, "allow_connections") == 0)
831 {
835 }
836 else if (strcmp(defel->defname, "connection_limit") == 0)
837 {
838 if (connlimitEl)
841 }
842 else if (strcmp(defel->defname, "collation_version") == 0)
843 {
844 if (collversionEl)
847 }
848 else if (strcmp(defel->defname, "location") == 0)
849 {
852 errmsg("LOCATION is not supported anymore"),
853 errhint("Consider using tablespaces instead."),
854 parser_errposition(pstate, defel->location)));
855 }
856 else if (strcmp(defel->defname, "oid") == 0)
857 {
858 dboid = defGetObjectId(defel);
859
860 /*
861 * We don't normally permit new databases to be created with
862 * system-assigned OIDs. pg_upgrade tries to preserve database
863 * OIDs, so we can't allow any database to be created with an OID
864 * that might be in use in a freshly-initialized cluster created
865 * by some future version. We assume all such OIDs will be from
866 * the system-managed OID range.
867 *
868 * As an exception, however, we permit any OID to be assigned when
869 * allow_system_table_mods=on (so that initdb can assign system
870 * OIDs to template0 and postgres) or when performing a binary
871 * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
872 * in the source cluster).
873 */
874 if (dboid < FirstNormalObjectId &&
878 errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
879 }
880 else if (strcmp(defel->defname, "strategy") == 0)
881 {
882 if (strategyEl)
885 }
886 else
889 errmsg("option \"%s\" not recognized", defel->defname),
890 parser_errposition(pstate, defel->location)));
891 }
892
893 if (ownerEl && ownerEl->arg)
895 if (templateEl && templateEl->arg)
897 if (encodingEl && encodingEl->arg)
898 {
899 const char *encoding_name;
900
901 if (IsA(encodingEl->arg, Integer))
902 {
905 if (strcmp(encoding_name, "") == 0 ||
909 errmsg("%d is not a valid encoding code",
910 encoding),
911 parser_errposition(pstate, encodingEl->location)));
912 }
913 else
914 {
917 if (encoding < 0)
920 errmsg("%s is not a valid encoding name",
922 parser_errposition(pstate, encodingEl->location)));
923 }
924 }
925 if (localeEl && localeEl->arg)
926 {
930 }
933 if (collateEl && collateEl->arg)
935 if (ctypeEl && ctypeEl->arg)
937 if (iculocaleEl && iculocaleEl->arg)
939 if (icurulesEl && icurulesEl->arg)
941 if (locproviderEl && locproviderEl->arg)
942 {
944
945 if (pg_strcasecmp(locproviderstr, "builtin") == 0)
947 else if (pg_strcasecmp(locproviderstr, "icu") == 0)
949 else if (pg_strcasecmp(locproviderstr, "libc") == 0)
951 else
954 errmsg("unrecognized locale provider: %s",
956 }
957 if (istemplateEl && istemplateEl->arg)
961 if (connlimitEl && connlimitEl->arg)
962 {
967 errmsg("invalid connection limit: %d", dbconnlimit)));
968 }
969 if (collversionEl)
971
972 /* obtain OID of proposed owner */
973 if (dbowner)
974 datdba = get_role_oid(dbowner, false);
975 else
976 datdba = GetUserId();
977
978 /*
979 * To create a database, must have createdb privilege and must be able to
980 * become the target role (this does not imply that the target role itself
981 * must have createdb privilege). The latter provision guards against
982 * "giveaway" attacks. Note that a superuser will always have both of
983 * these privileges a fortiori.
984 */
988 errmsg("permission denied to create database")));
989
991
992 /*
993 * Lookup database (template) to be cloned, and obtain share lock on it.
994 * ShareLock allows two CREATE DATABASEs to work from the same template
995 * concurrently, while ensuring no one is busy dropping it in parallel
996 * (which would be Very Bad since we'd likely get an incomplete copy
997 * without knowing it). This also prevents any new connections from being
998 * made to the source until we finish copying it, so we can be sure it
999 * won't change underneath us.
1000 */
1001 if (!dbtemplate)
1002 dbtemplate = "template1"; /* Default template database name */
1003
1005 &src_dboid, &src_owner, &src_encoding,
1010 ereport(ERROR,
1012 errmsg("template database \"%s\" does not exist",
1013 dbtemplate)));
1014
1015 /*
1016 * If the source database was in the process of being dropped, we can't
1017 * use it as a template.
1018 */
1019 if (database_is_invalid_oid(src_dboid))
1020 ereport(ERROR,
1022 errmsg("cannot use invalid database \"%s\" as template", dbtemplate),
1023 errhint("Use DROP DATABASE to drop invalid databases."));
1024
1025 /*
1026 * Permission check: to copy a DB that's not marked datistemplate, you
1027 * must be superuser or the owner thereof.
1028 */
1029 if (!src_istemplate)
1030 {
1032 ereport(ERROR,
1034 errmsg("permission denied to copy database \"%s\"",
1035 dbtemplate)));
1036 }
1037
1038 /* Validate the database creation strategy. */
1039 if (strategyEl && strategyEl->arg)
1040 {
1041 char *strategy;
1042
1043 strategy = defGetString(strategyEl);
1044 if (pg_strcasecmp(strategy, "wal_log") == 0)
1046 else if (pg_strcasecmp(strategy, "file_copy") == 0)
1047 {
1049 ereport(ERROR,
1051 errmsg("create database strategy \"%s\" not allowed when data checksums are being enabled",
1052 strategy));
1054 }
1055 else
1056 ereport(ERROR,
1058 errmsg("invalid create database strategy \"%s\"", strategy),
1059 errhint("Valid strategies are \"wal_log\" and \"file_copy\".")));
1060 }
1061
1062 /* If encoding or locales are defaulted, use source's setting */
1063 if (encoding < 0)
1065 if (dbcollate == NULL)
1067 if (dbctype == NULL)
1069 if (dblocprovider == '\0')
1073 if (dbicurules == NULL)
1075
1076 /* Some encodings are client only */
1078 ereport(ERROR,
1080 errmsg("invalid server encoding %d", encoding)));
1081
1082 /* Check that the chosen locales are valid, and get canonical spellings */
1084 {
1086 ereport(ERROR,
1088 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1089 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1090 else if (dblocprovider == COLLPROVIDER_ICU)
1091 ereport(ERROR,
1093 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1094 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1095 else
1096 ereport(ERROR,
1098 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate)));
1099 }
1102 {
1104 ereport(ERROR,
1106 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1107 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1108 else if (dblocprovider == COLLPROVIDER_ICU)
1109 ereport(ERROR,
1111 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1112 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1113 else
1114 ereport(ERROR,
1116 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype)));
1117 }
1118
1120
1122
1123 /* validate provider-specific parameters */
1125 {
1126 if (builtinlocaleEl)
1127 ereport(ERROR,
1129 errmsg("BUILTIN_LOCALE cannot be specified unless locale provider is builtin")));
1130 }
1131
1133 {
1134 if (iculocaleEl)
1135 ereport(ERROR,
1137 errmsg("ICU locale cannot be specified unless locale provider is ICU")));
1138
1139 if (dbicurules)
1140 ereport(ERROR,
1142 errmsg("ICU rules cannot be specified unless locale provider is ICU")));
1143 }
1144
1145 /* validate and canonicalize locale for the provider */
1147 {
1148 /*
1149 * This would happen if template0 uses the libc provider but the new
1150 * database uses builtin.
1151 */
1152 if (!dblocale)
1153 ereport(ERROR,
1155 errmsg("LOCALE or BUILTIN_LOCALE must be specified")));
1156
1158 }
1159 else if (dblocprovider == COLLPROVIDER_ICU)
1160 {
1162 ereport(ERROR,
1164 errmsg("encoding \"%s\" is not supported with ICU provider",
1166
1167 /*
1168 * This would happen if template0 uses the libc provider but the new
1169 * database uses icu.
1170 */
1171 if (!dblocale)
1172 ereport(ERROR,
1174 errmsg("LOCALE or ICU_LOCALE must be specified")));
1175
1176 /*
1177 * During binary upgrade, or when the locale came from the template
1178 * database, preserve locale string. Otherwise, canonicalize to a
1179 * language tag.
1180 */
1182 {
1185
1186 if (langtag && strcmp(dblocale, langtag) != 0)
1187 {
1189 (errmsg("using standard form \"%s\" for ICU locale \"%s\"",
1190 langtag, dblocale)));
1191
1192 dblocale = langtag;
1193 }
1194 }
1195
1197 }
1198
1199 /* for libc, locale comes from datcollate and datctype */
1201 dblocale = NULL;
1202
1203 /*
1204 * Check that the new encoding and locale settings match the source
1205 * database. We insist on this because we simply copy the source data ---
1206 * any non-ASCII data would be wrongly encoded, and any indexes sorted
1207 * according to the source locale would be wrong.
1208 *
1209 * However, we assume that template0 doesn't contain any non-ASCII data
1210 * nor any indexes that depend on collation or ctype, so template0 can be
1211 * used as template for creating a database with any encoding or locale.
1212 */
1213 if (strcmp(dbtemplate, "template0") != 0)
1214 {
1215 if (encoding != src_encoding)
1216 ereport(ERROR,
1218 errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1221 errhint("Use the same encoding as in the template database, or use template0 as template.")));
1222
1223 if (strcmp(dbcollate, src_collate) != 0)
1224 ereport(ERROR,
1226 errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1228 errhint("Use the same collation as in the template database, or use template0 as template.")));
1229
1230 if (strcmp(dbctype, src_ctype) != 0)
1231 ereport(ERROR,
1233 errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1235 errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1236
1238 ereport(ERROR,
1240 errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1242 errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1243
1245 {
1246 char *val1;
1247 char *val2;
1248
1251 if (strcmp(dblocale, src_locale) != 0)
1252 ereport(ERROR,
1254 errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1256 errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1257
1258 val1 = dbicurules;
1259 if (!val1)
1260 val1 = "";
1262 if (!val2)
1263 val2 = "";
1264 if (strcmp(val1, val2) != 0)
1265 ereport(ERROR,
1267 errmsg("new ICU collation rules (%s) are incompatible with the ICU collation rules of the template database (%s)",
1268 val1, val2),
1269 errhint("Use the same ICU collation rules as in the template database, or use template0 as template.")));
1270 }
1271 }
1272
1273 /*
1274 * If we got a collation version for the template database, check that it
1275 * matches the actual OS collation version. Otherwise error; the user
1276 * needs to fix the template database first. Don't complain if a
1277 * collation version was specified explicitly as a statement option; that
1278 * is used by pg_upgrade to reproduce the old state exactly.
1279 *
1280 * (If the template database has no collation version, then either the
1281 * platform/provider does not support collation versioning, or it's
1282 * template0, for which we stipulate that it does not contain
1283 * collation-using objects.)
1284 */
1286 {
1287 char *actual_versionstr;
1288 const char *locale;
1289
1291 locale = dbcollate;
1292 else
1293 locale = dblocale;
1294
1296 if (!actual_versionstr)
1297 ereport(ERROR,
1298 (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1299 dbtemplate)));
1300
1302 ereport(ERROR,
1303 (errmsg("template database \"%s\" has a collation version mismatch",
1304 dbtemplate),
1305 errdetail("The template database was created using collation version %s, "
1306 "but the operating system provides version %s.",
1308 errhint("Rebuild all objects in the template database that use the default collation and run "
1309 "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1310 "or build PostgreSQL with the right library version.",
1312 }
1313
1314 if (dbcollversion == NULL)
1316
1317 /*
1318 * Normally, we copy the collation version from the template database.
1319 * This last resort only applies if the template database does not have a
1320 * collation version, which is normally only the case for template0.
1321 */
1322 if (dbcollversion == NULL)
1323 {
1324 const char *locale;
1325
1327 locale = dbcollate;
1328 else
1329 locale = dblocale;
1330
1332 }
1333
1334 /* Resolve default tablespace for new database */
1336 {
1337 char *tablespacename;
1339
1340 tablespacename = defGetString(tablespacenameEl);
1341 dst_deftablespace = get_tablespace_oid(tablespacename, false);
1342 /* check permissions */
1344 ACL_CREATE);
1345 if (aclresult != ACLCHECK_OK)
1347 tablespacename);
1348
1349 /* pg_global must never be the default tablespace */
1351 ereport(ERROR,
1353 errmsg("pg_global cannot be used as default tablespace")));
1354
1355 /*
1356 * If we are trying to change the default tablespace of the template,
1357 * we require that the template not have any files in the new default
1358 * tablespace. This is necessary because otherwise the copied
1359 * database would contain pg_class rows that refer to its default
1360 * tablespace both explicitly (by OID) and implicitly (as zero), which
1361 * would cause problems. For example another CREATE DATABASE using
1362 * the copied database as template, and trying to change its default
1363 * tablespace again, would yield outright incorrect results (it would
1364 * improperly move tables to the new default tablespace that should
1365 * stay in the same tablespace).
1366 */
1368 {
1369 char *srcpath;
1370 struct stat st;
1371
1373
1374 if (stat(srcpath, &st) == 0 &&
1375 S_ISDIR(st.st_mode) &&
1377 ereport(ERROR,
1379 errmsg("cannot assign new default tablespace \"%s\"",
1380 tablespacename),
1381 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1382 dbtemplate)));
1383 pfree(srcpath);
1384 }
1385 }
1386 else
1387 {
1388 /* Use template database's default tablespace */
1390 /* Note there is no additional permission check in this path */
1391 }
1392
1393 /*
1394 * If built with appropriate switch, whine when regression-testing
1395 * conventions for database names are violated. But don't complain during
1396 * initdb.
1397 */
1398#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1399 if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1400 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1401#endif
1402
1403 /*
1404 * Check for db name conflict. This is just to give a more friendly error
1405 * message than "unique index violation". There's a race condition but
1406 * we're willing to accept the less friendly message in that case.
1407 */
1409 ereport(ERROR,
1411 errmsg("database \"%s\" already exists", dbname)));
1412
1413 /*
1414 * The source DB can't have any active backends, except this one
1415 * (exception is to allow CREATE DB while connected to template1).
1416 * Otherwise we might copy inconsistent data.
1417 *
1418 * This should be last among the basic error checks, because it involves
1419 * potential waiting; we may as well throw an error first if we're gonna
1420 * throw one.
1421 */
1423 ereport(ERROR,
1425 errmsg("source database \"%s\" is being accessed by other users",
1426 dbtemplate),
1428
1429 /*
1430 * Select an OID for the new database, checking that it doesn't have a
1431 * filename conflict with anything already existing in the tablespace
1432 * directories.
1433 */
1435
1436 /*
1437 * If database OID is configured, check if the OID is already in use or
1438 * data directory already exists.
1439 */
1440 if (OidIsValid(dboid))
1441 {
1442 char *existing_dbname = get_database_name(dboid);
1443
1444 if (existing_dbname != NULL)
1445 ereport(ERROR,
1447 errmsg("database OID %u is already in use by database \"%s\"",
1448 dboid, existing_dbname));
1449
1450 if (check_db_file_conflict(dboid))
1451 ereport(ERROR,
1453 errmsg("data directory with the specified OID %u already exists", dboid));
1454 }
1455 else
1456 {
1457 /* Select an OID for the new database if is not explicitly configured. */
1458 do
1459 {
1462 } while (check_db_file_conflict(dboid));
1463 }
1464
1465 /*
1466 * Insert a new tuple into pg_database. This establishes our ownership of
1467 * the new database name (anyone else trying to insert the same name will
1468 * block on the unique index, and fail after we commit).
1469 */
1470
1473
1474 /* Form tuple */
1490 if (dblocale)
1492 else
1494 if (dbicurules)
1496 else
1498 if (dbcollversion)
1500 else
1502
1503 /*
1504 * We deliberately set datacl to default (NULL), rather than copying it
1505 * from the template database. Copying it would be a bad idea when the
1506 * owner is not the same as the template's owner.
1507 */
1509
1512
1514
1515 /*
1516 * Now generate additional catalog entries associated with the new DB
1517 */
1518
1519 /* Register owner dependency */
1521
1522 /* Create pg_shdepend entries for objects within database */
1523 copyTemplateDependencies(src_dboid, dboid);
1524
1525 /* Post creation hook for new database */
1527
1528 /*
1529 * If we're going to be reading data for the to-be-created database into
1530 * shared_buffers, take a lock on it. Nobody should know that this
1531 * database exists yet, but it's good to maintain the invariant that an
1532 * AccessExclusiveLock on the database is sufficient to drop all of its
1533 * buffers without worrying about more being read later.
1534 *
1535 * Note that we need to do this before entering the
1536 * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1537 * expects this lock to be held already.
1538 */
1541
1542 /*
1543 * Once we start copying subdirectories, we need to be able to clean 'em
1544 * up if we fail. Use an ENSURE block to make sure this happens. (This
1545 * is not a 100% solution, because of the possibility of failure during
1546 * transaction commit after we leave this routine, but it should handle
1547 * most scenarios.)
1548 */
1549 fparms.src_dboid = src_dboid;
1550 fparms.dest_dboid = dboid;
1551 fparms.strategy = dbstrategy;
1552
1555 {
1556 /*
1557 * If the user has asked to create a database with WAL_LOG strategy
1558 * then call CreateDatabaseUsingWalLog, which will copy the database
1559 * at the block level and it will WAL log each copied block.
1560 * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1561 * database file by file.
1562 */
1566 else
1569
1570 /*
1571 * Close pg_database, but keep lock till commit.
1572 */
1574
1575 /*
1576 * Force synchronous commit, thus minimizing the window between
1577 * creation of the database files and committal of the transaction. If
1578 * we crash before committing, we'll have a DB that's taking up disk
1579 * space but is not in pg_database, which is not good.
1580 */
1582 }
1585
1586 return dboid;
1587}
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition acl.c:5605
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
TransactionId MultiXactId
Definition c.h:746
uint32 TransactionId
Definition c.h:736
#define OidIsValid(objectId)
Definition c.h:858
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition dbcommands.c:151
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
static bool check_db_file_conflict(Oid db_id)
static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition dbcommands.c:554
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 createdb_failure_callback(int code, Datum arg)
bool database_is_invalid_oid(Oid dboid)
Oid defGetObjectId(DefElem *def)
Definition define.c:205
#define WARNING
Definition elog.h:37
bool is_encoding_supported_by_icu(int encoding)
Definition encnames.c:453
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
bool IsUnderPostmaster
Definition globals.c:122
bool allowSystemTableMods
Definition globals.c:132
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:52
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
#define ShareLock
Definition lockdefs.h:40
char * get_database_name(Oid dbid)
Definition lsyscache.c:1312
#define InvalidMultiXactId
Definition multixact.h:25
Datum namein(PG_FUNCTION_ARGS)
Definition name.c:48
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define InvokeObjectPostCreateHook(classId, objectId, subId)
@ OBJECT_TABLESPACE
#define ACL_CREATE
Definition parsenodes.h:85
int icu_validation_level
Definition pg_locale.c:92
void icu_validate_locale(const char *loc_str)
Definition pg_locale.c:1789
char * icu_language_tag(const char *loc_str, int elevel)
Definition pg_locale.c:1731
const char * builtin_validate_locale(int encoding, const char *locale)
Definition pg_locale.c:1691
bool check_locale(int category, const char *locale, char **canonname)
Definition pg_locale.c:275
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
#define PG_VALID_BE_ENCODING(_enc)
Definition pg_wchar.h:134
#define pg_valid_server_encoding
Definition pg_wchar.h:484
int pg_strcasecmp(const char *s1, const char *s2)
static Datum TransactionIdGetDatum(TransactionId X)
Definition postgres.h:292
static Datum CharGetDatum(char X)
Definition postgres.h:132
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition procarray.c:3755
const char * quote_identifier(const char *ident)
#define InvalidTransactionId
Definition transam.h:31
#define FirstNormalObjectId
Definition transam.h:197
void ForceSyncCommit(void)
Definition xact.c:1182
bool DataChecksumsInProgressOn(void)
Definition xlog.c:4686

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, allowSystemTableMods, 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(), DataChecksumsInProgressOn(), DATCONNLIMIT_UNLIMITED, dbname, defGetBoolean(), defGetInt32(), defGetObjectId(), defGetString(), DirectFunctionCall1, directory_is_empty(), elog, encoding, ereport, errcode(), errdetail(), errdetail_busy_db(), errhint(), errmsg, ERROR, errorConflictingDefElem(), fb(), 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, 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, stat::st_mode, stat, stmt, 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 1650 of file dbcommands.c.

1651{
1653
1654 /*
1655 * If we were copying database at block levels then drop pages for the
1656 * destination database that are in the shared buffer cache. And tell
1657 * checkpointer to forget any pending fsync and unlink requests for files
1658 * in the database. The reasoning behind doing this is same as explained
1659 * in dropdb function. But unlike dropdb we don't need to call
1660 * pgstat_drop_database because this database is still not created so
1661 * there should not be any stat for this.
1662 */
1663 if (fparms->strategy == CREATEDB_WAL_LOG)
1664 {
1665 DropDatabaseBuffers(fparms->dest_dboid);
1667
1668 /* Release lock on the target database. */
1671 }
1672
1673 /*
1674 * Release lock on source database before doing recursive remove. This is
1675 * not essential but it seems desirable to release the lock as soon as
1676 * possible.
1677 */
1679
1680 /* Throw away any successfully copied subdirectories */
1681 remove_dbtablespaces(fparms->dest_dboid);
1682}
void DropDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5115
static void remove_dbtablespaces(Oid db_id)
Datum arg
Definition elog.c:1322
void ForgetDatabaseSyncRequests(Oid dbid)
Definition md.c:1594
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332

References AccessShareLock, arg, CREATEDB_WAL_LOG, DatumGetPointer(), DropDatabaseBuffers(), fb(), ForgetDatabaseSyncRequests(), remove_dbtablespaces(), ShareLock, and UnlockSharedObject().

Referenced by createdb().

◆ CreateDirAndVersionFile()

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

Definition at line 460 of file dbcommands.c.

461{
462 int fd;
463 int nbytes;
465 char buf[16];
466
467 /*
468 * Note that we don't have to copy version data from the source database;
469 * there's only one legal value.
470 */
471 sprintf(buf, "%s\n", PG_MAJORVERSION);
472 nbytes = strlen(PG_MAJORVERSION) + 1;
473
474 /* Create database directory. */
475 if (MakePGDirectory(dbpath) < 0)
476 {
477 /* Failure other than already exists or not in WAL replay? */
478 if (errno != EEXIST || !isRedo)
481 errmsg("could not create directory \"%s\": %m", dbpath)));
482 }
483
484 /*
485 * Create PG_VERSION file in the database path. If the file already
486 * exists and we are in WAL replay then try again to open it in write
487 * mode.
488 */
489 snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
490
492 if (fd < 0 && errno == EEXIST && isRedo)
494
495 if (fd < 0)
498 errmsg("could not create file \"%s\": %m", versionfile)));
499
500 /* Write PG_MAJORVERSION in the PG_VERSION file. */
502 errno = 0;
503 if ((int) write(fd, buf, nbytes) != nbytes)
504 {
505 /* If write didn't set errno, assume problem is no disk space. */
506 if (errno == 0)
507 errno = ENOSPC;
510 errmsg("could not write to file \"%s\": %m", versionfile)));
511 }
513
515 if (pg_fsync(fd) != 0)
518 errmsg("could not fsync file \"%s\": %m", versionfile)));
519 fsync_fname(dbpath, true);
521
522 /* Close the version file. */
524
525 /* If we are not in WAL replay then write the WAL. */
526 if (!isRedo)
527 {
529
531
532 xlrec.db_id = dbid;
533 xlrec.tablespace_id = tsid;
534
538
540
542 }
543}
#define PG_BINARY
Definition c.h:1374
#define XLOG_DBASE_CREATE_WAL_LOG
int errcode_for_file_access(void)
Definition elog.c:897
int MakePGDirectory(const char *directoryName)
Definition fd.c:3963
int CloseTransientFile(int fd)
Definition fd.c:2855
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:757
int data_sync_elevel(int elevel)
Definition fd.c:3986
int pg_fsync(int fd)
Definition fd.c:390
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2678
#define write(a, b, c)
Definition win32.h:14
#define START_CRIT_SECTION()
Definition miscadmin.h:152
#define END_CRIT_SECTION()
Definition miscadmin.h:154
#define MAXPGPATH
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define sprintf
Definition port.h:262
#define snprintf
Definition port.h:260
static int fd(const char *x, int i)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:67
static void pgstat_report_wait_end(void)
Definition wait_event.h:83

References buf, CloseTransientFile(), data_sync_elevel(), END_CRIT_SECTION, ereport, errcode_for_file_access(), errmsg, ERROR, fb(), fd(), fsync_fname(), MakePGDirectory(), MAXPGPATH, OpenTransientFile(), PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), snprintf, sprintf, START_CRIT_SECTION, 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 3236 of file dbcommands.c.

3237{
3238 return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
3239}
#define DATCONNLIMIT_INVALID_DB

References DATCONNLIMIT_INVALID_DB, and fb().

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

3247{
3250 bool invalid;
3251
3253 if (!HeapTupleIsValid(dbtup))
3254 elog(ERROR, "cache lookup failed for database %u", dboid);
3256
3258
3260
3261 return invalid;
3262}
invalidindex index d is invalid
Definition isn.c:138
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

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

Referenced by createdb().

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 3308 of file dbcommands.c.

3309{
3310 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3311
3312 /* Backup blocks are not used in dbase records */
3314
3315 if (info == XLOG_DBASE_CREATE_FILE_COPY)
3316 {
3319 char *src_path;
3320 char *dst_path;
3321 char *parent_path;
3322 struct stat st;
3323
3324 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3325 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3326
3327 /*
3328 * Our theory for replaying a CREATE is to forcibly drop the target
3329 * subdirectory if present, then re-copy the source data. This may be
3330 * more work than needed, but it is simple to implement.
3331 */
3332 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3333 {
3334 if (!rmtree(dst_path, true))
3335 /* If this failed, copydir() below is going to error. */
3337 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3338 dst_path)));
3339 }
3340
3341 /*
3342 * If the parent of the target path doesn't exist, create it now. This
3343 * enables us to create the target underneath later.
3344 */
3347 if (stat(parent_path, &st) < 0)
3348 {
3349 if (errno != ENOENT)
3350 ereport(FATAL,
3351 errmsg("could not stat directory \"%s\": %m",
3352 dst_path));
3353
3354 /* create the parent directory if needed and valid */
3356 }
3358
3359 /*
3360 * There's a case where the copy source directory is missing for the
3361 * same reason above. Create the empty source directory so that
3362 * copydir below doesn't fail. The directory will be dropped soon by
3363 * recovery.
3364 */
3365 if (stat(src_path, &st) < 0 && errno == ENOENT)
3367
3368 /*
3369 * Force dirty buffers out to disk, to ensure source database is
3370 * up-to-date for the copy.
3371 */
3372 FlushDatabaseBuffers(xlrec->src_db_id);
3373
3374 /* Close all smgr fds in all backends. */
3376
3377 /*
3378 * Copy this subdirectory to the new location
3379 *
3380 * We don't need to copy subdirectories
3381 */
3382 copydir(src_path, dst_path, false);
3383
3384 pfree(src_path);
3385 pfree(dst_path);
3386 }
3387 else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3388 {
3391 char *dbpath;
3392 char *parent_path;
3393
3394 dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3395
3396 /* create the parent directory if needed and valid */
3401
3402 /* Create the database directory with the version file. */
3403 CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3404 true);
3405 pfree(dbpath);
3406 }
3407 else if (info == XLOG_DBASE_DROP)
3408 {
3410 char *dst_path;
3411 int i;
3412
3413 if (InHotStandby)
3414 {
3415 /*
3416 * Lock database while we resolve conflicts to ensure that
3417 * InitPostgres() cannot fully re-execute concurrently. This
3418 * avoids backends re-connecting automatically to same database,
3419 * which can happen in some cases.
3420 *
3421 * This will lock out walsenders trying to connect to db-specific
3422 * slots for logical decoding too, so it's safe for us to drop
3423 * slots.
3424 */
3427 }
3428
3429 /* Drop any database-specific replication slots */
3431
3432 /* Drop pages for this database that are in the shared buffer cache */
3433 DropDatabaseBuffers(xlrec->db_id);
3434
3435 /* Also, clean out any fsync requests that might be pending in md.c */
3437
3438 /* Clean out the xlog relcache too */
3439 XLogDropDatabase(xlrec->db_id);
3440
3441 /* Close all smgr fds in all backends. */
3443
3444 for (i = 0; i < xlrec->ntablespaces; i++)
3445 {
3446 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3447
3448 /* And remove the physical files */
3449 if (!rmtree(dst_path, true))
3451 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3452 dst_path)));
3453 pfree(dst_path);
3454 }
3455
3456 if (InHotStandby)
3457 {
3458 /*
3459 * Release locks prior to commit. XXX There is a race condition
3460 * here that may allow backends to reconnect, but the window for
3461 * this is small because the gap between here and commit is mostly
3462 * fairly small and it is unlikely that people will be dropping
3463 * databases that we are trying to connect to anyway.
3464 */
3466 }
3467 }
3468 else
3469 elog(PANIC, "dbase_redo: unknown op code %u", info);
3470}
void FlushDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5526
uint8_t uint8
Definition c.h:622
static void recovery_create_dbdir(char *path, bool only_tblspc)
#define XLOG_DBASE_DROP
#define PANIC
Definition elog.h:44
int i
Definition isn.c:77
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1187
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1169
#define AccessExclusiveLock
Definition lockdefs.h:43
char * pstrdup(const char *in)
Definition mcxt.c:1781
void get_parent_directory(char *path)
Definition path.c:1068
void WaitForProcSignalBarrier(uint64 generation)
Definition procsignal.c:428
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition procsignal.c:360
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition procsignal.h:50
bool rmtree(const char *path, bool rmtopdir)
Definition rmtree.c:50
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition slot.c:1518
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition standby.c:572
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:410
#define XLogRecGetData(decoder)
Definition xlogreader.h:415
#define XLogRecHasAnyBlockRefs(decoder)
Definition xlogreader.h:417
void XLogDropDatabase(Oid dbid)
Definition xlogutils.c:641
#define InHotStandby
Definition xlogutils.h:60

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 2364 of file dbcommands.c.

2365{
2366 bool force = false;
2367 ListCell *lc;
2368
2369 foreach(lc, stmt->options)
2370 {
2371 DefElem *opt = (DefElem *) lfirst(lc);
2372
2373 if (strcmp(opt->defname, "force") == 0)
2374 force = true;
2375 else
2376 ereport(ERROR,
2378 errmsg("unrecognized %s option \"%s\"",
2379 "DROP DATABASE", opt->defname),
2380 parser_errposition(pstate, opt->location)));
2381 }
2382
2383 dropdb(stmt->dbname, stmt->missing_ok, force);
2384}
void dropdb(const char *dbname, bool missing_ok, bool force)
char * defname
Definition parsenodes.h:860
ParseLoc location
Definition parsenodes.h:864

References DefElem::defname, dropdb(), ereport, errcode(), errmsg, ERROR, fb(), 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 1689 of file dbcommands.c.

1690{
1691 Oid db_id;
1692 bool db_istemplate;
1694 HeapTuple tup;
1696 void *inplace_state;
1698 int notherbackends;
1699 int npreparedxacts;
1700 int nslots,
1702 int nsubscriptions;
1703
1704 /*
1705 * Look up the target database's OID, and get exclusive lock on it. We
1706 * need this to ensure that no new backend starts up in the target
1707 * database while we are deleting it (see postinit.c), and that no one is
1708 * using it as a CREATE DATABASE template or trying to delete it for
1709 * themselves.
1710 */
1712
1715 {
1716 if (!missing_ok)
1717 {
1718 ereport(ERROR,
1720 errmsg("database \"%s\" does not exist", dbname)));
1721 }
1722 else
1723 {
1724 /* Close pg_database, release the lock, since we changed nothing */
1727 (errmsg("database \"%s\" does not exist, skipping",
1728 dbname)));
1729 return;
1730 }
1731 }
1732
1733 /*
1734 * Permission checks
1735 */
1738 dbname);
1739
1740 /* DROP hook for the database being removed */
1742
1743 /*
1744 * Disallow dropping a DB that is marked istemplate. This is just to
1745 * prevent people from accidentally dropping template0 or template1; they
1746 * can do so if they're really determined ...
1747 */
1748 if (db_istemplate)
1749 ereport(ERROR,
1751 errmsg("cannot drop a template database")));
1752
1753 /* Obviously can't drop my own database */
1754 if (db_id == MyDatabaseId)
1755 ereport(ERROR,
1757 errmsg("cannot drop the currently open database")));
1758
1759 /*
1760 * Check whether there are active logical slots that refer to the
1761 * to-be-dropped database. The database lock we are holding prevents the
1762 * creation of new slots using the database or existing slots becoming
1763 * active.
1764 */
1766 if (nslots_active)
1767 {
1768 ereport(ERROR,
1770 errmsg("database \"%s\" is used by an active logical replication slot",
1771 dbname),
1772 errdetail_plural("There is %d active slot.",
1773 "There are %d active slots.",
1775 }
1776
1777 /*
1778 * Check if there are subscriptions defined in the target database.
1779 *
1780 * We can't drop them automatically because they might be holding
1781 * resources in other databases/instances.
1782 */
1783 if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1784 ereport(ERROR,
1786 errmsg("database \"%s\" is being used by logical replication subscription",
1787 dbname),
1788 errdetail_plural("There is %d subscription.",
1789 "There are %d subscriptions.",
1791
1792
1793 /*
1794 * Attempt to terminate all existing connections to the target database if
1795 * the user has requested to do so.
1796 */
1797 if (force)
1799
1800 /*
1801 * Check for other backends in the target database. (Because we hold the
1802 * database lock, no new ones can start after this.)
1803 *
1804 * As in CREATE DATABASE, check this after other error conditions.
1805 */
1807 ereport(ERROR,
1809 errmsg("database \"%s\" is being accessed by other users",
1810 dbname),
1812
1813 /*
1814 * Delete any comments or security labels associated with the database.
1815 */
1818
1819 /*
1820 * Remove settings associated with this database
1821 */
1822 DropSetting(db_id, InvalidOid);
1823
1824 /*
1825 * Remove shared dependency references for the database.
1826 */
1828
1829 /*
1830 * Tell the cumulative stats system to forget it immediately, too.
1831 */
1832 pgstat_drop_database(db_id);
1833
1834 /*
1835 * Except for the deletion of the catalog row, subsequent actions are not
1836 * transactional (consider DropDatabaseBuffers() discarding modified
1837 * buffers). But we might crash or get interrupted below. To prevent
1838 * accesses to a database with invalid contents, mark the database as
1839 * invalid using an in-place update.
1840 *
1841 * We need to flush the WAL before continuing, to guarantee the
1842 * modification is durable before performing irreversible filesystem
1843 * operations.
1844 */
1850 NULL, 1, &scankey, &tup, &inplace_state);
1851 if (!HeapTupleIsValid(tup))
1852 elog(ERROR, "cache lookup failed for database %u", db_id);
1854 datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1857
1858 /*
1859 * Also delete the tuple - transactionally. If this transaction commits,
1860 * the row will be gone, but if we fail, dropdb() can be invoked again.
1861 */
1862 CatalogTupleDelete(pgdbrel, &tup->t_self);
1864
1865 /*
1866 * Drop db-specific replication slots.
1867 */
1869
1870 /*
1871 * Drop pages for this database that are in the shared buffer cache. This
1872 * is important to ensure that no remaining backend tries to write out a
1873 * dirty buffer to the dead database later...
1874 */
1875 DropDatabaseBuffers(db_id);
1876
1877 /*
1878 * Tell checkpointer to forget any pending fsync and unlink requests for
1879 * files in the database; else the fsyncs will fail at next checkpoint, or
1880 * worse, it will delete files that belong to a newly created database
1881 * with the same OID.
1882 */
1884
1885 /*
1886 * Force a checkpoint to make sure the checkpointer has received the
1887 * message sent by ForgetDatabaseSyncRequests.
1888 */
1890
1891 /* Close all smgr fds in all backends. */
1893
1894 /*
1895 * Remove all tablespace subdirs belonging to the database.
1896 */
1897 remove_dbtablespaces(db_id);
1898
1899 /*
1900 * Close pg_database, but keep lock till commit.
1901 */
1903
1904 /*
1905 * Force synchronous commit, thus minimizing the window between removal of
1906 * the database files and committal of the transaction. If we crash before
1907 * committing, we'll have a DB that's gone on disk but still there
1908 * according to pg_database, which is not good.
1909 */
1911}
void DeleteSharedComments(Oid oid, Oid classoid)
Definition comment.c:384
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
void systable_inplace_update_begin(Relation relation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, const ScanKeyData *key, HeapTuple *oldtupcopy, void **state)
Definition genam.c:818
void systable_inplace_update_finish(void *state, HeapTuple tuple)
Definition genam.c:894
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
#define InvokeObjectDropHook(classId, objectId, subId)
void DropSetting(Oid databaseid, Oid roleid)
void dropDatabaseDependencies(Oid databaseId)
int CountDBSubscriptions(Oid dbid)
void pgstat_drop_database(Oid databaseid)
void TerminateOtherDBBackends(Oid databaseId)
Definition procarray.c:3848
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition seclabel.c:502
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition slot.c:1457
XLogRecPtr XactLastRecEnd
Definition xlog.c:261
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2801

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleDelete(), CHECKPOINT_FAST, CHECKPOINT_FORCE, CHECKPOINT_WAIT, CountDBSubscriptions(), CountOtherDBBackends(), CStringGetDatum(), DATCONNLIMIT_INVALID_DB, dbname, DeleteSharedComments(), DeleteSharedSecurityLabel(), DropDatabaseBuffers(), dropDatabaseDependencies(), DropSetting(), elog, EmitProcSignalBarrier(), ereport, errcode(), errdetail_busy_db(), errdetail_plural(), errmsg, ERROR, fb(), ForceSyncCommit(), ForgetDatabaseSyncRequests(), Form_pg_database, get_db_info(), GETSTRUCT(), GetUserId(), heap_freetuple(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, MyDatabaseId, NoLock, NOTICE, OBJECT_DATABASE, object_ownercheck(), pgstat_drop_database(), PROCSIGNAL_BARRIER_SMGRRELEASE, remove_dbtablespaces(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), RequestCheckpoint(), RowExclusiveLock, ScanKeyInit(), systable_inplace_update_begin(), systable_inplace_update_finish(), 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 3159 of file dbcommands.c.

3160{
3161 if (notherbackends > 0 && npreparedxacts > 0)
3162
3163 /*
3164 * We don't deal with singular versus plural here, since gettext
3165 * doesn't support multiple plurals in one string.
3166 */
3167 errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3169 else if (notherbackends > 0)
3170 errdetail_plural("There is %d other session using the database.",
3171 "There are %d other sessions using the database.",
3174 else
3175 errdetail_plural("There is %d prepared transaction using the database.",
3176 "There are %d prepared transactions using the database.",
3179 return 0; /* just to keep ereport macro happy */
3180}

References errdetail(), errdetail_plural(), and fb().

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

◆ get_database_oid()

Oid get_database_oid ( const char dbname,
bool  missing_ok 
)

Definition at line 3189 of file dbcommands.c.

3190{
3192 ScanKeyData entry[1];
3193 SysScanDesc scan;
3195 Oid oid;
3196
3197 /*
3198 * There's no syscache for pg_database indexed by name, so we must look
3199 * the hard way.
3200 */
3202 ScanKeyInit(&entry[0],
3207 NULL, 1, entry);
3208
3209 dbtuple = systable_getnext(scan);
3210
3211 /* We assume that there can be at most one matching tuple */
3213 oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3214 else
3215 oid = InvalidOid;
3216
3217 systable_endscan(scan);
3219
3220 if (!OidIsValid(oid) && !missing_ok)
3221 ereport(ERROR,
3223 errmsg("database \"%s\" does not exist",
3224 dbname)));
3225
3226 return oid;
3227}

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum(), dbname, ereport, errcode(), errmsg, ERROR, fb(), Form_pg_database, 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(), pg_database_size_name(), regdatabasein(), 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 2843 of file dbcommands.c.

2851{
2852 bool result = false;
2853 Relation relation;
2854
2855 Assert(name);
2856
2857 /* Caller may wish to grab a better lock on pg_database beforehand... */
2859
2860 /*
2861 * Loop covers the rare case where the database is renamed before we can
2862 * lock it. We try again just in case we can find a new one of the same
2863 * name.
2864 */
2865 for (;;)
2866 {
2868 SysScanDesc scan;
2869 HeapTuple tuple;
2870 Oid dbOid;
2871
2872 /*
2873 * there's no syscache for database-indexed-by-name, so must do it the
2874 * hard way
2875 */
2880
2881 scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2882 NULL, 1, &scanKey);
2883
2884 tuple = systable_getnext(scan);
2885
2886 if (!HeapTupleIsValid(tuple))
2887 {
2888 /* definitely no database of that name */
2889 systable_endscan(scan);
2890 break;
2891 }
2892
2893 dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2894
2895 systable_endscan(scan);
2896
2897 /*
2898 * Now that we have a database OID, we can try to lock the DB.
2899 */
2900 if (lockmode != NoLock)
2901 LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2902
2903 /*
2904 * And now, re-fetch the tuple by OID. If it's still there and still
2905 * the same name, we win; else, drop the lock and loop back to try
2906 * again.
2907 */
2909 if (HeapTupleIsValid(tuple))
2910 {
2912
2913 if (strcmp(name, NameStr(dbform->datname)) == 0)
2914 {
2915 Datum datum;
2916 bool isnull;
2917
2918 /* oid of the database */
2919 if (dbIdP)
2920 *dbIdP = dbOid;
2921 /* oid of the owner */
2922 if (ownerIdP)
2923 *ownerIdP = dbform->datdba;
2924 /* character encoding */
2925 if (encodingP)
2926 *encodingP = dbform->encoding;
2927 /* allowed as template? */
2928 if (dbIsTemplateP)
2929 *dbIsTemplateP = dbform->datistemplate;
2930 /* Has on login event trigger? */
2931 if (dbHasLoginEvtP)
2932 *dbHasLoginEvtP = dbform->dathasloginevt;
2933 /* allowing connections? */
2934 if (dbAllowConnP)
2935 *dbAllowConnP = dbform->datallowconn;
2936 /* limit of frozen XIDs */
2937 if (dbFrozenXidP)
2938 *dbFrozenXidP = dbform->datfrozenxid;
2939 /* minimum MultiXactId */
2940 if (dbMinMultiP)
2941 *dbMinMultiP = dbform->datminmxid;
2942 /* default tablespace for this database */
2943 if (dbTablespace)
2944 *dbTablespace = dbform->dattablespace;
2945 /* default locale settings for this database */
2946 if (dbLocProvider)
2947 *dbLocProvider = dbform->datlocprovider;
2948 if (dbCollate)
2949 {
2952 }
2953 if (dbCtype)
2954 {
2956 *dbCtype = TextDatumGetCString(datum);
2957 }
2958 if (dbLocale)
2959 {
2960 datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datlocale, &isnull);
2961 if (isnull)
2962 *dbLocale = NULL;
2963 else
2964 *dbLocale = TextDatumGetCString(datum);
2965 }
2966 if (dbIcurules)
2967 {
2969 if (isnull)
2970 *dbIcurules = NULL;
2971 else
2973 }
2974 if (dbCollversion)
2975 {
2977 if (isnull)
2979 else
2981 }
2982 ReleaseSysCache(tuple);
2983 result = true;
2984 break;
2985 }
2986 /* can only get here if it was just renamed */
2987 ReleaseSysCache(tuple);
2988 }
2989
2990 if (lockmode != NoLock)
2991 UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2992 }
2993
2994 table_close(relation, AccessShareLock);
2995
2996 return result;
2997}
#define NameStr(name)
Definition c.h:835
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
const char * name

References AccessShareLock, Assert, BTEqualStrategyNumber, CStringGetDatum(), fb(), Form_pg_database, GETSTRUCT(), HeapTupleIsValid, LockSharedObject(), name, NameStr, NoLock, ObjectIdGetDatum(), ReleaseSysCache(), result, 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 3001 of file dbcommands.c.

3002{
3003 bool result = false;
3005
3006 /* Superusers can always do everything */
3007 if (superuser())
3008 return true;
3009
3012 {
3015 }
3016 return result;
3017}
END_CATALOG_STRUCT typedef FormData_pg_authid * Form_pg_authid
Definition pg_authid.h:60
bool rolcreatedb
Definition pg_authid.h:40

References fb(), Form_pg_authid, GETSTRUCT(), GetUserId(), HeapTupleIsValid, ObjectIdGetDatum(), ReleaseSysCache(), result, 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 2025 of file dbcommands.c.

2026{
2027 Oid db_id;
2029 int notherbackends;
2030 int npreparedxacts;
2031 HeapTuple oldtuple,
2032 newtuple;
2038 char *src_dbpath;
2039 char *dst_dbpath;
2040 DIR *dstdir;
2041 struct dirent *xlde;
2043
2044 /*
2045 * Look up the target database's OID, and get exclusive lock on it. We
2046 * need this to ensure that no new backend starts up in the database while
2047 * we are moving it, and that no one is using it as a CREATE DATABASE
2048 * template or trying to delete it.
2049 */
2051
2054 ereport(ERROR,
2056 errmsg("database \"%s\" does not exist", dbname)));
2057
2058 /*
2059 * We actually need a session lock, so that the lock will persist across
2060 * the commit/restart below. (We could almost get away with letting the
2061 * lock be released at commit, except that someone could try to move
2062 * relations of the DB back into the old directory while we rmtree() it.)
2063 */
2066
2067 /*
2068 * Permission checks
2069 */
2072 dbname);
2073
2074 /*
2075 * Obviously can't move the tables of my own database
2076 */
2077 if (db_id == MyDatabaseId)
2078 ereport(ERROR,
2080 errmsg("cannot change the tablespace of the currently open database")));
2081
2082 /*
2083 * Get tablespace's oid
2084 */
2086
2087 /*
2088 * Permission checks
2089 */
2091 ACL_CREATE);
2092 if (aclresult != ACLCHECK_OK)
2094 tblspcname);
2095
2096 /*
2097 * pg_global must never be the default tablespace
2098 */
2100 ereport(ERROR,
2102 errmsg("pg_global cannot be used as default tablespace")));
2103
2104 /*
2105 * No-op if same tablespace
2106 */
2108 {
2112 return;
2113 }
2114
2115 /*
2116 * Check for other backends in the target database. (Because we hold the
2117 * database lock, no new ones can start after this.)
2118 *
2119 * As in CREATE DATABASE, check this after other error conditions.
2120 */
2122 ereport(ERROR,
2124 errmsg("database \"%s\" is being accessed by other users",
2125 dbname),
2127
2128 /*
2129 * Get old and new database paths
2130 */
2133
2134 /*
2135 * Force a checkpoint before proceeding. This will force all dirty
2136 * buffers, including those of unlogged tables, out to disk, to ensure
2137 * source database is up-to-date on disk for the copy.
2138 * FlushDatabaseBuffers() would suffice for that, but we also want to
2139 * process any pending unlink requests. Otherwise, the check for existing
2140 * files in the target directory might fail unnecessarily, not to mention
2141 * that the copy might fail due to source files getting deleted under it.
2142 * On Windows, this also ensures that background procs don't hold any open
2143 * files, which would cause rmdir() to fail.
2144 */
2147
2148 /* Close all smgr fds in all backends. */
2150
2151 /*
2152 * Now drop all buffers holding data of the target database; they should
2153 * no longer be dirty so DropDatabaseBuffers is safe.
2154 *
2155 * It might seem that we could just let these buffers age out of shared
2156 * buffers naturally, since they should not get referenced anymore. The
2157 * problem with that is that if the user later moves the database back to
2158 * its original tablespace, any still-surviving buffers would appear to
2159 * contain valid data again --- but they'd be missing any changes made in
2160 * the database while it was in the new tablespace. In any case, freeing
2161 * buffers that should never be used again seems worth the cycles.
2162 *
2163 * Note: it'd be sufficient to get rid of buffers matching db_id and
2164 * src_tblspcoid, but bufmgr.c presently provides no API for that.
2165 */
2166 DropDatabaseBuffers(db_id);
2167
2168 /*
2169 * Check for existence of files in the target directory, i.e., objects of
2170 * this database that are already in the target tablespace. We can't
2171 * allow the move in such a case, because we would need to change those
2172 * relations' pg_class.reltablespace entries to zero, and we don't have
2173 * access to the DB's pg_class to do so.
2174 */
2176 if (dstdir != NULL)
2177 {
2178 while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
2179 {
2180 if (strcmp(xlde->d_name, ".") == 0 ||
2181 strcmp(xlde->d_name, "..") == 0)
2182 continue;
2183
2184 ereport(ERROR,
2186 errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
2188 errhint("You must move them back to the database's default tablespace before using this command.")));
2189 }
2190
2191 FreeDir(dstdir);
2192
2193 /*
2194 * The directory exists but is empty. We must remove it before using
2195 * the copydir function.
2196 */
2197 if (rmdir(dst_dbpath) != 0)
2198 elog(ERROR, "could not remove directory \"%s\": %m",
2199 dst_dbpath);
2200 }
2201
2202 /*
2203 * Use an ENSURE block to make sure we remove the debris if the copy fails
2204 * (eg, due to out-of-disk-space). This is not a 100% solution, because
2205 * of the possibility of failure during transaction commit, but it should
2206 * handle most scenarios.
2207 */
2208 fparms.dest_dboid = db_id;
2209 fparms.dest_tsoid = dst_tblspcoid;
2212 {
2216
2217 /*
2218 * Copy files from the old tablespace to the new one
2219 */
2220 copydir(src_dbpath, dst_dbpath, false);
2221
2222 /*
2223 * Record the filesystem change in XLOG
2224 */
2225 {
2227
2228 xlrec.db_id = db_id;
2229 xlrec.tablespace_id = dst_tblspcoid;
2230 xlrec.src_db_id = db_id;
2231 xlrec.src_tablespace_id = src_tblspcoid;
2232
2236
2239 }
2240
2241 /*
2242 * Update the database's pg_database tuple
2243 */
2249 NULL, 1, &scankey);
2250 oldtuple = systable_getnext(sysscan);
2251 if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2252 ereport(ERROR,
2254 errmsg("database \"%s\" does not exist", dbname)));
2256
2259
2260 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2261 new_record,
2263 CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2265
2267
2269
2270 /*
2271 * Force another checkpoint here. As in CREATE DATABASE, this is to
2272 * ensure that we don't have to replay a committed
2273 * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2274 * any unlogged operations done in the new DB tablespace before the
2275 * next checkpoint.
2276 */
2278
2279 /*
2280 * Force synchronous commit, thus minimizing the window between
2281 * copying the database files and committal of the transaction. If we
2282 * crash before committing, we'll leave an orphaned set of files on
2283 * disk, which is not fatal but not good either.
2284 */
2286
2287 /*
2288 * Close pg_database, but keep lock till commit.
2289 */
2291 }
2294
2295 /*
2296 * Commit the transaction so that the pg_database update is committed. If
2297 * we crash while removing files, the database won't be corrupt, we'll
2298 * just leave some orphaned files in the old directory.
2299 *
2300 * (This is OK because we know we aren't inside a transaction block.)
2301 *
2302 * XXX would it be safe/better to do this inside the ensure block? Not
2303 * convinced it's a good idea; consider elog just after the transaction
2304 * really commits.
2305 */
2308
2309 /* Start new transaction for the remaining work; don't need a snapshot */
2311
2312 /*
2313 * Remove files from the old tablespace
2314 */
2315 if (!rmtree(src_dbpath, true))
2317 (errmsg("some useless files may be left behind in old database directory \"%s\"",
2318 src_dbpath)));
2319
2320 /*
2321 * Record the filesystem change in XLOG
2322 */
2323 {
2325
2326 xlrec.db_id = db_id;
2327 xlrec.ntablespaces = 1;
2328
2332
2335 }
2336
2337 /* Now it's safe to release the database lock */
2340
2343}
static void movedb_failure_callback(int code, Datum arg)
int FreeDir(DIR *dir)
Definition fd.c:3009
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
void PopActiveSnapshot(void)
Definition snapmgr.c:775
Definition dirent.c:26
void StartTransactionCommand(void)
Definition xact.c:3109
void CommitTransactionCommand(void)
Definition xact.c:3207

References AccessExclusiveLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AllocateDir(), BTEqualStrategyNumber, CatalogTupleUpdate(), CHECKPOINT_FAST, CHECKPOINT_FLUSH_UNLOGGED, CHECKPOINT_FORCE, CHECKPOINT_WAIT, CommitTransactionCommand(), copydir(), CountOtherDBBackends(), CStringGetDatum(), xl_dbase_create_file_copy_rec::db_id, xl_dbase_drop_rec::db_id, dbname, DropDatabaseBuffers(), elog, EmitProcSignalBarrier(), ereport, errcode(), errdetail_busy_db(), errhint(), errmsg, ERROR, fb(), ForceSyncCommit(), FreeDir(), get_db_info(), get_tablespace_oid(), GetDatabasePath(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvokeObjectPostAlterHook, LockSharedObjectForSession(), LockTuple(), movedb_failure_callback(), MyDatabaseId, NoLock, 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(), StartTransactionCommand(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), UnlockSharedObjectForSession(), UnlockTuple(), 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 2347 of file dbcommands.c.

2348{
2350 char *dstpath;
2351
2352 /* Get rid of anything we managed to copy to the target directory */
2353 dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2354
2355 (void) rmtree(dstpath, true);
2356
2357 pfree(dstpath);
2358}

References arg, DatumGetPointer(), dstpath, fb(), GetDatabasePath(), pfree(), and rmtree().

Referenced by movedb().

◆ pg_database_collation_actual_version()

Datum pg_database_collation_actual_version ( PG_FUNCTION_ARGS  )

Definition at line 2799 of file dbcommands.c.

2800{
2801 Oid dbid = PG_GETARG_OID(0);
2802 HeapTuple tp;
2803 char datlocprovider;
2804 Datum datum;
2805 char *version;
2806
2808 if (!HeapTupleIsValid(tp))
2809 ereport(ERROR,
2811 errmsg("database with OID %u does not exist", dbid)));
2812
2814
2817 else
2819
2821 TextDatumGetCString(datum));
2822
2823 ReleaseSysCache(tp);
2824
2825 if (version)
2827 else
2829}
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_RETURN_NULL()
Definition fmgr.h:346
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
char datlocprovider
Definition pg_database.h:46
text * cstring_to_text(const char *s)
Definition varlena.c:184

References cstring_to_text(), datlocprovider, ereport, errcode(), errmsg, ERROR, fb(), Form_pg_database, 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 3279 of file dbcommands.c.

3280{
3281 struct stat st;
3282
3284
3285 if (stat(path, &st) == 0)
3286 return;
3287
3288 if (only_tblspc && strstr(path, PG_TBLSPC_DIR_SLASH) == NULL)
3289 elog(PANIC, "requested to created invalid directory: %s", path);
3290
3292 ereport(PANIC,
3293 errmsg("missing directory \"%s\"", path));
3294
3296 "creating missing directory: %s", path);
3297
3298 if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3299 ereport(PANIC,
3300 errmsg("could not create missing directory \"%s\": %m", path));
3301}
bool allow_in_place_tablespaces
Definition tablespace.c:87
#define DEBUG1
Definition elog.h:31
int pg_dir_create_mode
Definition file_perm.c:18
int pg_mkdir_p(char *path, int omode)
Definition pgmkdirp.c:57
#define PG_TBLSPC_DIR_SLASH
Definition relpath.h:42
bool RecoveryInProgress(void)
Definition xlog.c:6830
bool reachedConsistency

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

Referenced by dbase_redo().

◆ remove_dbtablespaces()

static void remove_dbtablespaces ( Oid  db_id)
static

Definition at line 3026 of file dbcommands.c.

3027{
3028 Relation rel;
3029 TableScanDesc scan;
3030 HeapTuple tuple;
3031 List *ltblspc = NIL;
3032 ListCell *cell;
3033 int ntblspc;
3034 int i;
3035 Oid *tablespace_ids;
3036
3038 scan = table_beginscan_catalog(rel, 0, NULL);
3039 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3040 {
3042 Oid dsttablespace = spcform->oid;
3043 char *dstpath;
3044 struct stat st;
3045
3046 /* Don't mess with the global tablespace */
3048 continue;
3049
3051
3052 if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
3053 {
3054 /* Assume we can ignore it */
3055 pfree(dstpath);
3056 continue;
3057 }
3058
3059 if (!rmtree(dstpath, true))
3061 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3062 dstpath)));
3063
3065 pfree(dstpath);
3066 }
3067
3069 if (ntblspc == 0)
3070 {
3071 table_endscan(scan);
3073 return;
3074 }
3075
3076 tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
3077 i = 0;
3078 foreach(cell, ltblspc)
3079 tablespace_ids[i++] = lfirst_oid(cell);
3080
3081 /* Record the filesystem change in XLOG */
3082 {
3084
3085 xlrec.db_id = db_id;
3086 xlrec.ntablespaces = ntblspc;
3087
3090 XLogRegisterData(tablespace_ids, ntblspc * sizeof(Oid));
3091
3094 }
3095
3097 pfree(tablespace_ids);
3098
3099 table_endscan(scan);
3101}
#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:1387
#define lfirst_oid(lc)
Definition pg_list.h:174

References AccessShareLock, xl_dbase_drop_rec::db_id, dstpath, ereport, errmsg, fb(), Form_pg_tablespace, ForwardScanDirection, GetDatabasePath(), GETSTRUCT(), heap_getnext(), i, lappend_oid(), lfirst_oid, list_free(), list_length(), lstat, MinSizeOfDbaseDropRec, NIL, 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 1918 of file dbcommands.c.

1919{
1920 Oid db_id;
1923 Relation rel;
1924 int notherbackends;
1925 int npreparedxacts;
1926 ObjectAddress address;
1927
1928 /* Report error if name has \n or \r character. */
1929 if (strpbrk(newname, "\n\r"))
1930 ereport(ERROR,
1932 errmsg("database name \"%s\" contains a newline or carriage return character", newname)));
1933
1934 /*
1935 * Look up the target database's OID, and get exclusive lock on it. We
1936 * need this for the same reasons as DROP DATABASE.
1937 */
1939
1942 ereport(ERROR,
1944 errmsg("database \"%s\" does not exist", oldname)));
1945
1946 /* must be owner */
1949 oldname);
1950
1951 /* must have createdb rights */
1953 ereport(ERROR,
1955 errmsg("permission denied to rename database")));
1956
1957 /*
1958 * If built with appropriate switch, whine when regression-testing
1959 * conventions for database names are violated.
1960 */
1961#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1962 if (strstr(newname, "regression") == NULL)
1963 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1964#endif
1965
1966 /*
1967 * Make sure the new name doesn't exist. See notes for same error in
1968 * CREATE DATABASE.
1969 */
1970 if (OidIsValid(get_database_oid(newname, true)))
1971 ereport(ERROR,
1973 errmsg("database \"%s\" already exists", newname)));
1974
1975 /*
1976 * XXX Client applications probably store the current database somewhere,
1977 * so renaming it could cause confusion. On the other hand, there may not
1978 * be an actual problem besides a little confusion, so think about this
1979 * and decide.
1980 */
1981 if (db_id == MyDatabaseId)
1982 ereport(ERROR,
1984 errmsg("current database cannot be renamed")));
1985
1986 /*
1987 * Make sure the database does not have active sessions. This is the same
1988 * concern as above, but applied to other sessions.
1989 *
1990 * As in CREATE DATABASE, check this after other error conditions.
1991 */
1993 ereport(ERROR,
1995 errmsg("database \"%s\" is being accessed by other users",
1996 oldname),
1998
1999 /* rename */
2002 elog(ERROR, "cache lookup failed for database %u", db_id);
2003 otid = newtup->t_self;
2007
2009
2010 ObjectAddressSet(address, DatabaseRelationId, db_id);
2011
2012 /*
2013 * Close pg_database, but keep lock till commit.
2014 */
2015 table_close(rel, NoLock);
2016
2017 return address;
2018}
void namestrcpy(Name name, const char *str)
Definition name.c:233
NameData datname
Definition pg_database.h:37
HeapTuple SearchSysCacheLockedCopy1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:400

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), CountOtherDBBackends(), datname, elog, ereport, errcode(), errdetail_busy_db(), errmsg, ERROR, fb(), Form_pg_database, get_database_oid(), get_db_info(), GETSTRUCT(), GetUserId(), have_createdb_privilege(), HeapTupleIsValid, InplaceUpdateTupleLock, InvokeObjectPostAlterHook, MyDatabaseId, namestrcpy(), NoLock, OBJECT_DATABASE, object_ownercheck(), ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, RowExclusiveLock, SearchSysCacheLockedCopy1(), table_close(), table_open(), UnlockTuple(), and WARNING.

Referenced by ExecRenameStmt().

◆ ScanSourceDatabasePgClass()

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

Definition at line 253 of file dbcommands.c.

254{
255 RelFileLocator rlocator;
256 BlockNumber nblocks;
257 BlockNumber blkno;
258 Buffer buf;
259 RelFileNumber relfilenumber;
260 Page page;
262 LockRelId relid;
263 Snapshot snapshot;
264 SMgrRelation smgr;
265 BufferAccessStrategy bstrategy;
266
267 /* Get pg_class relfilenumber. */
270
271 /* Don't read data into shared_buffers without holding a relation lock. */
272 relid.dbId = dbid;
275
276 /* Prepare a RelFileLocator for the pg_class relation. */
277 rlocator.spcOid = tbid;
278 rlocator.dbOid = dbid;
279 rlocator.relNumber = relfilenumber;
280
281 smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
282 nblocks = smgrnblocks(smgr, MAIN_FORKNUM);
283 smgrclose(smgr);
284
285 /* Use a buffer access strategy since this is a bulk read operation. */
286 bstrategy = GetAccessStrategy(BAS_BULKREAD);
287
288 /*
289 * As explained in the function header comments, we need a snapshot that
290 * will see all committed transactions as committed, and our transaction
291 * snapshot - or the active snapshot - might not be new enough for that,
292 * but the return value of GetLatestSnapshot() should work fine.
293 */
295
296 /* Process the relation block by block. */
297 for (blkno = 0; blkno < nblocks; blkno++)
298 {
300
301 buf = ReadBufferWithoutRelcache(rlocator, MAIN_FORKNUM, blkno,
302 RBM_NORMAL, bstrategy, true);
303
305 page = BufferGetPage(buf);
306 if (PageIsNew(page) || PageIsEmpty(page))
307 {
309 continue;
310 }
311
312 /* Append relevant pg_class tuples for current page to rlocatorlist. */
315 snapshot);
316
318 }
319 UnregisterSnapshot(snapshot);
320
321 /* Release relation lock. */
323
324 return rlocatorlist;
325}
uint32 BlockNumber
Definition block.h:31
int Buffer
Definition buf.h:23
void UnlockReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5603
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition bufmgr.c:963
@ BAS_BULKREAD
Definition bufmgr.h:37
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:468
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:212
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:334
@ RBM_NORMAL
Definition bufmgr.h:46
static bool PageIsEmpty(const PageData *page)
Definition bufpage.h:248
static bool PageIsNew(const PageData *page)
Definition bufpage.h:258
PageData * Page
Definition bufpage.h:81
static List * ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
Definition dbcommands.c:332
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition freelist.c:426
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
RelFileNumber RelationMapOidToFilenumberForDatabase(char *dbpath, Oid relationId)
Definition relmapper.c:266
Oid RelFileNumber
Definition relpath.h:25
@ MAIN_FORKNUM
Definition relpath.h:58
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:819
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
void smgrclose(SMgrRelation reln)
Definition smgr.c:374
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
RelFileNumber relNumber

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

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

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

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

References Assert, elog, ERROR, fb(), GETSTRUCT(), InvalidRelFileNumber, OidIsValid, palloc_object, RelationMapOidToFilenumberForDatabase(), and RelFileNumberIsValid.

Referenced by ScanSourceDatabasePgClassPage().