PostgreSQL Source Code  git master
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-2022, 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/xlogutils.h"
34 #include "catalog/catalog.h"
35 #include "catalog/dependency.h"
36 #include "catalog/indexing.h"
37 #include "catalog/objectaccess.h"
38 #include "catalog/pg_authid.h"
39 #include "catalog/pg_collation.h"
40 #include "catalog/pg_database.h"
43 #include "catalog/pg_tablespace.h"
44 #include "commands/comment.h"
45 #include "commands/dbcommands.h"
47 #include "commands/defrem.h"
48 #include "commands/seclabel.h"
49 #include "commands/tablespace.h"
50 #include "mb/pg_wchar.h"
51 #include "miscadmin.h"
52 #include "pgstat.h"
53 #include "postmaster/bgwriter.h"
54 #include "replication/slot.h"
55 #include "storage/copydir.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "storage/lmgr.h"
59 #include "storage/md.h"
60 #include "storage/procarray.h"
61 #include "storage/smgr.h"
62 #include "utils/acl.h"
63 #include "utils/builtins.h"
64 #include "utils/fmgroids.h"
65 #include "utils/pg_locale.h"
66 #include "utils/relmapper.h"
67 #include "utils/snapmgr.h"
68 #include "utils/syscache.h"
69 
70 /*
71  * Create database strategy.
72  *
73  * CREATEDB_WAL_LOG will copy the database at the block level and WAL log each
74  * copied block.
75  *
76  * CREATEDB_FILE_COPY will simply perform a file system level copy of the
77  * database and log a single record for each tablespace copied. To make this
78  * safe, it also triggers checkpoints before and after the operation.
79  */
80 typedef enum CreateDBStrategy
81 {
85 
86 typedef struct
87 {
88  Oid src_dboid; /* source (template) DB */
89  Oid dest_dboid; /* DB we are trying to create */
90  CreateDBStrategy strategy; /* create db strategy */
92 
93 typedef struct
94 {
95  Oid dest_dboid; /* DB we are trying to move */
96  Oid dest_tsoid; /* tablespace we are trying to move to */
98 
99 /*
100  * Information about a relation to be copied when creating a database.
101  */
102 typedef struct CreateDBRelInfo
103 {
104  RelFileNode rnode; /* physical relation identifier */
105  Oid reloid; /* relation oid */
106  bool permanent; /* relation is permanent or unlogged */
108 
109 
110 /* non-export function prototypes */
111 static void createdb_failure_callback(int code, Datum arg);
112 static void movedb(const char *dbname, const char *tblspcname);
113 static void movedb_failure_callback(int code, Datum arg);
114 static bool get_db_info(const char *name, LOCKMODE lockmode,
115  Oid *dbIdP, Oid *ownerIdP,
116  int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
117  TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP,
118  Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbIculocale,
119  char *dbLocProvider,
120  char **dbCollversion);
121 static bool have_createdb_privilege(void);
122 static void remove_dbtablespaces(Oid db_id);
123 static bool check_db_file_conflict(Oid db_id);
124 static int errdetail_busy_db(int notherbackends, int npreparedxacts);
125 static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dboid, Oid src_tsid,
126  Oid dst_tsid);
127 static List *ScanSourceDatabasePgClass(Oid srctbid, Oid srcdbid, char *srcpath);
129  Oid dbid, char *srcpath,
130  List *rnodelist, Snapshot snapshot);
132  Oid tbid, Oid dbid,
133  char *srcpath);
134 static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid,
135  bool isRedo);
136 static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dboid, Oid src_tsid,
137  Oid dst_tsid);
138 
139 /*
140  * Create a new database using the WAL_LOG strategy.
141  *
142  * Each copied block is separately written to the write-ahead log.
143  */
144 static void
145 CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid,
146  Oid src_tsid, Oid dst_tsid)
147 {
148  char *srcpath;
149  char *dstpath;
150  List *rnodelist = NULL;
151  ListCell *cell;
152  LockRelId srcrelid;
153  LockRelId dstrelid;
154  RelFileNode srcrnode;
155  RelFileNode dstrnode;
156  CreateDBRelInfo *relinfo;
157 
158  /* Get source and destination database paths. */
159  srcpath = GetDatabasePath(src_dboid, src_tsid);
160  dstpath = GetDatabasePath(dst_dboid, dst_tsid);
161 
162  /* Create database directory and write PG_VERSION file. */
163  CreateDirAndVersionFile(dstpath, dst_dboid, dst_tsid, false);
164 
165  /* Copy relmap file from source database to the destination database. */
166  RelationMapCopy(dst_dboid, dst_tsid, srcpath, dstpath);
167 
168  /* Get list of relfilenodes to copy from the source database. */
169  rnodelist = ScanSourceDatabasePgClass(src_tsid, src_dboid, srcpath);
170  Assert(rnodelist != NIL);
171 
172  /*
173  * Database IDs will be the same for all relations so set them before
174  * entering the loop.
175  */
176  srcrelid.dbId = src_dboid;
177  dstrelid.dbId = dst_dboid;
178 
179  /* Loop over our list of relfilenodes and copy each one. */
180  foreach(cell, rnodelist)
181  {
182  relinfo = lfirst(cell);
183  srcrnode = relinfo->rnode;
184 
185  /*
186  * If the relation is from the source db's default tablespace then we
187  * need to create it in the destinations db's default tablespace.
188  * Otherwise, we need to create in the same tablespace as it is in the
189  * source database.
190  */
191  if (srcrnode.spcNode == src_tsid)
192  dstrnode.spcNode = dst_tsid;
193  else
194  dstrnode.spcNode = srcrnode.spcNode;
195 
196  dstrnode.dbNode = dst_dboid;
197  dstrnode.relNode = srcrnode.relNode;
198 
199  /*
200  * Acquire locks on source and target relations before copying.
201  *
202  * We typically do not read relation data into shared_buffers without
203  * holding a relation lock. It's unclear what could go wrong if we
204  * skipped it in this case, because nobody can be modifying either the
205  * source or destination database at this point, and we have locks on
206  * both databases, too, but let's take the conservative route.
207  */
208  dstrelid.relId = srcrelid.relId = relinfo->reloid;
209  LockRelationId(&srcrelid, AccessShareLock);
210  LockRelationId(&dstrelid, AccessShareLock);
211 
212  /* Copy relation storage from source to the destination. */
213  CreateAndCopyRelationData(srcrnode, dstrnode, relinfo->permanent);
214 
215  /* Release the relation locks. */
216  UnlockRelationId(&srcrelid, AccessShareLock);
217  UnlockRelationId(&dstrelid, AccessShareLock);
218  }
219 
220  pfree(srcpath);
221  pfree(dstpath);
222  list_free_deep(rnodelist);
223 }
224 
225 /*
226  * Scan the pg_class table in the source database to identify the relations
227  * that need to be copied to the destination database.
228  *
229  * This is an exception to the usual rule that cross-database access is
230  * not possible. We can make it work here because we know that there are no
231  * connections to the source database and (since there can't be prepared
232  * transactions touching that database) no in-doubt tuples either. This
233  * means that we don't need to worry about pruning removing anything from
234  * under us, and we don't need to be too picky about our snapshot either.
235  * As long as it sees all previously-committed XIDs as committed and all
236  * aborted XIDs as aborted, we should be fine: nothing else is possible
237  * here.
238  *
239  * We can't rely on the relcache for anything here, because that only knows
240  * about the database to which we are connected, and can't handle access to
241  * other databases. That also means we can't rely on the heap scan
242  * infrastructure, which would be a bad idea anyway since it might try
243  * to do things like HOT pruning which we definitely can't do safely in
244  * a database to which we're not even connected.
245  */
246 static List *
247 ScanSourceDatabasePgClass(Oid tbid, Oid dbid, char *srcpath)
248 {
249  RelFileNode rnode;
250  BlockNumber nblocks;
251  BlockNumber blkno;
252  Buffer buf;
253  Oid relfilenode;
254  Page page;
255  List *rnodelist = NIL;
256  LockRelId relid;
257  Relation rel;
258  Snapshot snapshot;
259  BufferAccessStrategy bstrategy;
260 
261  /* Get pg_class relfilenode. */
262  relfilenode = RelationMapOidToFilenodeForDatabase(srcpath,
263  RelationRelationId);
264 
265  /* Don't read data into shared_buffers without holding a relation lock. */
266  relid.dbId = dbid;
267  relid.relId = RelationRelationId;
269 
270  /* Prepare a RelFileNode for the pg_class relation. */
271  rnode.spcNode = tbid;
272  rnode.dbNode = dbid;
273  rnode.relNode = relfilenode;
274 
275  /*
276  * We can't use a real relcache entry for a relation in some other
277  * database, but since we're only going to access the fields related to
278  * physical storage, a fake one is good enough. If we didn't do this and
279  * used the smgr layer directly, we would have to worry about
280  * invalidations.
281  */
282  rel = CreateFakeRelcacheEntry(rnode);
283  nblocks = smgrnblocks(RelationGetSmgr(rel), MAIN_FORKNUM);
285 
286  /* Use a buffer access strategy since this is a bulk read operation. */
287  bstrategy = GetAccessStrategy(BAS_BULKREAD);
288 
289  /*
290  * As explained in the function header comments, we need a snapshot that
291  * will see all committed transactions as committed, and our transaction
292  * snapshot - or the active snapshot - might not be new enough for that,
293  * but the return value of GetLatestSnapshot() should work fine.
294  */
295  snapshot = GetLatestSnapshot();
296 
297  /* Process the relation block by block. */
298  for (blkno = 0; blkno < nblocks; blkno++)
299  {
301 
303  RBM_NORMAL, bstrategy, false);
304 
306  page = BufferGetPage(buf);
307  if (PageIsNew(page) || PageIsEmpty(page))
308  {
310  continue;
311  }
312 
313  /* Append relevant pg_class tuples for current page to rnodelist. */
314  rnodelist = ScanSourceDatabasePgClassPage(page, buf, tbid, dbid,
315  srcpath, rnodelist,
316  snapshot);
317 
319  }
320 
321  /* Release relation lock. */
323 
324  return rnodelist;
325 }
326 
327 /*
328  * Scan one page of the source database's pg_class relation and add relevant
329  * entries to rnodelist. The return value is the updated list.
330  */
331 static List *
333  char *srcpath, List *rnodelist,
334  Snapshot snapshot)
335 {
337  OffsetNumber offnum;
338  OffsetNumber maxoff;
339  HeapTupleData tuple;
340 
341  maxoff = PageGetMaxOffsetNumber(page);
342 
343  /* Loop over offsets. */
344  for (offnum = FirstOffsetNumber;
345  offnum <= maxoff;
346  offnum = OffsetNumberNext(offnum))
347  {
348  ItemId itemid;
349 
350  itemid = PageGetItemId(page, offnum);
351 
352  /* Nothing to do if slot is empty or already dead. */
353  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid) ||
354  ItemIdIsRedirected(itemid))
355  continue;
356 
357  Assert(ItemIdIsNormal(itemid));
358  ItemPointerSet(&(tuple.t_self), blkno, offnum);
359 
360  /* Initialize a HeapTupleData structure. */
361  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
362  tuple.t_len = ItemIdGetLength(itemid);
363  tuple.t_tableOid = RelationRelationId;
364 
365  /* Skip tuples that are not visible to this snapshot. */
366  if (HeapTupleSatisfiesVisibility(&tuple, snapshot, buf))
367  {
368  CreateDBRelInfo *relinfo;
369 
370  /*
371  * ScanSourceDatabasePgClassTuple is in charge of constructing a
372  * CreateDBRelInfo object for this tuple, but can also decide that
373  * this tuple isn't something we need to copy. If we do need to
374  * copy the relation, add it to the list.
375  */
376  relinfo = ScanSourceDatabasePgClassTuple(&tuple, tbid, dbid,
377  srcpath);
378  if (relinfo != NULL)
379  rnodelist = lappend(rnodelist, relinfo);
380  }
381  }
382 
383  return rnodelist;
384 }
385 
386 /*
387  * Decide whether a certain pg_class tuple represents something that
388  * needs to be copied from the source database to the destination database,
389  * and if so, construct a CreateDBRelInfo for it.
390  *
391  * Visibility checks are handled by the caller, so our job here is just
392  * to assess the data stored in the tuple.
393  */
396  char *srcpath)
397 {
398  CreateDBRelInfo *relinfo;
399  Form_pg_class classForm;
400  Oid relfilenode = InvalidOid;
401 
402  classForm = (Form_pg_class) GETSTRUCT(tuple);
403 
404  /*
405  * Return NULL if this object does not need to be copied.
406  *
407  * Shared objects don't need to be copied, because they are shared.
408  * Objects without storage can't be copied, because there's nothing to
409  * copy. Temporary relations don't need to be copied either, because they
410  * are inaccessible outside of the session that created them, which must
411  * be gone already, and couldn't connect to a different database if it
412  * still existed. autovacuum will eventually remove the pg_class entries
413  * as well.
414  */
415  if (classForm->reltablespace == GLOBALTABLESPACE_OID ||
416  !RELKIND_HAS_STORAGE(classForm->relkind) ||
417  classForm->relpersistence == RELPERSISTENCE_TEMP)
418  return NULL;
419 
420  /*
421  * If relfilenode is valid then directly use it. Otherwise, consult the
422  * relmap.
423  */
424  if (OidIsValid(classForm->relfilenode))
425  relfilenode = classForm->relfilenode;
426  else
427  relfilenode = RelationMapOidToFilenodeForDatabase(srcpath,
428  classForm->oid);
429 
430  /* We must have a valid relfilenode oid. */
431  if (!OidIsValid(relfilenode))
432  elog(ERROR, "relation with OID %u does not have a valid relfilenode",
433  classForm->oid);
434 
435  /* Prepare a rel info element and add it to the list. */
436  relinfo = (CreateDBRelInfo *) palloc(sizeof(CreateDBRelInfo));
437  if (OidIsValid(classForm->reltablespace))
438  relinfo->rnode.spcNode = classForm->reltablespace;
439  else
440  relinfo->rnode.spcNode = tbid;
441 
442  relinfo->rnode.dbNode = dbid;
443  relinfo->rnode.relNode = relfilenode;
444  relinfo->reloid = classForm->oid;
445 
446  /* Temporary relations were rejected above. */
447  Assert(classForm->relpersistence != RELPERSISTENCE_TEMP);
448  relinfo->permanent =
449  (classForm->relpersistence == RELPERSISTENCE_PERMANENT) ? true : false;
450 
451  return relinfo;
452 }
453 
454 /*
455  * Create database directory and write out the PG_VERSION file in the database
456  * path. If isRedo is true, it's okay for the database directory to exist
457  * already.
458  */
459 static void
460 CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
461 {
462  int fd;
463  int nbytes;
464  char versionfile[MAXPGPATH];
465  char buf[16];
466 
467  /*
468  * Prepare version data before starting a critical section.
469  *
470  * Note that we don't have to copy this from the source database; there's
471  * only one legal value.
472  */
473  sprintf(buf, "%s\n", PG_MAJORVERSION);
474  nbytes = strlen(PG_MAJORVERSION) + 1;
475 
476  /* If we are not in WAL replay then write the WAL. */
477  if (!isRedo)
478  {
480  XLogRecPtr lsn;
481 
483 
484  xlrec.db_id = dbid;
485  xlrec.tablespace_id = tsid;
486 
487  XLogBeginInsert();
488  XLogRegisterData((char *) (&xlrec),
490 
491  lsn = XLogInsert(RM_DBASE_ID, XLOG_DBASE_CREATE_WAL_LOG);
492 
493  /* As always, WAL must hit the disk before the data update does. */
494  XLogFlush(lsn);
495  }
496 
497  /* Create database directory. */
498  if (MakePGDirectory(dbpath) < 0)
499  {
500  /* Failure other than already exists or not in WAL replay? */
501  if (errno != EEXIST || !isRedo)
502  ereport(ERROR,
504  errmsg("could not create directory \"%s\": %m", dbpath)));
505  }
506 
507  /*
508  * Create PG_VERSION file in the database path. If the file already
509  * exists and we are in WAL replay then try again to open it in write
510  * mode.
511  */
512  snprintf(versionfile, sizeof(versionfile), "%s/%s", dbpath, "PG_VERSION");
513 
514  fd = OpenTransientFile(versionfile, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY);
515  if (fd < 0 && errno == EEXIST && isRedo)
516  fd = OpenTransientFile(versionfile, O_WRONLY | O_TRUNC | PG_BINARY);
517 
518  if (fd < 0)
519  ereport(ERROR,
521  errmsg("could not create file \"%s\": %m", versionfile)));
522 
523  /* Write PG_MAJORVERSION in the PG_VERSION file. */
525  errno = 0;
526  if ((int) write(fd, buf, nbytes) != nbytes)
527  {
528  /* If write didn't set errno, assume problem is no disk space. */
529  if (errno == 0)
530  errno = ENOSPC;
531  ereport(ERROR,
533  errmsg("could not write to file \"%s\": %m", versionfile)));
534  }
536 
537  /* Close the version file. */
539 
540  /* Critical section done. */
541  if (!isRedo)
543 }
544 
545 /*
546  * Create a new database using the FILE_COPY strategy.
547  *
548  * Copy each tablespace at the filesystem level, and log a single WAL record
549  * for each tablespace copied. This requires a checkpoint before and after the
550  * copy, which may be expensive, but it does greatly reduce WAL generation
551  * if the copied database is large.
552  */
553 static void
554 CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dst_dboid, Oid src_tsid,
555  Oid dst_tsid)
556 {
557  TableScanDesc scan;
558  Relation rel;
559  HeapTuple tuple;
560 
561  /*
562  * Force a checkpoint before starting the copy. This will force all dirty
563  * buffers, including those of unlogged tables, out to disk, to ensure
564  * source database is up-to-date on disk for the copy.
565  * FlushDatabaseBuffers() would suffice for that, but we also want to
566  * process any pending unlink requests. Otherwise, if a checkpoint
567  * happened while we're copying files, a file might be deleted just when
568  * we're about to copy it, causing the lstat() call in copydir() to fail
569  * with ENOENT.
570  */
573 
574  /*
575  * Iterate through all tablespaces of the template database, and copy each
576  * one to the new database.
577  */
578  rel = table_open(TableSpaceRelationId, AccessShareLock);
579  scan = table_beginscan_catalog(rel, 0, NULL);
580  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
581  {
582  Form_pg_tablespace spaceform = (Form_pg_tablespace) GETSTRUCT(tuple);
583  Oid srctablespace = spaceform->oid;
584  Oid dsttablespace;
585  char *srcpath;
586  char *dstpath;
587  struct stat st;
588 
589  /* No need to copy global tablespace */
590  if (srctablespace == GLOBALTABLESPACE_OID)
591  continue;
592 
593  srcpath = GetDatabasePath(src_dboid, srctablespace);
594 
595  if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
596  directory_is_empty(srcpath))
597  {
598  /* Assume we can ignore it */
599  pfree(srcpath);
600  continue;
601  }
602 
603  if (srctablespace == src_tsid)
604  dsttablespace = dst_tsid;
605  else
606  dsttablespace = srctablespace;
607 
608  dstpath = GetDatabasePath(dst_dboid, dsttablespace);
609 
610  /*
611  * Copy this subdirectory to the new location
612  *
613  * We don't need to copy subdirectories
614  */
615  copydir(srcpath, dstpath, false);
616 
617  /* Record the filesystem change in XLOG */
618  {
620 
621  xlrec.db_id = dst_dboid;
622  xlrec.tablespace_id = dsttablespace;
623  xlrec.src_db_id = src_dboid;
624  xlrec.src_tablespace_id = srctablespace;
625 
626  XLogBeginInsert();
627  XLogRegisterData((char *) &xlrec,
629 
630  (void) XLogInsert(RM_DBASE_ID,
632  }
633  pfree(srcpath);
634  pfree(dstpath);
635  }
636  table_endscan(scan);
638 
639  /*
640  * We force a checkpoint before committing. This effectively means that
641  * committed XLOG_DBASE_CREATE_FILE_COPY operations will never need to be
642  * replayed (at least not in ordinary crash recovery; we still have to
643  * make the XLOG entry for the benefit of PITR operations). This avoids
644  * two nasty scenarios:
645  *
646  * #1: When PITR is off, we don't XLOG the contents of newly created
647  * indexes; therefore the drop-and-recreate-whole-directory behavior of
648  * DBASE_CREATE replay would lose such indexes.
649  *
650  * #2: Since we have to recopy the source database during DBASE_CREATE
651  * replay, we run the risk of copying changes in it that were committed
652  * after the original CREATE DATABASE command but before the system crash
653  * that led to the replay. This is at least unexpected and at worst could
654  * lead to inconsistencies, eg duplicate table names.
655  *
656  * (Both of these were real bugs in releases 8.0 through 8.0.3.)
657  *
658  * In PITR replay, the first of these isn't an issue, and the second is
659  * only a risk if the CREATE DATABASE and subsequent template database
660  * change both occur while a base backup is being taken. There doesn't
661  * seem to be much we can do about that except document it as a
662  * limitation.
663  *
664  * See CreateDatabaseUsingWalLog() for a less cheesy CREATE DATABASE
665  * strategy that avoids these problems.
666  */
668 }
669 
670 /*
671  * CREATE DATABASE
672  */
673 Oid
674 createdb(ParseState *pstate, const CreatedbStmt *stmt)
675 {
676  Oid src_dboid;
677  Oid src_owner;
678  int src_encoding = -1;
679  char *src_collate = NULL;
680  char *src_ctype = NULL;
681  char *src_iculocale = NULL;
682  char src_locprovider = '\0';
683  char *src_collversion = NULL;
684  bool src_istemplate;
685  bool src_allowconn;
686  TransactionId src_frozenxid = InvalidTransactionId;
687  MultiXactId src_minmxid = InvalidMultiXactId;
688  Oid src_deftablespace;
689  volatile Oid dst_deftablespace;
690  Relation pg_database_rel;
691  HeapTuple tuple;
692  Datum new_record[Natts_pg_database];
693  bool new_record_nulls[Natts_pg_database];
694  Oid dboid = InvalidOid;
695  Oid datdba;
696  ListCell *option;
697  DefElem *dtablespacename = NULL;
698  DefElem *downer = NULL;
699  DefElem *dtemplate = NULL;
700  DefElem *dencoding = NULL;
701  DefElem *dlocale = NULL;
702  DefElem *dcollate = NULL;
703  DefElem *dctype = NULL;
704  DefElem *diculocale = NULL;
705  DefElem *dlocprovider = NULL;
706  DefElem *distemplate = NULL;
707  DefElem *dallowconnections = NULL;
708  DefElem *dconnlimit = NULL;
709  DefElem *dcollversion = NULL;
710  DefElem *dstrategy = NULL;
711  char *dbname = stmt->dbname;
712  char *dbowner = NULL;
713  const char *dbtemplate = NULL;
714  char *dbcollate = NULL;
715  char *dbctype = NULL;
716  char *dbiculocale = NULL;
717  char dblocprovider = '\0';
718  char *canonname;
719  int encoding = -1;
720  bool dbistemplate = false;
721  bool dballowconnections = true;
722  int dbconnlimit = -1;
723  char *dbcollversion = NULL;
724  int notherbackends;
725  int npreparedxacts;
726  CreateDBStrategy dbstrategy = CREATEDB_WAL_LOG;
728 
729  /* Extract options from the statement node tree */
730  foreach(option, stmt->options)
731  {
732  DefElem *defel = (DefElem *) lfirst(option);
733 
734  if (strcmp(defel->defname, "tablespace") == 0)
735  {
736  if (dtablespacename)
737  errorConflictingDefElem(defel, pstate);
738  dtablespacename = defel;
739  }
740  else if (strcmp(defel->defname, "owner") == 0)
741  {
742  if (downer)
743  errorConflictingDefElem(defel, pstate);
744  downer = defel;
745  }
746  else if (strcmp(defel->defname, "template") == 0)
747  {
748  if (dtemplate)
749  errorConflictingDefElem(defel, pstate);
750  dtemplate = defel;
751  }
752  else if (strcmp(defel->defname, "encoding") == 0)
753  {
754  if (dencoding)
755  errorConflictingDefElem(defel, pstate);
756  dencoding = defel;
757  }
758  else if (strcmp(defel->defname, "locale") == 0)
759  {
760  if (dlocale)
761  errorConflictingDefElem(defel, pstate);
762  dlocale = defel;
763  }
764  else if (strcmp(defel->defname, "lc_collate") == 0)
765  {
766  if (dcollate)
767  errorConflictingDefElem(defel, pstate);
768  dcollate = defel;
769  }
770  else if (strcmp(defel->defname, "lc_ctype") == 0)
771  {
772  if (dctype)
773  errorConflictingDefElem(defel, pstate);
774  dctype = defel;
775  }
776  else if (strcmp(defel->defname, "icu_locale") == 0)
777  {
778  if (diculocale)
779  errorConflictingDefElem(defel, pstate);
780  diculocale = defel;
781  }
782  else if (strcmp(defel->defname, "locale_provider") == 0)
783  {
784  if (dlocprovider)
785  errorConflictingDefElem(defel, pstate);
786  dlocprovider = defel;
787  }
788  else if (strcmp(defel->defname, "is_template") == 0)
789  {
790  if (distemplate)
791  errorConflictingDefElem(defel, pstate);
792  distemplate = defel;
793  }
794  else if (strcmp(defel->defname, "allow_connections") == 0)
795  {
796  if (dallowconnections)
797  errorConflictingDefElem(defel, pstate);
798  dallowconnections = defel;
799  }
800  else if (strcmp(defel->defname, "connection_limit") == 0)
801  {
802  if (dconnlimit)
803  errorConflictingDefElem(defel, pstate);
804  dconnlimit = defel;
805  }
806  else if (strcmp(defel->defname, "collation_version") == 0)
807  {
808  if (dcollversion)
809  errorConflictingDefElem(defel, pstate);
810  dcollversion = defel;
811  }
812  else if (strcmp(defel->defname, "location") == 0)
813  {
815  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
816  errmsg("LOCATION is not supported anymore"),
817  errhint("Consider using tablespaces instead."),
818  parser_errposition(pstate, defel->location)));
819  }
820  else if (strcmp(defel->defname, "oid") == 0)
821  {
822  dboid = defGetInt32(defel);
823 
824  /*
825  * We don't normally permit new databases to be created with
826  * system-assigned OIDs. pg_upgrade tries to preserve database
827  * OIDs, so we can't allow any database to be created with an OID
828  * that might be in use in a freshly-initialized cluster created
829  * by some future version. We assume all such OIDs will be from
830  * the system-managed OID range.
831  *
832  * As an exception, however, we permit any OID to be assigned when
833  * allow_system_table_mods=on (so that initdb can assign system
834  * OIDs to template0 and postgres) or when performing a binary
835  * upgrade (so that pg_upgrade can preserve whatever OIDs it finds
836  * in the source cluster).
837  */
838  if (dboid < FirstNormalObjectId &&
840  ereport(ERROR,
841  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
842  errmsg("OIDs less than %u are reserved for system objects", FirstNormalObjectId));
843  }
844  else if (strcmp(defel->defname, "strategy") == 0)
845  {
846  if (dstrategy)
847  errorConflictingDefElem(defel, pstate);
848  dstrategy = defel;
849  }
850  else
851  ereport(ERROR,
852  (errcode(ERRCODE_SYNTAX_ERROR),
853  errmsg("option \"%s\" not recognized", defel->defname),
854  parser_errposition(pstate, defel->location)));
855  }
856 
857  if (downer && downer->arg)
858  dbowner = defGetString(downer);
859  if (dtemplate && dtemplate->arg)
860  dbtemplate = defGetString(dtemplate);
861  if (dencoding && dencoding->arg)
862  {
863  const char *encoding_name;
864 
865  if (IsA(dencoding->arg, Integer))
866  {
867  encoding = defGetInt32(dencoding);
868  encoding_name = pg_encoding_to_char(encoding);
869  if (strcmp(encoding_name, "") == 0 ||
870  pg_valid_server_encoding(encoding_name) < 0)
871  ereport(ERROR,
872  (errcode(ERRCODE_UNDEFINED_OBJECT),
873  errmsg("%d is not a valid encoding code",
874  encoding),
875  parser_errposition(pstate, dencoding->location)));
876  }
877  else
878  {
879  encoding_name = defGetString(dencoding);
880  encoding = pg_valid_server_encoding(encoding_name);
881  if (encoding < 0)
882  ereport(ERROR,
883  (errcode(ERRCODE_UNDEFINED_OBJECT),
884  errmsg("%s is not a valid encoding name",
885  encoding_name),
886  parser_errposition(pstate, dencoding->location)));
887  }
888  }
889  if (dlocale && dlocale->arg)
890  {
891  dbcollate = defGetString(dlocale);
892  dbctype = defGetString(dlocale);
893  }
894  if (dcollate && dcollate->arg)
895  dbcollate = defGetString(dcollate);
896  if (dctype && dctype->arg)
897  dbctype = defGetString(dctype);
898  if (diculocale && diculocale->arg)
899  dbiculocale = defGetString(diculocale);
900  if (dlocprovider && dlocprovider->arg)
901  {
902  char *locproviderstr = defGetString(dlocprovider);
903 
904  if (pg_strcasecmp(locproviderstr, "icu") == 0)
905  dblocprovider = COLLPROVIDER_ICU;
906  else if (pg_strcasecmp(locproviderstr, "libc") == 0)
907  dblocprovider = COLLPROVIDER_LIBC;
908  else
909  ereport(ERROR,
910  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
911  errmsg("unrecognized locale provider: %s",
912  locproviderstr)));
913  }
914  if (diculocale && dblocprovider != COLLPROVIDER_ICU)
915  ereport(ERROR,
916  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
917  errmsg("ICU locale cannot be specified unless locale provider is ICU")));
918  if (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)
919  {
920  if (dlocale && dlocale->arg)
921  dbiculocale = defGetString(dlocale);
922  }
923  if (distemplate && distemplate->arg)
924  dbistemplate = defGetBoolean(distemplate);
925  if (dallowconnections && dallowconnections->arg)
926  dballowconnections = defGetBoolean(dallowconnections);
927  if (dconnlimit && dconnlimit->arg)
928  {
929  dbconnlimit = defGetInt32(dconnlimit);
930  if (dbconnlimit < -1)
931  ereport(ERROR,
932  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
933  errmsg("invalid connection limit: %d", dbconnlimit)));
934  }
935  if (dcollversion)
936  dbcollversion = defGetString(dcollversion);
937 
938  /* obtain OID of proposed owner */
939  if (dbowner)
940  datdba = get_role_oid(dbowner, false);
941  else
942  datdba = GetUserId();
943 
944  /*
945  * To create a database, must have createdb privilege and must be able to
946  * become the target role (this does not imply that the target role itself
947  * must have createdb privilege). The latter provision guards against
948  * "giveaway" attacks. Note that a superuser will always have both of
949  * these privileges a fortiori.
950  */
952  ereport(ERROR,
953  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
954  errmsg("permission denied to create database")));
955 
957 
958  /*
959  * Lookup database (template) to be cloned, and obtain share lock on it.
960  * ShareLock allows two CREATE DATABASEs to work from the same template
961  * concurrently, while ensuring no one is busy dropping it in parallel
962  * (which would be Very Bad since we'd likely get an incomplete copy
963  * without knowing it). This also prevents any new connections from being
964  * made to the source until we finish copying it, so we can be sure it
965  * won't change underneath us.
966  */
967  if (!dbtemplate)
968  dbtemplate = "template1"; /* Default template database name */
969 
970  if (!get_db_info(dbtemplate, ShareLock,
971  &src_dboid, &src_owner, &src_encoding,
972  &src_istemplate, &src_allowconn,
973  &src_frozenxid, &src_minmxid, &src_deftablespace,
974  &src_collate, &src_ctype, &src_iculocale, &src_locprovider,
975  &src_collversion))
976  ereport(ERROR,
977  (errcode(ERRCODE_UNDEFINED_DATABASE),
978  errmsg("template database \"%s\" does not exist",
979  dbtemplate)));
980 
981  /*
982  * Permission check: to copy a DB that's not marked datistemplate, you
983  * must be superuser or the owner thereof.
984  */
985  if (!src_istemplate)
986  {
987  if (!pg_database_ownercheck(src_dboid, GetUserId()))
988  ereport(ERROR,
989  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
990  errmsg("permission denied to copy database \"%s\"",
991  dbtemplate)));
992  }
993 
994  /* Validate the database creation strategy. */
995  if (dstrategy && dstrategy->arg)
996  {
997  char *strategy;
998 
999  strategy = defGetString(dstrategy);
1000  if (strcmp(strategy, "wal_log") == 0)
1001  dbstrategy = CREATEDB_WAL_LOG;
1002  else if (strcmp(strategy, "file_copy") == 0)
1003  dbstrategy = CREATEDB_FILE_COPY;
1004  else
1005  ereport(ERROR,
1006  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1007  errmsg("invalid create database strategy %s", strategy),
1008  errhint("Valid strategies are \"wal_log\", and \"file_copy\".")));
1009  }
1010 
1011  /* If encoding or locales are defaulted, use source's setting */
1012  if (encoding < 0)
1013  encoding = src_encoding;
1014  if (dbcollate == NULL)
1015  dbcollate = src_collate;
1016  if (dbctype == NULL)
1017  dbctype = src_ctype;
1018  if (dbiculocale == NULL)
1019  dbiculocale = src_iculocale;
1020  if (dblocprovider == '\0')
1021  dblocprovider = src_locprovider;
1022 
1023  /* Some encodings are client only */
1025  ereport(ERROR,
1026  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1027  errmsg("invalid server encoding %d", encoding)));
1028 
1029  /* Check that the chosen locales are valid, and get canonical spellings */
1030  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
1031  ereport(ERROR,
1032  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1033  errmsg("invalid locale name: \"%s\"", dbcollate)));
1034  dbcollate = canonname;
1035  if (!check_locale(LC_CTYPE, dbctype, &canonname))
1036  ereport(ERROR,
1037  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1038  errmsg("invalid locale name: \"%s\"", dbctype)));
1039  dbctype = canonname;
1040 
1041  check_encoding_locale_matches(encoding, dbcollate, dbctype);
1042 
1043  if (dblocprovider == COLLPROVIDER_ICU)
1044  {
1045  /*
1046  * This would happen if template0 uses the libc provider but the new
1047  * database uses icu.
1048  */
1049  if (!dbiculocale)
1050  ereport(ERROR,
1051  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1052  errmsg("ICU locale must be specified")));
1053  }
1054 
1055  if (dblocprovider == COLLPROVIDER_ICU)
1056  check_icu_locale(dbiculocale);
1057 
1058  /*
1059  * Check that the new encoding and locale settings match the source
1060  * database. We insist on this because we simply copy the source data ---
1061  * any non-ASCII data would be wrongly encoded, and any indexes sorted
1062  * according to the source locale would be wrong.
1063  *
1064  * However, we assume that template0 doesn't contain any non-ASCII data
1065  * nor any indexes that depend on collation or ctype, so template0 can be
1066  * used as template for creating a database with any encoding or locale.
1067  */
1068  if (strcmp(dbtemplate, "template0") != 0)
1069  {
1070  if (encoding != src_encoding)
1071  ereport(ERROR,
1072  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1073  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
1075  pg_encoding_to_char(src_encoding)),
1076  errhint("Use the same encoding as in the template database, or use template0 as template.")));
1077 
1078  if (strcmp(dbcollate, src_collate) != 0)
1079  ereport(ERROR,
1080  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1081  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
1082  dbcollate, src_collate),
1083  errhint("Use the same collation as in the template database, or use template0 as template.")));
1084 
1085  if (strcmp(dbctype, src_ctype) != 0)
1086  ereport(ERROR,
1087  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1088  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
1089  dbctype, src_ctype),
1090  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
1091 
1092  if (dblocprovider != src_locprovider)
1093  ereport(ERROR,
1094  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1095  errmsg("new locale provider (%s) does not match locale provider of the template database (%s)",
1096  collprovider_name(dblocprovider), collprovider_name(src_locprovider)),
1097  errhint("Use the same locale provider as in the template database, or use template0 as template.")));
1098 
1099  if (dblocprovider == COLLPROVIDER_ICU)
1100  {
1101  Assert(dbiculocale);
1102  Assert(src_iculocale);
1103  if (strcmp(dbiculocale, src_iculocale) != 0)
1104  ereport(ERROR,
1105  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1106  errmsg("new ICU locale (%s) is incompatible with the ICU locale of the template database (%s)",
1107  dbiculocale, src_iculocale),
1108  errhint("Use the same ICU locale as in the template database, or use template0 as template.")));
1109  }
1110  }
1111 
1112  /*
1113  * If we got a collation version for the template database, check that it
1114  * matches the actual OS collation version. Otherwise error; the user
1115  * needs to fix the template database first. Don't complain if a
1116  * collation version was specified explicitly as a statement option; that
1117  * is used by pg_upgrade to reproduce the old state exactly.
1118  *
1119  * (If the template database has no collation version, then either the
1120  * platform/provider does not support collation versioning, or it's
1121  * template0, for which we stipulate that it does not contain
1122  * collation-using objects.)
1123  */
1124  if (src_collversion && !dcollversion)
1125  {
1126  char *actual_versionstr;
1127 
1128  actual_versionstr = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1129  if (!actual_versionstr)
1130  ereport(ERROR,
1131  (errmsg("template database \"%s\" has a collation version, but no actual collation version could be determined",
1132  dbtemplate)));
1133 
1134  if (strcmp(actual_versionstr, src_collversion) != 0)
1135  ereport(ERROR,
1136  (errmsg("template database \"%s\" has a collation version mismatch",
1137  dbtemplate),
1138  errdetail("The template database was created using collation version %s, "
1139  "but the operating system provides version %s.",
1140  src_collversion, actual_versionstr),
1141  errhint("Rebuild all objects in the template database that use the default collation and run "
1142  "ALTER DATABASE %s REFRESH COLLATION VERSION, "
1143  "or build PostgreSQL with the right library version.",
1144  quote_identifier(dbtemplate))));
1145  }
1146 
1147  if (dbcollversion == NULL)
1148  dbcollversion = src_collversion;
1149 
1150  /*
1151  * Normally, we copy the collation version from the template database.
1152  * This last resort only applies if the template database does not have a
1153  * collation version, which is normally only the case for template0.
1154  */
1155  if (dbcollversion == NULL)
1156  dbcollversion = get_collation_actual_version(dblocprovider, dblocprovider == COLLPROVIDER_ICU ? dbiculocale : dbcollate);
1157 
1158  /* Resolve default tablespace for new database */
1159  if (dtablespacename && dtablespacename->arg)
1160  {
1161  char *tablespacename;
1162  AclResult aclresult;
1163 
1164  tablespacename = defGetString(dtablespacename);
1165  dst_deftablespace = get_tablespace_oid(tablespacename, false);
1166  /* check permissions */
1167  aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
1168  ACL_CREATE);
1169  if (aclresult != ACLCHECK_OK)
1170  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1171  tablespacename);
1172 
1173  /* pg_global must never be the default tablespace */
1174  if (dst_deftablespace == GLOBALTABLESPACE_OID)
1175  ereport(ERROR,
1176  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1177  errmsg("pg_global cannot be used as default tablespace")));
1178 
1179  /*
1180  * If we are trying to change the default tablespace of the template,
1181  * we require that the template not have any files in the new default
1182  * tablespace. This is necessary because otherwise the copied
1183  * database would contain pg_class rows that refer to its default
1184  * tablespace both explicitly (by OID) and implicitly (as zero), which
1185  * would cause problems. For example another CREATE DATABASE using
1186  * the copied database as template, and trying to change its default
1187  * tablespace again, would yield outright incorrect results (it would
1188  * improperly move tables to the new default tablespace that should
1189  * stay in the same tablespace).
1190  */
1191  if (dst_deftablespace != src_deftablespace)
1192  {
1193  char *srcpath;
1194  struct stat st;
1195 
1196  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
1197 
1198  if (stat(srcpath, &st) == 0 &&
1199  S_ISDIR(st.st_mode) &&
1200  !directory_is_empty(srcpath))
1201  ereport(ERROR,
1202  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1203  errmsg("cannot assign new default tablespace \"%s\"",
1204  tablespacename),
1205  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
1206  dbtemplate)));
1207  pfree(srcpath);
1208  }
1209  }
1210  else
1211  {
1212  /* Use template database's default tablespace */
1213  dst_deftablespace = src_deftablespace;
1214  /* Note there is no additional permission check in this path */
1215  }
1216 
1217  /*
1218  * If built with appropriate switch, whine when regression-testing
1219  * conventions for database names are violated. But don't complain during
1220  * initdb.
1221  */
1222 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1223  if (IsUnderPostmaster && strstr(dbname, "regression") == NULL)
1224  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1225 #endif
1226 
1227  /*
1228  * Check for db name conflict. This is just to give a more friendly error
1229  * message than "unique index violation". There's a race condition but
1230  * we're willing to accept the less friendly message in that case.
1231  */
1232  if (OidIsValid(get_database_oid(dbname, true)))
1233  ereport(ERROR,
1234  (errcode(ERRCODE_DUPLICATE_DATABASE),
1235  errmsg("database \"%s\" already exists", dbname)));
1236 
1237  /*
1238  * The source DB can't have any active backends, except this one
1239  * (exception is to allow CREATE DB while connected to template1).
1240  * Otherwise we might copy inconsistent data.
1241  *
1242  * This should be last among the basic error checks, because it involves
1243  * potential waiting; we may as well throw an error first if we're gonna
1244  * throw one.
1245  */
1246  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
1247  ereport(ERROR,
1248  (errcode(ERRCODE_OBJECT_IN_USE),
1249  errmsg("source database \"%s\" is being accessed by other users",
1250  dbtemplate),
1251  errdetail_busy_db(notherbackends, npreparedxacts)));
1252 
1253  /*
1254  * Select an OID for the new database, checking that it doesn't have a
1255  * filename conflict with anything already existing in the tablespace
1256  * directories.
1257  */
1258  pg_database_rel = table_open(DatabaseRelationId, RowExclusiveLock);
1259 
1260  /*
1261  * If database OID is configured, check if the OID is already in use or
1262  * data directory already exists.
1263  */
1264  if (OidIsValid(dboid))
1265  {
1266  char *existing_dbname = get_database_name(dboid);
1267 
1268  if (existing_dbname != NULL)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1271  errmsg("database OID %u is already in use by database \"%s\"",
1272  dboid, existing_dbname));
1273 
1274  if (check_db_file_conflict(dboid))
1275  ereport(ERROR,
1276  (errcode(ERRCODE_INVALID_PARAMETER_VALUE)),
1277  errmsg("data directory with the specified OID %u already exists", dboid));
1278  }
1279  else
1280  {
1281  /* Select an OID for the new database if is not explicitly configured. */
1282  do
1283  {
1284  dboid = GetNewOidWithIndex(pg_database_rel, DatabaseOidIndexId,
1285  Anum_pg_database_oid);
1286  } while (check_db_file_conflict(dboid));
1287  }
1288 
1289  /*
1290  * Insert a new tuple into pg_database. This establishes our ownership of
1291  * the new database name (anyone else trying to insert the same name will
1292  * block on the unique index, and fail after we commit).
1293  */
1294 
1295  Assert((dblocprovider == COLLPROVIDER_ICU && dbiculocale) ||
1296  (dblocprovider != COLLPROVIDER_ICU && !dbiculocale));
1297 
1298  /* Form tuple */
1299  MemSet(new_record, 0, sizeof(new_record));
1300  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1301 
1302  new_record[Anum_pg_database_oid - 1] = ObjectIdGetDatum(dboid);
1303  new_record[Anum_pg_database_datname - 1] =
1305  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
1306  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
1307  new_record[Anum_pg_database_datlocprovider - 1] = CharGetDatum(dblocprovider);
1308  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1309  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1310  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1311  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
1312  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
1313  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
1314  new_record[Anum_pg_database_datcollate - 1] = CStringGetTextDatum(dbcollate);
1315  new_record[Anum_pg_database_datctype - 1] = CStringGetTextDatum(dbctype);
1316  if (dbiculocale)
1317  new_record[Anum_pg_database_daticulocale - 1] = CStringGetTextDatum(dbiculocale);
1318  else
1319  new_record_nulls[Anum_pg_database_daticulocale - 1] = true;
1320  if (dbcollversion)
1321  new_record[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(dbcollversion);
1322  else
1323  new_record_nulls[Anum_pg_database_datcollversion - 1] = true;
1324 
1325  /*
1326  * We deliberately set datacl to default (NULL), rather than copying it
1327  * from the template database. Copying it would be a bad idea when the
1328  * owner is not the same as the template's owner.
1329  */
1330  new_record_nulls[Anum_pg_database_datacl - 1] = true;
1331 
1332  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
1333  new_record, new_record_nulls);
1334 
1335  CatalogTupleInsert(pg_database_rel, tuple);
1336 
1337  /*
1338  * Now generate additional catalog entries associated with the new DB
1339  */
1340 
1341  /* Register owner dependency */
1342  recordDependencyOnOwner(DatabaseRelationId, dboid, datdba);
1343 
1344  /* Create pg_shdepend entries for objects within database */
1345  copyTemplateDependencies(src_dboid, dboid);
1346 
1347  /* Post creation hook for new database */
1348  InvokeObjectPostCreateHook(DatabaseRelationId, dboid, 0);
1349 
1350  /*
1351  * If we're going to be reading data for the to-be-created database into
1352  * shared_buffers, take a lock on it. Nobody should know that this
1353  * database exists yet, but it's good to maintain the invariant that a
1354  * lock an AccessExclusiveLock on the database is sufficient to drop all
1355  * of its buffers without worrying about more being read later.
1356  *
1357  * Note that we need to do this before entering the
1358  * PG_ENSURE_ERROR_CLEANUP block below, because createdb_failure_callback
1359  * expects this lock to be held already.
1360  */
1361  if (dbstrategy == CREATEDB_WAL_LOG)
1362  LockSharedObject(DatabaseRelationId, dboid, 0, AccessShareLock);
1363 
1364  /*
1365  * Once we start copying subdirectories, we need to be able to clean 'em
1366  * up if we fail. Use an ENSURE block to make sure this happens. (This
1367  * is not a 100% solution, because of the possibility of failure during
1368  * transaction commit after we leave this routine, but it should handle
1369  * most scenarios.)
1370  */
1371  fparms.src_dboid = src_dboid;
1372  fparms.dest_dboid = dboid;
1373  fparms.strategy = dbstrategy;
1374 
1376  PointerGetDatum(&fparms));
1377  {
1378  /*
1379  * If the user has asked to create a database with WAL_LOG strategy
1380  * then call CreateDatabaseUsingWalLog, which will copy the database
1381  * at the block level and it will WAL log each copied block.
1382  * Otherwise, call CreateDatabaseUsingFileCopy that will copy the
1383  * database file by file.
1384  */
1385  if (dbstrategy == CREATEDB_WAL_LOG)
1386  CreateDatabaseUsingWalLog(src_dboid, dboid, src_deftablespace,
1387  dst_deftablespace);
1388  else
1389  CreateDatabaseUsingFileCopy(src_dboid, dboid, src_deftablespace,
1390  dst_deftablespace);
1391 
1392  /*
1393  * Close pg_database, but keep lock till commit.
1394  */
1395  table_close(pg_database_rel, NoLock);
1396 
1397  /*
1398  * Force synchronous commit, thus minimizing the window between
1399  * creation of the database files and committal of the transaction. If
1400  * we crash before committing, we'll have a DB that's taking up disk
1401  * space but is not in pg_database, which is not good.
1402  */
1403  ForceSyncCommit();
1404  }
1406  PointerGetDatum(&fparms));
1407 
1408  return dboid;
1409 }
1410 
1411 /*
1412  * Check whether chosen encoding matches chosen locale settings. This
1413  * restriction is necessary because libc's locale-specific code usually
1414  * fails when presented with data in an encoding it's not expecting. We
1415  * allow mismatch in four cases:
1416  *
1417  * 1. locale encoding = SQL_ASCII, which means that the locale is C/POSIX
1418  * which works with any encoding.
1419  *
1420  * 2. locale encoding = -1, which means that we couldn't determine the
1421  * locale's encoding and have to trust the user to get it right.
1422  *
1423  * 3. selected encoding is UTF8 and platform is win32. This is because
1424  * UTF8 is a pseudo codepage that is supported in all locales since it's
1425  * converted to UTF16 before being used.
1426  *
1427  * 4. selected encoding is SQL_ASCII, but only if you're a superuser. This
1428  * is risky but we have historically allowed it --- notably, the
1429  * regression tests require it.
1430  *
1431  * Note: if you change this policy, fix initdb to match.
1432  */
1433 void
1434 check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
1435 {
1436  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
1437  int collate_encoding = pg_get_encoding_from_locale(collate, true);
1438 
1439  if (!(ctype_encoding == encoding ||
1440  ctype_encoding == PG_SQL_ASCII ||
1441  ctype_encoding == -1 ||
1442 #ifdef WIN32
1443  encoding == PG_UTF8 ||
1444 #endif
1445  (encoding == PG_SQL_ASCII && superuser())))
1446  ereport(ERROR,
1447  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1448  errmsg("encoding \"%s\" does not match locale \"%s\"",
1450  ctype),
1451  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
1452  pg_encoding_to_char(ctype_encoding))));
1453 
1454  if (!(collate_encoding == encoding ||
1455  collate_encoding == PG_SQL_ASCII ||
1456  collate_encoding == -1 ||
1457 #ifdef WIN32
1458  encoding == PG_UTF8 ||
1459 #endif
1460  (encoding == PG_SQL_ASCII && superuser())))
1461  ereport(ERROR,
1462  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1463  errmsg("encoding \"%s\" does not match locale \"%s\"",
1465  collate),
1466  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
1467  pg_encoding_to_char(collate_encoding))));
1468 }
1469 
1470 /* Error cleanup callback for createdb */
1471 static void
1473 {
1475 
1476  /*
1477  * If we were copying database at block levels then drop pages for the
1478  * destination database that are in the shared buffer cache. And tell
1479  * checkpointer to forget any pending fsync and unlink requests for files
1480  * in the database. The reasoning behind doing this is same as explained
1481  * in dropdb function. But unlike dropdb we don't need to call
1482  * pgstat_drop_database because this database is still not created so
1483  * there should not be any stat for this.
1484  */
1485  if (fparms->strategy == CREATEDB_WAL_LOG)
1486  {
1489 
1490  /* Release lock on the target database. */
1491  UnlockSharedObject(DatabaseRelationId, fparms->dest_dboid, 0,
1492  AccessShareLock);
1493  }
1494 
1495  /*
1496  * Release lock on source database before doing recursive remove. This is
1497  * not essential but it seems desirable to release the lock as soon as
1498  * possible.
1499  */
1500  UnlockSharedObject(DatabaseRelationId, fparms->src_dboid, 0, ShareLock);
1501 
1502  /* Throw away any successfully copied subdirectories */
1504 }
1505 
1506 
1507 /*
1508  * DROP DATABASE
1509  */
1510 void
1511 dropdb(const char *dbname, bool missing_ok, bool force)
1512 {
1513  Oid db_id;
1514  bool db_istemplate;
1515  Relation pgdbrel;
1516  HeapTuple tup;
1517  int notherbackends;
1518  int npreparedxacts;
1519  int nslots,
1520  nslots_active;
1521  int nsubscriptions;
1522 
1523  /*
1524  * Look up the target database's OID, and get exclusive lock on it. We
1525  * need this to ensure that no new backend starts up in the target
1526  * database while we are deleting it (see postinit.c), and that no one is
1527  * using it as a CREATE DATABASE template or trying to delete it for
1528  * themselves.
1529  */
1530  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1531 
1532  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1533  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1534  {
1535  if (!missing_ok)
1536  {
1537  ereport(ERROR,
1538  (errcode(ERRCODE_UNDEFINED_DATABASE),
1539  errmsg("database \"%s\" does not exist", dbname)));
1540  }
1541  else
1542  {
1543  /* Close pg_database, release the lock, since we changed nothing */
1544  table_close(pgdbrel, RowExclusiveLock);
1545  ereport(NOTICE,
1546  (errmsg("database \"%s\" does not exist, skipping",
1547  dbname)));
1548  return;
1549  }
1550  }
1551 
1552  /*
1553  * Permission checks
1554  */
1555  if (!pg_database_ownercheck(db_id, GetUserId()))
1557  dbname);
1558 
1559  /* DROP hook for the database being removed */
1560  InvokeObjectDropHook(DatabaseRelationId, db_id, 0);
1561 
1562  /*
1563  * Disallow dropping a DB that is marked istemplate. This is just to
1564  * prevent people from accidentally dropping template0 or template1; they
1565  * can do so if they're really determined ...
1566  */
1567  if (db_istemplate)
1568  ereport(ERROR,
1569  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1570  errmsg("cannot drop a template database")));
1571 
1572  /* Obviously can't drop my own database */
1573  if (db_id == MyDatabaseId)
1574  ereport(ERROR,
1575  (errcode(ERRCODE_OBJECT_IN_USE),
1576  errmsg("cannot drop the currently open database")));
1577 
1578  /*
1579  * Check whether there are active logical slots that refer to the
1580  * to-be-dropped database. The database lock we are holding prevents the
1581  * creation of new slots using the database or existing slots becoming
1582  * active.
1583  */
1584  (void) ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active);
1585  if (nslots_active)
1586  {
1587  ereport(ERROR,
1588  (errcode(ERRCODE_OBJECT_IN_USE),
1589  errmsg("database \"%s\" is used by an active logical replication slot",
1590  dbname),
1591  errdetail_plural("There is %d active slot.",
1592  "There are %d active slots.",
1593  nslots_active, nslots_active)));
1594  }
1595 
1596  /*
1597  * Check if there are subscriptions defined in the target database.
1598  *
1599  * We can't drop them automatically because they might be holding
1600  * resources in other databases/instances.
1601  */
1602  if ((nsubscriptions = CountDBSubscriptions(db_id)) > 0)
1603  ereport(ERROR,
1604  (errcode(ERRCODE_OBJECT_IN_USE),
1605  errmsg("database \"%s\" is being used by logical replication subscription",
1606  dbname),
1607  errdetail_plural("There is %d subscription.",
1608  "There are %d subscriptions.",
1609  nsubscriptions, nsubscriptions)));
1610 
1611 
1612  /*
1613  * Attempt to terminate all existing connections to the target database if
1614  * the user has requested to do so.
1615  */
1616  if (force)
1617  TerminateOtherDBBackends(db_id);
1618 
1619  /*
1620  * Check for other backends in the target database. (Because we hold the
1621  * database lock, no new ones can start after this.)
1622  *
1623  * As in CREATE DATABASE, check this after other error conditions.
1624  */
1625  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1626  ereport(ERROR,
1627  (errcode(ERRCODE_OBJECT_IN_USE),
1628  errmsg("database \"%s\" is being accessed by other users",
1629  dbname),
1630  errdetail_busy_db(notherbackends, npreparedxacts)));
1631 
1632  /*
1633  * Remove the database's tuple from pg_database.
1634  */
1636  if (!HeapTupleIsValid(tup))
1637  elog(ERROR, "cache lookup failed for database %u", db_id);
1638 
1639  CatalogTupleDelete(pgdbrel, &tup->t_self);
1640 
1641  ReleaseSysCache(tup);
1642 
1643  /*
1644  * Delete any comments or security labels associated with the database.
1645  */
1646  DeleteSharedComments(db_id, DatabaseRelationId);
1647  DeleteSharedSecurityLabel(db_id, DatabaseRelationId);
1648 
1649  /*
1650  * Remove settings associated with this database
1651  */
1652  DropSetting(db_id, InvalidOid);
1653 
1654  /*
1655  * Remove shared dependency references for the database.
1656  */
1657  dropDatabaseDependencies(db_id);
1658 
1659  /*
1660  * Drop db-specific replication slots.
1661  */
1663 
1664  /*
1665  * Drop pages for this database that are in the shared buffer cache. This
1666  * is important to ensure that no remaining backend tries to write out a
1667  * dirty buffer to the dead database later...
1668  */
1669  DropDatabaseBuffers(db_id);
1670 
1671  /*
1672  * Tell the cumulative stats system to forget it immediately, too.
1673  */
1674  pgstat_drop_database(db_id);
1675 
1676  /*
1677  * Tell checkpointer to forget any pending fsync and unlink requests for
1678  * files in the database; else the fsyncs will fail at next checkpoint, or
1679  * worse, it will delete files that belong to a newly created database
1680  * with the same OID.
1681  */
1683 
1684  /*
1685  * Force a checkpoint to make sure the checkpointer has received the
1686  * message sent by ForgetDatabaseSyncRequests.
1687  */
1689 
1690  /* Close all smgr fds in all backends. */
1692 
1693  /*
1694  * Remove all tablespace subdirs belonging to the database.
1695  */
1696  remove_dbtablespaces(db_id);
1697 
1698  /*
1699  * Close pg_database, but keep lock till commit.
1700  */
1701  table_close(pgdbrel, NoLock);
1702 
1703  /*
1704  * Force synchronous commit, thus minimizing the window between removal of
1705  * the database files and committal of the transaction. If we crash before
1706  * committing, we'll have a DB that's gone on disk but still there
1707  * according to pg_database, which is not good.
1708  */
1709  ForceSyncCommit();
1710 }
1711 
1712 
1713 /*
1714  * Rename database
1715  */
1717 RenameDatabase(const char *oldname, const char *newname)
1718 {
1719  Oid db_id;
1720  HeapTuple newtup;
1721  Relation rel;
1722  int notherbackends;
1723  int npreparedxacts;
1724  ObjectAddress address;
1725 
1726  /*
1727  * Look up the target database's OID, and get exclusive lock on it. We
1728  * need this for the same reasons as DROP DATABASE.
1729  */
1730  rel = table_open(DatabaseRelationId, RowExclusiveLock);
1731 
1732  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
1733  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
1734  ereport(ERROR,
1735  (errcode(ERRCODE_UNDEFINED_DATABASE),
1736  errmsg("database \"%s\" does not exist", oldname)));
1737 
1738  /* must be owner */
1739  if (!pg_database_ownercheck(db_id, GetUserId()))
1741  oldname);
1742 
1743  /* must have createdb rights */
1744  if (!have_createdb_privilege())
1745  ereport(ERROR,
1746  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1747  errmsg("permission denied to rename database")));
1748 
1749  /*
1750  * If built with appropriate switch, whine when regression-testing
1751  * conventions for database names are violated.
1752  */
1753 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
1754  if (strstr(newname, "regression") == NULL)
1755  elog(WARNING, "databases created by regression test cases should have names including \"regression\"");
1756 #endif
1757 
1758  /*
1759  * Make sure the new name doesn't exist. See notes for same error in
1760  * CREATE DATABASE.
1761  */
1762  if (OidIsValid(get_database_oid(newname, true)))
1763  ereport(ERROR,
1764  (errcode(ERRCODE_DUPLICATE_DATABASE),
1765  errmsg("database \"%s\" already exists", newname)));
1766 
1767  /*
1768  * XXX Client applications probably store the current database somewhere,
1769  * so renaming it could cause confusion. On the other hand, there may not
1770  * be an actual problem besides a little confusion, so think about this
1771  * and decide.
1772  */
1773  if (db_id == MyDatabaseId)
1774  ereport(ERROR,
1775  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1776  errmsg("current database cannot be renamed")));
1777 
1778  /*
1779  * Make sure the database does not have active sessions. This is the same
1780  * concern as above, but applied to other sessions.
1781  *
1782  * As in CREATE DATABASE, check this after other error conditions.
1783  */
1784  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1785  ereport(ERROR,
1786  (errcode(ERRCODE_OBJECT_IN_USE),
1787  errmsg("database \"%s\" is being accessed by other users",
1788  oldname),
1789  errdetail_busy_db(notherbackends, npreparedxacts)));
1790 
1791  /* rename */
1793  if (!HeapTupleIsValid(newtup))
1794  elog(ERROR, "cache lookup failed for database %u", db_id);
1795  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1796  CatalogTupleUpdate(rel, &newtup->t_self, newtup);
1797 
1798  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
1799 
1800  ObjectAddressSet(address, DatabaseRelationId, db_id);
1801 
1802  /*
1803  * Close pg_database, but keep lock till commit.
1804  */
1805  table_close(rel, NoLock);
1806 
1807  return address;
1808 }
1809 
1810 
1811 /*
1812  * ALTER DATABASE SET TABLESPACE
1813  */
1814 static void
1815 movedb(const char *dbname, const char *tblspcname)
1816 {
1817  Oid db_id;
1818  Relation pgdbrel;
1819  int notherbackends;
1820  int npreparedxacts;
1821  HeapTuple oldtuple,
1822  newtuple;
1823  Oid src_tblspcoid,
1824  dst_tblspcoid;
1825  Datum new_record[Natts_pg_database];
1826  bool new_record_nulls[Natts_pg_database];
1827  bool new_record_repl[Natts_pg_database];
1828  ScanKeyData scankey;
1829  SysScanDesc sysscan;
1830  AclResult aclresult;
1831  char *src_dbpath;
1832  char *dst_dbpath;
1833  DIR *dstdir;
1834  struct dirent *xlde;
1835  movedb_failure_params fparms;
1836 
1837  /*
1838  * Look up the target database's OID, and get exclusive lock on it. We
1839  * need this to ensure that no new backend starts up in the database while
1840  * we are moving it, and that no one is using it as a CREATE DATABASE
1841  * template or trying to delete it.
1842  */
1843  pgdbrel = table_open(DatabaseRelationId, RowExclusiveLock);
1844 
1845  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1846  NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL, NULL, NULL, NULL))
1847  ereport(ERROR,
1848  (errcode(ERRCODE_UNDEFINED_DATABASE),
1849  errmsg("database \"%s\" does not exist", dbname)));
1850 
1851  /*
1852  * We actually need a session lock, so that the lock will persist across
1853  * the commit/restart below. (We could almost get away with letting the
1854  * lock be released at commit, except that someone could try to move
1855  * relations of the DB back into the old directory while we rmtree() it.)
1856  */
1857  LockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1859 
1860  /*
1861  * Permission checks
1862  */
1863  if (!pg_database_ownercheck(db_id, GetUserId()))
1865  dbname);
1866 
1867  /*
1868  * Obviously can't move the tables of my own database
1869  */
1870  if (db_id == MyDatabaseId)
1871  ereport(ERROR,
1872  (errcode(ERRCODE_OBJECT_IN_USE),
1873  errmsg("cannot change the tablespace of the currently open database")));
1874 
1875  /*
1876  * Get tablespace's oid
1877  */
1878  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1879 
1880  /*
1881  * Permission checks
1882  */
1883  aclresult = pg_tablespace_aclcheck(dst_tblspcoid, GetUserId(),
1884  ACL_CREATE);
1885  if (aclresult != ACLCHECK_OK)
1886  aclcheck_error(aclresult, OBJECT_TABLESPACE,
1887  tblspcname);
1888 
1889  /*
1890  * pg_global must never be the default tablespace
1891  */
1892  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1893  ereport(ERROR,
1894  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1895  errmsg("pg_global cannot be used as default tablespace")));
1896 
1897  /*
1898  * No-op if same tablespace
1899  */
1900  if (src_tblspcoid == dst_tblspcoid)
1901  {
1902  table_close(pgdbrel, NoLock);
1903  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
1905  return;
1906  }
1907 
1908  /*
1909  * Check for other backends in the target database. (Because we hold the
1910  * database lock, no new ones can start after this.)
1911  *
1912  * As in CREATE DATABASE, check this after other error conditions.
1913  */
1914  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1915  ereport(ERROR,
1916  (errcode(ERRCODE_OBJECT_IN_USE),
1917  errmsg("database \"%s\" is being accessed by other users",
1918  dbname),
1919  errdetail_busy_db(notherbackends, npreparedxacts)));
1920 
1921  /*
1922  * Get old and new database paths
1923  */
1924  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1925  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1926 
1927  /*
1928  * Force a checkpoint before proceeding. This will force all dirty
1929  * buffers, including those of unlogged tables, out to disk, to ensure
1930  * source database is up-to-date on disk for the copy.
1931  * FlushDatabaseBuffers() would suffice for that, but we also want to
1932  * process any pending unlink requests. Otherwise, the check for existing
1933  * files in the target directory might fail unnecessarily, not to mention
1934  * that the copy might fail due to source files getting deleted under it.
1935  * On Windows, this also ensures that background procs don't hold any open
1936  * files, which would cause rmdir() to fail.
1937  */
1940 
1941  /* Close all smgr fds in all backends. */
1943 
1944  /*
1945  * Now drop all buffers holding data of the target database; they should
1946  * no longer be dirty so DropDatabaseBuffers is safe.
1947  *
1948  * It might seem that we could just let these buffers age out of shared
1949  * buffers naturally, since they should not get referenced anymore. The
1950  * problem with that is that if the user later moves the database back to
1951  * its original tablespace, any still-surviving buffers would appear to
1952  * contain valid data again --- but they'd be missing any changes made in
1953  * the database while it was in the new tablespace. In any case, freeing
1954  * buffers that should never be used again seems worth the cycles.
1955  *
1956  * Note: it'd be sufficient to get rid of buffers matching db_id and
1957  * src_tblspcoid, but bufmgr.c presently provides no API for that.
1958  */
1959  DropDatabaseBuffers(db_id);
1960 
1961  /*
1962  * Check for existence of files in the target directory, i.e., objects of
1963  * this database that are already in the target tablespace. We can't
1964  * allow the move in such a case, because we would need to change those
1965  * relations' pg_class.reltablespace entries to zero, and we don't have
1966  * access to the DB's pg_class to do so.
1967  */
1968  dstdir = AllocateDir(dst_dbpath);
1969  if (dstdir != NULL)
1970  {
1971  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1972  {
1973  if (strcmp(xlde->d_name, ".") == 0 ||
1974  strcmp(xlde->d_name, "..") == 0)
1975  continue;
1976 
1977  ereport(ERROR,
1978  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1979  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1980  dbname, tblspcname),
1981  errhint("You must move them back to the database's default tablespace before using this command.")));
1982  }
1983 
1984  FreeDir(dstdir);
1985 
1986  /*
1987  * The directory exists but is empty. We must remove it before using
1988  * the copydir function.
1989  */
1990  if (rmdir(dst_dbpath) != 0)
1991  elog(ERROR, "could not remove directory \"%s\": %m",
1992  dst_dbpath);
1993  }
1994 
1995  /*
1996  * Use an ENSURE block to make sure we remove the debris if the copy fails
1997  * (eg, due to out-of-disk-space). This is not a 100% solution, because
1998  * of the possibility of failure during transaction commit, but it should
1999  * handle most scenarios.
2000  */
2001  fparms.dest_dboid = db_id;
2002  fparms.dest_tsoid = dst_tblspcoid;
2004  PointerGetDatum(&fparms));
2005  {
2006  /*
2007  * Copy files from the old tablespace to the new one
2008  */
2009  copydir(src_dbpath, dst_dbpath, false);
2010 
2011  /*
2012  * Record the filesystem change in XLOG
2013  */
2014  {
2016 
2017  xlrec.db_id = db_id;
2018  xlrec.tablespace_id = dst_tblspcoid;
2019  xlrec.src_db_id = db_id;
2020  xlrec.src_tablespace_id = src_tblspcoid;
2021 
2022  XLogBeginInsert();
2023  XLogRegisterData((char *) &xlrec,
2025 
2026  (void) XLogInsert(RM_DBASE_ID,
2028  }
2029 
2030  /*
2031  * Update the database's pg_database tuple
2032  */
2033  ScanKeyInit(&scankey,
2034  Anum_pg_database_datname,
2035  BTEqualStrategyNumber, F_NAMEEQ,
2037  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
2038  NULL, 1, &scankey);
2039  oldtuple = systable_getnext(sysscan);
2040  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
2041  ereport(ERROR,
2042  (errcode(ERRCODE_UNDEFINED_DATABASE),
2043  errmsg("database \"%s\" does not exist", dbname)));
2044 
2045  MemSet(new_record, 0, sizeof(new_record));
2046  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
2047  MemSet(new_record_repl, false, sizeof(new_record_repl));
2048 
2049  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
2050  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
2051 
2052  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
2053  new_record,
2054  new_record_nulls, new_record_repl);
2055  CatalogTupleUpdate(pgdbrel, &oldtuple->t_self, newtuple);
2056 
2057  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2058 
2059  systable_endscan(sysscan);
2060 
2061  /*
2062  * Force another checkpoint here. As in CREATE DATABASE, this is to
2063  * ensure that we don't have to replay a committed
2064  * XLOG_DBASE_CREATE_FILE_COPY operation, which would cause us to lose
2065  * any unlogged operations done in the new DB tablespace before the
2066  * next checkpoint.
2067  */
2069 
2070  /*
2071  * Force synchronous commit, thus minimizing the window between
2072  * copying the database files and committal of the transaction. If we
2073  * crash before committing, we'll leave an orphaned set of files on
2074  * disk, which is not fatal but not good either.
2075  */
2076  ForceSyncCommit();
2077 
2078  /*
2079  * Close pg_database, but keep lock till commit.
2080  */
2081  table_close(pgdbrel, NoLock);
2082  }
2084  PointerGetDatum(&fparms));
2085 
2086  /*
2087  * Commit the transaction so that the pg_database update is committed. If
2088  * we crash while removing files, the database won't be corrupt, we'll
2089  * just leave some orphaned files in the old directory.
2090  *
2091  * (This is OK because we know we aren't inside a transaction block.)
2092  *
2093  * XXX would it be safe/better to do this inside the ensure block? Not
2094  * convinced it's a good idea; consider elog just after the transaction
2095  * really commits.
2096  */
2099 
2100  /* Start new transaction for the remaining work; don't need a snapshot */
2102 
2103  /*
2104  * Remove files from the old tablespace
2105  */
2106  if (!rmtree(src_dbpath, true))
2107  ereport(WARNING,
2108  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2109  src_dbpath)));
2110 
2111  /*
2112  * Record the filesystem change in XLOG
2113  */
2114  {
2115  xl_dbase_drop_rec xlrec;
2116 
2117  xlrec.db_id = db_id;
2118  xlrec.ntablespaces = 1;
2119 
2120  XLogBeginInsert();
2121  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
2122  XLogRegisterData((char *) &src_tblspcoid, sizeof(Oid));
2123 
2124  (void) XLogInsert(RM_DBASE_ID,
2126  }
2127 
2128  /* Now it's safe to release the database lock */
2129  UnlockSharedObjectForSession(DatabaseRelationId, db_id, 0,
2131 
2132  pfree(src_dbpath);
2133  pfree(dst_dbpath);
2134 }
2135 
2136 /* Error cleanup callback for movedb */
2137 static void
2139 {
2141  char *dstpath;
2142 
2143  /* Get rid of anything we managed to copy to the target directory */
2144  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
2145 
2146  (void) rmtree(dstpath, true);
2147 
2148  pfree(dstpath);
2149 }
2150 
2151 /*
2152  * Process options and call dropdb function.
2153  */
2154 void
2156 {
2157  bool force = false;
2158  ListCell *lc;
2159 
2160  foreach(lc, stmt->options)
2161  {
2162  DefElem *opt = (DefElem *) lfirst(lc);
2163 
2164  if (strcmp(opt->defname, "force") == 0)
2165  force = true;
2166  else
2167  ereport(ERROR,
2168  (errcode(ERRCODE_SYNTAX_ERROR),
2169  errmsg("unrecognized DROP DATABASE option \"%s\"", opt->defname),
2170  parser_errposition(pstate, opt->location)));
2171  }
2172 
2173  dropdb(stmt->dbname, stmt->missing_ok, force);
2174 }
2175 
2176 /*
2177  * ALTER DATABASE name ...
2178  */
2179 Oid
2180 AlterDatabase(ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
2181 {
2182  Relation rel;
2183  Oid dboid;
2184  HeapTuple tuple,
2185  newtuple;
2186  Form_pg_database datform;
2187  ScanKeyData scankey;
2188  SysScanDesc scan;
2189  ListCell *option;
2190  bool dbistemplate = false;
2191  bool dballowconnections = true;
2192  int dbconnlimit = -1;
2193  DefElem *distemplate = NULL;
2194  DefElem *dallowconnections = NULL;
2195  DefElem *dconnlimit = NULL;
2196  DefElem *dtablespace = NULL;
2197  Datum new_record[Natts_pg_database];
2198  bool new_record_nulls[Natts_pg_database];
2199  bool new_record_repl[Natts_pg_database];
2200 
2201  /* Extract options from the statement node tree */
2202  foreach(option, stmt->options)
2203  {
2204  DefElem *defel = (DefElem *) lfirst(option);
2205 
2206  if (strcmp(defel->defname, "is_template") == 0)
2207  {
2208  if (distemplate)
2209  errorConflictingDefElem(defel, pstate);
2210  distemplate = defel;
2211  }
2212  else if (strcmp(defel->defname, "allow_connections") == 0)
2213  {
2214  if (dallowconnections)
2215  errorConflictingDefElem(defel, pstate);
2216  dallowconnections = defel;
2217  }
2218  else if (strcmp(defel->defname, "connection_limit") == 0)
2219  {
2220  if (dconnlimit)
2221  errorConflictingDefElem(defel, pstate);
2222  dconnlimit = defel;
2223  }
2224  else if (strcmp(defel->defname, "tablespace") == 0)
2225  {
2226  if (dtablespace)
2227  errorConflictingDefElem(defel, pstate);
2228  dtablespace = defel;
2229  }
2230  else
2231  ereport(ERROR,
2232  (errcode(ERRCODE_SYNTAX_ERROR),
2233  errmsg("option \"%s\" not recognized", defel->defname),
2234  parser_errposition(pstate, defel->location)));
2235  }
2236 
2237  if (dtablespace)
2238  {
2239  /*
2240  * While the SET TABLESPACE syntax doesn't allow any other options,
2241  * somebody could write "WITH TABLESPACE ...". Forbid any other
2242  * options from being specified in that case.
2243  */
2244  if (list_length(stmt->options) != 1)
2245  ereport(ERROR,
2246  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2247  errmsg("option \"%s\" cannot be specified with other options",
2248  dtablespace->defname),
2249  parser_errposition(pstate, dtablespace->location)));
2250  /* this case isn't allowed within a transaction block */
2251  PreventInTransactionBlock(isTopLevel, "ALTER DATABASE SET TABLESPACE");
2252  movedb(stmt->dbname, defGetString(dtablespace));
2253  return InvalidOid;
2254  }
2255 
2256  if (distemplate && distemplate->arg)
2257  dbistemplate = defGetBoolean(distemplate);
2258  if (dallowconnections && dallowconnections->arg)
2259  dballowconnections = defGetBoolean(dallowconnections);
2260  if (dconnlimit && dconnlimit->arg)
2261  {
2262  dbconnlimit = defGetInt32(dconnlimit);
2263  if (dbconnlimit < -1)
2264  ereport(ERROR,
2265  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2266  errmsg("invalid connection limit: %d", dbconnlimit)));
2267  }
2268 
2269  /*
2270  * Get the old tuple. We don't need a lock on the database per se,
2271  * because we're not going to do anything that would mess up incoming
2272  * connections.
2273  */
2274  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2275  ScanKeyInit(&scankey,
2276  Anum_pg_database_datname,
2277  BTEqualStrategyNumber, F_NAMEEQ,
2278  CStringGetDatum(stmt->dbname));
2279  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2280  NULL, 1, &scankey);
2281  tuple = systable_getnext(scan);
2282  if (!HeapTupleIsValid(tuple))
2283  ereport(ERROR,
2284  (errcode(ERRCODE_UNDEFINED_DATABASE),
2285  errmsg("database \"%s\" does not exist", stmt->dbname)));
2286 
2287  datform = (Form_pg_database) GETSTRUCT(tuple);
2288  dboid = datform->oid;
2289 
2290  if (!pg_database_ownercheck(dboid, GetUserId()))
2292  stmt->dbname);
2293 
2294  /*
2295  * In order to avoid getting locked out and having to go through
2296  * standalone mode, we refuse to disallow connections to the database
2297  * we're currently connected to. Lockout can still happen with concurrent
2298  * sessions but the likeliness of that is not high enough to worry about.
2299  */
2300  if (!dballowconnections && dboid == MyDatabaseId)
2301  ereport(ERROR,
2302  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2303  errmsg("cannot disallow connections for current database")));
2304 
2305  /*
2306  * Build an updated tuple, perusing the information just obtained
2307  */
2308  MemSet(new_record, 0, sizeof(new_record));
2309  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
2310  MemSet(new_record_repl, false, sizeof(new_record_repl));
2311 
2312  if (distemplate)
2313  {
2314  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
2315  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
2316  }
2317  if (dallowconnections)
2318  {
2319  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
2320  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
2321  }
2322  if (dconnlimit)
2323  {
2324  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
2325  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
2326  }
2327 
2328  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
2329  new_record_nulls, new_record_repl);
2330  CatalogTupleUpdate(rel, &tuple->t_self, newtuple);
2331 
2332  InvokeObjectPostAlterHook(DatabaseRelationId, dboid, 0);
2333 
2334  systable_endscan(scan);
2335 
2336  /* Close pg_database, but keep lock till commit */
2337  table_close(rel, NoLock);
2338 
2339  return dboid;
2340 }
2341 
2342 
2343 /*
2344  * ALTER DATABASE name REFRESH COLLATION VERSION
2345  */
2348 {
2349  Relation rel;
2350  ScanKeyData scankey;
2351  SysScanDesc scan;
2352  Oid db_id;
2353  HeapTuple tuple;
2354  Form_pg_database datForm;
2355  ObjectAddress address;
2356  Datum datum;
2357  bool isnull;
2358  char *oldversion;
2359  char *newversion;
2360 
2361  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2362  ScanKeyInit(&scankey,
2363  Anum_pg_database_datname,
2364  BTEqualStrategyNumber, F_NAMEEQ,
2365  CStringGetDatum(stmt->dbname));
2366  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2367  NULL, 1, &scankey);
2368  tuple = systable_getnext(scan);
2369  if (!HeapTupleIsValid(tuple))
2370  ereport(ERROR,
2371  (errcode(ERRCODE_UNDEFINED_DATABASE),
2372  errmsg("database \"%s\" does not exist", stmt->dbname)));
2373 
2374  datForm = (Form_pg_database) GETSTRUCT(tuple);
2375  db_id = datForm->oid;
2376 
2377  if (!pg_database_ownercheck(db_id, GetUserId()))
2379  stmt->dbname);
2380 
2381  datum = heap_getattr(tuple, Anum_pg_database_datcollversion, RelationGetDescr(rel), &isnull);
2382  oldversion = isnull ? NULL : TextDatumGetCString(datum);
2383 
2384  datum = heap_getattr(tuple, datForm->datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, RelationGetDescr(rel), &isnull);
2385  if (isnull)
2386  elog(ERROR, "unexpected null in pg_database");
2387  newversion = get_collation_actual_version(datForm->datlocprovider, TextDatumGetCString(datum));
2388 
2389  /* cannot change from NULL to non-NULL or vice versa */
2390  if ((!oldversion && newversion) || (oldversion && !newversion))
2391  elog(ERROR, "invalid collation version change");
2392  else if (oldversion && newversion && strcmp(newversion, oldversion) != 0)
2393  {
2394  bool nulls[Natts_pg_database] = {0};
2395  bool replaces[Natts_pg_database] = {0};
2396  Datum values[Natts_pg_database] = {0};
2397 
2398  ereport(NOTICE,
2399  (errmsg("changing version from %s to %s",
2400  oldversion, newversion)));
2401 
2402  values[Anum_pg_database_datcollversion - 1] = CStringGetTextDatum(newversion);
2403  replaces[Anum_pg_database_datcollversion - 1] = true;
2404 
2405  tuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
2406  values, nulls, replaces);
2407  CatalogTupleUpdate(rel, &tuple->t_self, tuple);
2408  heap_freetuple(tuple);
2409  }
2410  else
2411  ereport(NOTICE,
2412  (errmsg("version has not changed")));
2413 
2414  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2415 
2416  ObjectAddressSet(address, DatabaseRelationId, db_id);
2417 
2418  systable_endscan(scan);
2419 
2420  table_close(rel, NoLock);
2421 
2422  return address;
2423 }
2424 
2425 
2426 /*
2427  * ALTER DATABASE name SET ...
2428  */
2429 Oid
2431 {
2432  Oid datid = get_database_oid(stmt->dbname, false);
2433 
2434  /*
2435  * Obtain a lock on the database and make sure it didn't go away in the
2436  * meantime.
2437  */
2438  shdepLockAndCheckObject(DatabaseRelationId, datid);
2439 
2440  if (!pg_database_ownercheck(datid, GetUserId()))
2442  stmt->dbname);
2443 
2444  AlterSetting(datid, InvalidOid, stmt->setstmt);
2445 
2446  UnlockSharedObject(DatabaseRelationId, datid, 0, AccessShareLock);
2447 
2448  return datid;
2449 }
2450 
2451 
2452 /*
2453  * ALTER DATABASE name OWNER TO newowner
2454  */
2456 AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
2457 {
2458  Oid db_id;
2459  HeapTuple tuple;
2460  Relation rel;
2461  ScanKeyData scankey;
2462  SysScanDesc scan;
2463  Form_pg_database datForm;
2464  ObjectAddress address;
2465 
2466  /*
2467  * Get the old tuple. We don't need a lock on the database per se,
2468  * because we're not going to do anything that would mess up incoming
2469  * connections.
2470  */
2471  rel = table_open(DatabaseRelationId, RowExclusiveLock);
2472  ScanKeyInit(&scankey,
2473  Anum_pg_database_datname,
2474  BTEqualStrategyNumber, F_NAMEEQ,
2476  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
2477  NULL, 1, &scankey);
2478  tuple = systable_getnext(scan);
2479  if (!HeapTupleIsValid(tuple))
2480  ereport(ERROR,
2481  (errcode(ERRCODE_UNDEFINED_DATABASE),
2482  errmsg("database \"%s\" does not exist", dbname)));
2483 
2484  datForm = (Form_pg_database) GETSTRUCT(tuple);
2485  db_id = datForm->oid;
2486 
2487  /*
2488  * If the new owner is the same as the existing owner, consider the
2489  * command to have succeeded. This is to be consistent with other
2490  * objects.
2491  */
2492  if (datForm->datdba != newOwnerId)
2493  {
2494  Datum repl_val[Natts_pg_database];
2495  bool repl_null[Natts_pg_database];
2496  bool repl_repl[Natts_pg_database];
2497  Acl *newAcl;
2498  Datum aclDatum;
2499  bool isNull;
2500  HeapTuple newtuple;
2501 
2502  /* Otherwise, must be owner of the existing object */
2503  if (!pg_database_ownercheck(db_id, GetUserId()))
2505  dbname);
2506 
2507  /* Must be able to become new owner */
2508  check_is_member_of_role(GetUserId(), newOwnerId);
2509 
2510  /*
2511  * must have createdb rights
2512  *
2513  * NOTE: This is different from other alter-owner checks in that the
2514  * current user is checked for createdb privileges instead of the
2515  * destination owner. This is consistent with the CREATE case for
2516  * databases. Because superusers will always have this right, we need
2517  * no special case for them.
2518  */
2519  if (!have_createdb_privilege())
2520  ereport(ERROR,
2521  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2522  errmsg("permission denied to change owner of database")));
2523 
2524  memset(repl_null, false, sizeof(repl_null));
2525  memset(repl_repl, false, sizeof(repl_repl));
2526 
2527  repl_repl[Anum_pg_database_datdba - 1] = true;
2528  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
2529 
2530  /*
2531  * Determine the modified ACL for the new owner. This is only
2532  * necessary when the ACL is non-null.
2533  */
2534  aclDatum = heap_getattr(tuple,
2535  Anum_pg_database_datacl,
2536  RelationGetDescr(rel),
2537  &isNull);
2538  if (!isNull)
2539  {
2540  newAcl = aclnewowner(DatumGetAclP(aclDatum),
2541  datForm->datdba, newOwnerId);
2542  repl_repl[Anum_pg_database_datacl - 1] = true;
2543  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
2544  }
2545 
2546  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
2547  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
2548 
2549  heap_freetuple(newtuple);
2550 
2551  /* Update owner dependency reference */
2552  changeDependencyOnOwner(DatabaseRelationId, db_id, newOwnerId);
2553  }
2554 
2555  InvokeObjectPostAlterHook(DatabaseRelationId, db_id, 0);
2556 
2557  ObjectAddressSet(address, DatabaseRelationId, db_id);
2558 
2559  systable_endscan(scan);
2560 
2561  /* Close pg_database, but keep lock till commit */
2562  table_close(rel, NoLock);
2563 
2564  return address;
2565 }
2566 
2567 
2568 Datum
2570 {
2571  Oid dbid = PG_GETARG_OID(0);
2572  HeapTuple tp;
2573  char datlocprovider;
2574  Datum datum;
2575  bool isnull;
2576  char *version;
2577 
2579  if (!HeapTupleIsValid(tp))
2580  ereport(ERROR,
2581  (errcode(ERRCODE_UNDEFINED_OBJECT),
2582  errmsg("database with OID %u does not exist", dbid)));
2583 
2585 
2586  datum = SysCacheGetAttr(DATABASEOID, tp, datlocprovider == COLLPROVIDER_ICU ? Anum_pg_database_daticulocale : Anum_pg_database_datcollate, &isnull);
2587  if (isnull)
2588  elog(ERROR, "unexpected null in pg_database");
2590 
2591  ReleaseSysCache(tp);
2592 
2593  if (version)
2595  else
2596  PG_RETURN_NULL();
2597 }
2598 
2599 
2600 /*
2601  * Helper functions
2602  */
2603 
2604 /*
2605  * Look up info about the database named "name". If the database exists,
2606  * obtain the specified lock type on it, fill in any of the remaining
2607  * parameters that aren't NULL, and return true. If no such database,
2608  * return false.
2609  */
2610 static bool
2611 get_db_info(const char *name, LOCKMODE lockmode,
2612  Oid *dbIdP, Oid *ownerIdP,
2613  int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
2614  TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP,
2615  Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbIculocale,
2616  char *dbLocProvider,
2617  char **dbCollversion)
2618 {
2619  bool result = false;
2620  Relation relation;
2621 
2622  AssertArg(name);
2623 
2624  /* Caller may wish to grab a better lock on pg_database beforehand... */
2625  relation = table_open(DatabaseRelationId, AccessShareLock);
2626 
2627  /*
2628  * Loop covers the rare case where the database is renamed before we can
2629  * lock it. We try again just in case we can find a new one of the same
2630  * name.
2631  */
2632  for (;;)
2633  {
2634  ScanKeyData scanKey;
2635  SysScanDesc scan;
2636  HeapTuple tuple;
2637  Oid dbOid;
2638 
2639  /*
2640  * there's no syscache for database-indexed-by-name, so must do it the
2641  * hard way
2642  */
2643  ScanKeyInit(&scanKey,
2644  Anum_pg_database_datname,
2645  BTEqualStrategyNumber, F_NAMEEQ,
2647 
2648  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
2649  NULL, 1, &scanKey);
2650 
2651  tuple = systable_getnext(scan);
2652 
2653  if (!HeapTupleIsValid(tuple))
2654  {
2655  /* definitely no database of that name */
2656  systable_endscan(scan);
2657  break;
2658  }
2659 
2660  dbOid = ((Form_pg_database) GETSTRUCT(tuple))->oid;
2661 
2662  systable_endscan(scan);
2663 
2664  /*
2665  * Now that we have a database OID, we can try to lock the DB.
2666  */
2667  if (lockmode != NoLock)
2668  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2669 
2670  /*
2671  * And now, re-fetch the tuple by OID. If it's still there and still
2672  * the same name, we win; else, drop the lock and loop back to try
2673  * again.
2674  */
2675  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
2676  if (HeapTupleIsValid(tuple))
2677  {
2678  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
2679 
2680  if (strcmp(name, NameStr(dbform->datname)) == 0)
2681  {
2682  Datum datum;
2683  bool isnull;
2684 
2685  /* oid of the database */
2686  if (dbIdP)
2687  *dbIdP = dbOid;
2688  /* oid of the owner */
2689  if (ownerIdP)
2690  *ownerIdP = dbform->datdba;
2691  /* character encoding */
2692  if (encodingP)
2693  *encodingP = dbform->encoding;
2694  /* allowed as template? */
2695  if (dbIsTemplateP)
2696  *dbIsTemplateP = dbform->datistemplate;
2697  /* allowing connections? */
2698  if (dbAllowConnP)
2699  *dbAllowConnP = dbform->datallowconn;
2700  /* limit of frozen XIDs */
2701  if (dbFrozenXidP)
2702  *dbFrozenXidP = dbform->datfrozenxid;
2703  /* minimum MultiXactId */
2704  if (dbMinMultiP)
2705  *dbMinMultiP = dbform->datminmxid;
2706  /* default tablespace for this database */
2707  if (dbTablespace)
2708  *dbTablespace = dbform->dattablespace;
2709  /* default locale settings for this database */
2710  if (dbLocProvider)
2711  *dbLocProvider = dbform->datlocprovider;
2712  if (dbCollate)
2713  {
2714  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollate, &isnull);
2715  Assert(!isnull);
2716  *dbCollate = TextDatumGetCString(datum);
2717  }
2718  if (dbCtype)
2719  {
2720  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datctype, &isnull);
2721  Assert(!isnull);
2722  *dbCtype = TextDatumGetCString(datum);
2723  }
2724  if (dbIculocale)
2725  {
2726  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_daticulocale, &isnull);
2727  if (isnull)
2728  *dbIculocale = NULL;
2729  else
2730  *dbIculocale = TextDatumGetCString(datum);
2731  }
2732  if (dbCollversion)
2733  {
2734  datum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datcollversion, &isnull);
2735  if (isnull)
2736  *dbCollversion = NULL;
2737  else
2738  *dbCollversion = TextDatumGetCString(datum);
2739  }
2740  ReleaseSysCache(tuple);
2741  result = true;
2742  break;
2743  }
2744  /* can only get here if it was just renamed */
2745  ReleaseSysCache(tuple);
2746  }
2747 
2748  if (lockmode != NoLock)
2749  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
2750  }
2751 
2752  table_close(relation, AccessShareLock);
2753 
2754  return result;
2755 }
2756 
2757 /* Check if current user has createdb privileges */
2758 static bool
2760 {
2761  bool result = false;
2762  HeapTuple utup;
2763 
2764  /* Superusers can always do everything */
2765  if (superuser())
2766  return true;
2767 
2769  if (HeapTupleIsValid(utup))
2770  {
2771  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
2772  ReleaseSysCache(utup);
2773  }
2774  return result;
2775 }
2776 
2777 /*
2778  * Remove tablespace directories
2779  *
2780  * We don't know what tablespaces db_id is using, so iterate through all
2781  * tablespaces removing <tablespace>/db_id
2782  */
2783 static void
2785 {
2786  Relation rel;
2787  TableScanDesc scan;
2788  HeapTuple tuple;
2789  List *ltblspc = NIL;
2790  ListCell *cell;
2791  int ntblspc;
2792  int i;
2793  Oid *tablespace_ids;
2794 
2795  rel = table_open(TableSpaceRelationId, AccessShareLock);
2796  scan = table_beginscan_catalog(rel, 0, NULL);
2797  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2798  {
2799  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2800  Oid dsttablespace = spcform->oid;
2801  char *dstpath;
2802  struct stat st;
2803 
2804  /* Don't mess with the global tablespace */
2805  if (dsttablespace == GLOBALTABLESPACE_OID)
2806  continue;
2807 
2808  dstpath = GetDatabasePath(db_id, dsttablespace);
2809 
2810  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
2811  {
2812  /* Assume we can ignore it */
2813  pfree(dstpath);
2814  continue;
2815  }
2816 
2817  if (!rmtree(dstpath, true))
2818  ereport(WARNING,
2819  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2820  dstpath)));
2821 
2822  ltblspc = lappend_oid(ltblspc, dsttablespace);
2823  pfree(dstpath);
2824  }
2825 
2826  ntblspc = list_length(ltblspc);
2827  if (ntblspc == 0)
2828  {
2829  table_endscan(scan);
2831  return;
2832  }
2833 
2834  tablespace_ids = (Oid *) palloc(ntblspc * sizeof(Oid));
2835  i = 0;
2836  foreach(cell, ltblspc)
2837  tablespace_ids[i++] = lfirst_oid(cell);
2838 
2839  /* Record the filesystem change in XLOG */
2840  {
2841  xl_dbase_drop_rec xlrec;
2842 
2843  xlrec.db_id = db_id;
2844  xlrec.ntablespaces = ntblspc;
2845 
2846  XLogBeginInsert();
2847  XLogRegisterData((char *) &xlrec, MinSizeOfDbaseDropRec);
2848  XLogRegisterData((char *) tablespace_ids, ntblspc * sizeof(Oid));
2849 
2850  (void) XLogInsert(RM_DBASE_ID,
2852  }
2853 
2854  list_free(ltblspc);
2855  pfree(tablespace_ids);
2856 
2857  table_endscan(scan);
2859 }
2860 
2861 /*
2862  * Check for existing files that conflict with a proposed new DB OID;
2863  * return true if there are any
2864  *
2865  * If there were a subdirectory in any tablespace matching the proposed new
2866  * OID, we'd get a create failure due to the duplicate name ... and then we'd
2867  * try to remove that already-existing subdirectory during the cleanup in
2868  * remove_dbtablespaces. Nuking existing files seems like a bad idea, so
2869  * instead we make this extra check before settling on the OID of the new
2870  * database. This exactly parallels what GetNewRelFileNode() does for table
2871  * relfilenode values.
2872  */
2873 static bool
2875 {
2876  bool result = false;
2877  Relation rel;
2878  TableScanDesc scan;
2879  HeapTuple tuple;
2880 
2881  rel = table_open(TableSpaceRelationId, AccessShareLock);
2882  scan = table_beginscan_catalog(rel, 0, NULL);
2883  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2884  {
2885  Form_pg_tablespace spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
2886  Oid dsttablespace = spcform->oid;
2887  char *dstpath;
2888  struct stat st;
2889 
2890  /* Don't mess with the global tablespace */
2891  if (dsttablespace == GLOBALTABLESPACE_OID)
2892  continue;
2893 
2894  dstpath = GetDatabasePath(db_id, dsttablespace);
2895 
2896  if (lstat(dstpath, &st) == 0)
2897  {
2898  /* Found a conflicting file (or directory, whatever) */
2899  pfree(dstpath);
2900  result = true;
2901  break;
2902  }
2903 
2904  pfree(dstpath);
2905  }
2906 
2907  table_endscan(scan);
2909 
2910  return result;
2911 }
2912 
2913 /*
2914  * Issue a suitable errdetail message for a busy database
2915  */
2916 static int
2917 errdetail_busy_db(int notherbackends, int npreparedxacts)
2918 {
2919  if (notherbackends > 0 && npreparedxacts > 0)
2920 
2921  /*
2922  * We don't deal with singular versus plural here, since gettext
2923  * doesn't support multiple plurals in one string.
2924  */
2925  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
2926  notherbackends, npreparedxacts);
2927  else if (notherbackends > 0)
2928  errdetail_plural("There is %d other session using the database.",
2929  "There are %d other sessions using the database.",
2930  notherbackends,
2931  notherbackends);
2932  else
2933  errdetail_plural("There is %d prepared transaction using the database.",
2934  "There are %d prepared transactions using the database.",
2935  npreparedxacts,
2936  npreparedxacts);
2937  return 0; /* just to keep ereport macro happy */
2938 }
2939 
2940 /*
2941  * get_database_oid - given a database name, look up the OID
2942  *
2943  * If missing_ok is false, throw an error if database name not found. If
2944  * true, just return InvalidOid.
2945  */
2946 Oid
2947 get_database_oid(const char *dbname, bool missing_ok)
2948 {
2949  Relation pg_database;
2950  ScanKeyData entry[1];
2951  SysScanDesc scan;
2952  HeapTuple dbtuple;
2953  Oid oid;
2954 
2955  /*
2956  * There's no syscache for pg_database indexed by name, so we must look
2957  * the hard way.
2958  */
2959  pg_database = table_open(DatabaseRelationId, AccessShareLock);
2960  ScanKeyInit(&entry[0],
2961  Anum_pg_database_datname,
2962  BTEqualStrategyNumber, F_NAMEEQ,
2964  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
2965  NULL, 1, entry);
2966 
2967  dbtuple = systable_getnext(scan);
2968 
2969  /* We assume that there can be at most one matching tuple */
2970  if (HeapTupleIsValid(dbtuple))
2971  oid = ((Form_pg_database) GETSTRUCT(dbtuple))->oid;
2972  else
2973  oid = InvalidOid;
2974 
2975  systable_endscan(scan);
2976  table_close(pg_database, AccessShareLock);
2977 
2978  if (!OidIsValid(oid) && !missing_ok)
2979  ereport(ERROR,
2980  (errcode(ERRCODE_UNDEFINED_DATABASE),
2981  errmsg("database \"%s\" does not exist",
2982  dbname)));
2983 
2984  return oid;
2985 }
2986 
2987 
2988 /*
2989  * get_database_name - given a database OID, look up the name
2990  *
2991  * Returns a palloc'd string, or NULL if no such database.
2992  */
2993 char *
2995 {
2996  HeapTuple dbtuple;
2997  char *result;
2998 
2999  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
3000  if (HeapTupleIsValid(dbtuple))
3001  {
3002  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
3003  ReleaseSysCache(dbtuple);
3004  }
3005  else
3006  result = NULL;
3007 
3008  return result;
3009 }
3010 
3011 /*
3012  * DATABASE resource manager's routines
3013  */
3014 void
3016 {
3017  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
3018 
3019  /* Backup blocks are not used in dbase records */
3020  Assert(!XLogRecHasAnyBlockRefs(record));
3021 
3022  if (info == XLOG_DBASE_CREATE_FILE_COPY)
3023  {
3026  char *src_path;
3027  char *dst_path;
3028  struct stat st;
3029 
3030  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
3031  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3032 
3033  /*
3034  * Our theory for replaying a CREATE is to forcibly drop the target
3035  * subdirectory if present, then re-copy the source data. This may be
3036  * more work than needed, but it is simple to implement.
3037  */
3038  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
3039  {
3040  if (!rmtree(dst_path, true))
3041  /* If this failed, copydir() below is going to error. */
3042  ereport(WARNING,
3043  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3044  dst_path)));
3045  }
3046 
3047  /*
3048  * Force dirty buffers out to disk, to ensure source database is
3049  * up-to-date for the copy.
3050  */
3052 
3053  /* Close all sgmr fds in all backends. */
3055 
3056  /*
3057  * Copy this subdirectory to the new location
3058  *
3059  * We don't need to copy subdirectories
3060  */
3061  copydir(src_path, dst_path, false);
3062 
3063  pfree(src_path);
3064  pfree(dst_path);
3065  }
3066  else if (info == XLOG_DBASE_CREATE_WAL_LOG)
3067  {
3070  char *dbpath;
3071 
3072  dbpath = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
3073 
3074  /* Create the database directory with the version file. */
3075  CreateDirAndVersionFile(dbpath, xlrec->db_id, xlrec->tablespace_id,
3076  true);
3077  pfree(dbpath);
3078  }
3079  else if (info == XLOG_DBASE_DROP)
3080  {
3081  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
3082  char *dst_path;
3083  int i;
3084 
3085  if (InHotStandby)
3086  {
3087  /*
3088  * Lock database while we resolve conflicts to ensure that
3089  * InitPostgres() cannot fully re-execute concurrently. This
3090  * avoids backends re-connecting automatically to same database,
3091  * which can happen in some cases.
3092  *
3093  * This will lock out walsenders trying to connect to db-specific
3094  * slots for logical decoding too, so it's safe for us to drop
3095  * slots.
3096  */
3097  LockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3099  }
3100 
3101  /* Drop any database-specific replication slots */
3103 
3104  /* Drop pages for this database that are in the shared buffer cache */
3105  DropDatabaseBuffers(xlrec->db_id);
3106 
3107  /* Also, clean out any fsync requests that might be pending in md.c */
3109 
3110  /* Clean out the xlog relcache too */
3111  XLogDropDatabase(xlrec->db_id);
3112 
3113  /* Close all sgmr fds in all backends. */
3115 
3116  for (i = 0; i < xlrec->ntablespaces; i++)
3117  {
3118  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_ids[i]);
3119 
3120  /* And remove the physical files */
3121  if (!rmtree(dst_path, true))
3122  ereport(WARNING,
3123  (errmsg("some useless files may be left behind in old database directory \"%s\"",
3124  dst_path)));
3125  pfree(dst_path);
3126  }
3127 
3128  if (InHotStandby)
3129  {
3130  /*
3131  * Release locks prior to commit. XXX There is a race condition
3132  * here that may allow backends to reconnect, but the window for
3133  * this is small because the gap between here and commit is mostly
3134  * fairly small and it is unlikely that people will be dropping
3135  * databases that we are trying to connect to anyway.
3136  */
3137  UnlockSharedObjectForSession(DatabaseRelationId, xlrec->db_id, 0, AccessExclusiveLock);
3138  }
3139  }
3140  else
3141  elog(PANIC, "dbase_redo: unknown op code %u", info);
3142 }
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1053
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5177
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:5003
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
#define DatumGetAclP(X)
Definition: acl.h:120
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:5121
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:5589
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
bool directory_is_empty(const char *path)
Definition: tablespace.c:899
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1474
uint32 BlockNumber
Definition: block.h:31
static Datum values[MAXATTR]
Definition: bootstrap.c:156
int Buffer
Definition: buf.h:23
void CreateAndCopyRelationData(RelFileNode src_rnode, RelFileNode dst_rnode, bool permanent)
Definition: bufmgr.c:3778
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3404
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2755
Buffer ReadBufferWithoutRelcache(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool permanent)
Definition: bufmgr.c:789
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3938
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4156
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3852
@ BAS_BULKREAD
Definition: bufmgr.h:30
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
@ RBM_NORMAL
Definition: bufmgr.h:39
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
Pointer Page
Definition: bufpage.h:78
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:356
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:234
#define PageIsEmpty(page)
Definition: bufpage.h:221
#define PageGetItem(page, itemId)
Definition: bufpage.h:339
#define PageIsNew(page)
Definition: bufpage.h:228
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:681
#define PG_BINARY
Definition: c.h:1268
TransactionId MultiXactId
Definition: c.h:597
unsigned char uint8
Definition: c.h:439
#define MemSet(start, val, len)
Definition: c.h:1008
uint32 TransactionId
Definition: c.h:587
#define OidIsValid(objectId)
Definition: c.h:710
#define AssertArg(condition)
Definition: c.h:806
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:391
void RequestCheckpoint(int flags)
Definition: checkpointer.c:931
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype, char **dbIculocale, char *dbLocProvider, char **dbCollversion)
Definition: dbcommands.c:2611
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:2784
static void CreateDirAndVersionFile(char *dbpath, Oid dbid, Oid tsid, bool isRedo)
Definition: dbcommands.c:460
ObjectAddress AlterDatabaseRefreshColl(AlterDatabaseRefreshCollStmt *stmt)
Definition: dbcommands.c:2347
ObjectAddress RenameDatabase(const char *oldname, const char *newname)
Definition: dbcommands.c:1717
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2994
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2947
CreateDBStrategy
Definition: dbcommands.c:81
@ CREATEDB_FILE_COPY
Definition: dbcommands.c:83
@ CREATEDB_WAL_LOG
Definition: dbcommands.c:82
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:2138
static List * ScanSourceDatabasePgClass(Oid srctbid, Oid srcdbid, char *srcpath)
Definition: dbcommands.c:247
ObjectAddress AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
Definition: dbcommands.c:2456
Datum pg_database_collation_actual_version(PG_FUNCTION_ARGS)
Definition: dbcommands.c:2569
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1815
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Definition: dbcommands.c:1434
Oid createdb(ParseState *pstate, const CreatedbStmt *stmt)
Definition: dbcommands.c:674
Oid AlterDatabase(ParseState *pstate, AlterDatabaseStmt *stmt, bool isTopLevel)
Definition: dbcommands.c:2180
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:2917
static CreateDBRelInfo * ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid, char *srcpath)
Definition: dbcommands.c:395
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:2874
static void CreateDatabaseUsingFileCopy(Oid src_dboid, Oid dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:554
struct CreateDBRelInfo CreateDBRelInfo
static bool have_createdb_privilege(void)
Definition: dbcommands.c:2759
void dbase_redo(XLogReaderState *record)
Definition: dbcommands.c:3015
void DropDatabase(ParseState *pstate, DropdbStmt *stmt)
Definition: dbcommands.c:2155
void dropdb(const char *dbname, bool missing_ok, bool force)
Definition: dbcommands.c:1511
static void CreateDatabaseUsingWalLog(Oid src_dboid, Oid dboid, Oid src_tsid, Oid dst_tsid)
Definition: dbcommands.c:145
static List * ScanSourceDatabasePgClassPage(Page page, Buffer buf, Oid tbid, Oid dbid, char *srcpath, List *rnodelist, Snapshot snapshot)
Definition: dbcommands.c:332
Oid AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
Definition: dbcommands.c:2430
static void createdb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1472
#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:163
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:352
int errcode_for_file_access(void)
Definition: elog.c:716
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1129
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define WARNING
Definition: elog.h:30
#define PANIC
Definition: elog.h:36
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define NOTICE
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:143
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:500
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
const char * name
Definition: encode.c:561
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2788
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3803
int FreeDir(DIR *dir)
Definition: fd.c:2840
int CloseTransientFile(int fd)
Definition: fd.c:2688
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2511
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2722
static char dstpath[MAXPGPATH]
Definition: file_ops.c:32
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
bool IsBinaryUpgrade
Definition: globals.c:114
bool IsUnderPostmaster
Definition: globals.c:113
bool allowSystemTableMods
Definition: globals.c:124
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1296
bool HeapTupleSatisfiesVisibility(HeapTuple tup, Snapshot snapshot, Buffer buffer)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
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)
Definition: htup_details.h:788
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#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
int i
Definition: isn.c:73
#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
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
void list_free(List *list)
Definition: list.c:1505
void list_free_deep(List *list)
Definition: list.c:1519
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1106
void UnlockRelationId(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:213
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1067
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1088
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 ShareLock
Definition: lockdefs.h:40
#define RowExclusiveLock
Definition: lockdefs.h:38
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc(Size size)
Definition: mcxt.c:1068
void ForgetDatabaseSyncRequests(Oid dbid)
Definition: md.c:1039
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
Oid GetUserId(void)
Definition: miscinit.c:492
#define InvalidMultiXactId
Definition: multixact.h:24
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:624
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:171
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:195
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:180
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#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:110
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2176
@ OBJECT_DATABASE
Definition: parsenodes.h:2143
#define ACL_CREATE
Definition: parsenodes.h:91
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolcreatedb
Definition: pg_authid.h:38
void * arg
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define MAXPGPATH
char datlocprovider
Definition: pg_database.h:44
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
NameData datname
Definition: pg_database.h:35
int32 encoding
Definition: pg_database.h:41
void DropSetting(Oid databaseid, Oid roleid)
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define lfirst_oid(lc)
Definition: pg_list.h:171
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1684
void check_icu_locale(const char *icu_locale)
Definition: pg_locale.c:1991
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:246
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:953
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:312
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
Definition: pg_shdepend.c:849
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:1165
int CountDBSubscriptions(Oid dbid)
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
static char * buf
Definition: pg_test_fsync.c:67
@ PG_SQL_ASCII
Definition: pg_wchar.h:224
@ PG_UTF8
Definition: pg_wchar.h:230
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:279
void pgstat_drop_database(Oid databaseid)
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define sprintf
Definition: port.h:227
#define snprintf
Definition: port.h:225
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:451
#define TransactionIdGetDatum(X)
Definition: postgres.h:565
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define DatumGetPointer(X)
Definition: postgres.h:593
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define BoolGetDatum(X)
Definition: postgres.h:446
#define Int32GetDatum(X)
Definition: postgres.h:523
#define CharGetDatum(X)
Definition: postgres.h:460
#define PointerGetDatum(X)
Definition: postgres.h:600
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void TerminateOtherDBBackends(Oid databaseId)
Definition: procarray.c:3797
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:3719
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:392
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:332
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:52
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:556
#define RelationGetDescr(relation)
Definition: rel.h:515
void RelationMapCopy(Oid dbid, Oid tsid, char *srcdbpath, char *dstdbpath)
Definition: relmapper.c:288
Oid RelationMapOidToFilenodeForDatabase(char *dbpath, Oid relationId)
Definition: relmapper.c:261
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
@ MAIN_FORKNUM
Definition: relpath.h:43
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12192
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:26
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:982
void ReplicationSlotsDropDBSlots(Oid dboid)
Definition: slot.c:1038
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:579
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
void PopActiveSnapshot(void)
Definition: snapmgr.c:776
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:531
#define BTEqualStrategyNumber
Definition: stratnum.h:31
char * dbname
Definition: streamutil.c:51
VariableSetStmt * setstmt
Definition: parsenodes.h:3666
RelFileNode rnode
Definition: dbcommands.c:104
List * options
Definition: parsenodes.h:3642
char * dbname
Definition: parsenodes.h:3641
Definition: dirent.c:26
char * defname
Definition: parsenodes.h:765
int location
Definition: parsenodes.h:769
Node * arg
Definition: parsenodes.h:766
List * options
Definition: parsenodes.h:3678
char * dbname
Definition: parsenodes.h:3676
bool missing_ok
Definition: parsenodes.h:3677
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: value.h:29
Definition: pg_list.h:51
Definition: rel.h:38
Oid relId
Definition: rel.h:39
Oid dbId
Definition: rel.h:40
CreateDBStrategy strategy
Definition: dbcommands.c:90
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
unsigned short st_mode
Definition: win32_port.h:268
Oid tablespace_ids[FLEXIBLE_ARRAY_MEMBER]
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ AUTHOID
Definition: syscache.h:45
@ DATABASEOID
Definition: syscache.h:55
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:993
#define InvalidTransactionId
Definition: transam.h:31
#define FirstNormalObjectId
Definition: transam.h:197
text * cstring_to_text(const char *s)
Definition: varlena.c:188
@ WAIT_EVENT_VERSION_FILE_WRITE
Definition: wait_event.h:220
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:266
static void pgstat_report_wait_end(void)
Definition: wait_event.h:282
#define stat
Definition: win32_port.h:283
#define lstat(path, sb)
Definition: win32_port.h:284
#define S_ISDIR(m)
Definition: win32_port.h:324
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3462
void StartTransactionCommand(void)
Definition: xact.c:2925
void ForceSyncCommit(void)
Definition: xact.c:1124
void CommitTransactionCommand(void)
Definition: xact.c:3022
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2509
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:138
#define CHECKPOINT_FORCE
Definition: xlog.h:137
#define CHECKPOINT_WAIT
Definition: xlog.h:140
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:136
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:443
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:351
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:408
#define XLogRecGetData(decoder)
Definition: xlogreader.h:413
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:415
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
void FreeFakeRelcacheEntry(Relation fakerel)
Definition: xlogutils.c:640
Relation CreateFakeRelcacheEntry(RelFileNode rnode)
Definition: xlogutils.c:597
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:666
#define InHotStandby
Definition: xlogutils.h:57