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