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

2384{
2385 Relation rel;
2386 Oid dboid;
2387 HeapTuple tuple,
2388 newtuple;
2391 SysScanDesc scan;
2393 bool dbistemplate = false;
2394 bool dballowconnections = true;
2403
2404 /* Extract options from the statement node tree */
2405 foreach(option, stmt->options)
2406 {
2408
2409 if (strcmp(defel->defname, "is_template") == 0)
2410 {
2411 if (distemplate)
2414 }
2415 else if (strcmp(defel->defname, "allow_connections") == 0)
2416 {
2420 }
2421 else if (strcmp(defel->defname, "connection_limit") == 0)
2422 {
2423 if (dconnlimit)
2425 dconnlimit = defel;
2426 }
2427 else if (strcmp(defel->defname, "tablespace") == 0)
2428 {
2429 if (dtablespace)
2432 }
2433 else
2434 ereport(ERROR,
2436 errmsg("option \"%s\" not recognized", defel->defname),
2437 parser_errposition(pstate, defel->location)));
2438 }
2439
2440 if (dtablespace)
2441 {
2442 /*
2443 * While the SET TABLESPACE syntax doesn't allow any other options,
2444 * somebody could write "WITH TABLESPACE ...". Forbid any other
2445 * options from being specified in that case.
2446 */
2447 if (list_length(stmt->options) != 1)
2448 ereport(ERROR,
2450 errmsg("option \"%s\" cannot be specified with other options",
2451 dtablespace->defname),
2452 parser_errposition(pstate, dtablespace->location)));
2453 /* this case isn't allowed within a transaction block */
2454 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2456 return InvalidOid;
2457 }
2458
2459 if (distemplate && distemplate->arg)
2463 if (dconnlimit && dconnlimit->arg)
2464 {
2467 ereport(ERROR,
2469 errmsg("invalid connection limit: %d", dbconnlimit)));
2470 }
2471
2472 /*
2473 * Get the old tuple. We don't need a lock on the database per se,
2474 * because we're not going to do anything that would mess up incoming
2475 * connections.
2476 */
2481 CStringGetDatum(stmt->dbname));
2482 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2483 NULL, 1, &scankey);
2484 tuple = systable_getnext(scan);
2485 if (!HeapTupleIsValid(tuple))
2486 ereport(ERROR,
2488 errmsg("database \"%s\" does not exist", stmt->dbname)));
2490
2492 dboid = datform->oid;
2493
2495 {
2496 ereport(FATAL,
2498 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2499 errhint("Use DROP DATABASE to drop invalid databases."));
2500 }
2501
2504 stmt->dbname);
2505
2506 /*
2507 * In order to avoid getting locked out and having to go through
2508 * standalone mode, we refuse to disallow connections to the database
2509 * we're currently connected to. Lockout can still happen with concurrent
2510 * sessions but the likeliness of that is not high enough to worry about.
2511 */
2512 if (!dballowconnections && dboid == MyDatabaseId)
2513 ereport(ERROR,
2515 errmsg("cannot disallow connections for current database")));
2516
2517 /*
2518 * Build an updated tuple, perusing the information just obtained
2519 */
2520 if (distemplate)
2521 {
2524 }
2526 {
2529 }
2530 if (dconnlimit)
2531 {
2534 }
2535
2536 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2538 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2540
2542
2543 systable_endscan(scan);
2544
2545 /* Close pg_database, but keep lock till commit */
2546 table_close(rel, NoLock);
2547
2548 return dboid;
2549}
@ 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:41
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
Oid MyDatabaseId
Definition globals.c:94
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1130
#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:540
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:3670

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

2680{
2681 Oid db_id;
2682 HeapTuple tuple;
2683 Relation rel;
2685 SysScanDesc scan;
2687 ObjectAddress address;
2688
2689 /*
2690 * Get the old tuple. We don't need a lock on the database per se,
2691 * because we're not going to do anything that would mess up incoming
2692 * connections.
2693 */
2699 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2700 NULL, 1, &scankey);
2701 tuple = systable_getnext(scan);
2702 if (!HeapTupleIsValid(tuple))
2703 ereport(ERROR,
2705 errmsg("database \"%s\" does not exist", dbname)));
2706
2708 db_id = datForm->oid;
2709
2710 /*
2711 * If the new owner is the same as the existing owner, consider the
2712 * command to have succeeded. This is to be consistent with other
2713 * objects.
2714 */
2715 if (datForm->datdba != newOwnerId)
2716 {
2718 bool repl_null[Natts_pg_database] = {0};
2719 bool repl_repl[Natts_pg_database] = {0};
2720 Acl *newAcl;
2722 bool isNull;
2723 HeapTuple newtuple;
2724
2725 /* Otherwise, must be owner of the existing object */
2728 dbname);
2729
2730 /* Must be able to become new owner */
2732
2733 /*
2734 * must have createdb rights
2735 *
2736 * NOTE: This is different from other alter-owner checks in that the
2737 * current user is checked for createdb privileges instead of the
2738 * destination owner. This is consistent with the CREATE case for
2739 * databases. Because superusers will always have this right, we need
2740 * no special case for them.
2741 */
2743 ereport(ERROR,
2745 errmsg("permission denied to change owner of database")));
2746
2748
2751
2752 /*
2753 * Determine the modified ACL for the new owner. This is only
2754 * necessary when the ACL is non-null.
2755 */
2756 aclDatum = heap_getattr(tuple,
2758 RelationGetDescr(rel),
2759 &isNull);
2760 if (!isNull)
2761 {
2763 datForm->datdba, newOwnerId);
2766 }
2767
2769 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2771
2772 heap_freetuple(newtuple);
2773
2774 /* Update owner dependency reference */
2776 }
2777
2779
2780 ObjectAddressSet(address, DatabaseRelationId, db_id);
2781
2782 systable_endscan(scan);
2783
2784 /* Close pg_database, but keep lock till commit */
2785 table_close(rel, NoLock);
2786
2787 return address;
2788}
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:1384
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 2556 of file dbcommands.c.

