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

Go to the source code of this file.

Data Structures

struct  createdb_failure_params
 
struct  movedb_failure_params
 
struct  CreateDBRelInfo
 

Typedefs

typedef enum CreateDBStrategy CreateDBStrategy
 
typedef struct CreateDBRelInfo CreateDBRelInfo
 

Enumerations

enum  CreateDBStrategy { CREATEDB_WAL_LOG , CREATEDB_FILE_COPY }
 

Functions

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

Typedef Documentation

◆ CreateDBRelInfo

◆ CreateDBStrategy

Enumeration Type Documentation

◆ CreateDBStrategy

Enumerator
CREATEDB_WAL_LOG 
CREATEDB_FILE_COPY 

Definition at line 82 of file dbcommands.c.

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

Function Documentation

◆ AlterDatabase()

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

Definition at line 2342 of file dbcommands.c.

2343{
2344 Relation rel;
2345 Oid dboid;
2346 HeapTuple tuple,
2347 newtuple;
2348 Form_pg_database datform;
2349 ScanKeyData scankey;
2350 SysScanDesc scan;
2352 bool dbistemplate = false;
2353 bool dballowconnections = true;
2354 int dbconnlimit = DATCONNLIMIT_UNLIMITED;
2355 DefElem *distemplate = NULL;
2356 DefElem *dallowconnections = NULL;
2357 DefElem *dconnlimit = NULL;
2358 DefElem *dtablespace = NULL;
2359 Datum new_record[Natts_pg_database] = {0};
2360 bool new_record_nulls[Natts_pg_database] = {0};
2361 bool new_record_repl[Natts_pg_database] = {0};
2362
2363 /* Extract options from the statement node tree */
2364 foreach(option, stmt->options)
2365 {
2366 DefElem *defel = (DefElem *) lfirst(option);
2367
2368 if (strcmp(defel->defname, "is_template") == 0)
2369 {
2370 if (distemplate)
2371 errorConflictingDefElem(defel, pstate);
2372 distemplate = defel;
2373 }
2374 else if (strcmp(defel->defname, "allow_connections") == 0)
2375 {
2376 if (dallowconnections)
2377 errorConflictingDefElem(defel, pstate);
2378 dallowconnections = defel;
2379 }
2380 else if (strcmp(defel->defname, "connection_limit") == 0)
2381 {
2382 if (dconnlimit)
2383 errorConflictingDefElem(defel, pstate);
2384 dconnlimit = defel;
2385 }
2386 else if (strcmp(defel->defname, "tablespace") == 0)
2387 {
2388 if (dtablespace)
2389 errorConflictingDefElem(defel, pstate);
2390 dtablespace = defel;
2391 }
2392 else
2393 ereport(ERROR,
2394 (errcode(ERRCODE_SYNTAX_ERROR),
2395 errmsg("option \"%s\" not recognized", defel->defname),
2396 parser_errposition(pstate, defel->location)));
2397 }
2398
2399 if (dtablespace)
2400 {
2401 /*
2402 * While the SET TABLESPACE syntax doesn't allow any other options,
2403 * somebody could write "WITH TABLESPACE ...". Forbid any other
2404 * options from being specified in that case.
2405 */
2406 if (list_length(stmt->options) != 1)
2407 ereport(ERROR,
2408 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2409 errmsg("option \"%s\" cannot be specified with other options",
2410 dtablespace->defname),
2411 parser_errposition(pstate, dtablespace->location)));
2412 /* this case isn't allowed within a transaction block */
2413 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2414 movedb(stmt->dbname, defGetString(dtablespace));
2415 return InvalidOid;
2416 }
2417
2418 if (distemplate && distemplate->arg)
2419 dbistemplate = defGetBoolean(distemplate);
2420 if (dallowconnections && dallowconnections->arg)
2421 dballowconnections = defGetBoolean(dallowconnections);
2422 if (dconnlimit && dconnlimit->arg)
2423 {
2424 dbconnlimit = defGetInt32(dconnlimit);
2425 if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
2426 ereport(ERROR,
2427 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2428 errmsg("invalid connection limit: %d", dbconnlimit)));
2429 }
2430
2431 /*
2432 * Get the old tuple. We don't need a lock on the database per se,
2433 * because we're not going to do anything that would mess up incoming
2434 * connections.
2435 */
2436 rel = table_open(DatabaseRelationId, RowExclusiveLock);
2437 ScanKeyInit(&scankey,
2438 Anum_pg_database_datname,
2439 BTEqualStrategyNumber, F_NAMEEQ,
2440 CStringGetDatum(stmt->dbname));
2441 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2442 NULL, 1, &scankey);
2443 tuple = systable_getnext(scan);
2444 if (!HeapTupleIsValid(tuple))
2445 ereport(ERROR,
2446 (errcode(ERRCODE_UNDEFINED_DATABASE),
2447 errmsg("database \"%s\" does not exist", stmt->dbname)));
2449
2450 datform = (Form_pg_database) GETSTRUCT(tuple);
2451 dboid = datform->oid;
2452
2453 if (database_is_invalid_form(datform))
2454 {
2455 ereport(FATAL,
2456 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2457 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2458 errhint("Use DROP DATABASE to drop invalid databases."));
2459 }
2460
2461 if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2463 stmt->dbname);
2464
2465 /*
2466 * In order to avoid getting locked out and having to go through
2467 * standalone mode, we refuse to disallow connections to the database
2468 * we're currently connected to. Lockout can still happen with concurrent
2469 * sessions but the likeliness of that is not high enough to worry about.
2470 */
2471 if (!dballowconnections && dboid == MyDatabaseId)
2472 ereport(ERROR,
2473 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2474 errmsg("cannot disallow connections for current database")));
2475
2476 /*
2477 * Build an updated tuple, perusing the information just obtained
2478 */
2479 if (distemplate)
2480 {
2481 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2482 new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2483 }
2484 if (dallowconnections)
2485 {
2486 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2487 new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2488 }
2489 if (dconnlimit)
2490 {
2491 new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2492 new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2493 }
2494
2495 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2496 new_record_nulls, new_record_repl);
2497 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2499
2500 InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2501
2502 systable_endscan(scan);
2503
2504 /* Close pg_database, but keep lock till commit */
2505 table_close(rel, NoLock);
2506
2507 return dboid;
2508}
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2622
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4058
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3212
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1978
int32 defGetInt32(DefElem *def)
Definition: define.c:149
char * defGetString(DefElem *def)
Definition: define.c:35
bool defGetBoolean(DefElem *def)
Definition: define.c:94
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:371
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c: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:93
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1210
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
void LockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:562
void UnlockTuple(Relation relation, ItemPointer tid, LOCKMODE lockmode)
Definition: lmgr.c:601
#define NoLock
Definition: lockdefs.h:34
#define InplaceUpdateTupleLock
Definition: lockdefs.h:48
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:520
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ OBJECT_DATABASE
Definition: parsenodes.h:2326
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
#define DATCONNLIMIT_UNLIMITED
Definition: pg_database.h:117
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
uintptr_t Datum
Definition: postgres.h:69
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:355
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
#define RelationGetDescr(relation)
Definition: rel.h:539
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char * defname
Definition: parsenodes.h:826
ParseLoc location
Definition: parsenodes.h:830
Node * arg
Definition: parsenodes.h:827
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:3648

