PostgreSQL Source Code git master
Functions
dbcommands.h File Reference
#include "catalog/objectaddress.h"
#include "parser/parse_node.h"
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)
 
 
ObjectAddress  RenameDatabase (const char *oldname, const char *newname)
 
Oid  AlterDatabase (ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
 
 
 
ObjectAddress  AlterDatabaseOwner (const char *dbname, Oid newOwnerId)
 
 
void  check_encoding_locale_matches (int encoding, const char *collate, const char *ctype)
 

Function Documentation

AlterDatabase()

Oid AlterDatabase ( ParseStatepstate,
AlterDatabaseStmtstmt,
bool  isTopLevel 
)

Definition at line 2368 of file dbcommands.c.

2369{
2370 Relation rel;
2371 Oid dboid;
2372 HeapTuple tuple,
2373 newtuple;
2374 Form_pg_database datform;
2375 ScanKeyData scankey;
2376 SysScanDesc scan;
2378 bool dbistemplate = false;
2379 bool dballowconnections = true;
2380 int dbconnlimit = DATCONNLIMIT_UNLIMITED;
2381 DefElem *distemplate = NULL;
2382 DefElem *dallowconnections = NULL;
2383 DefElem *dconnlimit = NULL;
2384 DefElem *dtablespace = NULL;
2385 Datum new_record[Natts_pg_database] = {0};
2386 bool new_record_nulls[Natts_pg_database] = {0};
2387 bool new_record_repl[Natts_pg_database] = {0};
2388
2389 /* Extract options from the statement node tree */
2390 foreach(option, stmt->options)
2391 {
2392 DefElem *defel = (DefElem *) lfirst(option);
2393
2394 if (strcmp(defel->defname, "is_template") == 0)
2395 {
2396 if (distemplate)
2397 errorConflictingDefElem(defel, pstate);
2398 distemplate = defel;
2399 }
2400 else if (strcmp(defel->defname, "allow_connections") == 0)
2401 {
2402 if (dallowconnections)
2403 errorConflictingDefElem(defel, pstate);
2404 dallowconnections = defel;
2405 }
2406 else if (strcmp(defel->defname, "connection_limit") == 0)
2407 {
2408 if (dconnlimit)
2409 errorConflictingDefElem(defel, pstate);
2410 dconnlimit = defel;
2411 }
2412 else if (strcmp(defel->defname, "tablespace") == 0)
2413 {
2414 if (dtablespace)
2415 errorConflictingDefElem(defel, pstate);
2416 dtablespace = defel;
2417 }
2418 else
2419 ereport(ERROR,
2420 (errcode(ERRCODE_SYNTAX_ERROR),
2421 errmsg("option \"%s\" not recognized", defel->defname),
2422 parser_errposition(pstate, defel->location)));
2423 }
2424
2425 if (dtablespace)
2426 {
2427 /*
2428 * While the SET TABLESPACE syntax doesn't allow any other options,
2429 * somebody could write "WITH TABLESPACE ...". Forbid any other
2430 * options from being specified in that case.
2431 */
2432 if (list_length(stmt->options) != 1)
2433 ereport(ERROR,
2434 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2435 errmsg("option \"%s\" cannot be specified with other options",
2436 dtablespace->defname),
2437 parser_errposition(pstate, dtablespace->location)));
2438 /* this case isn't allowed within a transaction block */
2439 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2440 movedb(stmt->dbname, defGetString(dtablespace));
2441 return InvalidOid;
2442 }
2443
2444 if (distemplate && distemplate->arg)
2445 dbistemplate = defGetBoolean(distemplate);
2446 if (dallowconnections && dallowconnections->arg)
2447 dballowconnections = defGetBoolean(dallowconnections);
2448 if (dconnlimit && dconnlimit->arg)
2449 {
2450 dbconnlimit = defGetInt32(dconnlimit);
2451 if (dbconnlimit < DATCONNLIMIT_UNLIMITED)
2452 ereport(ERROR,
2453 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2454 errmsg("invalid connection limit: %d", dbconnlimit)));
2455 }
2456
2457 /*
2458 * Get the old tuple. We don't need a lock on the database per se,
2459 * because we're not going to do anything that would mess up incoming
2460 * connections.
2461 */
2462 rel = table_open(DatabaseRelationId, RowExclusiveLock);
2463 ScanKeyInit(&scankey,
2464 Anum_pg_database_datname,
2465 BTEqualStrategyNumber, F_NAMEEQ,
2466 CStringGetDatum(stmt->dbname));
2467 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2468 NULL, 1, &scankey);
2469 tuple = systable_getnext(scan);
2470 if (!HeapTupleIsValid(tuple))
2471 ereport(ERROR,
2472 (errcode(ERRCODE_UNDEFINED_DATABASE),
2473 errmsg("database \"%s\" does not exist", stmt->dbname)));
2475
2476 datform = (Form_pg_database) GETSTRUCT(tuple);
2477 dboid = datform->oid;
2478
2479 if (database_is_invalid_form(datform))
2480 {
2481 ereport(FATAL,
2482 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2483 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2484 errhint("Use DROP DATABASE to drop invalid databases."));
2485 }
2486
2487 if (!object_ownercheck(DatabaseRelationId, dboid, GetUserId()))
2489 stmt->dbname);
2490
2491 /*
2492 * In order to avoid getting locked out and having to go through
2493 * standalone mode, we refuse to disallow connections to the database
2494 * we're currently connected to. Lockout can still happen with concurrent
2495 * sessions but the likeliness of that is not high enough to worry about.
2496 */
2497 if (!dballowconnections && dboid == MyDatabaseId)
2498 ereport(ERROR,
2499 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2500 errmsg("cannot disallow connections for current database")));
2501
2502 /*
2503 * Build an updated tuple, perusing the information just obtained
2504 */
2505 if (distemplate)
2506 {
2507 new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2508 new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2509 }
2510 if (dallowconnections)
2511 {
2512 new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2513 new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2514 }
2515 if (dconnlimit)
2516 {
2517 new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2518 new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2519 }
2520
2521 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2522 new_record_nulls, new_record_repl);
2523 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2525
2526 InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2527
2528 systable_endscan(scan);
2529
2530 /* Close pg_database, but keep lock till commit */
2531 table_close(rel, NoLock);
2532
2533 return dboid;
2534}
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2652
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4088
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3214
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:2004
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:1321
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#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)
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 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:469
#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:2334
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
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:360
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define InvalidOid
Definition: postgres_ext.h:37
unsigned int Oid
Definition: postgres_ext.h:32
#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
char * defname
Definition: parsenodes.h:843
ParseLoc location
Definition: parsenodes.h:847
Node * arg
Definition: parsenodes.h:844
ItemPointerData t_self
Definition: htup.h:65
Definition: rel.h:56
Definition: skey.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
Definition: pg_list.h:46
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3660

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

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

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 ( AlterDatabaseRefreshCollStmtstmt )