2557{
2558 Relation rel;
2560 SysScanDesc scan;
2561 Oid db_id;
2562 HeapTuple tuple;
2564 ObjectAddress address;
2565 Datum datum;
2566 bool isnull;
2567 char *oldversion;
2568 char *newversion;
2569
2574 CStringGetDatum(stmt->dbname));
2575 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2576 NULL, 1, &scankey);
2577 tuple = systable_getnext(scan);
2578 if (!HeapTupleIsValid(tuple))
2579 ereport(ERROR,
2581 errmsg("database \"%s\" does not exist", stmt->dbname)));
2582
2584 db_id = datForm->oid;
2585
2588 stmt->dbname);
2590
2591 datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2592 oldversion = isnull ? NULL : TextDatumGetCString(datum);
2593
2594 if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2595 {
2596 datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2597 if (isnull)
2598 elog(ERROR, "unexpected null in pg_database");
2599 }
2600 else
2601 {
2602 datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2603 if (isnull)
2604 elog(ERROR, "unexpected null in pg_database");
2605 }
2606
2608 TextDatumGetCString(datum));
2609
2610 /* cannot change from NULL to non-NULL or vice versa */
2611 if ((!oldversion && newversion) || (oldversion && !newversion))
2612 elog(ERROR, "invalid collation version change");
2613 else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2614 {
2615 bool nulls[Natts_pg_database] = {0};
2616 bool replaces[Natts_pg_database] = {0};
2618 HeapTuple newtuple;
2619
2621 (errmsg("changing version from %s to %s",
2623
2626
2627 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2628 values, nulls, replaces);
2629 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2630 heap_freetuple(newtuple);
2631 }
2632 else
2634 (errmsg("version has not changed")));
2636
2638
2639 ObjectAddressSet(address, DatabaseRelationId, db_id);
2640
2641 systable_endscan(scan);
2642
2643 table_close(rel, NoLock);
2644
2645 return address;
2646}
static Datum values[MAXATTR]
Definition bootstrap.c:188
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define TextDatumGetCString(d)
Definition builtins.h:99
#define elog(elevel,...)
Definition elog.h:226
#define NOTICE
Definition elog.h:35
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 2653 of file dbcommands.c.

2654{
2655 Oid datid = get_database_oid(stmt->dbname, false);
2656
2657 /*
2658 * Obtain a lock on the database and make sure it didn't go away in the
2659 * meantime.
2660 */
2662
2665 stmt->dbname);
2666
2667 AlterSetting(datid, InvalidOid, stmt->setstmt);
2668
2670
2671 return datid;
2672}
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 3109 of file dbcommands.c.

3110{
3111 bool result = false;
3112 Relation rel;
3113 TableScanDesc scan;
3114 HeapTuple tuple;
3115
3117 scan = table_beginscan_catalog(rel, 0, NULL);
3118 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3119 {
3121 Oid dsttablespace = spcform->oid;
3122 char *dstpath;
3123 struct stat st;
3124
3125 /* Don't mess with the global tablespace */
3127 continue;
3128
3130
3131 if (lstat(dstpath, &st) == 0)
3132 {
3133 /* Found a conflicting file (or directory, whatever) */
3134 pfree(dstpath);
3135 result = true;
3136 break;
3137 }
3138
3139 pfree(dstpath);
3140 }
3141
3142 table_endscan(scan);
3144
3145 return result;
3146}
static char dstpath[MAXPGPATH]
Definition file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1420
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:1004
#define lstat(path, sb)
Definition win32_port.h:275

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

Referenced by createdb().

◆ check_encoding_locale_matches()

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

Definition at line 1605 of file dbcommands.c.

