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

2384{
2385 Relation rel;
2386 Oid dboid;
2387 HeapTuple tuple,
2388 newtuple;
2391 SysScanDesc scan;
2393 bool dbistemplate = false;
2394 bool dballowconnections = true;
2403
2404 /* Extract options from the statement node tree */
2405 foreach(option, stmt->options)
2406 {
2408
2409 if (strcmp(defel->defname, "is_template") == 0)
2410 {
2411 if (distemplate)
2414 }
2415 else if (strcmp(defel->defname, "allow_connections") == 0)
2416 {
2420 }
2421 else if (strcmp(defel->defname, "connection_limit") == 0)
2422 {
2423 if (dconnlimit)
2425 dconnlimit = defel;
2426 }
2427 else if (strcmp(defel->defname, "tablespace") == 0)
2428 {
2429 if (dtablespace)
2432 }
2433 else
2434 ereport(ERROR,
2436 errmsg("option \"%s\" not recognized", defel->defname),
2437 parser_errposition(pstate, defel->location)));
2438 }
2439
2440 if (dtablespace)
2441 {
2442 /*
2443 * While the SET TABLESPACE syntax doesn't allow any other options,
2444 * somebody could write "WITH TABLESPACE ...". Forbid any other
2445 * options from being specified in that case.
2446 */
2447 if (list_length(stmt->options) != 1)
2448 ereport(ERROR,
2450 errmsg("option \"%s\" cannot be specified with other options",
2451 dtablespace->defname),
2452 parser_errposition(pstate, dtablespace->location)));
2453 /* this case isn't allowed within a transaction block */
2454 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2456 return InvalidOid;
2457 }
2458
2459 if (distemplate && distemplate->arg)
2463 if (dconnlimit && dconnlimit->arg)
2464 {
2467 ereport(ERROR,
2469 errmsg("invalid connection limit: %d", dbconnlimit)));
2470 }
2471
2472 /*
2473 * Get the old tuple. We don't need a lock on the database per se,
2474 * because we're not going to do anything that would mess up incoming
2475 * connections.
2476 */
2481 CStringGetDatum(stmt->dbname));
2482 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2483 NULL, 1, &scankey);
2484 tuple = systable_getnext(scan);
2485 if (!HeapTupleIsValid(tuple))
2486 ereport(ERROR,
2488 errmsg("database \"%s\" does not exist", stmt->dbname)));
2490
2492 dboid = datform->oid;
2493
2495 {
2496 ereport(FATAL,
2498 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2499 errhint("Use DROP DATABASE to drop invalid databases."));
2500 }
2501
2504 stmt->dbname);
2505
2506 /*
2507 * In order to avoid getting locked out and having to go through
2508 * standalone mode, we refuse to disallow connections to the database
2509 * we're currently connected to. Lockout can still happen with concurrent
2510 * sessions but the likeliness of that is not high enough to worry about.
2511 */
2512 if (!dballowconnections && dboid == MyDatabaseId)
2513 ereport(ERROR,
2515 errmsg("cannot disallow connections for current database")));
2516
2517 /*
2518 * Build an updated tuple, perusing the information just obtained
2519 */
2520 if (distemplate)
2521 {
2524 }
2526 {
2529 }
2530 if (dconnlimit)
2531 {
2534 }
2535
2536 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2538 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2540
2542
2543 systable_endscan(scan);
2544
2545 /* Close pg_database, but keep lock till commit */
2546 table_close(rel, NoLock);
2547
2548 return dboid;
2549}
@ ACLCHECK_NOT_OWNER
Definition acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2654
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4108
bool database_is_invalid_form(Form_pg_database datform)
static void movedb(const char *dbname, const char *tblspcname)
int32 defGetInt32(DefElem *def)
Definition define.c:148
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
Oid MyDatabaseId
Definition globals.c:94
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
void LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:562
#define NoLock
Definition lockdefs.h:34
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
#define RowExclusiveLock
Definition lockdefs.h:38
Oid GetUserId(void)
Definition miscinit.c:470
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
@ OBJECT_DATABASE
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
#define DATCONNLIMIT_UNLIMITED
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
uint64_t Datum
Definition postgres.h:70
static Datum CStringGetDatum(const char *X)
Definition postgres.h:370
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
#define InvalidOid
unsigned int Oid
static int fb(int x)
#define RelationGetDescr(relation)
Definition rel.h:540
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
#define BTEqualStrategyNumber
Definition stratnum.h:31
ItemPointerData t_self
Definition htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition xact.c:3670

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char dbname,
Oid  newOwnerId 
)
extern

Definition at line 2679 of file dbcommands.c.

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

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)
extern

Definition at line 2556 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)
extern

Definition at line 2653 of file dbcommands.c.

2654{
2655 Oid datid = get_database_oid(stmt->dbname, false);
2656
2657 /*
2658 * Obtain a lock on the database and make sure it didn't go away in the
2659 * meantime.
2660 */
2662
2665 stmt->dbname);
2666
2667 AlterSetting(datid, InvalidOid, stmt->setstmt);
2668
2670
2671 return datid;
2672}
Oid get_database_oid(const char *dbname, bool missing_ok)
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1148
#define AccessShareLock
Definition lockdefs.h:36
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
void shdepLockAndCheckObject(Oid classId, Oid objectId)

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

Referenced by standard_ProcessUtility().

◆ check_encoding_locale_matches()

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

Definition at line 1605 of file dbcommands.c.

1606{
1608 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1609
1610 if (!(ctype_encoding == encoding ||
1612 ctype_encoding == -1 ||
1613#ifdef WIN32
1614 encoding == PG_UTF8 ||
1615#endif
1616 (encoding == PG_SQL_ASCII && superuser())))
1617 ereport(ERROR,
1619 errmsg("encoding \"%s\" does not match locale \"%s\"",
1621 ctype),
1622 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1624
1625 if (!(collate_encoding == encoding ||
1627 collate_encoding == -1 ||
1628#ifdef WIN32
1629 encoding == PG_UTF8 ||
1630#endif
1631 (encoding == PG_SQL_ASCII && superuser())))
1632 ereport(ERROR,
1634 errmsg("encoding \"%s\" does not match locale \"%s\"",
1636 collate),
1637 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1639}
int errdetail(const char *fmt,...) pg_attribute_printf(1
static char * encoding
Definition initdb.c:139
#define PG_UTF8
Definition mbprint.c:43
@ PG_SQL_ASCII
Definition pg_wchar.h:226
#define pg_encoding_to_char
Definition pg_wchar.h:630
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition chklocale.c:301
bool superuser(void)
Definition superuser.c:47

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

Referenced by createdb(), and DefineCollation().

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

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

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)
extern

Definition at line 2357 of file dbcommands.c.

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

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

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

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

2995{
2996 bool result = false;
2998
2999 /* Superusers can always do everything */
3000 if (superuser())
3001 return true;
3002
3005 {
3008 }
3009 return result;
3010}
END_CATALOG_STRUCT typedef FormData_pg_authid * Form_pg_authid
Definition pg_authid.h:60
bool rolcreatedb
Definition pg_authid.h:40
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220

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

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

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

Referenced by ExecRenameStmt().