References aclcheck_error(), ACLCHECK_NOT_OWNER, DefElem::arg, BoolGetDatum(), BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), database_is_invalid_form(), DATCONNLIMIT_UNLIMITED, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errhint(), errmsg(), ERROR, errorConflictingDefElem(), FATAL, GETSTRUCT(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InplaceUpdateTupleLock, Int32GetDatum(), InvalidOid, InvokeObjectPostAlterHook, lfirst, list_length(), DefElem::location, 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 2638 of file dbcommands.c.

2639{
2640 Oid db_id;
2641 HeapTuple tuple;
2642 Relation rel;
2643 ScanKeyData scankey;
2644 SysScanDesc scan;
2645 Form_pg_database datForm;
2646 ObjectAddress address;
2647
2648 /*
2649 * Get the old tuple. We don't need a lock on the database per se,
2650 * because we're not going to do anything that would mess up incoming
2651 * connections.
2652 */
2653 rel = table_open(DatabaseRelationId, RowExclusiveLock);
2654 ScanKeyInit(&scankey,
2655 Anum_pg_database_datname,
2656 BTEqualStrategyNumber, F_NAMEEQ,
2658 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2659 NULL, 1, &scankey);
2660 tuple = systable_getnext(scan);
2661 if (!HeapTupleIsValid(tuple))
2662 ereport(ERROR,
2663 (errcode(ERRCODE_UNDEFINED_DATABASE),
2664 errmsg("database \"%s\" does not exist", dbname)));
2665
2666 datForm = (Form_pg_database) GETSTRUCT(tuple);
2667 db_id = datForm->oid;
2668
2669 /*
2670 * If the new owner is the same as the existing owner, consider the
2671 * command to have succeeded. This is to be consistent with other
2672 * objects.
2673 */
2674 if (datForm->datdba != newOwnerId)
2675 {
2676 Datum repl_val[Natts_pg_database];
2677 bool repl_null[Natts_pg_database] = {0};
2678 bool repl_repl[Natts_pg_database] = {0};
2679 Acl *newAcl;
2680 Datum aclDatum;
2681 bool isNull;
2682 HeapTuple newtuple;
2683
2684 /* Otherwise, must be owner of the existing object */
2685 if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2687 dbname);
2688
2689 /* Must be able to become new owner */
2690 check_can_set_role(GetUserId(), newOwnerId);
2691
2692 /*
2693 * must have createdb rights
2694 *
2695 * NOTE: This is different from other alter-owner checks in that the
2696 * current user is checked for createdb privileges instead of the
2697 * destination owner. This is consistent with the CREATE case for
2698 * databases. Because superusers will always have this right, we need
2699 * no special case for them.
2700 */
2702 ereport(ERROR,
2703 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2704 errmsg("permission denied to change owner of database")));
2705
2707
2708 repl_repl[Anum_pg_database_datdba - 1] = true;
2709 repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2710
2711 /*
2712 * Determine the modified ACL for the new owner. This is only
2713 * necessary when the ACL is non-null.
2714 */
2715 aclDatum = heap_getattr(tuple,
2716 Anum_pg_database_datacl,
2717 RelationGetDescr(rel),
2718 &isNull);
2719 if (!isNull)
2720 {
2721 newAcl = aclnewowner(DatumGetAclP(aclDatum),
2722 datForm->datdba, newOwnerId);
2723 repl_repl[Anum_pg_database_datacl - 1] = true;
2724 repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2725 }
2726
2727 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2728 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2730
2731 heap_freetuple(newtuple);
2732
2733 /* Update owner dependency reference */
2734 changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2735 }
2736
2737 InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2738
2739 ObjectAddressSet(address, DatabaseRelationId, db_id);
2740
2741 systable_endscan(scan);
2742
2743 /* Close pg_database, but keep lock till commit */
2744 table_close(rel, NoLock);
2745
2746 return address;
2747}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1103
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5325
#define DatumGetAclP(X)
Definition: acl.h:120
bool have_createdb_privilege(void)
Definition: dbcommands.c:2953
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:316
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
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, 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 2515 of file dbcommands.c.