1606{
1608 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1609
1610 if (!(ctype_encoding == encoding ||
1612 ctype_encoding == -1 ||
1613#ifdef WIN32
1614 encoding == PG_UTF8 ||
1615#endif
1616 (encoding == PG_SQL_ASCII && superuser())))
1617 ereport(ERROR,
1619 errmsg("encoding \"%s\" does not match locale \"%s\"",
1621 ctype),
1622 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1624
1625 if (!(collate_encoding == encoding ||
1627 collate_encoding == -1 ||
1628#ifdef WIN32
1629 encoding == PG_UTF8 ||
1630#endif
1631 (encoding == PG_SQL_ASCII && superuser())))
1632 ereport(ERROR,
1634 errmsg("encoding \"%s\" does not match locale \"%s\"",
1636 collate),
1637 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1639}
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:226
#define pg_encoding_to_char
Definition pg_wchar.h:630
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:860
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:121
#define stat
Definition win32_port.h:74
#define S_ISDIR(m)
Definition win32_port.h:315
#define CHECKPOINT_FLUSH_UNLOGGED
Definition xlog.h:154
#define CHECKPOINT_FORCE
Definition xlog.h:153
#define CHECKPOINT_WAIT
Definition xlog.h:156
#define CHECKPOINT_FAST
Definition xlog.h:152
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:479
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:369
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:5381
#define Assert(condition)
Definition c.h:945
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)
1048 else
1049 ereport(ERROR,
1051 errmsg("invalid create database strategy \"%s\"", strategy),
1052 errhint("Valid strategies are \"wal_log\" and \"file_copy\".")));
1053 }
1054
1055 /* If encoding or locales are defaulted, use source's setting */
1056 if (encoding < 0)
1058 if (dbcollate == NULL)
1060 if (dbctype == NULL)
1062 if (dblocprovider == '\0')
1066 if (dbicurules == NULL)
1068
1069 /* Some encodings are client only */
1071 ereport(ERROR,
1073 errmsg("invalid server encoding %d", encoding)));
1074
1075 /* Check that the chosen locales are valid, and get canonical spellings */
1077 {
1079 ereport(ERROR,
1081 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1082 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1083 else if (dblocprovider == COLLPROVIDER_ICU)
1084 ereport(ERROR,
1086 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1087 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1088 else
1089 ereport(ERROR,
1091 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate)));
1092 }
1095 {
1097 ereport(ERROR,
1099 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1100 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1101 else if (dblocprovider == COLLPROVIDER_ICU)
1102 ereport(ERROR,
1104 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1105 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1106 else
1107 ereport(ERROR,
1109 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype)));
1110 }
1111
1113
1115
1116 /* validate provider-specific parameters */
1118 {
1119 if (builtinlocaleEl)
1120 ereport(ERROR,
1122 errmsg("BUILTIN_LOCALE cannot be specified unless locale provider is builtin")));
1123 }
1124
1126 {
1127 if (iculocaleEl)
1128 ereport(ERROR,
1130 errmsg("ICU locale cannot be specified unless locale provider is ICU")));
1131
1132 if (dbicurules)
1133 ereport(ERROR,
1135 errmsg("ICU rules cannot be specified unless locale provider is ICU")));
1136 }
1137
1138 /* validate and canonicalize locale for the provider */
1140 {
1141 /*
1142 * This would happen if template0 uses the libc provider but the new
1143 * database uses builtin.
1144 */
1145 if (!dblocale)
1146 ereport(ERROR,
1148 errmsg("LOCALE or BUILTIN_LOCALE must be specified")));
1149
1151 }
1152 else if (dblocprovider == COLLPROVIDER_ICU)
1153 {
1155 ereport(ERROR,
1157 errmsg("encoding \"%s\" is not supported with ICU provider",
1159
1160 /*
1161 * This would happen if template0 uses the libc provider but the new
1162 * database uses icu.
1163 */
1164 if (!dblocale)
1165 ereport(ERROR,
1167 errmsg("LOCALE or ICU_LOCALE must be specified")));
1168
1169 /*
1170 * During binary upgrade, or when the locale came from the template
1171 * database, preserve locale string. Otherwise, canonicalize to a
1172 * language tag.
1173 */
1175 {
1178
1179 if (langtag && strcmp(dblocale, langtag) != 0)
1180 {
1182 (errmsg("using standard form \"%s\" for ICU locale \"%s\"",
1183 langtag, dblocale)));
1184
1185 dblocale = langtag;
1186 }
1187 }
1188
1190 }
1191
1192 /* for libc, locale comes from datcollate and datctype */
1194 dblocale = NULL;
1195
1196 /*
1197 * Check that the new encoding and locale settings match the source
1198 * database. We insist on this because we simply copy the source data ---
1199 * any non-ASCII data would be wrongly encoded, and any indexes sorted
1200 * according to the source locale would be wrong.
1201 *
1202 * However, we assume that template0 doesn't contain any non-ASCII data
1203 * nor any indexes that depend on collation or ctype, so template0 can be
1204 * used as template for creating a database with any encoding or locale.
1205 */
1206 if (strcmp(dbtemplate, "template0") != 0)
1207 {
1208 if (encoding != src_encoding)
1209 ereport(ERROR,
1211 errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1214 errhint("Use the same encoding as in the template database, or use template0 as template.")));
1215
1216 if (strcmp(dbcollate, src_collate) != 0)
1217 ereport(ERROR,
1219 errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1221 errhint("Use the same collation as in the template database, or use template0 as template.")));
1222
1223 if (strcmp(dbctype, src_ctype) != 0)
1224 ereport(ERROR,
1226 errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1228 errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1229
1231 ereport(ERROR,
1233 errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1235 errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1236
1238 {
1239 char *val1;
1240 char *val2;
1241
1244 if (strcmp(dblocale, src_locale) != 0)
1245 ereport(ERROR,
1247 errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1249 errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1250
1251 val1 = dbicurules;
1252 if (!val1)
1253 val1 = "";
1255 if (!val2)
1256 val2 = "";
1257 if (strcmp(val1, val2) != 0)
1258 ereport(ERROR,
1260 errmsg("new ICU collation rules (%s) are incompatible with the ICU collation rules of the template database (%s)",
1261 val1, val2),
1262 errhint("Use the same ICU collation rules as in the template database, or use template0 as template.")));
1263 }
1264 }
1265
1266 /*
1267 * If we got a collation version for the template database, check that it
1268 * matches the actual OS collation version. Otherwise error; the user
1269 * needs to fix the template database first. Don't complain if a
1270 * collation version was specified explicitly as a statement option; that
1271 * is used by pg_upgrade to reproduce the old state exactly.
1272 *
1273 * (If the template database has no collation version, then either the
1274 * platform/provider does not support collation versioning, or it's
1275 * template0, for which we stipulate that it does not contain
1276 * collation-using objects.)
1277 */
1279 {
1280 char *actual_versionstr;
1281 const char *locale;
1282
1284 locale = dbcollate;
1285 else
1286 locale = dblocale;
1287
1289 if (!actual_versionstr)
1290 ereport(ERROR,
1291 (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1292 dbtemplate)));
1293
1295 ereport(ERROR,
1296 (errmsg("template database \"%s\" has a collation version mismatch",
1297 dbtemplate),
1298 errdetail("The template database was created using collation version %s, "
1299 "but the operating system provides version %s.",
1301 errhint("Rebuild all objects in the template database that use the default collation and run "
1302 "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1303 "or build PostgreSQL with the right library version.",
1305 }
1306
1307 if (dbcollversion == NULL)
1309
1310 /*
1311 * Normally, we copy the collation version from the template database.
1312 * This last resort only applies if the template database does not have a
1313 * collation version, which is normally only the case for template0.
1314 */
1315 if (dbcollversion == NULL)
1316 {
1317 const char *locale;
1318
1320 locale = dbcollate;
1321 else
1322 locale = dblocale;
1323
1325 }
1326
1327 /* Resolve default tablespace for new database */
1329 {
1330 char *tablespacename;
1332
1333 tablespacename = defGetString(tablespacenameEl);
1334 dst_deftablespace = get_tablespace_oid(tablespacename, false);
1335 /* check permissions */
1337 ACL_CREATE);
1338 if (aclresult != ACLCHECK_OK)
1340 tablespacename);
1341
1342 /* pg_global must never be the default tablespace */
1344 ereport(ERROR,
1346 errmsg("pg_global cannot be used as default tablespace")));
1347
1348 /*
1349 * If we are trying to change the default tablespace of the template,
1350 * we require that the template not have any files in the new default
1351 * tablespace. This is necessary because otherwise the copied
1352 * database would contain pg_class rows that refer to its default
1353 * tablespace both explicitly (by OID) and implicitly (as zero), which
1354 * would cause problems. For example another CREATE DATABASE using
1355 * the copied database as template, and trying to change its default
1356 * tablespace again, would yield outright incorrect results (it would
1357 * improperly move tables to the new default tablespace that should
1358 * stay in the same tablespace).
1359 */
1361 {
1362 char *srcpath;
1363 struct stat st;
1364
1366
1367 if (stat(srcpath, &st) == 0 &&
1368 S_ISDIR(st.st_mode) &&
1370 ereport(ERROR,
1372 errmsg("cannot assign new default tablespace \"%s\"",
1373 tablespacename),
1374 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1375 dbtemplate)));
1376 pfree(srcpath);
1377 }
1378 }
1379 else
1380 {
1381 /* Use template database's default tablespace */
1383 /* Note there is no additional permission check in this path */
1384 }
1385
1386 /*
1387 * If built with appropriate switch, whine when regression-testing
1388 * conventions for database names are violated. But don't complain during
1389 * initdb.
1390 */
1391#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1392 if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1393 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1394#endif
1395
1396 /*
1397 * Check for db name conflict. This is just to give a more friendly error
1398 * message than "unique index violation". There's a race condition but
1399 * we're willing to accept the less friendly message in that case.
1400 */
1402 ereport(ERROR,
1404 errmsg("database \"%s\" already exists", dbname)));
1405
1406 /*
1407 * The source DB can't have any active backends, except this one
1408 * (exception is to allow CREATE DB while connected to template1).
1409 * Otherwise we might copy inconsistent data.
1410 *
1411 * This should be last among the basic error checks, because it involves
1412 * potential waiting; we may as well throw an error first if we're gonna
1413 * throw one.
1414 */
1416 ereport(ERROR,
1418 errmsg("source database \"%s\" is being accessed by other users",
1419 dbtemplate),
1421
1422 /*
1423 * Select an OID for the new database, checking that it doesn't have a
1424 * filename conflict with anything already existing in the tablespace
1425 * directories.
1426 */
1428
1429 /*
1430 * If database OID is configured, check if the OID is already in use or
1431 * data directory already exists.
1432 */
1433 if (OidIsValid(dboid))
1434 {
1435 char *existing_dbname = get_database_name(dboid);
1436
1437 if (existing_dbname != NULL)
1438 ereport(ERROR,
1440 errmsg("database OID %u is already in use by database \"%s\"",
1441 dboid, existing_dbname));
1442
1443 if (check_db_file_conflict(dboid))
1444 ereport(ERROR,
1446 errmsg("data directory with the specified OID %u already exists", dboid));
1447 }
1448 else
1449 {
1450 /* Select an OID for the new database if is not explicitly configured. */
1451 do
1452 {
1455 } while (check_db_file_conflict(dboid));
1456 }
1457
1458 /*
1459 * Insert a new tuple into pg_database. This establishes our ownership of
1460 * the new database name (anyone else trying to insert the same name will
1461 * block on the unique index, and fail after we commit).
1462 */
1463
1466
1467 /* Form tuple */
1483 if (dblocale)
1485 else
1487 if (dbicurules)
1489 else
1491 if (dbcollversion)
1493 else
1495
1496 /*
1497 * We deliberately set datacl to default (NULL), rather than copying it
1498 * from the template database. Copying it would be a bad idea when the
1499 * owner is not the same as the template's owner.
1500 */
1502
1505
1507
1508 /*
1509 * Now generate additional catalog entries associated with the new DB
1510 */
1511
1512 /* Register owner dependency */
1514
1515 /* Create pg_shdepend entries for objects within database */
1516 copyTemplateDependencies(src_dboid, dboid);
1517
1518 /* Post creation hook for new database */
1520
1521 /*
1522 * If we're going to be reading data for the to-be-created database into
1523 * shared_buffers, take a lock on it. Nobody should know that this
1524 * database exists yet, but it's good to maintain the invariant that an
1525 * AccessExclusiveLock on the database is sufficient to drop all of its
1526 * buffers without worrying about more being read later.
1527 *
1528 * Note that we need to do this before entering the
1529 * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1530 * expects this lock to be held already.
1531 */
1534
1535 /*
1536 * Once we start copying subdirectories, we need to be able to clean 'em
1537 * up if we fail. Use an ENSURE block to make sure this happens. (This
1538 * is not a 100% solution, because of the possibility of failure during
1539 * transaction commit after we leave this routine, but it should handle
1540 * most scenarios.)
1541 */
1542 fparms.src_dboid = src_dboid;
1543 fparms.dest_dboid = dboid;
1544 fparms.strategy = dbstrategy;
1545
1548 {
1549 /*
1550 * If the user has asked to create a database with WAL_LOG strategy
1551 * then call CreateDatabaseUsingWalLog, which will copy the database
1552 * at the block level and it will WAL log each copied block.
1553 * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1554 * database file by file.
1555 */
1559 else
1562
1563 /*
1564 * Close pg_database, but keep lock till commit.
1565 */
1567
1568 /*
1569 * Force synchronous commit, thus minimizing the window between
1570 * creation of the database files and committal of the transaction. If
1571 * we crash before committing, we'll have a DB that's taking up disk
1572 * space but is not in pg_database, which is not good.
1573 */
1575 }
1578
1579 return dboid;
1580}
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:748
uint32 TransactionId
Definition c.h:738
#define OidIsValid(objectId)
Definition c.h:860
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:36
bool is_encoding_supported_by_icu(int encoding)
Definition encnames.c:461
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
bool IsUnderPostmaster
Definition globals.c:120
bool allowSystemTableMods
Definition globals.c:130
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1037
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:281
#define pg_valid_server_encoding
Definition pg_wchar.h:631
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:3742
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:1154

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(), 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 1643 of file dbcommands.c.

