PostgreSQL Source Code git master
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)
 
Oid get_database_oid (const char *dbname, bool missing_ok)
 
char * get_database_name (Oid dbid)
 
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 
)

Definition at line 2342 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseOwner()

ObjectAddress AlterDatabaseOwner ( const char *  dbname,
Oid  newOwnerId 
)

Definition at line 2638 of file dbcommands.c.

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

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

Referenced by ExecAlterOwnerStmt().

◆ AlterDatabaseRefreshColl()

ObjectAddress AlterDatabaseRefreshColl ( AlterDatabaseRefreshCollStmt stmt)

Definition at line 2515 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ AlterDatabaseSet()

Oid AlterDatabaseSet ( AlterDatabaseSetStmt stmt)

Definition at line 2612 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ check_encoding_locale_matches()

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

Definition at line 1571 of file dbcommands.c.

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

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

Referenced by createdb(), and DefineCollation().

◆ createdb()

Oid createdb ( ParseState pstate,
const CreatedbStmt stmt 
)

Definition at line 684 of file dbcommands.c.

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

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

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

◆ DropDatabase()

void DropDatabase ( ParseState pstate,
DropdbStmt stmt 
)

Definition at line 2317 of file dbcommands.c.

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

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

Referenced by standard_ProcessUtility().

◆ dropdb()

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

Definition at line 1648 of file dbcommands.c.

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

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

Referenced by DropDatabase().

◆ get_database_name()

char * get_database_name ( Oid  dbid)

Definition at line 3188 of file dbcommands.c.

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

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

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

◆ get_database_oid()

Oid get_database_oid ( const char *  dbname,
bool  missing_ok 
)

Definition at line 3141 of file dbcommands.c.

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

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

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

◆ have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2953 of file dbcommands.c.

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

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

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

◆ RenameDatabase()

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

Definition at line 1877 of file dbcommands.c.

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

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

Referenced by ExecRenameStmt().