2516{
2517 Relation rel;
2518 ScanKeyData scankey;
2519 SysScanDesc scan;
2520 Oid db_id;
2521 HeapTuple tuple;
2522 Form_pg_database datForm;
2523 ObjectAddress address;
2524 Datum datum;
2525 bool isnull;
2526 char *oldversion;
2527 char *newversion;
2528
2529 rel = table_open(DatabaseRelationId, RowExclusiveLock);
2530 ScanKeyInit(&scankey,
2531 Anum_pg_database_datname,
2532 BTEqualStrategyNumber, F_NAMEEQ,
2533 CStringGetDatum(stmt->dbname));
2534 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2535 NULL, 1, &scankey);
2536 tuple = systable_getnext(scan);
2537 if (!HeapTupleIsValid(tuple))
2538 ereport(ERROR,
2539 (errcode(ERRCODE_UNDEFINED_DATABASE),
2540 errmsg("database \"%s\" does not exist", stmt->dbname)));
2541
2542 datForm = (Form_pg_database) GETSTRUCT(tuple);
2543 db_id = datForm->oid;
2544
2545 if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2547 stmt->dbname);
2549
2550 datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2551 oldversion = isnull ? NULL : TextDatumGetCString(datum);
2552
2553 if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2554 {
2555 datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2556 if (isnull)
2557 elog(ERROR, "unexpected null in pg_database");
2558 }
2559 else
2560 {
2561 datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2562 if (isnull)
2563 elog(ERROR, "unexpected null in pg_database");
2564 }
2565
2566 newversion = get_collation_actual_version(datForm->datlocprovider,
2567 TextDatumGetCString(datum));
2568
2569 /* cannot change from NULL to non-NULL or vice versa */
2570 if ((!oldversion && newversion) || (oldversion && !newversion))
2571 elog(ERROR, "invalid collation version change");
2572 else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2573 {
2574 bool nulls[Natts_pg_database] = {0};
2575 bool replaces[Natts_pg_database] = {0};
2576 Datum values[Natts_pg_database] = {0};
2577 HeapTuple newtuple;
2578
2580 (errmsg("changing version from %s to %s",
2581 oldversion, newversion)));
2582
2583 values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2584 replaces[Anum_pg_database_datcollversion - 1] = true;
2585
2586 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2587 values, nulls, replaces);
2588 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2589 heap_freetuple(newtuple);
2590 }
2591 else
2593 (errmsg("version has not changed")));
2595
2596 InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2597
2598 ObjectAddressSet(address, DatabaseRelationId, db_id);
2599
2600 systable_endscan(scan);
2601
2602 table_close(rel, NoLock);
2603
2604 return address;
2605}
static Datum values[MAXATTR]
Definition: bootstrap.c:151
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define elog(elevel,...)
Definition: elog.h:225
#define NOTICE
Definition: elog.h:35
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1295

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), CStringGetTextDatum, elog, ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), GETSTRUCT(), GetUserId(), heap_freetuple(), heap_getattr(), heap_modify_tuple(), HeapTupleIsValid, 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 2612 of file dbcommands.c.