1644{
1646
1647 /*
1648 * If we were copying database at block levels then drop pages for the
1649 * destination database that are in the shared buffer cache. And tell
1650 * checkpointer to forget any pending fsync and unlink requests for files
1651 * in the database. The reasoning behind doing this is same as explained
1652 * in dropdb function. But unlike dropdb we don't need to call
1653 * pgstat_drop_database because this database is still not created so
1654 * there should not be any stat for this.
1655 */
1656 if (fparms->strategy == CREATEDB_WAL_LOG)
1657 {
1658 DropDatabaseBuffers(fparms->dest_dboid);
1660
1661 /* Release lock on the target database. */
1664 }
1665
1666 /*
1667 * Release lock on source database before doing recursive remove. This is
1668 * not essential but it seems desirable to release the lock as soon as
1669 * possible.
1670 */
1672
1673 /* Throw away any successfully copied subdirectories */
1674 remove_dbtablespaces(fparms->dest_dboid);
1675}
void DropDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5034
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:1376
#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:150
#define END_CRIT_SECTION()
Definition miscadmin.h:152
#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:69
static void pgstat_report_wait_end(void)
Definition wait_event.h:85

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

3230{
3231 return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
3232}
#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 3239 of file dbcommands.c.

3240{
3243 bool invalid;
3244
3246 if (!HeapTupleIsValid(dbtup))
3247 elog(ERROR, "cache lookup failed for database %u", dboid);
3249
3251
3253
3254 return invalid;
3255}
invalidindex index d is invalid
Definition isn.c:138
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220

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