Definition at line 2541 of file dbcommands.c.

2542{
2543 Relation rel;
2544 ScanKeyData scankey;
2545 SysScanDesc scan;
2546 Oid db_id;
2547 HeapTuple tuple;
2548 Form_pg_database datForm;
2549 ObjectAddress address;
2550 Datum datum;
2551 bool isnull;
2552 char *oldversion;
2553 char *newversion;
2554
2555 rel = table_open(DatabaseRelationId, RowExclusiveLock);
2556 ScanKeyInit(&scankey,
2557 Anum_pg_database_datname,
2558 BTEqualStrategyNumber, F_NAMEEQ,
2559 CStringGetDatum(stmt->dbname));
2560 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2561 NULL, 1, &scankey);
2562 tuple = systable_getnext(scan);
2563 if (!HeapTupleIsValid(tuple))
2564 ereport(ERROR,
2565 (errcode(ERRCODE_UNDEFINED_DATABASE),
2566 errmsg("database \"%s\" does not exist", stmt->dbname)));
2567
2568 datForm = (Form_pg_database) GETSTRUCT(tuple);
2569 db_id = datForm->oid;
2570
2571 if (!object_ownercheck(DatabaseRelationId, db_id, GetUserId()))
2573 stmt->dbname);
2575
2576 datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2577 oldversion = isnull ? NULL : TextDatumGetCString(datum);
2578
2579 if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2580 {
2581 datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2582 if (isnull)
2583 elog(ERROR, "unexpected null in pg_database");
2584 }
2585 else
2586 {
2587 datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2588 if (isnull)
2589 elog(ERROR, "unexpected null in pg_database");
2590 }
2591
2592 newversion = get_collation_actual_version(datForm->datlocprovider,
2593 TextDatumGetCString(datum));
2594
2595 /* cannot change from NULL to non-NULL or vice versa */
2596 if ((!oldversion && newversion) || (oldversion && !newversion))
2597 elog(ERROR, "invalid collation version change");
2598 else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2599 {
2600 bool nulls[Natts_pg_database] = {0};
2601 bool replaces[Natts_pg_database] = {0};
2602 Datum values[Natts_pg_database] = {0};
2603 HeapTuple newtuple;
2604
2606 (errmsg("changing version from %s to %s",
2607 oldversion, newversion)));
2608
2609 values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2610 replaces[Anum_pg_database_datcollversion - 1] = true;
2611
2612 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2613 values, nulls, replaces);
2614 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2615 heap_freetuple(newtuple);
2616 }
2617 else
2619 (errmsg("version has not changed")));
2621
2622 InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2623
2624 ObjectAddressSet(address, DatabaseRelationId, db_id);
2625
2626 systable_endscan(scan);
2627
2628 table_close(rel, NoLock);
2629
2630 return address;
2631}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:98
#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:1217

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 ( AlterDatabaseSetStmtstmt )