2613{
2614 Oid datid = get_database_oid(stmt->dbname, false);
2615
2616 /*
2617 * Obtain a lock on the database and make sure it didn't go away in the
2618 * meantime.
2619 */
2620 shdepLockAndCheckObject(DatabaseRelationId, datid);
2621
2622 if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2624 stmt->dbname);
2625
2626 AlterSetting(datid, InvalidOid, stmt->setstmt);
2627
2628 UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2629
2630 return datid;
2631}
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3141
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1142
#define AccessShareLock
Definition: lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1211

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

Referenced by standard_ProcessUtility().

◆ check_db_file_conflict()

static bool check_db_file_conflict ( Oid  db_id)
static

Definition at line 3068 of file dbcommands.c.

3069{
3070 bool result = false;
3071 Relation rel;
3072 TableScanDesc scan;
3073 HeapTuple tuple;
3074
3075 rel = table_open(TableSpaceRelationId, AccessShareLock);
3076 scan = table_beginscan_catalog(rel, 0, NULL);
3077 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3078 {
3080 Oid dsttablespace = spcform->oid;
3081 char *dstpath;
3082 struct stat st;
3083
3084 /* Don't mess with the global tablespace */
3085 if (dsttablespace == GLOBALTABLESPACE_OID)
3086 continue;
3087
3088 dstpath = GetDatabasePath(db_id, dsttablespace);
3089
3090 if (lstat(dstpath, &st) == 0)
3091 {
3092 /* Found a conflicting file (or directory, whatever) */
3093 pfree(dstpath);
3094 result = true;
3095 break;
3096 }
3097
3098 pfree(dstpath);
3099 }
3100
3101 table_endscan(scan);
3103
3104 return result;
3105}
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1347
void pfree(void *pointer)
Definition: mcxt.c:1524
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
@ ForwardScanDirection
Definition: sdir.h:28
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:989
#define lstat(path, sb)
Definition: win32_port.h:275

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

Referenced by createdb().

◆ check_encoding_locale_matches()

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

Definition at line 1571 of file dbcommands.c.

1572{
1573 int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1574 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1575
1576 if (!(ctype_encoding == encoding ||
1577 ctype_encoding == PG_SQL_ASCII ||
1578 ctype_encoding == -1 ||
1579#ifdef WIN32
1580 encoding == PG_UTF8 ||
1581#endif
1582 (encoding == PG_SQL_ASCII && superuser())))
1583 ereport(ERROR,
1584 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1585 errmsg("encoding \"%s\" does not match locale \"%s\"",
1587 ctype),
1588 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1589 pg_encoding_to_char(ctype_encoding))));
1590
1591 if (!(collate_encoding == encoding ||
1592 collate_encoding == PG_SQL_ASCII ||
1593 collate_encoding == -1 ||
1594#ifdef WIN32
1595 encoding == PG_UTF8 ||
1596#endif
1597 (encoding == PG_SQL_ASCII && superuser())))
1598 ereport(ERROR,
1599 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1600 errmsg("encoding \"%s\" does not match locale \"%s\"",
1602 collate),
1603 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1604 pg_encoding_to_char(collate_encoding))));
1605}
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int32 encoding
Definition: pg_database.h:41
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
#define pg_encoding_to_char
Definition: pg_wchar.h:630
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:301
bool superuser(void)
Definition: superuser.c:46

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