3302{
3303 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3304
3305 /* Backup blocks are not used in dbase records */
3307
3308 if (info == XLOG_DBASE_CREATE_FILE_COPY)
3309 {
3312 char *src_path;
3313 char *dst_path;
3314 char *parent_path;
3315 struct stat st;
3316
3317 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3318 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3319
3320 /*
3321 * Our theory for replaying a CREATE is to forcibly drop the target
3322 * subdirectory if present, then re-copy the source data. This may be
3323 * more work than needed, but it is simple to implement.
3324 */
3325 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3326 {
3327 if (!rmtree(dst_path, true))
3328 /* If this failed, copydir() below is going to error. */
3330 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3331 dst_path)));
3332 }
3333
3334 /*
3335 * If the parent of the target path doesn't exist, create it now. This
3336 * enables us to create the target underneath later.
3337 */
3340 if (stat(parent_path, &st) < 0)
3341 {
3342 if (errno != ENOENT)
3343 ereport(FATAL,
3344 errmsg("could not stat directory \"%s\": %m",
3345 dst_path));
3346
3347 /* create the parent directory if needed and valid */
3349 }
3351
3352 /*
3353 * There's a case where the copy source directory is missing for the
3354 * same reason above. Create the empty source directory so that
3355 * copydir below doesn't fail. The directory will be dropped soon by
3356 * recovery.
3357 */
3358 if (stat(src_path, &st) < 0 && errno == ENOENT)
3360
3361 /*
3362 * Force dirty buffers out to disk, to ensure source database is
3363 * up-to-date for the copy.
3364 */
3365 FlushDatabaseBuffers(xlrec->src_db_id);
3366
3367 /* Close all smgr fds in all backends. */
3369
3370 /*
3371 * Copy this subdirectory to the new location
3372 *
3373 * We don't need to copy subdirectories
3374 */
3375 copydir(src_path, dst_path, false);
3376
3377 pfree(src_path);
3378 pfree(dst_path);
3379 }
3380 else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3381 {
3384 char *dbpath;
3385 char *parent_path;
3386
3387 dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3388
3389 /* create the parent directory if needed and valid */
3394
3395 /* Create the database directory with the version file. */
3396 CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3397 true);
3398 pfree(dbpath);
3399 }
3400 else if (info == XLOG_DBASE_DROP)
3401 {
3403 char *dst_path;
3404 int i;
3405
3406 if (InHotStandby)
3407 {
3408 /*
3409 * Lock database while we resolve conflicts to ensure that
3410 * InitPostgres() cannot fully re-execute concurrently. This
3411 * avoids backends re-connecting automatically to same database,
3412 * which can happen in some cases.
3413 *
3414 * This will lock out walsenders trying to connect to db-specific
3415 * slots for logical decoding too, so it's safe for us to drop
3416 * slots.
3417 */
3420 }
3421
3422 /* Drop any database-specific replication slots */
3424
3425 /* Drop pages for this database that are in the shared buffer cache */
3426 DropDatabaseBuffers(xlrec->db_id);
3427
3428 /* Also, clean out any fsync requests that might be pending in md.c */
3430
3431 /* Clean out the xlog relcache too */
3432 XLogDropDatabase(xlrec->db_id);
3433
3434 /* Close all smgr fds in all backends. */
3436
3437 for (i = 0; i < xlrec->ntablespaces; i++)
3438 {
3439 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3440
3441 /* And remove the physical files */
3442 if (!rmtree(dst_path, true))
3444 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3445 dst_path)));
3446 pfree(dst_path);
3447 }
3448
3449 if (InHotStandby)
3450 {
3451 /*
3452 * Release locks prior to commit. XXX There is a race condition
3453 * here that may allow backends to reconnect, but the window for
3454 * this is small because the gap between here and commit is mostly
3455 * fairly small and it is unlikely that people will be dropping
3456 * databases that we are trying to connect to anyway.
3457 */
3459 }
3460 }
3461 else
3462 elog(PANIC, "dbase_redo: unknown op code %u", info);
3463}
void FlushDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5445
uint8_t uint8
Definition c.h:616
static void recovery_create_dbdir(char *path, bool only_tblspc)
#define XLOG_DBASE_DROP
#define PANIC
Definition elog.h:42
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:427
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition procsignal.c:359
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition procsignal.h:48
bool rmtree(const char *path, bool rmtopdir)
Definition rmtree.c:50
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition slot.c:1511
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition standby.c:571
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:409
#define XLogRecGetData(decoder)
Definition xlogreader.h:414
#define XLogRecHasAnyBlockRefs(decoder)
Definition xlogreader.h:416
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 2357 of file dbcommands.c.

2358{
2359 bool force = false;
2360 ListCell *lc;
2361
2362 foreach(lc, stmt->options)
2363 {
2364 DefElem *opt = (DefElem *) lfirst(lc);
2365
2366 if (strcmp(opt->defname, "force") == 0)
2367 force = true;
2368 else
2369 ereport(ERROR,
2371 errmsg("unrecognized %s option \"%s\"",
2372 "DROP DATABASE", opt->defname),
2373 parser_errposition(pstate, opt->location)));
2374 }
2375
2376 dropdb(stmt->dbname, stmt->missing_ok, force);
2377}
void dropdb(const char *dbname, bool missing_ok, bool force)
char * defname
Definition parsenodes.h:857
ParseLoc location
Definition parsenodes.h:861

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