Definition at line 2638 of file dbcommands.c.

2639{
2640 Oid datid = get_database_oid(stmt->dbname, false);
2641
2642 /*
2643 * Obtain a lock on the database and make sure it didn't go away in the
2644 * meantime.
2645 */
2646 shdepLockAndCheckObject(DatabaseRelationId, datid);
2647
2648 if (!object_ownercheck(DatabaseRelationId, datid, GetUserId()))
2650 stmt->dbname);
2651
2652 AlterSetting(datid, InvalidOid, stmt->setstmt);
2653
2654 UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2655
2656 return datid;
2657}
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:3167
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)
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 1597 of file dbcommands.c.

1598{
1599 int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1600 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1601
1602 if (!(ctype_encoding == encoding ||
1603 ctype_encoding == PG_SQL_ASCII ||
1604 ctype_encoding == -1 ||
1605#ifdef WIN32
1606 encoding == PG_UTF8 ||
1607#endif
1608 (encoding == PG_SQL_ASCII && superuser())))
1609 ereport(ERROR,
1610 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1611 errmsg("encoding \"%s\" does not match locale \"%s\"",
1613 ctype),
1614 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1615 pg_encoding_to_char(ctype_encoding))));
1616
1617 if (!(collate_encoding == encoding ||
1618 collate_encoding == PG_SQL_ASCII ||
1619 collate_encoding == -1 ||
1620#ifdef WIN32
1621 encoding == PG_UTF8 ||
1622#endif
1623 (encoding == PG_SQL_ASCII && superuser())))
1624 ereport(ERROR,
1625 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1626 errmsg("encoding \"%s\" does not match locale \"%s\"",
1628 collate),
1629 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1630 pg_encoding_to_char(collate_encoding))));
1631}
int errdetail(const char *fmt,...)
Definition: elog.c:1207
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 ( ParseStatepstate,
const CreatedbStmtstmt 
)

Definition at line 685 of file dbcommands.c.

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

Definition at line 2343 of file dbcommands.c.

2344{
2345 bool force = false;
2346 ListCell *lc;
2347
2348 foreach(lc, stmt->options)
2349 {
2350 DefElem *opt = (DefElem *) lfirst(lc);
2351
2352 if (strcmp(opt->defname, "force") == 0)
2353 force = true;
2354 else
2355 ereport(ERROR,
2356 (errcode(ERRCODE_SYNTAX_ERROR),
2357 errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2358 parser_errposition(pstate, opt->location)));
2359 }
2360
2361 dropdb(stmt->dbname, stmt->missing_ok, force);
2362}
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1674

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

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

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, 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().

have_createdb_privilege()

bool have_createdb_privilege ( void  )

Definition at line 2979 of file dbcommands.c.

2980{
2981 bool result = false;
2982 HeapTuple utup;
2983
2984 /* Superusers can always do everything */
2985 if (superuser())
2986 return true;
2987
2988 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(GetUserId()));
2989 if (HeapTupleIsValid(utup))
2990 {
2991 result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2992 ReleaseSysCache(utup);
2993 }
2994 return result;
2995}
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:220

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

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

AltStyle によって変換されたページ (->オリジナル) /