Referenced by createdb(), and DefineCollation().

◆ CreateDatabaseUsingFileCopy()

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

Definition at line 551 of file dbcommands.c.

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

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

Referenced by createdb().

◆ CreateDatabaseUsingWalLog()

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

Definition at line 148 of file dbcommands.c.

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

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

Referenced by createdb().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 684 of file dbcommands.c.

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

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

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

◆ createdb_failure_callback()

static void createdb_failure_callback ( int  code,
Datum  arg 
)
static

Definition at line 1609 of file dbcommands.c.

1610{
1612
1613 /*
1614 * If we were copying database at block levels then drop pages for the
1615 * destination database that are in the shared buffer cache. And tell
1616 * checkpointer to forget any pending fsync and unlink requests for files
1617 * in the database. The reasoning behind doing this is same as explained
1618 * in dropdb function. But unlike dropdb we don't need to call
1619 * pgstat_drop_database because this database is still not created so
1620 * there should not be any stat for this.
1621 */
1622 if (fparms->strategy == CREATEDB_WAL_LOG)
1623 {
1626
1627 /* Release lock on the target database. */
1628 UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1630 }
1631
1632 /*
1633 * Release lock on source database before doing recursive remove. This is
1634 * not essential but it seems desirable to release the lock as soon as
1635 * possible.
1636 */
1637 UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1638
1639 /* Throw away any successfully copied subdirectories */
1641}
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:4458
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2978
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1453
void * arg
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317

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

Referenced by createdb().

◆ CreateDirAndVersionFile()

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

Definition at line 457 of file dbcommands.c.

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

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

Referenced by CreateDatabaseUsingWalLog(), and dbase_redo().

◆ database_is_invalid_form()

bool database_is_invalid_form ( Form_pg_database  datform)

Definition at line 3212 of file dbcommands.c.

3213{
3214 return datform->datconnlimit == DATCONNLIMIT_INVALID_DB;
3215}
#define DATCONNLIMIT_INVALID_DB
Definition: pg_database.h:124

References DATCONNLIMIT_INVALID_DB.

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

◆ database_is_invalid_oid()

bool database_is_invalid_oid ( Oid  dboid)

Definition at line 3222 of file dbcommands.c.

3223{
3224 HeapTuple dbtup;
3225 Form_pg_database dbform;
3226 bool invalid;
3227
3228 dbtup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dboid));
3229 if (!HeapTupleIsValid(dbtup))
3230 elog(ERROR, "cache lookup failed for database %u", dboid);
3231 dbform = (Form_pg_database) GETSTRUCT(dbtup);
3232
3234
3235 ReleaseSysCache(dbtup);
3236
3237 return invalid;
3238}
invalidindex index d is invalid
Definition: isn.c:138
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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

Referenced by createdb().

◆ dbase_redo()

void dbase_redo ( XLogReaderState record)

Definition at line 3284 of file dbcommands.c.

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

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 2317 of file dbcommands.c.

2318{
2319 bool force = false;
2320 ListCell *lc;
2321
2322 foreach(lc, stmt->options)
2323 {
2324 DefElem *opt = (DefElem *) lfirst(lc);
2325
2326 if (strcmp(opt->defname, "force") == 0)
2327 force = true;
2328 else
2329 ereport(ERROR,
2330 (errcode(ERRCODE_SYNTAX_ERROR),
2331 errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2332 parser_errposition(pstate, opt->location)));
2333 }
2334
2335 dropdb(stmt->dbname, stmt->missing_ok, force);
2336}
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1648

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1648 of file dbcommands.c.

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

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleDelete(), CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, 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, ForceSyncCommit(), ForgetDatabaseSyncRequests(), 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(), HeapTupleData::t_self, table_close(), table_open(), TerminateOtherDBBackends(), WaitForProcSignalBarrier(), XactLastRecEnd, and XLogFlush().

Referenced by DropDatabase().

◆ errdetail_busy_db()

static int errdetail_busy_db ( int  notherbackends,
int  npreparedxacts 
)
static

Definition at line 3111 of file dbcommands.c.