1683{
1684 Oid db_id;
1685 bool db_istemplate;
1687 HeapTuple tup;
1689 void *inplace_state;
1691 int notherbackends;
1692 int npreparedxacts;
1693 int nslots,
1695 int nsubscriptions;
1696
1697 /*
1698 * Look up the target database's OID, and get exclusive lock on it. We
1699 * need this to ensure that no new backend starts up in the target
1700 * database while we are deleting it (see postinit.c), and that no one is
1701 * using it as a CREATE DATABASE template or trying to delete it for
1702 * themselves.
1703 */
1705
1708 {
1709 if (!missing_ok)
1710 {
1711 ereport(ERROR,
1713 errmsg("database \"%s\" does not exist", dbname)));
1714 }
1715 else
1716 {
1717 /* Close pg_database, release the lock, since we changed nothing */
1720 (errmsg("database \"%s\" does not exist, skipping",
1721 dbname)));
1722 return;
1723 }
1724 }
1725
1726 /*
1727 * Permission checks
1728 */
1731 dbname);
1732
1733 /* DROP hook for the database being removed */
1735
1736 /*
1737 * Disallow dropping a DB that is marked istemplate. This is just to
1738 * prevent people from accidentally dropping template0 or template1; they
1739 * can do so if they're really determined ...
1740 */
1741 if (db_istemplate)
1742 ereport(ERROR,
1744 errmsg("cannot drop a template database")));
1745
1746 /* Obviously can't drop my own database */
1747 if (db_id == MyDatabaseId)
1748 ereport(ERROR,
1750 errmsg("cannot drop the currently open database")));
1751
1752 /*
1753 * Check whether there are active logical slots that refer to the
1754 * to-be-dropped database. The database lock we are holding prevents the
1755 * creation of new slots using the database or existing slots becoming
1756 * active.
1757 */
1759 if (nslots_active)
1760 {
1761 ereport(ERROR,
1763 errmsg("database \"%s\" is used by an active logical replication slot",
1764 dbname),
1765 errdetail_plural("There is %d active slot.",
1766 "There are %d active slots.",
1768 }
1769
1770 /*
1771 * Check if there are subscriptions defined in the target database.
1772 *
1773 * We can't drop them automatically because they might be holding
1774 * resources in other databases/instances.
1775 */
1776 if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1777 ereport(ERROR,
1779 errmsg("database \"%s\" is being used by logical replication subscription",
1780 dbname),
1781 errdetail_plural("There is %d subscription.",
1782 "There are %d subscriptions.",
1784
1785
1786 /*
1787 * Attempt to terminate all existing connections to the target database if
1788 * the user has requested to do so.
1789 */
1790 if (force)
1792
1793 /*
1794 * Check for other backends in the target database. (Because we hold the
1795 * database lock, no new ones can start after this.)
1796 *
1797 * As in CREATE DATABASE, check this after other error conditions.
1798 */
1800 ereport(ERROR,
1802 errmsg("database \"%s\" is being accessed by other users",
1803 dbname),
1805
1806 /*
1807 * Delete any comments or security labels associated with the database.
1808 */
1811
1812 /*
1813 * Remove settings associated with this database
1814 */
1815 DropSetting(db_id, InvalidOid);
1816
1817 /*
1818 * Remove shared dependency references for the database.
1819 */
1821
1822 /*
1823 * Tell the cumulative stats system to forget it immediately, too.
1824 */
1825 pgstat_drop_database(db_id);
1826
1827 /*
1828 * Except for the deletion of the catalog row, subsequent actions are not
1829 * transactional (consider DropDatabaseBuffers() discarding modified
1830 * buffers). But we might crash or get interrupted below. To prevent
1831 * accesses to a database with invalid contents, mark the database as
1832 * invalid using an in-place update.
1833 *
1834 * We need to flush the WAL before continuing, to guarantee the
1835 * modification is durable before performing irreversible filesystem
1836 * operations.
1837 */
1843 NULL, 1, &scankey, &tup, &inplace_state);
1844 if (!HeapTupleIsValid(tup))
1845 elog(ERROR, "cache lookup failed for database %u", db_id);
1847 datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1850
1851 /*
1852 * Also delete the tuple - transactionally. If this transaction commits,
1853 * the row will be gone, but if we fail, dropdb() can be invoked again.
1854 */
1855 CatalogTupleDelete(pgdbrel, &tup->t_self);
1857
1858 /*
1859 * Drop db-specific replication slots.
1860 */
1862
1863 /*
1864 * Drop pages for this database that are in the shared buffer cache. This
1865 * is important to ensure that no remaining backend tries to write out a
1866 * dirty buffer to the dead database later...
1867 */
1868 DropDatabaseBuffers(db_id);
1869
1870 /*
1871 * Tell checkpointer to forget any pending fsync and unlink requests for
1872 * files in the database; else the fsyncs will fail at next checkpoint, or
1873 * worse, it will delete files that belong to a newly created database
1874 * with the same OID.
1875 */
1877
1878 /*
1879 * Force a checkpoint to make sure the checkpointer has received the
1880 * message sent by ForgetDatabaseSyncRequests.
1881 */
1883
1884 /* Close all smgr fds in all backends. */
1886
1887 /*
1888 * Remove all tablespace subdirs belonging to the database.
1889 */
1890 remove_dbtablespaces(db_id);
1891
1892 /*
1893 * Close pg_database, but keep lock till commit.
1894 */
1896
1897 /*
1898 * Force synchronous commit, thus minimizing the window between removal of
1899 * the database files and committal of the transaction. If we crash before
1900 * committing, we'll have a DB that's gone on disk but still there
1901 * according to pg_database, which is not good.
1902 */
1904}
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:808
void systable_inplace_update_finish(void *state, HeapTuple tuple)
Definition genam.c:884
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:3835
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition seclabel.c:502
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition slot.c:1450
XLogRecPtr XactLastRecEnd
Definition xlog.c:258
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2767

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

3153{
3154 if (notherbackends > 0 && npreparedxacts > 0)
3155
3156 /*
3157 * We don't deal with singular versus plural here, since gettext
3158 * doesn't support multiple plurals in one string.
3159 */
3160 errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3162 else if (notherbackends > 0)
3163 errdetail_plural("There is %d other session using the database.",
3164 "There are %d other sessions using the database.",
3167 else
3168 errdetail_plural("There is %d prepared transaction using the database.",
3169 "There are %d prepared transactions using the database.",
3172 return 0; /* just to keep ereport macro happy */
3173}

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

3183{
3185 ScanKeyData entry[1];
3186 SysScanDesc scan;
3188 Oid oid;
3189
3190 /*
3191 * There's no syscache for pg_database indexed by name, so we must look
3192 * the hard way.
3193 */
3195 ScanKeyInit(&entry[0],
3200 NULL, 1, entry);
3201
3202 dbtuple = systable_getnext(scan);
3203
3204 /* We assume that there can be at most one matching tuple */
3206 oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3207 else
3208 oid = InvalidOid;
3209
3210 systable_endscan(scan);
3212
3213 if (!OidIsValid(oid) && !missing_ok)
3214 ereport(ERROR,
3216 errmsg("database \"%s\" does not exist",
3217 dbname)));
3218
3219 return oid;
3220}

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

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

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

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

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2994 of file dbcommands.c.

2995{
2996 bool result = false;
2998
2999 /* Superusers can always do everything */
3000 if (superuser())
3001 return true;
3002
3005 {
3008 }
3009 return result;
3010}
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(), 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 2018 of file dbcommands.c.

2019{
2020 Oid db_id;
2022 int notherbackends;
2023 int npreparedxacts;
2024 HeapTuple oldtuple,
2025 newtuple;
2031 char *src_dbpath;
2032 char *dst_dbpath;
2033 DIR *dstdir;
2034 struct dirent *xlde;
2036
2037 /*
2038 * Look up the target database's OID, and get exclusive lock on it. We
2039 * need this to ensure that no new backend starts up in the database while
2040 * we are moving it, and that no one is using it as a CREATE DATABASE
2041 * template or trying to delete it.
2042 */
2044
2047 ereport(ERROR,
2049 errmsg("database \"%s\" does not exist", dbname)));
2050
2051 /*
2052 * We actually need a session lock, so that the lock will persist across
2053 * the commit/restart below. (We could almost get away with letting the
2054 * lock be released at commit, except that someone could try to move
2055 * relations of the DB back into the old directory while we rmtree() it.)
2056 */
2059
2060 /*
2061 * Permission checks
2062 */
2065 dbname);
2066
2067 /*
2068 * Obviously can't move the tables of my own database
2069 */
2070 if (db_id == MyDatabaseId)
2071 ereport(ERROR,
2073 errmsg("cannot change the tablespace of the currently open database")));
2074
2075 /*
2076 * Get tablespace's oid
2077 */
2079
2080 /*
2081 * Permission checks
2082 */
2084 ACL_CREATE);
2085 if (aclresult != ACLCHECK_OK)
2087 tblspcname);
2088
2089 /*
2090 * pg_global must never be the default tablespace
2091 */
2093 ereport(ERROR,
2095 errmsg("pg_global cannot be used as default tablespace")));
2096
2097 /*
2098 * No-op if same tablespace
2099 */
2101 {
2105 return;
2106 }
2107
2108 /*
2109 * Check for other backends in the target database. (Because we hold the
2110 * database lock, no new ones can start after this.)
2111 *
2112 * As in CREATE DATABASE, check this after other error conditions.
2113 */
2115 ereport(ERROR,
2117 errmsg("database \"%s\" is being accessed by other users",
2118 dbname),
2120
2121 /*
2122 * Get old and new database paths
2123 */
2126
2127 /*
2128 * Force a checkpoint before proceeding. This will force all dirty
2129 * buffers, including those of unlogged tables, out to disk, to ensure
2130 * source database is up-to-date on disk for the copy.
2131 * FlushDatabaseBuffers() would suffice for that, but we also want to
2132 * process any pending unlink requests. Otherwise, the check for existing
2133 * files in the target directory might fail unnecessarily, not to mention
2134 * that the copy might fail due to source files getting deleted under it.
2135 * On Windows, this also ensures that background procs don't hold any open
2136 * files, which would cause rmdir() to fail.
2137 */
2140
2141 /* Close all smgr fds in all backends. */
2143
2144 /*
2145 * Now drop all buffers holding data of the target database; they should
2146 * no longer be dirty so DropDatabaseBuffers is safe.
2147 *
2148 * It might seem that we could just let these buffers age out of shared
2149 * buffers naturally, since they should not get referenced anymore. The
2150 * problem with that is that if the user later moves the database back to
2151 * its original tablespace, any still-surviving buffers would appear to
2152 * contain valid data again --- but they'd be missing any changes made in
2153 * the database while it was in the new tablespace. In any case, freeing
2154 * buffers that should never be used again seems worth the cycles.
2155 *
2156 * Note: it'd be sufficient to get rid of buffers matching db_id and
2157 * src_tblspcoid, but bufmgr.c presently provides no API for that.
2158 */
2159 DropDatabaseBuffers(db_id);
2160
2161 /*
2162 * Check for existence of files in the target directory, i.e., objects of
2163 * this database that are already in the target tablespace. We can't
2164 * allow the move in such a case, because we would need to change those
2165 * relations' pg_class.reltablespace entries to zero, and we don't have
2166 * access to the DB's pg_class to do so.
2167 */
2169 if (dstdir != NULL)
2170 {
2171 while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
2172 {
2173 if (strcmp(xlde->d_name, ".") == 0 ||
2174 strcmp(xlde->d_name, "..") == 0)
2175 continue;
2176
2177 ereport(ERROR,
2179 errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
2181 errhint("You must move them back to the database's default tablespace before using this command.")));
2182 }
2183
2184 FreeDir(dstdir);
2185
2186 /*
2187 * The directory exists but is empty. We must remove it before using
2188 * the copydir function.
2189 */
2190 if (rmdir(dst_dbpath) != 0)
2191 elog(ERROR, "could not remove directory \"%s\": %m",
2192 dst_dbpath);
2193 }
2194
2195 /*
2196 * Use an ENSURE block to make sure we remove the debris if the copy fails
2197 * (eg, due to out-of-disk-space). This is not a 100% solution, because
2198 * of the possibility of failure during transaction commit, but it should
2199 * handle most scenarios.
2200 */
2201 fparms.dest_dboid = db_id;
2202 fparms.dest_tsoid = dst_tblspcoid;
2205 {
2209
2210 /*
2211 * Copy files from the old tablespace to the new one
2212 */
2213 copydir(src_dbpath, dst_dbpath, false);
2214
2215 /*
2216 * Record the filesystem change in XLOG
2217 */
2218 {
2220
2221 xlrec.db_id = db_id;
2222 xlrec.tablespace_id = dst_tblspcoid;
2223 xlrec.src_db_id = db_id;
2224 xlrec.src_tablespace_id = src_tblspcoid;
2225
2229
2232 }
2233
2234 /*
2235 * Update the database's pg_database tuple
2236 */
2242 NULL, 1, &scankey);
2243 oldtuple = systable_getnext(sysscan);
2244 if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2245 ereport(ERROR,
2247 errmsg("database \"%s\" does not exist", dbname)));
2249
2252
2253 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2254 new_record,
2256 CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2258
2260
2262
2263 /*
2264 * Force another checkpoint here. As in CREATE DATABASE, this is to
2265 * ensure that we don't have to replay a committed
2266 * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2267 * any unlogged operations done in the new DB tablespace before the
2268 * next checkpoint.
2269 */
2271
2272 /*
2273 * Force synchronous commit, thus minimizing the window between
2274 * copying the database files and committal of the transaction. If we
2275 * crash before committing, we'll leave an orphaned set of files on
2276 * disk, which is not fatal but not good either.
2277 */
2279
2280 /*
2281 * Close pg_database, but keep lock till commit.
2282 */
2284 }
2287
2288 /*
2289 * Commit the transaction so that the pg_database update is committed. If
2290 * we crash while removing files, the database won't be corrupt, we'll
2291 * just leave some orphaned files in the old directory.
2292 *
2293 * (This is OK because we know we aren't inside a transaction block.)
2294 *
2295 * XXX would it be safe/better to do this inside the ensure block? Not
2296 * convinced it's a good idea; consider elog just after the transaction
2297 * really commits.
2298 */
2301
2302 /* Start new transaction for the remaining work; don't need a snapshot */
2304
2305 /*
2306 * Remove files from the old tablespace
2307 */
2308 if (!rmtree(src_dbpath, true))
2310 (errmsg("some useless files may be left behind in old database directory \"%s\"",
2311 src_dbpath)));
2312
2313 /*
2314 * Record the filesystem change in XLOG
2315 */
2316 {
2318
2319 xlrec.db_id = db_id;
2320 xlrec.ntablespaces = 1;
2321
2325
2328 }
2329
2330 /* Now it's safe to release the database lock */
2333
2336}
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:3081
void CommitTransactionCommand(void)
Definition xact.c:3179

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

