PostgreSQL Source Code git master
Loading...
Searching...
No Matches
dbcommands.h File Reference
Include dependency graph for dbcommands.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

Oid createdb (ParseState *pstate, const CreatedbStmt *stmt)
 
void dropdb (const char *dbname, bool missing_ok, bool force)
 
void DropDatabase (ParseState *pstate, DropdbStmt *stmt)
 
ObjectAddress RenameDatabase (const char *oldname, const char *newname)
 
Oid AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterDatabaseRefreshColl (AlterDatabaseRefreshCollStmt *stmt)
 
Oid AlterDatabaseSet (AlterDatabaseSetStmt *stmt)
 
ObjectAddress AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
bool have_createdb_privilege (void)
 
void check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 

Function Documentation

◆ AlterDatabase()

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

Definition at line 2390 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char dbname,
Oid  newOwnerId 
)
extern

Definition at line 2686 of file dbcommands.c.

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

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)
extern

Definition at line 2563 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)
extern

Definition at line 2660 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ check_encoding_locale_matches()

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

Definition at line 1612 of file dbcommands.c.

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

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

Referenced by createdb(), and DefineCollation().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)
extern

Definition at line 687 of file dbcommands.c.

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

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

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)
extern

Definition at line 2364 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1689 of file dbcommands.c.

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

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleDelete(), CHECKPOINT_FAST, CHECKPOINT_FORCE, CHECKPOINT_WAIT, CountDBSubscriptions(), CountOtherDBBackends(), CStringGetDatum(), DATCONNLIMIT_INVALID_DB, dbname, DeleteSharedComments(), DeleteSharedSecurityLabel(), DropDatabaseBuffers(), dropDatabaseDependencies(), DropSetting(), elog, EmitProcSignalBarrier(), ereport, errcode(), errdetail_busy_db(), errdetail_plural(), errmsg, ERROR, fb(), ForceSyncCommit(), ForgetDatabaseSyncRequests(), Form_pg_database, get_db_info(), GETSTRUCT(), GetUserId(), heap_freetuple(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, MyDatabaseId, NoLock, NOTICE, OBJECT_DATABASE, object_ownercheck(), pgstat_drop_database(), PROCSIGNAL_BARRIER_SMGRRELEASE, remove_dbtablespaces(), ReplicationSlotsCountDBSlots(), ReplicationSlotsDropDBSlots(), RequestCheckpoint(), RowExclusiveLock, ScanKeyInit(), systable_inplace_update_begin(), systable_inplace_update_finish(), table_close(), table_open(), TerminateOtherDBBackends(), WaitForProcSignalBarrier(), XactLastRecEnd, and XLogFlush().

Referenced by DropDatabase().

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )
extern

Definition at line 3001 of file dbcommands.c.

3002{
3003 bool result = false;
3005
3006 /* Superusers can always do everything */
3007 if (superuser())
3008 return true;
3009
3012 {
3015 }
3016 return result;
3017}
uint32 result
END_CATALOG_STRUCT typedef FormData_pg_authid * Form_pg_authid
Definition pg_authid.h:60
bool rolcreatedb
Definition pg_authid.h:40
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

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

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

◆ RenameDatabase()

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

Definition at line 1918 of file dbcommands.c.

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

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

Referenced by ExecRenameStmt().