3112{
3113 if (notherbackends > 0 && npreparedxacts > 0)
3114
3115 /*
3116 * We don't deal with singular versus plural here, since gettext
3117 * doesn't support multiple plurals in one string.
3118 */
3119 errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3120 notherbackends, npreparedxacts);
3121 else if (notherbackends > 0)
3122 errdetail_plural("There is %d other session using the database.",
3123 "There are %d other sessions using the database.",
3124 notherbackends,
3125 notherbackends);
3126 else
3127 errdetail_plural("There is %d prepared transaction using the database.",
3128 "There are %d prepared transactions using the database.",
3129 npreparedxacts,
3130 npreparedxacts);
3131 return 0; /* just to keep ereport macro happy */
3132}

References errdetail(), and errdetail_plural().

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

◆ get_database_name()

char * get_database_name ( Oid  dbid)

Definition at line 3188 of file dbcommands.c.

3189{
3190 HeapTuple dbtuple;
3191 char *result;
3192
3193 dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3194 if (HeapTupleIsValid(dbtuple))
3195 {
3196 result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3197 ReleaseSysCache(dbtuple);
3198 }
3199 else
3200 result = NULL;
3201
3202 return result;
3203}
#define NameStr(name)
Definition: c.h:717
NameData datname
Definition: pg_database.h:35

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 3141 of file dbcommands.c.

3142{
3143 Relation pg_database;
3144 ScanKeyData entry[1];
3145 SysScanDesc scan;
3146 HeapTuple dbtuple;
3147 Oid oid;
3148
3149 /*
3150 * There's no syscache for pg_database indexed by name, so we must look
3151 * the hard way.
3152 */
3153 pg_database = table_open(DatabaseRelationId, AccessShareLock);
3154 ScanKeyInit(&entry[0],
3155 Anum_pg_database_datname,
3156 BTEqualStrategyNumber, F_NAMEEQ,
3158 scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
3159 NULL, 1, entry);
3160
3161 dbtuple = systable_getnext(scan);
3162
3163 /* We assume that there can be at most one matching tuple */
3164 if (HeapTupleIsValid(dbtuple))
3165 oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3166 else
3167 oid = InvalidOid;
3168
3169 systable_endscan(scan);
3170 table_close(pg_database, AccessShareLock);
3171
3172 if (!OidIsValid(oid) && !missing_ok)
3173 ereport(ERROR,
3174 (errcode(ERRCODE_UNDEFINED_DATABASE),
3175 errmsg("database \"%s\" does not exist",
3176 dbname)));
3177
3178 return oid;
3179}

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

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

◆ get_db_info()

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

Definition at line 2795 of file dbcommands.c.

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

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

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

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2953 of file dbcommands.c.

2954{
2955 bool result = false;
2956 HeapTuple utup;
2957
2958 /* Superusers can always do everything */
2959 if (superuser())
2960 return true;
2961
2962 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2963 if (HeapTupleIsValid(utup))
2964 {
2965 result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2966 ReleaseSysCache(utup);
2967 }
2968 return result;
2969}
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38

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

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

◆ movedb()

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

Definition at line 1978 of file dbcommands.c.

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

References AccessExclusiveLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AllocateDir(), BTEqualStrategyNumber, CatalogTupleUpdate(), CHECKPOINT_FLUSH_ALL, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, CommitTransactionCommand(), copydir(), CountOtherDBBackends(), CStringGetDatum(), dirent::d_name, xl_dbase_create_file_copy_rec::db_id, xl_dbase_drop_rec::db_id, dbname, movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, DropDatabaseBuffers(), elog, EmitProcSignalBarrier(), ereport, errcode(), errdetail_busy_db(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FreeDir(), get_db_info(), get_tablespace_oid(), GetDatabasePath(), GetUserId(), heap_modify_tuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvokeObjectPostAlterHook, LockSharedObjectForSession(), LockTuple(), movedb_failure_callback(), MyDatabaseId, NoLock, xl_dbase_drop_rec::ntablespaces, object_aclcheck(), OBJECT_DATABASE, object_ownercheck(), OBJECT_TABLESPACE, ObjectIdGetDatum(), pfree(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, PointerGetDatum(), PopActiveSnapshot(), PROCSIGNAL_BARRIER_SMGRRELEASE, ReadDir(), RelationGetDescr, RequestCheckpoint(), rmtree(), RowExclusiveLock, ScanKeyInit(), xl_dbase_create_file_copy_rec::src_db_id, xl_dbase_create_file_copy_rec::src_tablespace_id, StartTransactionCommand(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), xl_dbase_create_file_copy_rec::tablespace_id, UnlockSharedObjectForSession(), 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 2300 of file dbcommands.c.

2301{
2303 char *dstpath;
2304
2305 /* Get rid of anything we managed to copy to the target directory */
2306 dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2307
2308 (void) rmtree(dstpath, true);
2309
2310 pfree(dstpath);
2311}

References arg, DatumGetPointer(), movedb_failure_params::dest_dboid, movedb_failure_params::dest_tsoid, dstpath, GetDatabasePath(), pfree(), and rmtree().

Referenced by movedb().

◆ pg_database_collation_actual_version()

Datum pg_database_collation_actual_version ( PG_FUNCTION_ARGS  )

Definition at line 2751 of file dbcommands.c.

2752{
2753 Oid dbid = PG_GETARG_OID(0);
2754 HeapTuple tp;
2755 char datlocprovider;
2756 Datum datum;
2757 char *version;
2758
2759 tp = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2760 if (!HeapTupleIsValid(tp))
2761 ereport(ERROR,
2762 (errcode(ERRCODE_UNDEFINED_OBJECT),
2763 errmsg("database with OID %u does not exist", dbid)));
2764
2766
2767 if (datlocprovider == COLLPROVIDER_LIBC)
2768 datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datcollate);
2769 else
2770 datum = SysCacheGetAttrNotNull(DATABASEOID, tp, Anum_pg_database_datlocale);
2771
2773 TextDatumGetCString(datum));
2774
2775 ReleaseSysCache(tp);
2776
2777 if (version)
2779 else
2781}
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
char datlocprovider
Definition: pg_database.h:44
text * cstring_to_text(const char *s)
Definition: varlena.c:192

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