2341{
2343 char *dstpath;
2344
2345 /* Get rid of anything we managed to copy to the target directory */
2346 dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2347
2348 (void) rmtree(dstpath, true);
2349
2350 pfree(dstpath);
2351}

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

2793{
2794 Oid dbid = PG_GETARG_OID(0);
2795 HeapTuple tp;
2796 char datlocprovider;
2797 Datum datum;
2798 char *version;
2799
2801 if (!HeapTupleIsValid(tp))
2802 ereport(ERROR,
2804 errmsg("database with OID %u does not exist", dbid)));
2805
2807
2810 else
2812
2814 TextDatumGetCString(datum));
2815
2816 ReleaseSysCache(tp);
2817
2818 if (version)
2820 else
2822}
#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 3272 of file dbcommands.c.

3273{
3274 struct stat st;
3275
3277
3278 if (stat(path, &st) == 0)
3279 return;
3280
3281 if (only_tblspc && strstr(path, PG_TBLSPC_DIR_SLASH) == NULL)
3282 elog(PANIC, "requested to created invalid directory: %s", path);
3283
3285 ereport(PANIC,
3286 errmsg("missing directory \"%s\"", path));
3287
3289 "creating missing directory: %s", path);
3290
3291 if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3292 ereport(PANIC,
3293 errmsg("could not create missing directory \"%s\": %m", path));
3294}
bool allow_in_place_tablespaces
Definition tablespace.c:86
#define DEBUG1
Definition elog.h:30
int pg_dir_create_mode
Definition file_perm.c:18
int pg_mkdir_p(char *path, int omode)
Definition pgmkdirp.c:57
#define PG_TBLSPC_DIR_SLASH
Definition relpath.h:42
bool RecoveryInProgress(void)
Definition xlog.c:6444
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 3019 of file dbcommands.c.

