PostgreSQL Source Code git master
Loading...
Searching...
No Matches
dbcommands.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * dbcommands.c
4 * Database management commands (create/drop database).
5 *
6 * Note: database creation/destruction commands use exclusive locks on
7 * the database objects (as expressed by LockSharedObject()) to avoid
8 * stepping on each others' toes. Formerly we used table-level locks
9 * on pg_database, but that's too coarse-grained.
10 *
11 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
13 *
14 *
15 * IDENTIFICATION
16 * src/backend/commands/dbcommands.c
17 *
18 *-------------------------------------------------------------------------
19 */
20#include "postgres.h"
21
22#include <fcntl.h>
23#include <unistd.h>
24#include <sys/stat.h>
25
26#include "access/genam.h"
27#include "access/heapam.h"
28#include "access/htup_details.h"
29#include "access/multixact.h"
30#include "access/tableam.h"
31#include "access/xact.h"
32#include "access/xloginsert.h"
33#include "access/xlogrecovery.h"
34#include "access/xlogutils.h"
35#include "catalog/catalog.h"
36#include "catalog/dependency.h"
37#include "catalog/indexing.h"
39#include "catalog/pg_authid.h"
41#include "catalog/pg_database.h"
45#include "commands/comment.h"
46#include "commands/dbcommands.h"
48#include "commands/defrem.h"
49#include "commands/seclabel.h"
50#include "commands/tablespace.h"
51#include "common/file_perm.h"
52#include "mb/pg_wchar.h"
53#include "miscadmin.h"
54#include "pgstat.h"
55#include "postmaster/bgwriter.h"
56#include "replication/slot.h"
57#include "storage/copydir.h"
58#include "storage/fd.h"
59#include "storage/ipc.h"
60#include "storage/lmgr.h"
61#include "storage/md.h"
62#include "storage/procarray.h"
63#include "storage/procsignal.h"
64#include "storage/smgr.h"
65#include "utils/acl.h"
66#include "utils/builtins.h"
67#include "utils/fmgroids.h"
68#include "utils/lsyscache.h"
69#include "utils/pg_locale.h"
70#include "utils/relmapper.h"
71#include "utils/snapmgr.h"
72#include "utils/syscache.h"
73
74/*
75 * Create database strategy.
76 *
77 * CREATEDB_WAL_LOG will copy the database at the block level and WAL log each
78 * copied block.
79 *
80 * CREATEDB_FILE_COPY will simply perform a file system level copy of the
81 * database and log a single record for each tablespace copied. To make this
82 * safe, it also triggers checkpoints before and after the operation.
83 */
89
90typedef struct
91{
92 Oid src_dboid; /* source (template) DB */
93 Oid dest_dboid; /* DB we are trying to create */
94 CreateDBStrategy strategy; /* create db strategy */
96
97typedef struct
98{
99 Oid dest_dboid; /* DB we are trying to move */
100 Oid dest_tsoid; /* tablespace we are trying to move to */
102
103/*
104 * Information about a relation to be copied when creating a database.
105 */
106typedef struct CreateDBRelInfo
107{
108 RelFileLocator rlocator; /* physical relation identifier */
109 Oid reloid; /* relation oid */
110 bool permanent; /* relation is permanent or unlogged */
112
113
114/* non-export function prototypes */
115static void createdb_failure_callback(int code, Datum arg);
116static void movedb(const char *dbname, const char *tblspcname);
117static void movedb_failure_callback(int code, Datum arg);
118static bool get_db_info(const char *name, LOCKMODE lockmode,
120 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, bool *dbHasLoginEvtP,
122 Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbLocale,
123 char **dbIcurules,
124 char *dbLocProvider,
125 char **dbCollversion);
126static void remove_dbtablespaces(Oid db_id);
127static bool check_db_file_conflict(Oid db_id);
129static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, Oid src_tsid,
130 Oid dst_tsid);
131static List *ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath);
133 Oid dbid, char *srcpath,
134 List *rlocatorlist, Snapshot snapshot);
136 Oid tbid, Oid dbid,
137 char *srcpath);
138static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid,
139 bool isRedo);
140static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid,
142static void recovery_create_dbdir(char *path, bool only_tblspc);
143
144/*
145 * Create a new database using the WAL_LOG strategy.
146 *
147 * Each copied block is separately written to the write-ahead log.
148 */
149static void
152{
153 char *srcpath;
154 char *dstpath;
156 ListCell *cell;
162
163 /* Get source and destination database paths. */
164 srcpath = GetDatabasePath(src_dboid, src_tsid);
166
167 /* Create database directory and write PG_VERSION file. */
169
170 /* Copy relmap file from source database to the destination database. */
172
173 /* Get list of relfilelocators to copy from the source database. */
176
177 /*
178 * Database IDs will be the same for all relations so set them before
179 * entering the loop.
180 */
181 srcrelid.dbId = src_dboid;
182 dstrelid.dbId = dst_dboid;
183
184 /* Loop over our list of relfilelocators and copy each one. */
185 foreach(cell, rlocatorlist)
186 {
187 relinfo = lfirst(cell);
188 srcrlocator = relinfo->rlocator;
189
190 /*
191 * If the relation is from the source db's default tablespace then we
192 * need to create it in the destination db's default tablespace.
193 * Otherwise, we need to create in the same tablespace as it is in the
194 * source database.
195 */
196 if (srcrlocator.spcOid == src_tsid)
197 dstrlocator.spcOid = dst_tsid;
198 else
199 dstrlocator.spcOid = srcrlocator.spcOid;
200
201 dstrlocator.dbOid = dst_dboid;
202 dstrlocator.relNumber = srcrlocator.relNumber;
203
204 /*
205 * Acquire locks on source and target relations before copying.
206 *
207 * We typically do not read relation data into shared_buffers without
208 * holding a relation lock. It's unclear what could go wrong if we
209 * skipped it in this case, because nobody can be modifying either the
210 * source or destination database at this point, and we have locks on
211 * both databases, too, but let's take the conservative route.
212 */
213 dstrelid.relId = srcrelid.relId = relinfo->reloid;
216
217 /* Copy relation storage from source to the destination. */
219
220 /* Release the relation locks. */
223 }
224
225 pfree(srcpath);
226 pfree(dstpath);
228}
229
230/*
231 * Scan the pg_class table in the source database to identify the relations
232 * that need to be copied to the destination database.
233 *
234 * This is an exception to the usual rule that cross-database access is
235 * not possible. We can make it work here because we know that there are no
236 * connections to the source database and (since there can't be prepared
237 * transactions touching that database) no in-doubt tuples either. This
238 * means that we don't need to worry about pruning removing anything from
239 * under us, and we don't need to be too picky about our snapshot either.
240 * As long as it sees all previously-committed XIDs as committed and all
241 * aborted XIDs as aborted, we should be fine: nothing else is possible
242 * here.
243 *
244 * We can't rely on the relcache for anything here, because that only knows
245 * about the database to which we are connected, and can't handle access to
246 * other databases. That also means we can't rely on the heap scan
247 * infrastructure, which would be a bad idea anyway since it might try
248 * to do things like HOT pruning which we definitely can't do safely in
249 * a database to which we're not even connected.
250 */
251static List *
253{
254 RelFileLocator rlocator;
255 BlockNumber nblocks;
256 BlockNumber blkno;
257 Buffer buf;
258 RelFileNumber relfilenumber;
259 Page page;
261 LockRelId relid;
262 Snapshot snapshot;
263 SMgrRelation smgr;
264 BufferAccessStrategy bstrategy;
265
266 /* Get pg_class relfilenumber. */
269
270 /* Don't read data into shared_buffers without holding a relation lock. */
271 relid.dbId = dbid;
274
275 /* Prepare a RelFileLocator for the pg_class relation. */
276 rlocator.spcOid = tbid;
277 rlocator.dbOid = dbid;
278 rlocator.relNumber = relfilenumber;
279
280 smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
281 nblocks = smgrnblocks(smgr, MAIN_FORKNUM);
282 smgrclose(smgr);
283
284 /* Use a buffer access strategy since this is a bulk read operation. */
285 bstrategy = GetAccessStrategy(BAS_BULKREAD);
286
287 /*
288 * As explained in the function header comments, we need a snapshot that
289 * will see all committed transactions as committed, and our transaction
290 * snapshot - or the active snapshot - might not be new enough for that,
291 * but the return value of GetLatestSnapshot() should work fine.
292 */
294
295 /* Process the relation block by block. */
296 for (blkno = 0; blkno < nblocks; blkno++)
297 {
299
300 buf = ReadBufferWithoutRelcache(rlocator, MAIN_FORKNUM, blkno,
301 RBM_NORMAL, bstrategy, true);
302
304 page = BufferGetPage(buf);
305 if (PageIsNew(page) || PageIsEmpty(page))
306 {
308 continue;
309 }
310
311 /* Append relevant pg_class tuples for current page to rlocatorlist. */
314 snapshot);
315
317 }
318 UnregisterSnapshot(snapshot);
319
320 /* Release relation lock. */
322
323 return rlocatorlist;
324}
325
326/*
327 * Scan one page of the source database's pg_class relation and add relevant
328 * entries to rlocatorlist. The return value is the updated list.
329 */
330static List *
332 char *srcpath, List *rlocatorlist,
333 Snapshot snapshot)
334{
336 OffsetNumber offnum;
337 OffsetNumber maxoff;
338 HeapTupleData tuple;
339
340 maxoff = PageGetMaxOffsetNumber(page);
341
342 /* Loop over offsets. */
343 for (offnum = FirstOffsetNumber;
344 offnum <= maxoff;
345 offnum = OffsetNumberNext(offnum))
346 {
347 ItemId itemid;
348
349 itemid = PageGetItemId(page, offnum);
350
351 /* Nothing to do if slot is empty or already dead. */
352 if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
353 ItemIdIsRedirected(itemid))
354 continue;
355
356 Assert(ItemIdIsNormal(itemid));
357 ItemPointerSet(&(tuple.t_self), blkno, offnum);
358
359 /* Initialize a HeapTupleData structure. */
360 tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
361 tuple.t_len = ItemIdGetLength(itemid);
363
364 /* Skip tuples that are not visible to this snapshot. */
365 if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
366 {
368
369 /*
370 * ScanSourceDatabasePgClassTuple is in charge of constructing a
371 * CreateDBRelInfo object for this tuple, but can also decide that
372 * this tuple isn't something we need to copy. If we do need to
373 * copy the relation, add it to the list.
374 */
376 srcpath);
377 if (relinfo != NULL)
379 }
380 }
381
382 return rlocatorlist;
383}
384
385/*
386 * Decide whether a certain pg_class tuple represents something that
387 * needs to be copied from the source database to the destination database,
388 * and if so, construct a CreateDBRelInfo for it.
389 *
390 * Visibility checks are handled by the caller, so our job here is just
391 * to assess the data stored in the tuple.
392 */
395 char *srcpath)
396{
399 RelFileNumber relfilenumber = InvalidRelFileNumber;
400
402
403 /*
404 * Return NULL if this object does not need to be copied.
405 *
406 * Shared objects don't need to be copied, because they are shared.
407 * Objects without storage can't be copied, because there's nothing to
408 * copy. Temporary relations don't need to be copied either, because they
409 * are inaccessible outside of the session that created them, which must
410 * be gone already, and couldn't connect to a different database if it
411 * still existed. autovacuum will eventually remove the pg_class entries
412 * as well.
413 */
414 if (classForm->reltablespace == GLOBALTABLESPACE_OID ||
415 !RELKIND_HAS_STORAGE(classForm->relkind) ||
416 classForm->relpersistence == RELPERSISTENCE_TEMP)
417 return NULL;
418
419 /*
420 * If relfilenumber is valid then directly use it. Otherwise, consult the
421 * relmap.
422 */
423 if (RelFileNumberIsValid(classForm->relfilenode))
424 relfilenumber = classForm->relfilenode;
425 else
427 classForm->oid);
428
429 /* We must have a valid relfilenumber. */
430 if (!RelFileNumberIsValid(relfilenumber))
431 elog(ERROR, "relation with OID %u does not have a valid relfilenumber",
432 classForm->oid);
433
434 /* Prepare a rel info element and add it to the list. */
436 if (OidIsValid(classForm->reltablespace))
437 relinfo->rlocator.spcOid = classForm->reltablespace;
438 else
439 relinfo->rlocator.spcOid = tbid;
440
441 relinfo->rlocator.dbOid = dbid;
442 relinfo->rlocator.relNumber = relfilenumber;
443 relinfo->reloid = classForm->oid;
444
445 /* Temporary relations were rejected above. */
446 Assert(classForm->relpersistence != RELPERSISTENCE_TEMP);
447 relinfo->permanent =
448 (classForm->relpersistence == RELPERSISTENCE_PERMANENT) ? true : false;
449
450 return relinfo;
451}
452
453/*
454 * Create database directory and write out the PG_VERSION file in the database
455 * path. If isRedo is true, it's okay for the database directory to exist
456 * already.
457 */
458static void
460{
461 int fd;
462 int nbytes;
464 char buf[16];
465
466 /*
467 * Note that we don't have to copy version data from the source database;
468 * there's only one legal value.
469 */
470 sprintf(buf, "%s\n", PG_MAJORVERSION);
471 nbytes = strlen(PG_MAJORVERSION) + 1;
472
473 /* Create database directory. */
474 if (MakePGDirectory(dbpath) < 0)
475 {
476 /* Failure other than already exists or not in WAL replay? */
477 if (errno != EEXIST || !isRedo)
480 errmsg("could not create directory \"%s\": %m", dbpath)));
481 }
482
483 /*
484 * Create PG_VERSION file in the database path. If the file already
485 * exists and we are in WAL replay then try again to open it in write
486 * mode.
487 */
488 snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
489
491 if (fd < 0 && errno == EEXIST && isRedo)
493
494 if (fd < 0)
497 errmsg("could not create file \"%s\": %m", versionfile)));
498
499 /* Write PG_MAJORVERSION in the PG_VERSION file. */
501 errno = 0;
502 if ((int) write(fd, buf, nbytes) != nbytes)
503 {
504 /* If write didn't set errno, assume problem is no disk space. */
505 if (errno == 0)
506 errno = ENOSPC;
509 errmsg("could not write to file \"%s\": %m", versionfile)));
510 }
512
514 if (pg_fsync(fd) != 0)
517 errmsg("could not fsync file \"%s\": %m", versionfile)));
518 fsync_fname(dbpath, true);
520
521 /* Close the version file. */
523
524 /* If we are not in WAL replay then write the WAL. */
525 if (!isRedo)
526 {
528
530
531 xlrec.db_id = dbid;
532 xlrec.tablespace_id = tsid;
533
537
539
541 }
542}
543
544/*
545 * Create a new database using the FILE_COPY strategy.
546 *
547 * Copy each tablespace at the filesystem level, and log a single WAL record
548 * for each tablespace copied. This requires a checkpoint before and after the
549 * copy, which may be expensive, but it does greatly reduce WAL generation
550 * if the copied database is large.
551 */
552static void
555{
556 TableScanDesc scan;
557 Relation rel;
558 HeapTuple tuple;
559
560 /*
561 * Force a checkpoint before starting the copy. This will force all dirty
562 * buffers, including those of unlogged tables, out to disk, to ensure
563 * source database is up-to-date on disk for the copy.
564 * FlushDatabaseBuffers() would suffice for that, but we also want to
565 * process any pending unlink requests. Otherwise, if a checkpoint
566 * happened while we're copying files, a file might be deleted just when
567 * we're about to copy it, causing the lstat() call in copydir() to fail
568 * with ENOENT.
569 *
570 * In binary upgrade mode, we can skip this checkpoint because pg_upgrade
571 * is careful to ensure that template0 is fully written to disk prior to
572 * any CREATE DATABASE commands.
573 */
574 if (!IsBinaryUpgrade)
577
578 /*
579 * Iterate through all tablespaces of the template database, and copy each
580 * one to the new database.
581 */
583 scan = table_beginscan_catalog(rel, 0, NULL);
584 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
585 {
589 char *srcpath;
590 char *dstpath;
591 struct stat st;
592
593 /* No need to copy global tablespace */
595 continue;
596
598
599 if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
601 {
602 /* Assume we can ignore it */
603 pfree(srcpath);
604 continue;
605 }
606
607 if (srctablespace == src_tsid)
609 else
611
613
614 /*
615 * Copy this subdirectory to the new location
616 *
617 * We don't need to copy subdirectories
618 */
619 copydir(srcpath, dstpath, false);
620
621 /* Record the filesystem change in XLOG */
622 {
624
626 xlrec.tablespace_id = dsttablespace;
627 xlrec.src_db_id = src_dboid;
628 xlrec.src_tablespace_id = srctablespace;
629
633
636 }
637 pfree(srcpath);
638 pfree(dstpath);
639 }
640 table_endscan(scan);
642
643 /*
644 * We force a checkpoint before committing. This effectively means that
645 * committed XLOG_DBASE_CREATE_FILE_COPY operations will never need to be
646 * replayed (at least not in ordinary crash recovery; we still have to
647 * make the XLOG entry for the benefit of PITR operations). This avoids
648 * two nasty scenarios:
649 *
650 * #1: At wal_level=minimal, we don't XLOG the contents of newly created
651 * relfilenodes; therefore the drop-and-recreate-whole-directory behavior
652 * of DBASE_CREATE replay would lose such files created in the new
653 * database between our commit and the next checkpoint.
654 *
655 * #2: Since we have to recopy the source database during DBASE_CREATE
656 * replay, we run the risk of copying changes in it that were committed
657 * after the original CREATE DATABASE command but before the system crash
658 * that led to the replay. This is at least unexpected and at worst could
659 * lead to inconsistencies, eg duplicate table names.
660 *
661 * (Both of these were real bugs in releases 8.0 through 8.0.3.)
662 *
663 * In PITR replay, the first of these isn't an issue, and the second is
664 * only a risk if the CREATE DATABASE and subsequent template database
665 * change both occur while a base backup is being taken. There doesn't
666 * seem to be much we can do about that except document it as a
667 * limitation.
668 *
669 * In binary upgrade mode, we can skip this checkpoint because neither of
670 * these problems applies: we don't ever replay the WAL generated during
671 * pg_upgrade, and we don't support taking base backups during pg_upgrade
672 * (not to mention that we don't concurrently modify template0, either).
673 *
674 * See CreateDatabaseUsingWalLog() for a less cheesy CREATE DATABASE
675 * strategy that avoids these problems.
676 */
677 if (!IsBinaryUpgrade)
680}
681
682/*
683 * CREATE DATABASE
684 */
685Oid
687{
688 Oid src_dboid;
690 int src_encoding = -1;
691 char *src_collate = NULL;
692 char *src_ctype = NULL;
693 char *src_locale = NULL;
694 char *src_icurules = NULL;
695 char src_locprovider = '\0';
696 char *src_collversion = NULL;
697 bool src_istemplate;
698 bool src_hasloginevt = false;
699 bool src_allowconn;
703 volatile Oid dst_deftablespace;
705 HeapTuple tuple;
708 Oid dboid = InvalidOid;
709 Oid datdba;
727 char *dbname = stmt->dbname;
728 char *dbowner = NULL;
729 const char *dbtemplate = NULL;
730 char *dbcollate = NULL;
731 char *dbctype = NULL;
732 const char *dblocale = NULL;
733 char *dbicurules = NULL;
734 char dblocprovider = '\0';
735 char *canonname;
736 int encoding = -1;
737 bool dbistemplate = false;
738 bool dballowconnections = true;
740 char *dbcollversion = NULL;
741 int notherbackends;
742 int npreparedxacts;
745
746 /* Report error if name has \n or \r character. */
747 if (strpbrk(dbname, "\n\r"))
750 errmsg("database name \"%s\" contains a newline or carriage return character", dbname)));
751
752 /* Extract options from the statement node tree */
753 foreach(option, stmt->options)
754 {
756
757 if (strcmp(defel->defname, "tablespace") == 0)
758 {
762 }
763 else if (strcmp(defel->defname, "owner") == 0)
764 {
765 if (ownerEl)
767 ownerEl = defel;
768 }
769 else if (strcmp(defel->defname, "template") == 0)
770 {
771 if (templateEl)
774 }
775 else if (strcmp(defel->defname, "encoding") == 0)
776 {
777 if (encodingEl)
780 }
781 else if (strcmp(defel->defname, "locale") == 0)
782 {
783 if (localeEl)
785 localeEl = defel;
786 }
787 else if (strcmp(defel->defname, "builtin_locale") == 0)
788 {
789 if (builtinlocaleEl)
792 }
793 else if (strcmp(defel->defname, "lc_collate") == 0)
794 {
795 if (collateEl)
798 }
799 else if (strcmp(defel->defname, "lc_ctype") == 0)
800 {
801 if (ctypeEl)
803 ctypeEl = defel;
804 }
805 else if (strcmp(defel->defname, "icu_locale") == 0)
806 {
807 if (iculocaleEl)
810 }
811 else if (strcmp(defel->defname, "icu_rules") == 0)
812 {
813 if (icurulesEl)
816 }
817 else if (strcmp(defel->defname, "locale_provider") == 0)
818 {
819 if (locproviderEl)
822 }
823 else if (strcmp(defel->defname, "is_template") == 0)
824 {
825 if (istemplateEl)
828 }
829 else if (strcmp(defel->defname, "allow_connections") == 0)
830 {
834 }
835 else if (strcmp(defel->defname, "connection_limit") == 0)
836 {
837 if (connlimitEl)
840 }
841 else if (strcmp(defel->defname, "collation_version") == 0)
842 {
843 if (collversionEl)
846 }
847 else if (strcmp(defel->defname, "location") == 0)
848 {
851 errmsg("LOCATION is not supported anymore"),
852 errhint("Consider using tablespaces instead."),
853 parser_errposition(pstate, defel->location)));
854 }
855 else if (strcmp(defel->defname, "oid") == 0)
856 {
857 dboid = defGetObjectId(defel);
858
859 /*
860 * We don't normally permit new databases to be created with
861 * system-assigned OIDs. pg_upgrade tries to preserve database
862 * OIDs, so we can't allow any database to be created with an OID
863 * that might be in use in a freshly-initialized cluster created
864 * by some future version. We assume all such OIDs will be from
865 * the system-managed OID range.
866 *
867 * As an exception, however, we permit any OID to be assigned when
868 * allow_system_table_mods=on (so that initdb can assign system
869 * OIDs to template0 and postgres) or when performing a binary
870 * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
871 * in the source cluster).
872 */
873 if (dboid < FirstNormalObjectId &&
877 errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
878 }
879 else if (strcmp(defel->defname, "strategy") == 0)
880 {
881 if (strategyEl)
884 }
885 else
888 errmsg("option \"%s\" not recognized", defel->defname),
889 parser_errposition(pstate, defel->location)));
890 }
891
892 if (ownerEl && ownerEl->arg)
894 if (templateEl && templateEl->arg)
896 if (encodingEl && encodingEl->arg)
897 {
898 const char *encoding_name;
899
900 if (IsA(encodingEl->arg, Integer))
901 {
904 if (strcmp(encoding_name, "") == 0 ||
908 errmsg("%d is not a valid encoding code",
909 encoding),
910 parser_errposition(pstate, encodingEl->location)));
911 }
912 else
913 {
916 if (encoding < 0)
919 errmsg("%s is not a valid encoding name",
921 parser_errposition(pstate, encodingEl->location)));
922 }
923 }
924 if (localeEl && localeEl->arg)
925 {
929 }
932 if (collateEl && collateEl->arg)
934 if (ctypeEl && ctypeEl->arg)
936 if (iculocaleEl && iculocaleEl->arg)
938 if (icurulesEl && icurulesEl->arg)
940 if (locproviderEl && locproviderEl->arg)
941 {
943
944 if (pg_strcasecmp(locproviderstr, "builtin") == 0)
946 else if (pg_strcasecmp(locproviderstr, "icu") == 0)
948 else if (pg_strcasecmp(locproviderstr, "libc") == 0)
950 else
953 errmsg("unrecognized locale provider: %s",
955 }
956 if (istemplateEl && istemplateEl->arg)
960 if (connlimitEl && connlimitEl->arg)
961 {
966 errmsg("invalid connection limit: %d", dbconnlimit)));
967 }
968 if (collversionEl)
970
971 /* obtain OID of proposed owner */
972 if (dbowner)
973 datdba = get_role_oid(dbowner, false);
974 else
975 datdba = GetUserId();
976
977 /*
978 * To create a database, must have createdb privilege and must be able to
979 * become the target role (this does not imply that the target role itself
980 * must have createdb privilege). The latter provision guards against
981 * "giveaway" attacks. Note that a superuser will always have both of
982 * these privileges a fortiori.
983 */
987 errmsg("permission denied to create database")));
988
990
991 /*
992 * Lookup database (template) to be cloned, and obtain share lock on it.
993 * ShareLock allows two CREATE DATABASEs to work from the same template
994 * concurrently, while ensuring no one is busy dropping it in parallel
995 * (which would be Very Bad since we'd likely get an incomplete copy
996 * without knowing it). This also prevents any new connections from being
997 * made to the source until we finish copying it, so we can be sure it
998 * won't change underneath us.
999 */
1000 if (!dbtemplate)
1001 dbtemplate = "template1"; /* Default template database name */
1002
1004 &src_dboid, &src_owner, &src_encoding,
1009 ereport(ERROR,
1011 errmsg("template database \"%s\" does not exist",
1012 dbtemplate)));
1013
1014 /*
1015 * If the source database was in the process of being dropped, we can't
1016 * use it as a template.
1017 */
1018 if (database_is_invalid_oid(src_dboid))
1019 ereport(ERROR,
1021 errmsg("cannot use invalid database \"%s\" as template", dbtemplate),
1022 errhint("Use DROP DATABASE to drop invalid databases."));
1023
1024 /*
1025 * Permission check: to copy a DB that's not marked datistemplate, you
1026 * must be superuser or the owner thereof.
1027 */
1028 if (!src_istemplate)
1029 {
1031 ereport(ERROR,
1033 errmsg("permission denied to copy database \"%s\"",
1034 dbtemplate)));
1035 }
1036
1037 /* Validate the database creation strategy. */
1038 if (strategyEl && strategyEl->arg)
1039 {
1040 char *strategy;
1041
1042 strategy = defGetString(strategyEl);
1043 if (pg_strcasecmp(strategy, "wal_log") == 0)
1045 else if (pg_strcasecmp(strategy, "file_copy") == 0)
1047 else
1048 ereport(ERROR,
1050 errmsg("invalid create database strategy \"%s\"", strategy),
1051 errhint("Valid strategies are \"wal_log\" and \"file_copy\".")));
1052 }
1053
1054 /* If encoding or locales are defaulted, use source's setting */
1055 if (encoding < 0)
1057 if (dbcollate == NULL)
1059 if (dbctype == NULL)
1061 if (dblocprovider == '\0')
1065 if (dbicurules == NULL)
1067
1068 /* Some encodings are client only */
1070 ereport(ERROR,
1072 errmsg("invalid server encoding %d", encoding)));
1073
1074 /* Check that the chosen locales are valid, and get canonical spellings */
1076 {
1078 ereport(ERROR,
1080 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1081 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1082 else if (dblocprovider == COLLPROVIDER_ICU)
1083 ereport(ERROR,
1085 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate),
1086 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1087 else
1088 ereport(ERROR,
1090 errmsg("invalid LC_COLLATE locale name: \"%s\"", dbcollate)));
1091 }
1094 {
1096 ereport(ERROR,
1098 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1099 errhint("If the locale name is specific to the builtin provider, use BUILTIN_LOCALE.")));
1100 else if (dblocprovider == COLLPROVIDER_ICU)
1101 ereport(ERROR,
1103 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype),
1104 errhint("If the locale name is specific to the ICU provider, use ICU_LOCALE.")));
1105 else
1106 ereport(ERROR,
1108 errmsg("invalid LC_CTYPE locale name: \"%s\"", dbctype)));
1109 }
1110
1112
1114
1115 /* validate provider-specific parameters */
1117 {
1118 if (builtinlocaleEl)
1119 ereport(ERROR,
1121 errmsg("BUILTIN_LOCALE cannot be specified unless locale provider is builtin")));
1122 }
1123
1125 {
1126 if (iculocaleEl)
1127 ereport(ERROR,
1129 errmsg("ICU locale cannot be specified unless locale provider is ICU")));
1130
1131 if (dbicurules)
1132 ereport(ERROR,
1134 errmsg("ICU rules cannot be specified unless locale provider is ICU")));
1135 }
1136
1137 /* validate and canonicalize locale for the provider */
1139 {
1140 /*
1141 * This would happen if template0 uses the libc provider but the new
1142 * database uses builtin.
1143 */
1144 if (!dblocale)
1145 ereport(ERROR,
1147 errmsg("LOCALE or BUILTIN_LOCALE must be specified")));
1148
1150 }
1151 else if (dblocprovider == COLLPROVIDER_ICU)
1152 {
1154 ereport(ERROR,
1156 errmsg("encoding \"%s\" is not supported with ICU provider",
1158
1159 /*
1160 * This would happen if template0 uses the libc provider but the new
1161 * database uses icu.
1162 */
1163 if (!dblocale)
1164 ereport(ERROR,
1166 errmsg("LOCALE or ICU_LOCALE must be specified")));
1167
1168 /*
1169 * During binary upgrade, or when the locale came from the template
1170 * database, preserve locale string. Otherwise, canonicalize to a
1171 * language tag.
1172 */
1174 {
1177
1178 if (langtag && strcmp(dblocale, langtag) != 0)
1179 {
1181 (errmsg("using standard form \"%s\" for ICU locale \"%s\"",
1182 langtag, dblocale)));
1183
1184 dblocale = langtag;
1185 }
1186 }
1187
1189 }
1190
1191 /* for libc, locale comes from datcollate and datctype */
1193 dblocale = NULL;
1194
1195 /*
1196 * Check that the new encoding and locale settings match the source
1197 * database. We insist on this because we simply copy the source data ---
1198 * any non-ASCII data would be wrongly encoded, and any indexes sorted
1199 * according to the source locale would be wrong.
1200 *
1201 * However, we assume that template0 doesn't contain any non-ASCII data
1202 * nor any indexes that depend on collation or ctype, so template0 can be
1203 * used as template for creating a database with any encoding or locale.
1204 */
1205 if (strcmp(dbtemplate, "template0") != 0)
1206 {
1207 if (encoding != src_encoding)
1208 ereport(ERROR,
1210 errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1213 errhint("Use the same encoding as in the template database, or use template0 as template.")));
1214
1215 if (strcmp(dbcollate, src_collate) != 0)
1216 ereport(ERROR,
1218 errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1220 errhint("Use the same collation as in the template database, or use template0 as template.")));
1221
1222 if (strcmp(dbctype, src_ctype) != 0)
1223 ereport(ERROR,
1225 errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1227 errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1228
1230 ereport(ERROR,
1232 errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1234 errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1235
1237 {
1238 char *val1;
1239 char *val2;
1240
1243 if (strcmp(dblocale, src_locale) != 0)
1244 ereport(ERROR,
1246 errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1248 errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1249
1250 val1 = dbicurules;
1251 if (!val1)
1252 val1 = "";
1254 if (!val2)
1255 val2 = "";
1256 if (strcmp(val1, val2) != 0)
1257 ereport(ERROR,
1259 errmsg("new ICU collation rules (%s) are incompatible with the ICU collation rules of the template database (%s)",
1260 val1, val2),
1261 errhint("Use the same ICU collation rules as in the template database, or use template0 as template.")));
1262 }
1263 }
1264
1265 /*
1266 * If we got a collation version for the template database, check that it
1267 * matches the actual OS collation version. Otherwise error; the user
1268 * needs to fix the template database first. Don't complain if a
1269 * collation version was specified explicitly as a statement option; that
1270 * is used by pg_upgrade to reproduce the old state exactly.
1271 *
1272 * (If the template database has no collation version, then either the
1273 * platform/provider does not support collation versioning, or it's
1274 * template0, for which we stipulate that it does not contain
1275 * collation-using objects.)
1276 */
1278 {
1279 char *actual_versionstr;
1280 const char *locale;
1281
1283 locale = dbcollate;
1284 else
1285 locale = dblocale;
1286
1288 if (!actual_versionstr)
1289 ereport(ERROR,
1290 (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1291 dbtemplate)));
1292
1294 ereport(ERROR,
1295 (errmsg("template database \"%s\" has a collation version mismatch",
1296 dbtemplate),
1297 errdetail("The template database was created using collation version %s, "
1298 "but the operating system provides version %s.",
1300 errhint("Rebuild all objects in the template database that use the default collation and run "
1301 "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1302 "or build PostgreSQL with the right library version.",
1304 }
1305
1306 if (dbcollversion == NULL)
1308
1309 /*
1310 * Normally, we copy the collation version from the template database.
1311 * This last resort only applies if the template database does not have a
1312 * collation version, which is normally only the case for template0.
1313 */
1314 if (dbcollversion == NULL)
1315 {
1316 const char *locale;
1317
1319 locale = dbcollate;
1320 else
1321 locale = dblocale;
1322
1324 }
1325
1326 /* Resolve default tablespace for new database */
1328 {
1329 char *tablespacename;
1331
1332 tablespacename = defGetString(tablespacenameEl);
1333 dst_deftablespace = get_tablespace_oid(tablespacename, false);
1334 /* check permissions */
1336 ACL_CREATE);
1337 if (aclresult != ACLCHECK_OK)
1339 tablespacename);
1340
1341 /* pg_global must never be the default tablespace */
1343 ereport(ERROR,
1345 errmsg("pg_global cannot be used as default tablespace")));
1346
1347 /*
1348 * If we are trying to change the default tablespace of the template,
1349 * we require that the template not have any files in the new default
1350 * tablespace. This is necessary because otherwise the copied
1351 * database would contain pg_class rows that refer to its default
1352 * tablespace both explicitly (by OID) and implicitly (as zero), which
1353 * would cause problems. For example another CREATE DATABASE using
1354 * the copied database as template, and trying to change its default
1355 * tablespace again, would yield outright incorrect results (it would
1356 * improperly move tables to the new default tablespace that should
1357 * stay in the same tablespace).
1358 */
1360 {
1361 char *srcpath;
1362 struct stat st;
1363
1365
1366 if (stat(srcpath, &st) == 0 &&
1367 S_ISDIR(st.st_mode) &&
1369 ereport(ERROR,
1371 errmsg("cannot assign new default tablespace \"%s\"",
1372 tablespacename),
1373 errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1374 dbtemplate)));
1375 pfree(srcpath);
1376 }
1377 }
1378 else
1379 {
1380 /* Use template database's default tablespace */
1382 /* Note there is no additional permission check in this path */
1383 }
1384
1385 /*
1386 * If built with appropriate switch, whine when regression-testing
1387 * conventions for database names are violated. But don't complain during
1388 * initdb.
1389 */
1390#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1391 if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1392 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1393#endif
1394
1395 /*
1396 * Check for db name conflict. This is just to give a more friendly error
1397 * message than "unique index violation". There's a race condition but
1398 * we're willing to accept the less friendly message in that case.
1399 */
1401 ereport(ERROR,
1403 errmsg("database \"%s\" already exists", dbname)));
1404
1405 /*
1406 * The source DB can't have any active backends, except this one
1407 * (exception is to allow CREATE DB while connected to template1).
1408 * Otherwise we might copy inconsistent data.
1409 *
1410 * This should be last among the basic error checks, because it involves
1411 * potential waiting; we may as well throw an error first if we're gonna
1412 * throw one.
1413 */
1415 ereport(ERROR,
1417 errmsg("source database \"%s\" is being accessed by other users",
1418 dbtemplate),
1420
1421 /*
1422 * Select an OID for the new database, checking that it doesn't have a
1423 * filename conflict with anything already existing in the tablespace
1424 * directories.
1425 */
1427
1428 /*
1429 * If database OID is configured, check if the OID is already in use or
1430 * data directory already exists.
1431 */
1432 if (OidIsValid(dboid))
1433 {
1434 char *existing_dbname = get_database_name(dboid);
1435
1436 if (existing_dbname != NULL)
1437 ereport(ERROR,
1439 errmsg("database OID %u is already in use by database \"%s\"",
1440 dboid, existing_dbname));
1441
1442 if (check_db_file_conflict(dboid))
1443 ereport(ERROR,
1445 errmsg("data directory with the specified OID %u already exists", dboid));
1446 }
1447 else
1448 {
1449 /* Select an OID for the new database if is not explicitly configured. */
1450 do
1451 {
1454 } while (check_db_file_conflict(dboid));
1455 }
1456
1457 /*
1458 * Insert a new tuple into pg_database. This establishes our ownership of
1459 * the new database name (anyone else trying to insert the same name will
1460 * block on the unique index, and fail after we commit).
1461 */
1462
1465
1466 /* Form tuple */
1482 if (dblocale)
1484 else
1486 if (dbicurules)
1488 else
1490 if (dbcollversion)
1492 else
1494
1495 /*
1496 * We deliberately set datacl to default (NULL), rather than copying it
1497 * from the template database. Copying it would be a bad idea when the
1498 * owner is not the same as the template's owner.
1499 */
1501
1504
1506
1507 /*
1508 * Now generate additional catalog entries associated with the new DB
1509 */
1510
1511 /* Register owner dependency */
1513
1514 /* Create pg_shdepend entries for objects within database */
1515 copyTemplateDependencies(src_dboid, dboid);
1516
1517 /* Post creation hook for new database */
1519
1520 /*
1521 * If we're going to be reading data for the to-be-created database into
1522 * shared_buffers, take a lock on it. Nobody should know that this
1523 * database exists yet, but it's good to maintain the invariant that an
1524 * AccessExclusiveLock on the database is sufficient to drop all of its
1525 * buffers without worrying about more being read later.
1526 *
1527 * Note that we need to do this before entering the
1528 * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1529 * expects this lock to be held already.
1530 */
1533
1534 /*
1535 * Once we start copying subdirectories, we need to be able to clean 'em
1536 * up if we fail. Use an ENSURE block to make sure this happens. (This
1537 * is not a 100% solution, because of the possibility of failure during
1538 * transaction commit after we leave this routine, but it should handle
1539 * most scenarios.)
1540 */
1541 fparms.src_dboid = src_dboid;
1542 fparms.dest_dboid = dboid;
1543 fparms.strategy = dbstrategy;
1544
1547 {
1548 /*
1549 * If the user has asked to create a database with WAL_LOG strategy
1550 * then call CreateDatabaseUsingWalLog, which will copy the database
1551 * at the block level and it will WAL log each copied block.
1552 * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1553 * database file by file.
1554 */
1558 else
1561
1562 /*
1563 * Close pg_database, but keep lock till commit.
1564 */
1566
1567 /*
1568 * Force synchronous commit, thus minimizing the window between
1569 * creation of the database files and committal of the transaction. If
1570 * we crash before committing, we'll have a DB that's taking up disk
1571 * space but is not in pg_database, which is not good.
1572 */
1574 }
1577
1578 return dboid;
1579}
1580
1581/*
1582 * Check whether chosen encoding matches chosen locale settings. This
1583 * restriction is necessary because libc's locale-specific code usually
1584 * fails when presented with data in an encoding it's not expecting. We
1585 * allow mismatch in four cases:
1586 *
1587 * 1. locale encoding = SQL_ASCII, which means that the locale is C/POSIX
1588 * which works with any encoding.
1589 *
1590 * 2. locale encoding = -1, which means that we couldn't determine the
1591 * locale's encoding and have to trust the user to get it right.
1592 *
1593 * 3. selected encoding is UTF8 and platform is win32. This is because
1594 * UTF8 is a pseudo codepage that is supported in all locales since it's
1595 * converted to UTF16 before being used.
1596 *
1597 * 4. selected encoding is SQL_ASCII, but only if you're a superuser. This
1598 * is risky but we have historically allowed it --- notably, the
1599 * regression tests require it.
1600 *
1601 * Note: if you change this policy, fix initdb to match.
1602 */
1603void
1604check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
1605{
1607 int collate_encoding = pg_get_encoding_from_locale(collate, true);
1608
1609 if (!(ctype_encoding == encoding ||
1611 ctype_encoding == -1 ||
1612#ifdef WIN32
1613 encoding == PG_UTF8 ||
1614#endif
1615 (encoding == PG_SQL_ASCII && superuser())))
1616 ereport(ERROR,
1618 errmsg("encoding \"%s\" does not match locale \"%s\"",
1620 ctype),
1621 errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1623
1624 if (!(collate_encoding == encoding ||
1626 collate_encoding == -1 ||
1627#ifdef WIN32
1628 encoding == PG_UTF8 ||
1629#endif
1630 (encoding == PG_SQL_ASCII && superuser())))
1631 ereport(ERROR,
1633 errmsg("encoding \"%s\" does not match locale \"%s\"",
1635 collate),
1636 errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1638}
1639
1640/* Error cleanup callback for createdb */
1641static void
1643{
1645
1646 /*
1647 * If we were copying database at block levels then drop pages for the
1648 * destination database that are in the shared buffer cache. And tell
1649 * checkpointer to forget any pending fsync and unlink requests for files
1650 * in the database. The reasoning behind doing this is same as explained
1651 * in dropdb function. But unlike dropdb we don't need to call
1652 * pgstat_drop_database because this database is still not created so
1653 * there should not be any stat for this.
1654 */
1655 if (fparms->strategy == CREATEDB_WAL_LOG)
1656 {
1657 DropDatabaseBuffers(fparms->dest_dboid);
1659
1660 /* Release lock on the target database. */
1663 }
1664
1665 /*
1666 * Release lock on source database before doing recursive remove. This is
1667 * not essential but it seems desirable to release the lock as soon as
1668 * possible.
1669 */
1671
1672 /* Throw away any successfully copied subdirectories */
1673 remove_dbtablespaces(fparms->dest_dboid);
1674}
1675
1676
1677/*
1678 * DROP DATABASE
1679 */
1680void
1681dropdb(const char *dbname, bool missing_ok, bool force)
1682{
1683 Oid db_id;
1684 bool db_istemplate;
1686 HeapTuple tup;
1688 void *inplace_state;
1690 int notherbackends;
1691 int npreparedxacts;
1692 int nslots,
1694 int nsubscriptions;
1695
1696 /*
1697 * Look up the target database's OID, and get exclusive lock on it. We
1698 * need this to ensure that no new backend starts up in the target
1699 * database while we are deleting it (see postinit.c), and that no one is
1700 * using it as a CREATE DATABASE template or trying to delete it for
1701 * themselves.
1702 */
1704
1707 {
1708 if (!missing_ok)
1709 {
1710 ereport(ERROR,
1712 errmsg("database \"%s\" does not exist", dbname)));
1713 }
1714 else
1715 {
1716 /* Close pg_database, release the lock, since we changed nothing */
1719 (errmsg("database \"%s\" does not exist, skipping",
1720 dbname)));
1721 return;
1722 }
1723 }
1724
1725 /*
1726 * Permission checks
1727 */
1730 dbname);
1731
1732 /* DROP hook for the database being removed */
1734
1735 /*
1736 * Disallow dropping a DB that is marked istemplate. This is just to
1737 * prevent people from accidentally dropping template0 or template1; they
1738 * can do so if they're really determined ...
1739 */
1740 if (db_istemplate)
1741 ereport(ERROR,
1743 errmsg("cannot drop a template database")));
1744
1745 /* Obviously can't drop my own database */
1746 if (db_id == MyDatabaseId)
1747 ereport(ERROR,
1749 errmsg("cannot drop the currently open database")));
1750
1751 /*
1752 * Check whether there are active logical slots that refer to the
1753 * to-be-dropped database. The database lock we are holding prevents the
1754 * creation of new slots using the database or existing slots becoming
1755 * active.
1756 */
1758 if (nslots_active)
1759 {
1760 ereport(ERROR,
1762 errmsg("database \"%s\" is used by an active logical replication slot",
1763 dbname),
1764 errdetail_plural("There is %d active slot.",
1765 "There are %d active slots.",
1767 }
1768
1769 /*
1770 * Check if there are subscriptions defined in the target database.
1771 *
1772 * We can't drop them automatically because they might be holding
1773 * resources in other databases/instances.
1774 */
1775 if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1776 ereport(ERROR,
1778 errmsg("database \"%s\" is being used by logical replication subscription",
1779 dbname),
1780 errdetail_plural("There is %d subscription.",
1781 "There are %d subscriptions.",
1783
1784
1785 /*
1786 * Attempt to terminate all existing connections to the target database if
1787 * the user has requested to do so.
1788 */
1789 if (force)
1791
1792 /*
1793 * Check for other backends in the target database. (Because we hold the
1794 * database lock, no new ones can start after this.)
1795 *
1796 * As in CREATE DATABASE, check this after other error conditions.
1797 */
1799 ereport(ERROR,
1801 errmsg("database \"%s\" is being accessed by other users",
1802 dbname),
1804
1805 /*
1806 * Delete any comments or security labels associated with the database.
1807 */
1810
1811 /*
1812 * Remove settings associated with this database
1813 */
1814 DropSetting(db_id, InvalidOid);
1815
1816 /*
1817 * Remove shared dependency references for the database.
1818 */
1820
1821 /*
1822 * Tell the cumulative stats system to forget it immediately, too.
1823 */
1824 pgstat_drop_database(db_id);
1825
1826 /*
1827 * Except for the deletion of the catalog row, subsequent actions are not
1828 * transactional (consider DropDatabaseBuffers() discarding modified
1829 * buffers). But we might crash or get interrupted below. To prevent
1830 * accesses to a database with invalid contents, mark the database as
1831 * invalid using an in-place update.
1832 *
1833 * We need to flush the WAL before continuing, to guarantee the
1834 * modification is durable before performing irreversible filesystem
1835 * operations.
1836 */
1842 NULL, 1, &scankey, &tup, &inplace_state);
1843 if (!HeapTupleIsValid(tup))
1844 elog(ERROR, "cache lookup failed for database %u", db_id);
1846 datform->datconnlimit = DATCONNLIMIT_INVALID_DB;
1849
1850 /*
1851 * Also delete the tuple - transactionally. If this transaction commits,
1852 * the row will be gone, but if we fail, dropdb() can be invoked again.
1853 */
1854 CatalogTupleDelete(pgdbrel, &tup->t_self);
1856
1857 /*
1858 * Drop db-specific replication slots.
1859 */
1861
1862 /*
1863 * Drop pages for this database that are in the shared buffer cache. This
1864 * is important to ensure that no remaining backend tries to write out a
1865 * dirty buffer to the dead database later...
1866 */
1867 DropDatabaseBuffers(db_id);
1868
1869 /*
1870 * Tell checkpointer to forget any pending fsync and unlink requests for
1871 * files in the database; else the fsyncs will fail at next checkpoint, or
1872 * worse, it will delete files that belong to a newly created database
1873 * with the same OID.
1874 */
1876
1877 /*
1878 * Force a checkpoint to make sure the checkpointer has received the
1879 * message sent by ForgetDatabaseSyncRequests.
1880 */
1882
1883 /* Close all smgr fds in all backends. */
1885
1886 /*
1887 * Remove all tablespace subdirs belonging to the database.
1888 */
1889 remove_dbtablespaces(db_id);
1890
1891 /*
1892 * Close pg_database, but keep lock till commit.
1893 */
1895
1896 /*
1897 * Force synchronous commit, thus minimizing the window between removal of
1898 * the database files and committal of the transaction. If we crash before
1899 * committing, we'll have a DB that's gone on disk but still there
1900 * according to pg_database, which is not good.
1901 */
1903}
1904
1905
1906/*
1907 * Rename database
1908 */
1910RenameDatabase(const char *oldname, const char *newname)
1911{
1912 Oid db_id;
1915 Relation rel;
1916 int notherbackends;
1917 int npreparedxacts;
1918 ObjectAddress address;
1919
1920 /* Report error if name has \n or \r character. */
1921 if (strpbrk(newname, "\n\r"))
1922 ereport(ERROR,
1924 errmsg("database name \"%s\" contains a newline or carriage return character", newname)));
1925
1926 /*
1927 * Look up the target database's OID, and get exclusive lock on it. We
1928 * need this for the same reasons as DROP DATABASE.
1929 */
1931
1934 ereport(ERROR,
1936 errmsg("database \"%s\" does not exist", oldname)));
1937
1938 /* must be owner */
1941 oldname);
1942
1943 /* must have createdb rights */
1945 ereport(ERROR,
1947 errmsg("permission denied to rename database")));
1948
1949 /*
1950 * If built with appropriate switch, whine when regression-testing
1951 * conventions for database names are violated.
1952 */
1953#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1954 if (strstr(newname, "regression") == NULL)
1955 elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1956#endif
1957
1958 /*
1959 * Make sure the new name doesn't exist. See notes for same error in
1960 * CREATE DATABASE.
1961 */
1962 if (OidIsValid(get_database_oid(newname, true)))
1963 ereport(ERROR,
1965 errmsg("database \"%s\" already exists", newname)));
1966
1967 /*
1968 * XXX Client applications probably store the current database somewhere,
1969 * so renaming it could cause confusion. On the other hand, there may not
1970 * be an actual problem besides a little confusion, so think about this
1971 * and decide.
1972 */
1973 if (db_id == MyDatabaseId)
1974 ereport(ERROR,
1976 errmsg("current database cannot be renamed")));
1977
1978 /*
1979 * Make sure the database does not have active sessions. This is the same
1980 * concern as above, but applied to other sessions.
1981 *
1982 * As in CREATE DATABASE, check this after other error conditions.
1983 */
1985 ereport(ERROR,
1987 errmsg("database \"%s\" is being accessed by other users",
1988 oldname),
1990
1991 /* rename */
1994 elog(ERROR, "cache lookup failed for database %u", db_id);
1995 otid = newtup->t_self;
1999
2001
2002 ObjectAddressSet(address, DatabaseRelationId, db_id);
2003
2004 /*
2005 * Close pg_database, but keep lock till commit.
2006 */
2007 table_close(rel, NoLock);
2008
2009 return address;
2010}
2011
2012
2013/*
2014 * ALTER DATABASE SET TABLESPACE
2015 */
2016static void
2017movedb(const char *dbname, const char *tblspcname)
2018{
2019 Oid db_id;
2021 int notherbackends;
2022 int npreparedxacts;
2023 HeapTuple oldtuple,
2024 newtuple;
2030 char *src_dbpath;
2031 char *dst_dbpath;
2032 DIR *dstdir;
2033 struct dirent *xlde;
2035
2036 /*
2037 * Look up the target database's OID, and get exclusive lock on it. We
2038 * need this to ensure that no new backend starts up in the database while
2039 * we are moving it, and that no one is using it as a CREATE DATABASE
2040 * template or trying to delete it.
2041 */
2043
2046 ereport(ERROR,
2048 errmsg("database \"%s\" does not exist", dbname)));
2049
2050 /*
2051 * We actually need a session lock, so that the lock will persist across
2052 * the commit/restart below. (We could almost get away with letting the
2053 * lock be released at commit, except that someone could try to move
2054 * relations of the DB back into the old directory while we rmtree() it.)
2055 */
2058
2059 /*
2060 * Permission checks
2061 */
2064 dbname);
2065
2066 /*
2067 * Obviously can't move the tables of my own database
2068 */
2069 if (db_id == MyDatabaseId)
2070 ereport(ERROR,
2072 errmsg("cannot change the tablespace of the currently open database")));
2073
2074 /*
2075 * Get tablespace's oid
2076 */
2078
2079 /*
2080 * Permission checks
2081 */
2083 ACL_CREATE);
2084 if (aclresult != ACLCHECK_OK)
2086 tblspcname);
2087
2088 /*
2089 * pg_global must never be the default tablespace
2090 */
2092 ereport(ERROR,
2094 errmsg("pg_global cannot be used as default tablespace")));
2095
2096 /*
2097 * No-op if same tablespace
2098 */
2100 {
2104 return;
2105 }
2106
2107 /*
2108 * Check for other backends in the target database. (Because we hold the
2109 * database lock, no new ones can start after this.)
2110 *
2111 * As in CREATE DATABASE, check this after other error conditions.
2112 */
2114 ereport(ERROR,
2116 errmsg("database \"%s\" is being accessed by other users",
2117 dbname),
2119
2120 /*
2121 * Get old and new database paths
2122 */
2125
2126 /*
2127 * Force a checkpoint before proceeding. This will force all dirty
2128 * buffers, including those of unlogged tables, out to disk, to ensure
2129 * source database is up-to-date on disk for the copy.
2130 * FlushDatabaseBuffers() would suffice for that, but we also want to
2131 * process any pending unlink requests. Otherwise, the check for existing
2132 * files in the target directory might fail unnecessarily, not to mention
2133 * that the copy might fail due to source files getting deleted under it.
2134 * On Windows, this also ensures that background procs don't hold any open
2135 * files, which would cause rmdir() to fail.
2136 */
2139
2140 /* Close all smgr fds in all backends. */
2142
2143 /*
2144 * Now drop all buffers holding data of the target database; they should
2145 * no longer be dirty so DropDatabaseBuffers is safe.
2146 *
2147 * It might seem that we could just let these buffers age out of shared
2148 * buffers naturally, since they should not get referenced anymore. The
2149 * problem with that is that if the user later moves the database back to
2150 * its original tablespace, any still-surviving buffers would appear to
2151 * contain valid data again --- but they'd be missing any changes made in
2152 * the database while it was in the new tablespace. In any case, freeing
2153 * buffers that should never be used again seems worth the cycles.
2154 *
2155 * Note: it'd be sufficient to get rid of buffers matching db_id and
2156 * src_tblspcoid, but bufmgr.c presently provides no API for that.
2157 */
2158 DropDatabaseBuffers(db_id);
2159
2160 /*
2161 * Check for existence of files in the target directory, i.e., objects of
2162 * this database that are already in the target tablespace. We can't
2163 * allow the move in such a case, because we would need to change those
2164 * relations' pg_class.reltablespace entries to zero, and we don't have
2165 * access to the DB's pg_class to do so.
2166 */
2168 if (dstdir != NULL)
2169 {
2170 while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
2171 {
2172 if (strcmp(xlde->d_name, ".") == 0 ||
2173 strcmp(xlde->d_name, "..") == 0)
2174 continue;
2175
2176 ereport(ERROR,
2178 errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
2180 errhint("You must move them back to the database's default tablespace before using this command.")));
2181 }
2182
2183 FreeDir(dstdir);
2184
2185 /*
2186 * The directory exists but is empty. We must remove it before using
2187 * the copydir function.
2188 */
2189 if (rmdir(dst_dbpath) != 0)
2190 elog(ERROR, "could not remove directory \"%s\": %m",
2191 dst_dbpath);
2192 }
2193
2194 /*
2195 * Use an ENSURE block to make sure we remove the debris if the copy fails
2196 * (eg, due to out-of-disk-space). This is not a 100% solution, because
2197 * of the possibility of failure during transaction commit, but it should
2198 * handle most scenarios.
2199 */
2200 fparms.dest_dboid = db_id;
2201 fparms.dest_tsoid = dst_tblspcoid;
2204 {
2208
2209 /*
2210 * Copy files from the old tablespace to the new one
2211 */
2212 copydir(src_dbpath, dst_dbpath, false);
2213
2214 /*
2215 * Record the filesystem change in XLOG
2216 */
2217 {
2219
2220 xlrec.db_id = db_id;
2221 xlrec.tablespace_id = dst_tblspcoid;
2222 xlrec.src_db_id = db_id;
2223 xlrec.src_tablespace_id = src_tblspcoid;
2224
2228
2231 }
2232
2233 /*
2234 * Update the database's pg_database tuple
2235 */
2241 NULL, 1, &scankey);
2242 oldtuple = systable_getnext(sysscan);
2243 if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2244 ereport(ERROR,
2246 errmsg("database \"%s\" does not exist", dbname)));
2248
2251
2252 newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2253 new_record,
2255 CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2257
2259
2261
2262 /*
2263 * Force another checkpoint here. As in CREATE DATABASE, this is to
2264 * ensure that we don't have to replay a committed
2265 * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2266 * any unlogged operations done in the new DB tablespace before the
2267 * next checkpoint.
2268 */
2270
2271 /*
2272 * Force synchronous commit, thus minimizing the window between
2273 * copying the database files and committal of the transaction. If we
2274 * crash before committing, we'll leave an orphaned set of files on
2275 * disk, which is not fatal but not good either.
2276 */
2278
2279 /*
2280 * Close pg_database, but keep lock till commit.
2281 */
2283 }
2286
2287 /*
2288 * Commit the transaction so that the pg_database update is committed. If
2289 * we crash while removing files, the database won't be corrupt, we'll
2290 * just leave some orphaned files in the old directory.
2291 *
2292 * (This is OK because we know we aren't inside a transaction block.)
2293 *
2294 * XXX would it be safe/better to do this inside the ensure block? Not
2295 * convinced it's a good idea; consider elog just after the transaction
2296 * really commits.
2297 */
2300
2301 /* Start new transaction for the remaining work; don't need a snapshot */
2303
2304 /*
2305 * Remove files from the old tablespace
2306 */
2307 if (!rmtree(src_dbpath, true))
2309 (errmsg("some useless files may be left behind in old database directory \"%s\"",
2310 src_dbpath)));
2311
2312 /*
2313 * Record the filesystem change in XLOG
2314 */
2315 {
2317
2318 xlrec.db_id = db_id;
2319 xlrec.ntablespaces = 1;
2320
2324
2327 }
2328
2329 /* Now it's safe to release the database lock */
2332
2335}
2336
2337/* Error cleanup callback for movedb */
2338static void
2340{
2342 char *dstpath;
2343
2344 /* Get rid of anything we managed to copy to the target directory */
2345 dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2346
2347 (void) rmtree(dstpath, true);
2348
2349 pfree(dstpath);
2350}
2351
2352/*
2353 * Process options and call dropdb function.
2354 */
2355void
2357{
2358 bool force = false;
2359 ListCell *lc;
2360
2361 foreach(lc, stmt->options)
2362 {
2363 DefElem *opt = (DefElem *) lfirst(lc);
2364
2365 if (strcmp(opt->defname, "force") == 0)
2366 force = true;
2367 else
2368 ereport(ERROR,
2370 errmsg("unrecognized %s option \"%s\"",
2371 "DROP DATABASE", opt->defname),
2372 parser_errposition(pstate, opt->location)));
2373 }
2374
2375 dropdb(stmt->dbname, stmt->missing_ok, force);
2376}
2377
2378/*
2379 * ALTER DATABASE name ...
2380 */
2381Oid
2383{
2384 Relation rel;
2385 Oid dboid;
2386 HeapTuple tuple,
2387 newtuple;
2390 SysScanDesc scan;
2392 bool dbistemplate = false;
2393 bool dballowconnections = true;
2402
2403 /* Extract options from the statement node tree */
2404 foreach(option, stmt->options)
2405 {
2407
2408 if (strcmp(defel->defname, "is_template") == 0)
2409 {
2410 if (distemplate)
2413 }
2414 else if (strcmp(defel->defname, "allow_connections") == 0)
2415 {
2419 }
2420 else if (strcmp(defel->defname, "connection_limit") == 0)
2421 {
2422 if (dconnlimit)
2424 dconnlimit = defel;
2425 }
2426 else if (strcmp(defel->defname, "tablespace") == 0)
2427 {
2428 if (dtablespace)
2431 }
2432 else
2433 ereport(ERROR,
2435 errmsg("option \"%s\" not recognized", defel->defname),
2436 parser_errposition(pstate, defel->location)));
2437 }
2438
2439 if (dtablespace)
2440 {
2441 /*
2442 * While the SET TABLESPACE syntax doesn't allow any other options,
2443 * somebody could write "WITH TABLESPACE ...". Forbid any other
2444 * options from being specified in that case.
2445 */
2446 if (list_length(stmt->options) != 1)
2447 ereport(ERROR,
2449 errmsg("option \"%s\" cannot be specified with other options",
2450 dtablespace->defname),
2451 parser_errposition(pstate, dtablespace->location)));
2452 /* this case isn't allowed within a transaction block */
2453 PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2455 return InvalidOid;
2456 }
2457
2458 if (distemplate && distemplate->arg)
2462 if (dconnlimit && dconnlimit->arg)
2463 {
2466 ereport(ERROR,
2468 errmsg("invalid connection limit: %d", dbconnlimit)));
2469 }
2470
2471 /*
2472 * Get the old tuple. We don't need a lock on the database per se,
2473 * because we're not going to do anything that would mess up incoming
2474 * connections.
2475 */
2480 CStringGetDatum(stmt->dbname));
2481 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2482 NULL, 1, &scankey);
2483 tuple = systable_getnext(scan);
2484 if (!HeapTupleIsValid(tuple))
2485 ereport(ERROR,
2487 errmsg("database \"%s\" does not exist", stmt->dbname)));
2489
2491 dboid = datform->oid;
2492
2494 {
2495 ereport(FATAL,
2497 errmsg("cannot alter invalid database \"%s\"", stmt->dbname),
2498 errhint("Use DROP DATABASE to drop invalid databases."));
2499 }
2500
2503 stmt->dbname);
2504
2505 /*
2506 * In order to avoid getting locked out and having to go through
2507 * standalone mode, we refuse to disallow connections to the database
2508 * we're currently connected to. Lockout can still happen with concurrent
2509 * sessions but the likeliness of that is not high enough to worry about.
2510 */
2511 if (!dballowconnections && dboid == MyDatabaseId)
2512 ereport(ERROR,
2514 errmsg("cannot disallow connections for current database")));
2515
2516 /*
2517 * Build an updated tuple, perusing the information just obtained
2518 */
2519 if (distemplate)
2520 {
2523 }
2525 {
2528 }
2529 if (dconnlimit)
2530 {
2533 }
2534
2535 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2537 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2539
2541
2542 systable_endscan(scan);
2543
2544 /* Close pg_database, but keep lock till commit */
2545 table_close(rel, NoLock);
2546
2547 return dboid;
2548}
2549
2550
2551/*
2552 * ALTER DATABASE name REFRESH COLLATION VERSION
2553 */
2556{
2557 Relation rel;
2559 SysScanDesc scan;
2560 Oid db_id;
2561 HeapTuple tuple;
2563 ObjectAddress address;
2564 Datum datum;
2565 bool isnull;
2566 char *oldversion;
2567 char *newversion;
2568
2573 CStringGetDatum(stmt->dbname));
2574 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2575 NULL, 1, &scankey);
2576 tuple = systable_getnext(scan);
2577 if (!HeapTupleIsValid(tuple))
2578 ereport(ERROR,
2580 errmsg("database \"%s\" does not exist", stmt->dbname)));
2581
2583 db_id = datForm->oid;
2584
2587 stmt->dbname);
2589
2590 datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2591 oldversion = isnull ? NULL : TextDatumGetCString(datum);
2592
2593 if (datForm->datlocprovider == COLLPROVIDER_LIBC)
2594 {
2595 datum = heap_getattr(tuple, Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2596 if (isnull)
2597 elog(ERROR, "unexpected null in pg_database");
2598 }
2599 else
2600 {
2601 datum = heap_getattr(tuple, Anum_pg_database_datlocale, RelationGetDescr(rel), &isnull);
2602 if (isnull)
2603 elog(ERROR, "unexpected null in pg_database");
2604 }
2605
2607 TextDatumGetCString(datum));
2608
2609 /* cannot change from NULL to non-NULL or vice versa */
2610 if ((!oldversion && newversion) || (oldversion && !newversion))
2611 elog(ERROR, "invalid collation version change");
2612 else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2613 {
2614 bool nulls[Natts_pg_database] = {0};
2615 bool replaces[Natts_pg_database] = {0};
2617 HeapTuple newtuple;
2618
2620 (errmsg("changing version from %s to %s",
2622
2625
2626 newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2627 values, nulls, replaces);
2628 CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2629 heap_freetuple(newtuple);
2630 }
2631 else
2633 (errmsg("version has not changed")));
2635
2637
2638 ObjectAddressSet(address, DatabaseRelationId, db_id);
2639
2640 systable_endscan(scan);
2641
2642 table_close(rel, NoLock);
2643
2644 return address;
2645}
2646
2647
2648/*
2649 * ALTER DATABASE name SET ...
2650 */
2651Oid
2653{
2654 Oid datid = get_database_oid(stmt->dbname, false);
2655
2656 /*
2657 * Obtain a lock on the database and make sure it didn't go away in the
2658 * meantime.
2659 */
2661
2664 stmt->dbname);
2665
2666 AlterSetting(datid, InvalidOid, stmt->setstmt);
2667
2669
2670 return datid;
2671}
2672
2673
2674/*
2675 * ALTER DATABASE name OWNER TO newowner
2676 */
2679{
2680 Oid db_id;
2681 HeapTuple tuple;
2682 Relation rel;
2684 SysScanDesc scan;
2686 ObjectAddress address;
2687
2688 /*
2689 * Get the old tuple. We don't need a lock on the database per se,
2690 * because we're not going to do anything that would mess up incoming
2691 * connections.
2692 */
2698 scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2699 NULL, 1, &scankey);
2700 tuple = systable_getnext(scan);
2701 if (!HeapTupleIsValid(tuple))
2702 ereport(ERROR,
2704 errmsg("database \"%s\" does not exist", dbname)));
2705
2707 db_id = datForm->oid;
2708
2709 /*
2710 * If the new owner is the same as the existing owner, consider the
2711 * command to have succeeded. This is to be consistent with other
2712 * objects.
2713 */
2714 if (datForm->datdba != newOwnerId)
2715 {
2717 bool repl_null[Natts_pg_database] = {0};
2718 bool repl_repl[Natts_pg_database] = {0};
2719 Acl *newAcl;
2721 bool isNull;
2722 HeapTuple newtuple;
2723
2724 /* Otherwise, must be owner of the existing object */
2727 dbname);
2728
2729 /* Must be able to become new owner */
2731
2732 /*
2733 * must have createdb rights
2734 *
2735 * NOTE: This is different from other alter-owner checks in that the
2736 * current user is checked for createdb privileges instead of the
2737 * destination owner. This is consistent with the CREATE case for
2738 * databases. Because superusers will always have this right, we need
2739 * no special case for them.
2740 */
2742 ereport(ERROR,
2744 errmsg("permission denied to change owner of database")));
2745
2747
2750
2751 /*
2752 * Determine the modified ACL for the new owner. This is only
2753 * necessary when the ACL is non-null.
2754 */
2755 aclDatum = heap_getattr(tuple,
2757 RelationGetDescr(rel),
2758 &isNull);
2759 if (!isNull)
2760 {
2762 datForm->datdba, newOwnerId);
2765 }
2766
2768 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2770
2771 heap_freetuple(newtuple);
2772
2773 /* Update owner dependency reference */
2775 }
2776
2778
2779 ObjectAddressSet(address, DatabaseRelationId, db_id);
2780
2781 systable_endscan(scan);
2782
2783 /* Close pg_database, but keep lock till commit */
2784 table_close(rel, NoLock);
2785
2786 return address;
2787}
2788
2789
2790Datum
2792{
2793 Oid dbid = PG_GETARG_OID(0);
2794 HeapTuple tp;
2795 char datlocprovider;
2796 Datum datum;
2797 char *version;
2798
2800 if (!HeapTupleIsValid(tp))
2801 ereport(ERROR,
2803 errmsg("database with OID %u does not exist", dbid)));
2804
2806
2809 else
2811
2813 TextDatumGetCString(datum));
2814
2815 ReleaseSysCache(tp);
2816
2817 if (version)
2819 else
2821}
2822
2823
2824/*
2825 * Helper functions
2826 */
2827
2828/*
2829 * Look up info about the database named "name". If the database exists,
2830 * obtain the specified lock type on it, fill in any of the remaining
2831 * parameters that aren't NULL, and return true. If no such database,
2832 * return false.
2833 */
2834static bool
2835get_db_info(const char *name, LOCKMODE lockmode,
2836 Oid *dbIdP, Oid *ownerIdP,
2837 int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, bool *dbHasLoginEvtP,
2839 Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbLocale,
2840 char **dbIcurules,
2841 char *dbLocProvider,
2842 char **dbCollversion)
2843{
2844 bool result = false;
2845 Relation relation;
2846
2847 Assert(name);
2848
2849 /* Caller may wish to grab a better lock on pg_database beforehand... */
2851
2852 /*
2853 * Loop covers the rare case where the database is renamed before we can
2854 * lock it. We try again just in case we can find a new one of the same
2855 * name.
2856 */
2857 for (;;)
2858 {
2860 SysScanDesc scan;
2861 HeapTuple tuple;
2862 Oid dbOid;
2863
2864 /*
2865 * there's no syscache for database-indexed-by-name, so must do it the
2866 * hard way
2867 */
2872
2873 scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2874 NULL, 1, &scanKey);
2875
2876 tuple = systable_getnext(scan);
2877
2878 if (!HeapTupleIsValid(tuple))
2879 {
2880 /* definitely no database of that name */
2881 systable_endscan(scan);
2882 break;
2883 }
2884
2885 dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2886
2887 systable_endscan(scan);
2888
2889 /*
2890 * Now that we have a database OID, we can try to lock the DB.
2891 */
2892 if (lockmode != NoLock)
2893 LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2894
2895 /*
2896 * And now, re-fetch the tuple by OID. If it's still there and still
2897 * the same name, we win; else, drop the lock and loop back to try
2898 * again.
2899 */
2901 if (HeapTupleIsValid(tuple))
2902 {
2904
2905 if (strcmp(name, NameStr(dbform->datname)) == 0)
2906 {
2907 Datum datum;
2908 bool isnull;
2909
2910 /* oid of the database */
2911 if (dbIdP)
2912 *dbIdP = dbOid;
2913 /* oid of the owner */
2914 if (ownerIdP)
2915 *ownerIdP = dbform->datdba;
2916 /* character encoding */
2917 if (encodingP)
2918 *encodingP = dbform->encoding;
2919 /* allowed as template? */
2920 if (dbIsTemplateP)
2921 *dbIsTemplateP = dbform->datistemplate;
2922 /* Has on login event trigger? */
2923 if (dbHasLoginEvtP)
2924 *dbHasLoginEvtP = dbform->dathasloginevt;
2925 /* allowing connections? */
2926 if (dbAllowConnP)
2927 *dbAllowConnP = dbform->datallowconn;
2928 /* limit of frozen XIDs */
2929 if (dbFrozenXidP)
2930 *dbFrozenXidP = dbform->datfrozenxid;
2931 /* minimum MultiXactId */
2932 if (dbMinMultiP)
2933 *dbMinMultiP = dbform->datminmxid;
2934 /* default tablespace for this database */
2935 if (dbTablespace)
2936 *dbTablespace = dbform->dattablespace;
2937 /* default locale settings for this database */
2938 if (dbLocProvider)
2939 *dbLocProvider = dbform->datlocprovider;
2940 if (dbCollate)
2941 {
2944 }
2945 if (dbCtype)
2946 {
2948 *dbCtype = TextDatumGetCString(datum);
2949 }
2950 if (dbLocale)
2951 {
2952 datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datlocale, &isnull);
2953 if (isnull)
2954 *dbLocale = NULL;
2955 else
2956 *dbLocale = TextDatumGetCString(datum);
2957 }
2958 if (dbIcurules)
2959 {
2961 if (isnull)
2962 *dbIcurules = NULL;
2963 else
2965 }
2966 if (dbCollversion)
2967 {
2969 if (isnull)
2971 else
2973 }
2974 ReleaseSysCache(tuple);
2975 result = true;
2976 break;
2977 }
2978 /* can only get here if it was just renamed */
2979 ReleaseSysCache(tuple);
2980 }
2981
2982 if (lockmode != NoLock)
2983 UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2984 }
2985
2986 table_close(relation, AccessShareLock);
2987
2988 return result;
2989}
2990
2991/* Check if current user has createdb privileges */
2992bool
2994{
2995 bool result = false;
2997
2998 /* Superusers can always do everything */
2999 if (superuser())
3000 return true;
3001
3004 {
3007 }
3008 return result;
3009}
3010
3011/*
3012 * Remove tablespace directories
3013 *
3014 * We don't know what tablespaces db_id is using, so iterate through all
3015 * tablespaces removing <tablespace>/db_id
3016 */
3017static void
3019{
3020 Relation rel;
3021 TableScanDesc scan;
3022 HeapTuple tuple;
3023 List *ltblspc = NIL;
3024 ListCell *cell;
3025 int ntblspc;
3026 int i;
3027 Oid *tablespace_ids;
3028
3030 scan = table_beginscan_catalog(rel, 0, NULL);
3031 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3032 {
3034 Oid dsttablespace = spcform->oid;
3035 char *dstpath;
3036 struct stat st;
3037
3038 /* Don't mess with the global tablespace */
3040 continue;
3041
3043
3044 if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
3045 {
3046 /* Assume we can ignore it */
3047 pfree(dstpath);
3048 continue;
3049 }
3050
3051 if (!rmtree(dstpath, true))
3053 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3054 dstpath)));
3055
3057 pfree(dstpath);
3058 }
3059
3061 if (ntblspc == 0)
3062 {
3063 table_endscan(scan);
3065 return;
3066 }
3067
3068 tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
3069 i = 0;
3070 foreach(cell, ltblspc)
3071 tablespace_ids[i++] = lfirst_oid(cell);
3072
3073 /* Record the filesystem change in XLOG */
3074 {
3076
3077 xlrec.db_id = db_id;
3078 xlrec.ntablespaces = ntblspc;
3079
3082 XLogRegisterData(tablespace_ids, ntblspc * sizeof(Oid));
3083
3086 }
3087
3089 pfree(tablespace_ids);
3090
3091 table_endscan(scan);
3093}
3094
3095/*
3096 * Check for existing files that conflict with a proposed new DB OID;
3097 * return true if there are any
3098 *
3099 * If there were a subdirectory in any tablespace matching the proposed new
3100 * OID, we'd get a create failure due to the duplicate name ... and then we'd
3101 * try to remove that already-existing subdirectory during the cleanup in
3102 * remove_dbtablespaces. Nuking existing files seems like a bad idea, so
3103 * instead we make this extra check before settling on the OID of the new
3104 * database. This exactly parallels what GetNewRelFileNumber() does for table
3105 * relfilenumber values.
3106 */
3107static bool
3109{
3110 bool result = false;
3111 Relation rel;
3112 TableScanDesc scan;
3113 HeapTuple tuple;
3114
3116 scan = table_beginscan_catalog(rel, 0, NULL);
3117 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
3118 {
3120 Oid dsttablespace = spcform->oid;
3121 char *dstpath;
3122 struct stat st;
3123
3124 /* Don't mess with the global tablespace */
3126 continue;
3127
3129
3130 if (lstat(dstpath, &st) == 0)
3131 {
3132 /* Found a conflicting file (or directory, whatever) */
3133 pfree(dstpath);
3134 result = true;
3135 break;
3136 }
3137
3138 pfree(dstpath);
3139 }
3140
3141 table_endscan(scan);
3143
3144 return result;
3145}
3146
3147/*
3148 * Issue a suitable errdetail message for a busy database
3149 */
3150static int
3152{
3153 if (notherbackends > 0 && npreparedxacts > 0)
3154
3155 /*
3156 * We don't deal with singular versus plural here, since gettext
3157 * doesn't support multiple plurals in one string.
3158 */
3159 errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
3161 else if (notherbackends > 0)
3162 errdetail_plural("There is %d other session using the database.",
3163 "There are %d other sessions using the database.",
3166 else
3167 errdetail_plural("There is %d prepared transaction using the database.",
3168 "There are %d prepared transactions using the database.",
3171 return 0; /* just to keep ereport macro happy */
3172}
3173
3174/*
3175 * get_database_oid - given a database name, look up the OID
3176 *
3177 * If missing_ok is false, throw an error if database name not found. If
3178 * true, just return InvalidOid.
3179 */
3180Oid
3181get_database_oid(const char *dbname, bool missing_ok)
3182{
3184 ScanKeyData entry[1];
3185 SysScanDesc scan;
3187 Oid oid;
3188
3189 /*
3190 * There's no syscache for pg_database indexed by name, so we must look
3191 * the hard way.
3192 */
3194 ScanKeyInit(&entry[0],
3199 NULL, 1, entry);
3200
3201 dbtuple = systable_getnext(scan);
3202
3203 /* We assume that there can be at most one matching tuple */
3205 oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
3206 else
3207 oid = InvalidOid;
3208
3209 systable_endscan(scan);
3211
3212 if (!OidIsValid(oid) && !missing_ok)
3213 ereport(ERROR,
3215 errmsg("database \"%s\" does not exist",
3216 dbname)));
3217
3218 return oid;
3219}
3220
3221
3222/*
3223 * While dropping a database the pg_database row is marked invalid, but the
3224 * catalog contents still exist. Connections to such a database are not
3225 * allowed.
3226 */
3227bool
3232
3233
3234/*
3235 * Convenience wrapper around database_is_invalid_form()
3236 */
3237bool
3239{
3242 bool invalid;
3243
3245 if (!HeapTupleIsValid(dbtup))
3246 elog(ERROR, "cache lookup failed for database %u", dboid);
3248
3250
3252
3253 return invalid;
3254}
3255
3256
3257/*
3258 * recovery_create_dbdir()
3259 *
3260 * During recovery, there's a case where we validly need to recover a missing
3261 * tablespace directory so that recovery can continue. This happens when
3262 * recovery wants to create a database but the holding tablespace has been
3263 * removed before the server stopped. Since we expect that the directory will
3264 * be gone before reaching recovery consistency, and we have no knowledge about
3265 * the tablespace other than its OID here, we create a real directory under
3266 * pg_tblspc here instead of restoring the symlink.
3267 *
3268 * If only_tblspc is true, then the requested directory must be in pg_tblspc/
3269 */
3270static void
3272{
3273 struct stat st;
3274
3276
3277 if (stat(path, &st) == 0)
3278 return;
3279
3280 if (only_tblspc && strstr(path, PG_TBLSPC_DIR_SLASH) == NULL)
3281 elog(PANIC, "requested to created invalid directory: %s", path);
3282
3284 ereport(PANIC,
3285 errmsg("missing directory \"%s\"", path));
3286
3288 "creating missing directory: %s", path);
3289
3290 if (pg_mkdir_p(path, pg_dir_create_mode) != 0)
3291 ereport(PANIC,
3292 errmsg("could not create missing directory \"%s\": %m", path));
3293}
3294
3295
3296/*
3297 * DATABASE resource manager's routines
3298 */
3299void
3301{
3302 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3303
3304 /* Backup blocks are not used in dbase records */
3306
3307 if (info == XLOG_DBASE_CREATE_FILE_COPY)
3308 {
3311 char *src_path;
3312 char *dst_path;
3313 char *parent_path;
3314 struct stat st;
3315
3316 src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3317 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3318
3319 /*
3320 * Our theory for replaying a CREATE is to forcibly drop the target
3321 * subdirectory if present, then re-copy the source data. This may be
3322 * more work than needed, but it is simple to implement.
3323 */
3324 if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3325 {
3326 if (!rmtree(dst_path, true))
3327 /* If this failed, copydir() below is going to error. */
3329 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3330 dst_path)));
3331 }
3332
3333 /*
3334 * If the parent of the target path doesn't exist, create it now. This
3335 * enables us to create the target underneath later.
3336 */
3339 if (stat(parent_path, &st) < 0)
3340 {
3341 if (errno != ENOENT)
3342 ereport(FATAL,
3343 errmsg("could not stat directory \"%s\": %m",
3344 dst_path));
3345
3346 /* create the parent directory if needed and valid */
3348 }
3350
3351 /*
3352 * There's a case where the copy source directory is missing for the
3353 * same reason above. Create the empty source directory so that
3354 * copydir below doesn't fail. The directory will be dropped soon by
3355 * recovery.
3356 */
3357 if (stat(src_path, &st) < 0 && errno == ENOENT)
3359
3360 /*
3361 * Force dirty buffers out to disk, to ensure source database is
3362 * up-to-date for the copy.
3363 */
3364 FlushDatabaseBuffers(xlrec->src_db_id);
3365
3366 /* Close all smgr fds in all backends. */
3368
3369 /*
3370 * Copy this subdirectory to the new location
3371 *
3372 * We don't need to copy subdirectories
3373 */
3374 copydir(src_path, dst_path, false);
3375
3376 pfree(src_path);
3377 pfree(dst_path);
3378 }
3379 else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3380 {
3383 char *dbpath;
3384 char *parent_path;
3385
3386 dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3387
3388 /* create the parent directory if needed and valid */
3393
3394 /* Create the database directory with the version file. */
3395 CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3396 true);
3397 pfree(dbpath);
3398 }
3399 else if (info == XLOG_DBASE_DROP)
3400 {
3402 char *dst_path;
3403 int i;
3404
3405 if (InHotStandby)
3406 {
3407 /*
3408 * Lock database while we resolve conflicts to ensure that
3409 * InitPostgres() cannot fully re-execute concurrently. This
3410 * avoids backends re-connecting automatically to same database,
3411 * which can happen in some cases.
3412 *
3413 * This will lock out walsenders trying to connect to db-specific
3414 * slots for logical decoding too, so it's safe for us to drop
3415 * slots.
3416 */
3419 }
3420
3421 /* Drop any database-specific replication slots */
3423
3424 /* Drop pages for this database that are in the shared buffer cache */
3425 DropDatabaseBuffers(xlrec->db_id);
3426
3427 /* Also, clean out any fsync requests that might be pending in md.c */
3429
3430 /* Clean out the xlog relcache too */
3431 XLogDropDatabase(xlrec->db_id);
3432
3433 /* Close all smgr fds in all backends. */
3435
3436 for (i = 0; i < xlrec->ntablespaces; i++)
3437 {
3438 dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3439
3440 /* And remove the physical files */
3441 if (!rmtree(dst_path, true))
3443 (errmsg("some useless files may be left behind in old database directory \"%s\"",
3444 dst_path)));
3445 pfree(dst_path);
3446 }
3447
3448 if (InHotStandby)
3449 {
3450 /*
3451 * Release locks prior to commit. XXX There is a race condition
3452 * here that may allow backends to reconnect, but the window for
3453 * this is small because the gap between here and commit is mostly
3454 * fairly small and it is unlikely that people will be dropping
3455 * databases that we are trying to connect to anyway.
3456 */
3458 }
3459 }
3460 else
3461 elog(PANIC, "dbase_redo: unknown op code %u", info);
3462}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition acl.c:1120
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition acl.c:5554
void check_can_set_role(Oid member, Oid role)
Definition acl.c:5343
AclResult
Definition acl.h:182
@ ACLCHECK_OK
Definition acl.h:183
@ ACLCHECK_NOT_OWNER
Definition acl.h:185
#define DatumGetAclP(X)
Definition acl.h:120
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2654
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3854
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4108
bool directory_is_empty(const char *path)
Definition tablespace.c:860
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
bool allow_in_place_tablespaces
Definition tablespace.c:86
uint32 BlockNumber
Definition block.h:31
static Datum values[MAXATTR]
Definition bootstrap.c:147
int Buffer
Definition buf.h:23
void DropDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5031
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition bufmgr.c:4357
void CreateAndCopyRelationData(RelFileLocator src_rlocator, RelFileLocator dst_rlocator, bool permanent)
Definition bufmgr.c:5378
void UnlockReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5519
Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition bufmgr.c:949
void FlushDatabaseBuffers(Oid dbid)
Definition bufmgr.c:5442
@ BAS_BULKREAD
Definition bufmgr.h:37
static Page BufferGetPage(Buffer buffer)
Definition bufmgr.h:466
@ BUFFER_LOCK_SHARE
Definition bufmgr.h:210
static void LockBuffer(Buffer buffer, BufferLockMode mode)
Definition bufmgr.h:328
@ RBM_NORMAL
Definition bufmgr.h:46
static bool PageIsEmpty(const PageData *page)
Definition bufpage.h:223
static bool PageIsNew(const PageData *page)
Definition bufpage.h:233
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition bufpage.h:243
static void * PageGetItem(PageData *page, const ItemIdData *itemId)
Definition bufpage.h:353
PageData * Page
Definition bufpage.h:81
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition bufpage.h:371
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:798
uint8_t uint8
Definition c.h:577
#define Assert(condition)
Definition c.h:906
#define PG_BINARY
Definition c.h:1330
TransactionId MultiXactId
Definition c.h:709
uint32 TransactionId
Definition c.h:699
#define OidIsValid(objectId)
Definition c.h:821
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
void RequestCheckpoint(int flags)
void DeleteSharedComments(Oid oid, Oid classoid)
Definition comment.c:384
void copydir(const char *fromdir, const char *todir, bool recurse)
Definition copydir.c:48
static void remove_dbtablespaces(Oid db_id)
static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
Definition dbcommands.c:459
ObjectAddress AlterDatabaseRefreshColl(AlterDatabaseRefreshCollStmt *stmt)
bool have_createdb_privilege(void)
ObjectAddress RenameDatabase(const char *oldname, const char *newname)
Oid get_database_oid(const char *dbname, bool missing_ok)
CreateDBStrategy
Definition dbcommands.c:85
@ CREATEDB_FILE_COPY
Definition dbcommands.c:87
@ CREATEDB_WAL_LOG
Definition dbcommands.c:86
static void movedb_failure_callback(int code, Datum arg)
static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition dbcommands.c:150
static List * ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath)
Definition dbcommands.c:252
static void recovery_create_dbdir(char *path, bool only_tblspc)
ObjectAddress AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
bool database_is_invalid_form(Form_pg_database datform)
Datum pg_database_collation_actual_version(PG_FUNCTION_ARGS)
static void movedb(const char *dbname, const char *tblspcname)
static List * ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rlocatorlist, Snapshot snapshot)
Definition dbcommands.c:331
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Oid createdb(ParseState *pstate, const CreatedbStmt *stmt)
Definition dbcommands.c:686
Oid AlterDatabase(ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
static CreateDBRelInfo * ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
Definition dbcommands.c:394
static bool check_db_file_conflict(Oid db_id)
void dbase_redo(XLogReaderState *record)
static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid, Oid dst_tsid)
Definition dbcommands.c:553
void DropDatabase(ParseState *pstate, DropdbStmt *stmt)
void dropdb(const char *dbname, bool missing_ok, bool force)
Oid AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, bool *dbHasLoginEvtP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbLocale, char **dbIcurules, char *dbLocProvider, char **dbCollversion)
static void createdb_failure_callback(int code, Datum arg)
bool database_is_invalid_oid(Oid dboid)
#define XLOG_DBASE_CREATE_WAL_LOG
#define XLOG_DBASE_DROP
#define MinSizeOfDbaseDropRec
#define XLOG_DBASE_CREATE_FILE_COPY
int32 defGetInt32(DefElem *def)
Definition define.c:148
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition define.c:370
Oid defGetObjectId(DefElem *def)
Definition define.c:205
Datum arg
Definition elog.c:1322
int errcode_for_file_access(void)
Definition elog.c:897
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
#define WARNING
Definition elog.h:36
#define PANIC
Definition elog.h:42
#define DEBUG1
Definition elog.h:30
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define NOTICE
Definition elog.h:35
#define ereport(elevel,...)
Definition elog.h:150
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
bool is_encoding_supported_by_icu(int encoding)
Definition encnames.c:461
int MakePGDirectory(const char *directoryName)
Definition fd.c:3962
int FreeDir(DIR *dir)
Definition fd.c:3008
int CloseTransientFile(int fd)
Definition fd.c:2854
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:756
int data_sync_elevel(int elevel)
Definition fd.c:3985
DIR * AllocateDir(const char *dirname)
Definition fd.c:2890
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2956
int pg_fsync(int fd)
Definition fd.c:389
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2677
#define palloc_object(type)
Definition fe_memutils.h:74
static char dstpath[MAXPGPATH]
Definition file_ops.c:32
int pg_dir_create_mode
Definition file_perm.c:18
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
#define PG_RETURN_NULL()
Definition fmgr.h:346
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition freelist.c:461
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
void systable_inplace_update_begin(Relation relation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, const ScanKeyData *key, HeapTuple *oldtupcopy, void **state)
Definition genam.c:808
void systable_inplace_update_finish(void *state, HeapTuple tuple)
Definition genam.c:884
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
bool IsBinaryUpgrade
Definition globals.c:121
bool IsUnderPostmaster
Definition globals.c:120
bool allowSystemTableMods
Definition globals.c:130
Oid MyDatabaseId
Definition globals.c:94
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1410
bool HeapTupleSatisfiesVisibility(HeapTuple htup, Snapshot snapshot, Buffer buffer)
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1117
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
HeapTupleHeaderData * HeapTupleHeader
Definition htup.h:23
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
static char * encoding
Definition initdb.c:139
#define write(a, b, c)
Definition win32.h:14
#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
invalidindex index d is invalid
Definition isn.c:138
int i
Definition isn.c:77
#define ItemIdGetLength(itemId)
Definition itemid.h:59
#define ItemIdIsNormal(itemId)
Definition itemid.h:99
#define ItemIdIsDead(itemId)
Definition itemid.h:113
#define ItemIdIsUsed(itemId)
Definition itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition itemid.h:106
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition itemptr.h:135
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free(List *list)
Definition list.c:1546
void list_free_deep(List *list)
Definition list.c:1560
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1187
void UnlockRelationId(LockRelId *relid, LOCKMODE lockmode)
Definition lmgr.c:214
void LockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:562
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1148
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1169
void LockRelationId(LockRelId *relid, LOCKMODE lockmode)
Definition lmgr.c:185
int LOCKMODE
Definition lockdefs.h:26
#define NoLock
Definition lockdefs.h:34
#define AccessExclusiveLock
Definition lockdefs.h:43
#define AccessShareLock
Definition lockdefs.h:36
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
#define ShareLock
Definition lockdefs.h:40
#define RowExclusiveLock
Definition lockdefs.h:38
char * get_database_name(Oid dbid)
Definition lsyscache.c:1242
#define PG_UTF8
Definition mbprint.c:43
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
void ForgetDatabaseSyncRequests(Oid dbid)
Definition md.c:1593
#define START_CRIT_SECTION()
Definition miscadmin.h:150
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define END_CRIT_SECTION()
Definition miscadmin.h:152
Oid GetUserId(void)
Definition miscinit.c:469
#define InvalidMultiXactId
Definition multixact.h:25
void namestrcpy(Name name, const char *str)
Definition name.c:233
Datum namein(PG_FUNCTION_ARGS)
Definition name.c:48
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define InvokeObjectPostCreateHook(classId, objectId, subId)
#define InvokeObjectPostAlterHook(classId, objectId, subId)
#define InvokeObjectDropHook(classId, objectId, subId)
#define ObjectAddressSet(addr, class_id, object_id)
#define OffsetNumberNext(offsetNumber)
Definition off.h:52
uint16 OffsetNumber
Definition off.h:24
#define FirstOffsetNumber
Definition off.h:27
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
@ OBJECT_TABLESPACE
@ OBJECT_DATABASE
#define ACL_CREATE
Definition parsenodes.h:85
END_CATALOG_STRUCT typedef FormData_pg_authid * Form_pg_authid
Definition pg_authid.h:60
bool rolcreatedb
Definition pg_authid.h:40
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
#define MAXPGPATH
char datlocprovider
Definition pg_database.h:46
NameData datname
Definition pg_database.h:37
#define DATCONNLIMIT_INVALID_DB
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
#define DATCONNLIMIT_UNLIMITED
void DropSetting(Oid databaseid, Oid roleid)
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define lfirst_oid(lc)
Definition pg_list.h:174
int icu_validation_level
Definition pg_locale.c:92
void icu_validate_locale(const char *loc_str)
Definition pg_locale.c:1789
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition pg_locale.c:1247
char * icu_language_tag(const char *loc_str, int elevel)
Definition pg_locale.c:1731
const char * builtin_validate_locale(int encoding, const char *locale)
Definition pg_locale.c:1691
bool check_locale(int category, const char *locale, char **canonname)
Definition pg_locale.c:275
void dropDatabaseDependencies(Oid databaseId)
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
void shdepLockAndCheckObject(Oid classId, Oid objectId)
int CountDBSubscriptions(Oid dbid)
END_CATALOG_STRUCT typedef FormData_pg_tablespace * Form_pg_tablespace
static char buf[DEFAULT_XLOG_SEG_SIZE]
@ PG_SQL_ASCII
Definition pg_wchar.h:226
#define PG_VALID_BE_ENCODING(_enc)
Definition pg_wchar.h:281
#define pg_encoding_to_char
Definition pg_wchar.h:630
#define pg_valid_server_encoding
Definition pg_wchar.h:631
void pgstat_drop_database(Oid databaseid)
int pg_mkdir_p(char *path, int omode)
Definition pgmkdirp.c:57
int pg_strcasecmp(const char *s1, const char *s2)
#define sprintf
Definition port.h:262
void get_parent_directory(char *path)
Definition path.c:1068
#define snprintf
Definition port.h:260
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition chklocale.c:301
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum TransactionIdGetDatum(TransactionId X)
Definition postgres.h:302
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static Datum CStringGetDatum(const char *X)
Definition postgres.h:380
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
static Datum CharGetDatum(char X)
Definition postgres.h:132
#define InvalidOid
unsigned int Oid
static int fd(const char *x, int i)
static int fb(int x)
void TerminateOtherDBBackends(Oid databaseId)
Definition procarray.c:3839
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition procarray.c:3746
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
void WaitForProcSignalBarrier(uint64 generation)
Definition procsignal.c:426
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition procsignal.c:358
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition procsignal.h:48
#define RelationGetDescr(relation)
Definition rel.h:540
RelFileNumber RelationMapOidToFilenumberForDatabase(char *dbpath, Oid relationId)
Definition relmapper.c:265
void RelationMapCopy(Oid dbid, Oid tsid, char *srcdbpath, char *dstdbpath)
Definition relmapper.c:292
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition relpath.c:110
#define PG_TBLSPC_DIR_SLASH
Definition relpath.h:42
Oid RelFileNumber
Definition relpath.h:25
@ MAIN_FORKNUM
Definition relpath.h:58
#define InvalidRelFileNumber
Definition relpath.h:26
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27
bool rmtree(const char *path, bool rmtopdir)
Definition rmtree.c:50
const char * quote_identifier(const char *ident)
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition seclabel.c:501
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition slot.c:1449
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition slot.c:1510
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:819
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
void smgrclose(SMgrRelation reln)
Definition smgr.c:374
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
void PopActiveSnapshot(void)
Definition snapmgr.c:775
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition standby.c:570
#define BTEqualStrategyNumber
Definition stratnum.h:31
char * dbname
Definition streamutil.c:49
RelFileLocator rlocator
Definition dbcommands.c:108
Definition dirent.c:26
char * defname
Definition parsenodes.h:844
ParseLoc location
Definition parsenodes.h:848
ItemPointerData t_self
Definition htup.h:65
uint32 t_len
Definition htup.h:64
HeapTupleHeader t_data
Definition htup.h:68
Oid t_tableOid
Definition htup.h:66
Definition pg_list.h:54
Oid relId
Definition rel.h:40
Oid dbId
Definition rel.h:41
RelFileNumber relNumber
CreateDBStrategy strategy
Definition dbcommands.c:94
unsigned short st_mode
Definition win32_port.h:258
bool superuser(void)
Definition superuser.c:47
HeapTuple SearchSysCacheLockedCopy1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:399
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1004
#define InvalidTransactionId
Definition transam.h:31
#define FirstNormalObjectId
Definition transam.h:197
text * cstring_to_text(const char *s)
Definition varlena.c:182
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:69
static void pgstat_report_wait_end(void)
Definition wait_event.h:85
const char * name
#define stat
Definition win32_port.h:74
#define lstat(path, sb)
Definition win32_port.h:275
#define S_ISDIR(m)
Definition win32_port.h:315
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition xact.c:3669
void StartTransactionCommand(void)
Definition xact.c:3080
void ForceSyncCommit(void)
Definition xact.c:1153
void CommitTransactionCommand(void)
Definition xact.c:3178
bool RecoveryInProgress(void)
Definition xlog.c:6443
XLogRecPtr XactLastRecEnd
Definition xlog.c:257
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2766
#define CHECKPOINT_FLUSH_UNLOGGED
Definition xlog.h:154
#define CHECKPOINT_FORCE
Definition xlog.h:153
#define CHECKPOINT_WAIT
Definition xlog.h:156
#define CHECKPOINT_FAST
Definition xlog.h:152
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:478
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:368
void XLogBeginInsert(void)
Definition xloginsert.c:152
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:409
#define XLogRecGetData(decoder)
Definition xlogreader.h:414
#define XLogRecHasAnyBlockRefs(decoder)
Definition xlogreader.h:416
#define XLR_SPECIAL_REL_UPDATE
Definition xlogrecord.h:82
bool reachedConsistency
void XLogDropDatabase(Oid dbid)
Definition xlogutils.c:641
#define InHotStandby
Definition xlogutils.h:60