◆ recovery_create_dbdir()

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

Definition at line 3255 of file dbcommands.c.

3256{
3257 struct stat st;
3258
3260
3261 if (stat(path, &st) == 0)
3262 return;
3263
3264 if (only_tblspc && strstr(path, PG_TBLSPC_DIR_SLASH) == NULL)
3265 elog(PANIC, "requested to created invalid directory: %s", path);
3266
3268 ereport(PANIC,
3269 errmsg("missing directory \"%s\"", path));
3270
3272 "creating missing directory: %s", path);
3273
3274 if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3275 ereport(PANIC,
3276 errmsg("could not create missing directory \"%s\": %m", path));
3277}
bool allow_in_place_tablespaces
Definition: tablespace.c:85
#define DEBUG1
Definition: elog.h:30
int pg_dir_create_mode
Definition: file_perm.c:18
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
#define PG_TBLSPC_DIR_SLASH
Definition: relpath.h:42
bool RecoveryInProgress(void)
Definition: xlog.c:6380
bool reachedConsistency
Definition: xlogrecovery.c:295

References allow_in_place_tablespaces, Assert(), DEBUG1, elog, ereport, errmsg(), 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 2978 of file dbcommands.c.

2979{
2980 Relation rel;
2981 TableScanDesc scan;
2982 HeapTuple tuple;
2983 List *ltblspc = NIL;
2984 ListCell *cell;
2985 int ntblspc;
2986 int i;
2987 Oid *tablespace_ids;
2988
2989 rel = table_open(TableSpaceRelationId, AccessShareLock);
2990 scan = table_beginscan_catalog(rel, 0, NULL);
2991 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2992 {
2994 Oid dsttablespace = spcform->oid;
2995 char *dstpath;
2996 struct stat st;
2997
2998 /* Don't mess with the global tablespace */
2999 if (dsttablespace == GLOBALTABLESPACE_OID)
3000 continue;
3001
3002 dstpath = GetDatabasePath(db_id, dsttablespace);
3003
3004 if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
3005 {
3006 /* Assume we can ignore it */
3007 pfree(dstpath);
3008 continue;
3009 }
3010
3011 if (!rmtree(dstpath, true))
3013 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3014 dstpath)));
3015
3016 ltblspc = lappend_oid(ltblspc, dsttablespace);
3017 pfree(dstpath);
3018 }
3019
3020 ntblspc = list_length(ltblspc);
3021 if (ntblspc == 0)
3022 {
3023 table_endscan(scan);
3025 return;
3026 }
3027
3028 tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
3029 i = 0;
3030 foreach(cell, ltblspc)
3031 tablespace_ids[i++] = lfirst_oid(cell);
3032
3033 /* Record the filesystem change in XLOG */
3034 {
3035 xl_dbase_drop_rec xlrec;
3036
3037 xlrec.db_id = db_id;
3038 xlrec.ntablespaces = ntblspc;
3039
3042 XLogRegisterData(tablespace_ids, ntblspc * sizeof(Oid));
3043
3044 (void) XLogInsert(RM_DBASE_ID,
3046 }
3047
3048 list_free(ltblspc);
3049 pfree(tablespace_ids);
3050
3051 table_endscan(scan);
3053}
#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:1317
#define lfirst_oid(lc)
Definition: pg_list.h:174

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