3020{
3021 Relation rel;
3022 TableScanDesc scan;
3023 HeapTuple tuple;
3024 List *ltblspc = NIL;
3025 ListCell *cell;
3026 int ntblspc;
3027 int i;
3028 Oid *tablespace_ids;
3029
3031 scan = table_beginscan_catalog(rel, 0, NULL);
3032 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3033 {
3035 Oid dsttablespace = spcform->oid;
3036 char *dstpath;
3037 struct stat st;
3038
3039 /* Don't mess with the global tablespace */
3041 continue;
3042
3044
3045 if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
3046 {
3047 /* Assume we can ignore it */
3048 pfree(dstpath);
3049 continue;
3050 }
3051
3052 if (!rmtree(dstpath, true))
3054 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3055 dstpath)));
3056
3058 pfree(dstpath);
3059 }
3060
3062 if (ntblspc == 0)
3063 {
3064 table_endscan(scan);
3066 return;
3067 }
3068
3069 tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
3070 i = 0;
3071 foreach(cell, ltblspc)
3072 tablespace_ids[i++] = lfirst_oid(cell);
3073
3074 /* Record the filesystem change in XLOG */
3075 {
3077
3078 xlrec.db_id = db_id;
3079 xlrec.ntablespaces = ntblspc;
3080
3083 XLogRegisterData(tablespace_ids, ntblspc * sizeof(Oid));
3084
3087 }
3088
3090 pfree(tablespace_ids);
3091
3092 table_endscan(scan);
3094}
#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 1911 of file dbcommands.c.

1912{
1913 Oid db_id;
1916 Relation rel;
1917 int notherbackends;
1918 int npreparedxacts;
1919 ObjectAddress address;
1920
1921 /* Report error if name has \n or \r character. */
1922 if (strpbrk(newname, "\n\r"))
1923 ereport(ERROR,
1925 errmsg("database name \"%s\" contains a newline or carriage return character", newname)));
1926
1927 /*
1928 * Look up the target database's OID, and get exclusive lock on it. We
1929 * need this for the same reasons as DROP DATABASE.
1930 */
1932
1935 ereport(ERROR,
1937 errmsg("database \"%s\" does not exist", oldname)));
1938
1939 /* must be owner */
1942 oldname);
1943
1944 /* must have createdb rights */
1946 ereport(ERROR,
1948 errmsg("permission denied to rename database")));
1949
1950 /*
1951 * If built with appropriate switch, whine when regression-testing
1952 * conventions for database names are violated.
1953 */
1954#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1955 if (strstr(newname, "regression") == NULL)
1956 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1957#endif
1958
1959 /*
1960 * Make sure the new name doesn't exist. See notes for same error in
1961 * CREATE DATABASE.
1962 */
1963 if (OidIsValid(get_database_oid(newname, true)))
1964 ereport(ERROR,
1966 errmsg("database \"%s\" already exists", newname)));
1967
1968 /*
1969 * XXX Client applications probably store the current database somewhere,
1970 * so renaming it could cause confusion. On the other hand, there may not
1971 * be an actual problem besides a little confusion, so think about this
1972 * and decide.
1973 */
1974 if (db_id == MyDatabaseId)
1975 ereport(ERROR,
1977 errmsg("current database cannot be renamed")));
1978
1979 /*
1980 * Make sure the database does not have active sessions. This is the same
1981 * concern as above, but applied to other sessions.
1982 *
1983 * As in CREATE DATABASE, check this after other error conditions.
1984 */
1986 ereport(ERROR,
1988 errmsg("database \"%s\" is being accessed by other users",
1989 oldname),
1991
1992 /* rename */
1995 elog(ERROR, "cache lookup failed for database %u", db_id);
1996 otid = newtup->t_self;
2000
2002
2003 ObjectAddressSet(address, DatabaseRelationId, db_id);
2004
2005 /*
2006 * Close pg_database, but keep lock till commit.
2007 */
2008 table_close(rel, NoLock);
2009
2010 return address;
2011}
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:399

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:5522
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition bufmgr.c:958
@ BAS_BULKREAD
Definition bufmgr.h:37
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:470
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:210
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:332
@ RBM_NORMAL
Definition bufmgr.h:46
static bool PageIsEmpty(const PageData *page)
Definition bufpage.h:249
static bool PageIsNew(const PageData *page)
Definition bufpage.h:259
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:461
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#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:4357
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:269
static void * PageGetItem(PageData *page, const ItemIdData *itemId)
Definition bufpage.h:379
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition bufpage.h:397
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().