Referenced by createdb_failure_callback(), and dropdb().

◆ RenameDatabase()

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

Definition at line 1877 of file dbcommands.c.

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

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

Referenced by ExecRenameStmt().

◆ ScanSourceDatabasePgClass()

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

Definition at line 250 of file dbcommands.c.

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

References AccessShareLock, BAS_BULKREAD, buf, BUFFER_LOCK_SHARE, BufferGetPage(), CHECK_FOR_INTERRUPTS, LockRelId::dbId, RelFileLocator::dbOid, GetAccessStrategy(), GetLatestSnapshot(), INVALID_PROC_NUMBER, LockBuffer(), LockRelationId(), MAIN_FORKNUM, NIL, PageIsEmpty(), PageIsNew(), RBM_NORMAL, ReadBufferWithoutRelcache(), 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 329 of file dbcommands.c.

332{
334 OffsetNumber offnum;
335 OffsetNumber maxoff;
336 HeapTupleData tuple;
337
338 maxoff = PageGetMaxOffsetNumber(page);
339
340 /* Loop over offsets. */
341 for (offnum = FirstOffsetNumber;
342 offnum <= maxoff;
343 offnum = OffsetNumberNext(offnum))
344 {
345 ItemId itemid;
346
347 itemid = PageGetItemId(page, offnum);
348
349 /* Nothing to do if slot is empty or already dead. */
350 if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
351 ItemIdIsRedirected(itemid))
352 continue;
353
354 Assert(ItemIdIsNormal(itemid));
355 ItemPointerSet(&(tuple.t_self), blkno, offnum);
356
357 /* Initialize a HeapTupleData structure. */
358 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
359 tuple.t_len = ItemIdGetLength(itemid);
360 tuple.t_tableOid = RelationRelationId;
361
362 /* Skip tuples that are not visible to this snapshot. */
363 if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
364 {
365 CreateDBRelInfo *relinfo;
366
367 /*
368 * ScanSourceDatabasePgClassTuple is in charge of constructing a
369 * CreateDBRelInfo object for this tuple, but can also decide that
370 * this tuple isn't something we need to copy. If we do need to
371 * copy the relation, add it to the list.
372 */
373 relinfo = ScanSourceDatabasePgClassTuple(&tuple, tbid, dbid,
374 srcpath);
375 if (relinfo != NULL)
376 rlocatorlist = lappend(rlocatorlist, relinfo);
377 }
378 }
379
380 return rlocatorlist;
381}
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:3795
static Item PageGetItem(const PageData *page, const ItemIdData *itemId)
Definition: bufpage.h:354
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:244
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition: bufpage.h:372
static CreateDBRelInfo * ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
Definition: dbcommands.c:392
bool HeapTupleSatisfiesVisibility(HeapTuple htup, Snapshot snapshot, Buffer buffer)
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition: itemptr.h:135
List * lappend(List *list, void *datum)
Definition: list.c:339
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
uint16 OffsetNumber
Definition: off.h:24
#define FirstOffsetNumber
Definition: off.h:27
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66

References Assert(), buf, BufferGetBlockNumber(), FirstOffsetNumber, HeapTupleSatisfiesVisibility(), ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet(), lappend(), OffsetNumberNext, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), ScanSourceDatabasePgClassTuple(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by ScanSourceDatabasePgClass().

◆ ScanSourceDatabasePgClassTuple()

CreateDBRelInfo * ScanSourceDatabasePgClassTuple ( HeapTupleData tuple,
Oid  tbid,
Oid  dbid,
char *  srcpath 
)
static

Definition at line 392 of file dbcommands.c.

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

References Assert(), RelFileLocator::dbOid, elog, ERROR, GETSTRUCT(), InvalidRelFileNumber, OidIsValid, palloc(), CreateDBRelInfo::permanent, RelationMapOidToFilenumberForDatabase(), RelFileNumberIsValid, RelFileLocator::relNumber, CreateDBRelInfo::reloid, CreateDBRelInfo::rlocator, and RelFileLocator::spcOid.

Referenced by ScanSourceDatabasePgClassPage().