PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2016, 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 <locale.h>
24 #include <unistd.h>
25 #include <sys/stat.h>
26 
27 #include "access/genam.h"
28 #include "access/heapam.h"
29 #include "access/htup_details.h"
30 #include "access/xact.h"
31 #include "access/xloginsert.h"
32 #include "access/xlogutils.h"
33 #include "catalog/catalog.h"
34 #include "catalog/dependency.h"
35 #include "catalog/indexing.h"
36 #include "catalog/objectaccess.h"
37 #include "catalog/pg_authid.h"
38 #include "catalog/pg_database.h"
40 #include "catalog/pg_tablespace.h"
41 #include "commands/comment.h"
42 #include "commands/dbcommands.h"
44 #include "commands/defrem.h"
45 #include "commands/seclabel.h"
46 #include "commands/tablespace.h"
47 #include "mb/pg_wchar.h"
48 #include "miscadmin.h"
49 #include "pgstat.h"
50 #include "postmaster/bgwriter.h"
51 #include "replication/slot.h"
52 #include "storage/copydir.h"
53 #include "storage/fd.h"
54 #include "storage/lmgr.h"
55 #include "storage/ipc.h"
56 #include "storage/procarray.h"
57 #include "storage/smgr.h"
58 #include "utils/acl.h"
59 #include "utils/builtins.h"
60 #include "utils/fmgroids.h"
61 #include "utils/pg_locale.h"
62 #include "utils/snapmgr.h"
63 #include "utils/syscache.h"
64 #include "utils/tqual.h"
65 
66 
67 typedef struct
68 {
69  Oid src_dboid; /* source (template) DB */
70  Oid dest_dboid; /* DB we are trying to create */
72 
73 typedef struct
74 {
75  Oid dest_dboid; /* DB we are trying to move */
76  Oid dest_tsoid; /* tablespace we are trying to move to */
78 
79 /* non-export function prototypes */
80 static void createdb_failure_callback(int code, Datum arg);
81 static void movedb(const char *dbname, const char *tblspcname);
82 static void movedb_failure_callback(int code, Datum arg);
83 static bool get_db_info(const char *name, LOCKMODE lockmode,
84  Oid *dbIdP, Oid *ownerIdP,
85  int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
86  Oid *dbLastSysOidP, TransactionId *dbFrozenXidP,
87  MultiXactId *dbMinMultiP,
88  Oid *dbTablespace, char **dbCollate, char **dbCtype);
89 static bool have_createdb_privilege(void);
90 static void remove_dbtablespaces(Oid db_id);
91 static bool check_db_file_conflict(Oid db_id);
92 static int errdetail_busy_db(int notherbackends, int npreparedxacts);
93 
94 
95 /*
96  * CREATE DATABASE
97  */
98 Oid
99 createdb(const CreatedbStmt *stmt)
100 {
101  HeapScanDesc scan;
102  Relation rel;
103  Oid src_dboid;
104  Oid src_owner;
105  int src_encoding;
106  char *src_collate;
107  char *src_ctype;
108  bool src_istemplate;
109  bool src_allowconn;
110  Oid src_lastsysoid;
111  TransactionId src_frozenxid;
112  MultiXactId src_minmxid;
113  Oid src_deftablespace;
114  volatile Oid dst_deftablespace;
115  Relation pg_database_rel;
116  HeapTuple tuple;
117  Datum new_record[Natts_pg_database];
118  bool new_record_nulls[Natts_pg_database];
119  Oid dboid;
120  Oid datdba;
121  ListCell *option;
122  DefElem *dtablespacename = NULL;
123  DefElem *downer = NULL;
124  DefElem *dtemplate = NULL;
125  DefElem *dencoding = NULL;
126  DefElem *dcollate = NULL;
127  DefElem *dctype = NULL;
128  DefElem *distemplate = NULL;
129  DefElem *dallowconnections = NULL;
130  DefElem *dconnlimit = NULL;
131  char *dbname = stmt->dbname;
132  char *dbowner = NULL;
133  const char *dbtemplate = NULL;
134  char *dbcollate = NULL;
135  char *dbctype = NULL;
136  char *canonname;
137  int encoding = -1;
138  bool dbistemplate = false;
139  bool dballowconnections = true;
140  int dbconnlimit = -1;
141  int notherbackends;
142  int npreparedxacts;
144 
145  /* Extract options from the statement node tree */
146  foreach(option, stmt->options)
147  {
148  DefElem *defel = (DefElem *) lfirst(option);
149 
150  if (strcmp(defel->defname, "tablespace") == 0)
151  {
152  if (dtablespacename)
153  ereport(ERROR,
154  (errcode(ERRCODE_SYNTAX_ERROR),
155  errmsg("conflicting or redundant options")));
156  dtablespacename = defel;
157  }
158  else if (strcmp(defel->defname, "owner") == 0)
159  {
160  if (downer)
161  ereport(ERROR,
162  (errcode(ERRCODE_SYNTAX_ERROR),
163  errmsg("conflicting or redundant options")));
164  downer = defel;
165  }
166  else if (strcmp(defel->defname, "template") == 0)
167  {
168  if (dtemplate)
169  ereport(ERROR,
170  (errcode(ERRCODE_SYNTAX_ERROR),
171  errmsg("conflicting or redundant options")));
172  dtemplate = defel;
173  }
174  else if (strcmp(defel->defname, "encoding") == 0)
175  {
176  if (dencoding)
177  ereport(ERROR,
178  (errcode(ERRCODE_SYNTAX_ERROR),
179  errmsg("conflicting or redundant options")));
180  dencoding = defel;
181  }
182  else if (strcmp(defel->defname, "lc_collate") == 0)
183  {
184  if (dcollate)
185  ereport(ERROR,
186  (errcode(ERRCODE_SYNTAX_ERROR),
187  errmsg("conflicting or redundant options")));
188  dcollate = defel;
189  }
190  else if (strcmp(defel->defname, "lc_ctype") == 0)
191  {
192  if (dctype)
193  ereport(ERROR,
194  (errcode(ERRCODE_SYNTAX_ERROR),
195  errmsg("conflicting or redundant options")));
196  dctype = defel;
197  }
198  else if (strcmp(defel->defname, "is_template") == 0)
199  {
200  if (distemplate)
201  ereport(ERROR,
202  (errcode(ERRCODE_SYNTAX_ERROR),
203  errmsg("conflicting or redundant options")));
204  distemplate = defel;
205  }
206  else if (strcmp(defel->defname, "allow_connections") == 0)
207  {
208  if (dallowconnections)
209  ereport(ERROR,
210  (errcode(ERRCODE_SYNTAX_ERROR),
211  errmsg("conflicting or redundant options")));
212  dallowconnections = defel;
213  }
214  else if (strcmp(defel->defname, "connection_limit") == 0)
215  {
216  if (dconnlimit)
217  ereport(ERROR,
218  (errcode(ERRCODE_SYNTAX_ERROR),
219  errmsg("conflicting or redundant options")));
220  dconnlimit = defel;
221  }
222  else if (strcmp(defel->defname, "location") == 0)
223  {
225  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
226  errmsg("LOCATION is not supported anymore"),
227  errhint("Consider using tablespaces instead.")));
228  }
229  else
230  ereport(ERROR,
231  (errcode(ERRCODE_SYNTAX_ERROR),
232  errmsg("option \"%s\" not recognized", defel->defname)));
233  }
234 
235  if (downer && downer->arg)
236  dbowner = defGetString(downer);
237  if (dtemplate && dtemplate->arg)
238  dbtemplate = defGetString(dtemplate);
239  if (dencoding && dencoding->arg)
240  {
241  const char *encoding_name;
242 
243  if (IsA(dencoding->arg, Integer))
244  {
245  encoding = defGetInt32(dencoding);
246  encoding_name = pg_encoding_to_char(encoding);
247  if (strcmp(encoding_name, "") == 0 ||
248  pg_valid_server_encoding(encoding_name) < 0)
249  ereport(ERROR,
250  (errcode(ERRCODE_UNDEFINED_OBJECT),
251  errmsg("%d is not a valid encoding code",
252  encoding)));
253  }
254  else
255  {
256  encoding_name = defGetString(dencoding);
257  encoding = pg_valid_server_encoding(encoding_name);
258  if (encoding < 0)
259  ereport(ERROR,
260  (errcode(ERRCODE_UNDEFINED_OBJECT),
261  errmsg("%s is not a valid encoding name",
262  encoding_name)));
263  }
264  }
265  if (dcollate && dcollate->arg)
266  dbcollate = defGetString(dcollate);
267  if (dctype && dctype->arg)
268  dbctype = defGetString(dctype);
269  if (distemplate && distemplate->arg)
270  dbistemplate = defGetBoolean(distemplate);
271  if (dallowconnections && dallowconnections->arg)
272  dballowconnections = defGetBoolean(dallowconnections);
273  if (dconnlimit && dconnlimit->arg)
274  {
275  dbconnlimit = defGetInt32(dconnlimit);
276  if (dbconnlimit < -1)
277  ereport(ERROR,
278  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
279  errmsg("invalid connection limit: %d", dbconnlimit)));
280  }
281 
282  /* obtain OID of proposed owner */
283  if (dbowner)
284  datdba = get_role_oid(dbowner, false);
285  else
286  datdba = GetUserId();
287 
288  /*
289  * To create a database, must have createdb privilege and must be able to
290  * become the target role (this does not imply that the target role itself
291  * must have createdb privilege). The latter provision guards against
292  * "giveaway" attacks. Note that a superuser will always have both of
293  * these privileges a fortiori.
294  */
296  ereport(ERROR,
297  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
298  errmsg("permission denied to create database")));
299 
301 
302  /*
303  * Lookup database (template) to be cloned, and obtain share lock on it.
304  * ShareLock allows two CREATE DATABASEs to work from the same template
305  * concurrently, while ensuring no one is busy dropping it in parallel
306  * (which would be Very Bad since we'd likely get an incomplete copy
307  * without knowing it). This also prevents any new connections from being
308  * made to the source until we finish copying it, so we can be sure it
309  * won't change underneath us.
310  */
311  if (!dbtemplate)
312  dbtemplate = "template1"; /* Default template database name */
313 
314  if (!get_db_info(dbtemplate, ShareLock,
315  &src_dboid, &src_owner, &src_encoding,
316  &src_istemplate, &src_allowconn, &src_lastsysoid,
317  &src_frozenxid, &src_minmxid, &src_deftablespace,
318  &src_collate, &src_ctype))
319  ereport(ERROR,
320  (errcode(ERRCODE_UNDEFINED_DATABASE),
321  errmsg("template database \"%s\" does not exist",
322  dbtemplate)));
323 
324  /*
325  * Permission check: to copy a DB that's not marked datistemplate, you
326  * must be superuser or the owner thereof.
327  */
328  if (!src_istemplate)
329  {
330  if (!pg_database_ownercheck(src_dboid, GetUserId()))
331  ereport(ERROR,
332  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
333  errmsg("permission denied to copy database \"%s\"",
334  dbtemplate)));
335  }
336 
337  /* If encoding or locales are defaulted, use source's setting */
338  if (encoding < 0)
339  encoding = src_encoding;
340  if (dbcollate == NULL)
341  dbcollate = src_collate;
342  if (dbctype == NULL)
343  dbctype = src_ctype;
344 
345  /* Some encodings are client only */
346  if (!PG_VALID_BE_ENCODING(encoding))
347  ereport(ERROR,
348  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
349  errmsg("invalid server encoding %d", encoding)));
350 
351  /* Check that the chosen locales are valid, and get canonical spellings */
352  if (!check_locale(LC_COLLATE, dbcollate, &canonname))
353  ereport(ERROR,
354  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
355  errmsg("invalid locale name: \"%s\"", dbcollate)));
356  dbcollate = canonname;
357  if (!check_locale(LC_CTYPE, dbctype, &canonname))
358  ereport(ERROR,
359  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
360  errmsg("invalid locale name: \"%s\"", dbctype)));
361  dbctype = canonname;
362 
363  check_encoding_locale_matches(encoding, dbcollate, dbctype);
364 
365  /*
366  * Check that the new encoding and locale settings match the source
367  * database. We insist on this because we simply copy the source data ---
368  * any non-ASCII data would be wrongly encoded, and any indexes sorted
369  * according to the source locale would be wrong.
370  *
371  * However, we assume that template0 doesn't contain any non-ASCII data
372  * nor any indexes that depend on collation or ctype, so template0 can be
373  * used as template for creating a database with any encoding or locale.
374  */
375  if (strcmp(dbtemplate, "template0") != 0)
376  {
377  if (encoding != src_encoding)
378  ereport(ERROR,
379  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
380  errmsg("new encoding (%s) is incompatible with the encoding of the template database (%s)",
381  pg_encoding_to_char(encoding),
382  pg_encoding_to_char(src_encoding)),
383  errhint("Use the same encoding as in the template database, or use template0 as template.")));
384 
385  if (strcmp(dbcollate, src_collate) != 0)
386  ereport(ERROR,
387  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
388  errmsg("new collation (%s) is incompatible with the collation of the template database (%s)",
389  dbcollate, src_collate),
390  errhint("Use the same collation as in the template database, or use template0 as template.")));
391 
392  if (strcmp(dbctype, src_ctype) != 0)
393  ereport(ERROR,
394  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
395  errmsg("new LC_CTYPE (%s) is incompatible with the LC_CTYPE of the template database (%s)",
396  dbctype, src_ctype),
397  errhint("Use the same LC_CTYPE as in the template database, or use template0 as template.")));
398  }
399 
400  /* Resolve default tablespace for new database */
401  if (dtablespacename && dtablespacename->arg)
402  {
403  char *tablespacename;
404  AclResult aclresult;
405 
406  tablespacename = defGetString(dtablespacename);
407  dst_deftablespace = get_tablespace_oid(tablespacename, false);
408  /* check permissions */
409  aclresult = pg_tablespace_aclcheck(dst_deftablespace, GetUserId(),
410  ACL_CREATE);
411  if (aclresult != ACLCHECK_OK)
413  tablespacename);
414 
415  /* pg_global must never be the default tablespace */
416  if (dst_deftablespace == GLOBALTABLESPACE_OID)
417  ereport(ERROR,
418  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
419  errmsg("pg_global cannot be used as default tablespace")));
420 
421  /*
422  * If we are trying to change the default tablespace of the template,
423  * we require that the template not have any files in the new default
424  * tablespace. This is necessary because otherwise the copied
425  * database would contain pg_class rows that refer to its default
426  * tablespace both explicitly (by OID) and implicitly (as zero), which
427  * would cause problems. For example another CREATE DATABASE using
428  * the copied database as template, and trying to change its default
429  * tablespace again, would yield outright incorrect results (it would
430  * improperly move tables to the new default tablespace that should
431  * stay in the same tablespace).
432  */
433  if (dst_deftablespace != src_deftablespace)
434  {
435  char *srcpath;
436  struct stat st;
437 
438  srcpath = GetDatabasePath(src_dboid, dst_deftablespace);
439 
440  if (stat(srcpath, &st) == 0 &&
441  S_ISDIR(st.st_mode) &&
442  !directory_is_empty(srcpath))
443  ereport(ERROR,
444  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
445  errmsg("cannot assign new default tablespace \"%s\"",
446  tablespacename),
447  errdetail("There is a conflict because database \"%s\" already has some tables in this tablespace.",
448  dbtemplate)));
449  pfree(srcpath);
450  }
451  }
452  else
453  {
454  /* Use template database's default tablespace */
455  dst_deftablespace = src_deftablespace;
456  /* Note there is no additional permission check in this path */
457  }
458 
459  /*
460  * Check for db name conflict. This is just to give a more friendly error
461  * message than "unique index violation". There's a race condition but
462  * we're willing to accept the less friendly message in that case.
463  */
464  if (OidIsValid(get_database_oid(dbname, true)))
465  ereport(ERROR,
466  (errcode(ERRCODE_DUPLICATE_DATABASE),
467  errmsg("database \"%s\" already exists", dbname)));
468 
469  /*
470  * The source DB can't have any active backends, except this one
471  * (exception is to allow CREATE DB while connected to template1).
472  * Otherwise we might copy inconsistent data.
473  *
474  * This should be last among the basic error checks, because it involves
475  * potential waiting; we may as well throw an error first if we're gonna
476  * throw one.
477  */
478  if (CountOtherDBBackends(src_dboid, &notherbackends, &npreparedxacts))
479  ereport(ERROR,
480  (errcode(ERRCODE_OBJECT_IN_USE),
481  errmsg("source database \"%s\" is being accessed by other users",
482  dbtemplate),
483  errdetail_busy_db(notherbackends, npreparedxacts)));
484 
485  /*
486  * Select an OID for the new database, checking that it doesn't have a
487  * filename conflict with anything already existing in the tablespace
488  * directories.
489  */
490  pg_database_rel = heap_open(DatabaseRelationId, RowExclusiveLock);
491 
492  do
493  {
494  dboid = GetNewOid(pg_database_rel);
495  } while (check_db_file_conflict(dboid));
496 
497  /*
498  * Insert a new tuple into pg_database. This establishes our ownership of
499  * the new database name (anyone else trying to insert the same name will
500  * block on the unique index, and fail after we commit).
501  */
502 
503  /* Form tuple */
504  MemSet(new_record, 0, sizeof(new_record));
505  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
506 
507  new_record[Anum_pg_database_datname - 1] =
509  new_record[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(datdba);
510  new_record[Anum_pg_database_encoding - 1] = Int32GetDatum(encoding);
511  new_record[Anum_pg_database_datcollate - 1] =
513  new_record[Anum_pg_database_datctype - 1] =
515  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
516  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
517  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
518  new_record[Anum_pg_database_datlastsysoid - 1] = ObjectIdGetDatum(src_lastsysoid);
519  new_record[Anum_pg_database_datfrozenxid - 1] = TransactionIdGetDatum(src_frozenxid);
520  new_record[Anum_pg_database_datminmxid - 1] = TransactionIdGetDatum(src_minmxid);
521  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_deftablespace);
522 
523  /*
524  * We deliberately set datacl to default (NULL), rather than copying it
525  * from the template database. Copying it would be a bad idea when the
526  * owner is not the same as the template's owner.
527  */
528  new_record_nulls[Anum_pg_database_datacl - 1] = true;
529 
530  tuple = heap_form_tuple(RelationGetDescr(pg_database_rel),
531  new_record, new_record_nulls);
532 
533  HeapTupleSetOid(tuple, dboid);
534 
535  simple_heap_insert(pg_database_rel, tuple);
536 
537  /* Update indexes */
538  CatalogUpdateIndexes(pg_database_rel, tuple);
539 
540  /*
541  * Now generate additional catalog entries associated with the new DB
542  */
543 
544  /* Register owner dependency */
546 
547  /* Create pg_shdepend entries for objects within database */
548  copyTemplateDependencies(src_dboid, dboid);
549 
550  /* Post creation hook for new database */
552 
553  /*
554  * Force a checkpoint before starting the copy. This will force all dirty
555  * buffers, including those of unlogged tables, out to disk, to ensure
556  * source database is up-to-date on disk for the copy.
557  * FlushDatabaseBuffers() would suffice for that, but we also want to
558  * process any pending unlink requests. Otherwise, if a checkpoint
559  * happened while we're copying files, a file might be deleted just when
560  * we're about to copy it, causing the lstat() call in copydir() to fail
561  * with ENOENT.
562  */
565 
566  /*
567  * Once we start copying subdirectories, we need to be able to clean 'em
568  * up if we fail. Use an ENSURE block to make sure this happens. (This
569  * is not a 100% solution, because of the possibility of failure during
570  * transaction commit after we leave this routine, but it should handle
571  * most scenarios.)
572  */
573  fparms.src_dboid = src_dboid;
574  fparms.dest_dboid = dboid;
576  PointerGetDatum(&fparms));
577  {
578  /*
579  * Iterate through all tablespaces of the template database, and copy
580  * each one to the new database.
581  */
583  scan = heap_beginscan_catalog(rel, 0, NULL);
584  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
585  {
586  Oid srctablespace = HeapTupleGetOid(tuple);
587  Oid dsttablespace;
588  char *srcpath;
589  char *dstpath;
590  struct stat st;
591 
592  /* No need to copy global tablespace */
593  if (srctablespace == GLOBALTABLESPACE_OID)
594  continue;
595 
596  srcpath = GetDatabasePath(src_dboid, srctablespace);
597 
598  if (stat(srcpath, &st) < 0 || !S_ISDIR(st.st_mode) ||
599  directory_is_empty(srcpath))
600  {
601  /* Assume we can ignore it */
602  pfree(srcpath);
603  continue;
604  }
605 
606  if (srctablespace == src_deftablespace)
607  dsttablespace = dst_deftablespace;
608  else
609  dsttablespace = srctablespace;
610 
611  dstpath = GetDatabasePath(dboid, dsttablespace);
612 
613  /*
614  * Copy this subdirectory to the new location
615  *
616  * We don't need to copy subdirectories
617  */
618  copydir(srcpath, dstpath, false);
619 
620  /* Record the filesystem change in XLOG */
621  {
622  xl_dbase_create_rec xlrec;
623 
624  xlrec.db_id = dboid;
625  xlrec.tablespace_id = dsttablespace;
626  xlrec.src_db_id = src_dboid;
627  xlrec.src_tablespace_id = srctablespace;
628 
629  XLogBeginInsert();
630  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
631 
632  (void) XLogInsert(RM_DBASE_ID,
634  }
635  }
636  heap_endscan(scan);
638 
639  /*
640  * We force a checkpoint before committing. This effectively means
641  * that committed XLOG_DBASE_CREATE operations will never need to be
642  * replayed (at least not in ordinary crash recovery; we still have to
643  * make the XLOG entry for the benefit of PITR operations). This
644  * avoids two nasty scenarios:
645  *
646  * #1: When PITR is off, we don't XLOG the contents of newly created
647  * indexes; therefore the drop-and-recreate-whole-directory behavior
648  * of DBASE_CREATE replay would lose such indexes.
649  *
650  * #2: Since we have to recopy the source database during DBASE_CREATE
651  * replay, we run the risk of copying changes in it that were
652  * committed after the original CREATE DATABASE command but before the
653  * system crash that led to the replay. This is at least unexpected
654  * and at worst could lead to inconsistencies, eg duplicate table
655  * names.
656  *
657  * (Both of these were real bugs in releases 8.0 through 8.0.3.)
658  *
659  * In PITR replay, the first of these isn't an issue, and the second
660  * is only a risk if the CREATE DATABASE and subsequent template
661  * database change both occur while a base backup is being taken.
662  * There doesn't seem to be much we can do about that except document
663  * it as a limitation.
664  *
665  * Perhaps if we ever implement CREATE DATABASE in a less cheesy way,
666  * we can avoid this.
667  */
669 
670  /*
671  * Close pg_database, but keep lock till commit.
672  */
673  heap_close(pg_database_rel, NoLock);
674 
675  /*
676  * Force synchronous commit, thus minimizing the window between
677  * creation of the database files and commital of the transaction. If
678  * we crash before committing, we'll have a DB that's taking up disk
679  * space but is not in pg_database, which is not good.
680  */
681  ForceSyncCommit();
682  }
684  PointerGetDatum(&fparms));
685 
686  return dboid;
687 }
688 
689 /*
690  * Check whether chosen encoding matches chosen locale settings. This
691  * restriction is necessary because libc's locale-specific code usually
692  * fails when presented with data in an encoding it's not expecting. We
693  * allow mismatch in four cases:
694  *
695  * 1. locale encoding = SQL_ASCII, which means that the locale is C/POSIX
696  * which works with any encoding.
697  *
698  * 2. locale encoding = -1, which means that we couldn't determine the
699  * locale's encoding and have to trust the user to get it right.
700  *
701  * 3. selected encoding is UTF8 and platform is win32. This is because
702  * UTF8 is a pseudo codepage that is supported in all locales since it's
703  * converted to UTF16 before being used.
704  *
705  * 4. selected encoding is SQL_ASCII, but only if you're a superuser. This
706  * is risky but we have historically allowed it --- notably, the
707  * regression tests require it.
708  *
709  * Note: if you change this policy, fix initdb to match.
710  */
711 void
712 check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
713 {
714  int ctype_encoding = pg_get_encoding_from_locale(ctype, true);
715  int collate_encoding = pg_get_encoding_from_locale(collate, true);
716 
717  if (!(ctype_encoding == encoding ||
718  ctype_encoding == PG_SQL_ASCII ||
719  ctype_encoding == -1 ||
720 #ifdef WIN32
721  encoding == PG_UTF8 ||
722 #endif
723  (encoding == PG_SQL_ASCII && superuser())))
724  ereport(ERROR,
725  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
726  errmsg("encoding \"%s\" does not match locale \"%s\"",
727  pg_encoding_to_char(encoding),
728  ctype),
729  errdetail("The chosen LC_CTYPE setting requires encoding \"%s\".",
730  pg_encoding_to_char(ctype_encoding))));
731 
732  if (!(collate_encoding == encoding ||
733  collate_encoding == PG_SQL_ASCII ||
734  collate_encoding == -1 ||
735 #ifdef WIN32
736  encoding == PG_UTF8 ||
737 #endif
738  (encoding == PG_SQL_ASCII && superuser())))
739  ereport(ERROR,
740  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
741  errmsg("encoding \"%s\" does not match locale \"%s\"",
742  pg_encoding_to_char(encoding),
743  collate),
744  errdetail("The chosen LC_COLLATE setting requires encoding \"%s\".",
745  pg_encoding_to_char(collate_encoding))));
746 }
747 
748 /* Error cleanup callback for createdb */
749 static void
751 {
753 
754  /*
755  * Release lock on source database before doing recursive remove. This is
756  * not essential but it seems desirable to release the lock as soon as
757  * possible.
758  */
760 
761  /* Throw away any successfully copied subdirectories */
763 }
764 
765 
766 /*
767  * DROP DATABASE
768  */
769 void
770 dropdb(const char *dbname, bool missing_ok)
771 {
772  Oid db_id;
773  bool db_istemplate;
774  Relation pgdbrel;
775  HeapTuple tup;
776  int notherbackends;
777  int npreparedxacts;
778  int nslots,
779  nslots_active;
780 
781  /*
782  * Look up the target database's OID, and get exclusive lock on it. We
783  * need this to ensure that no new backend starts up in the target
784  * database while we are deleting it (see postinit.c), and that no one is
785  * using it as a CREATE DATABASE template or trying to delete it for
786  * themselves.
787  */
789 
790  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
791  &db_istemplate, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
792  {
793  if (!missing_ok)
794  {
795  ereport(ERROR,
796  (errcode(ERRCODE_UNDEFINED_DATABASE),
797  errmsg("database \"%s\" does not exist", dbname)));
798  }
799  else
800  {
801  /* Close pg_database, release the lock, since we changed nothing */
802  heap_close(pgdbrel, RowExclusiveLock);
803  ereport(NOTICE,
804  (errmsg("database \"%s\" does not exist, skipping",
805  dbname)));
806  return;
807  }
808  }
809 
810  /*
811  * Permission checks
812  */
813  if (!pg_database_ownercheck(db_id, GetUserId()))
815  dbname);
816 
817  /* DROP hook for the database being removed */
819 
820  /*
821  * Disallow dropping a DB that is marked istemplate. This is just to
822  * prevent people from accidentally dropping template0 or template1; they
823  * can do so if they're really determined ...
824  */
825  if (db_istemplate)
826  ereport(ERROR,
827  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
828  errmsg("cannot drop a template database")));
829 
830  /* Obviously can't drop my own database */
831  if (db_id == MyDatabaseId)
832  ereport(ERROR,
833  (errcode(ERRCODE_OBJECT_IN_USE),
834  errmsg("cannot drop the currently open database")));
835 
836  /*
837  * Check whether there are, possibly unconnected, logical slots that refer
838  * to the to-be-dropped database. The database lock we are holding
839  * prevents the creation of new slots using the database.
840  */
841  if (ReplicationSlotsCountDBSlots(db_id, &nslots, &nslots_active))
842  ereport(ERROR,
843  (errcode(ERRCODE_OBJECT_IN_USE),
844  errmsg("database \"%s\" is used by a logical replication slot",
845  dbname),
846  errdetail_plural("There is %d slot, %d of them active.",
847  "There are %d slots, %d of them active.",
848  nslots,
849  nslots, nslots_active)));
850 
851  /*
852  * Check for other backends in the target database. (Because we hold the
853  * database lock, no new ones can start after this.)
854  *
855  * As in CREATE DATABASE, check this after other error conditions.
856  */
857  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
858  ereport(ERROR,
859  (errcode(ERRCODE_OBJECT_IN_USE),
860  errmsg("database \"%s\" is being accessed by other users",
861  dbname),
862  errdetail_busy_db(notherbackends, npreparedxacts)));
863 
864  /*
865  * Remove the database's tuple from pg_database.
866  */
868  if (!HeapTupleIsValid(tup))
869  elog(ERROR, "cache lookup failed for database %u", db_id);
870 
871  simple_heap_delete(pgdbrel, &tup->t_self);
872 
873  ReleaseSysCache(tup);
874 
875  /*
876  * Delete any comments or security labels associated with the database.
877  */
880 
881  /*
882  * Remove settings associated with this database
883  */
884  DropSetting(db_id, InvalidOid);
885 
886  /*
887  * Remove shared dependency references for the database.
888  */
890 
891  /*
892  * Drop pages for this database that are in the shared buffer cache. This
893  * is important to ensure that no remaining backend tries to write out a
894  * dirty buffer to the dead database later...
895  */
896  DropDatabaseBuffers(db_id);
897 
898  /*
899  * Tell the stats collector to forget it immediately, too.
900  */
901  pgstat_drop_database(db_id);
902 
903  /*
904  * Tell checkpointer to forget any pending fsync and unlink requests for
905  * files in the database; else the fsyncs will fail at next checkpoint, or
906  * worse, it will delete files that belong to a newly created database
907  * with the same OID.
908  */
910 
911  /*
912  * Force a checkpoint to make sure the checkpointer has received the
913  * message sent by ForgetDatabaseFsyncRequests. On Windows, this also
914  * ensures that background procs don't hold any open files, which would
915  * cause rmdir() to fail.
916  */
918 
919  /*
920  * Remove all tablespace subdirs belonging to the database.
921  */
922  remove_dbtablespaces(db_id);
923 
924  /*
925  * Close pg_database, but keep lock till commit.
926  */
927  heap_close(pgdbrel, NoLock);
928 
929  /*
930  * Force synchronous commit, thus minimizing the window between removal of
931  * the database files and commital of the transaction. If we crash before
932  * committing, we'll have a DB that's gone on disk but still there
933  * according to pg_database, which is not good.
934  */
935  ForceSyncCommit();
936 }
937 
938 
939 /*
940  * Rename database
941  */
943 RenameDatabase(const char *oldname, const char *newname)
944 {
945  Oid db_id;
946  HeapTuple newtup;
947  Relation rel;
948  int notherbackends;
949  int npreparedxacts;
950  ObjectAddress address;
951 
952  /*
953  * Look up the target database's OID, and get exclusive lock on it. We
954  * need this for the same reasons as DROP DATABASE.
955  */
957 
958  if (!get_db_info(oldname, AccessExclusiveLock, &db_id, NULL, NULL,
959  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
960  ereport(ERROR,
961  (errcode(ERRCODE_UNDEFINED_DATABASE),
962  errmsg("database \"%s\" does not exist", oldname)));
963 
964  /* must be owner */
965  if (!pg_database_ownercheck(db_id, GetUserId()))
967  oldname);
968 
969  /* must have createdb rights */
971  ereport(ERROR,
972  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
973  errmsg("permission denied to rename database")));
974 
975  /*
976  * Make sure the new name doesn't exist. See notes for same error in
977  * CREATE DATABASE.
978  */
979  if (OidIsValid(get_database_oid(newname, true)))
980  ereport(ERROR,
981  (errcode(ERRCODE_DUPLICATE_DATABASE),
982  errmsg("database \"%s\" already exists", newname)));
983 
984  /*
985  * XXX Client applications probably store the current database somewhere,
986  * so renaming it could cause confusion. On the other hand, there may not
987  * be an actual problem besides a little confusion, so think about this
988  * and decide.
989  */
990  if (db_id == MyDatabaseId)
991  ereport(ERROR,
992  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
993  errmsg("current database cannot be renamed")));
994 
995  /*
996  * Make sure the database does not have active sessions. This is the same
997  * concern as above, but applied to other sessions.
998  *
999  * As in CREATE DATABASE, check this after other error conditions.
1000  */
1001  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1002  ereport(ERROR,
1003  (errcode(ERRCODE_OBJECT_IN_USE),
1004  errmsg("database \"%s\" is being accessed by other users",
1005  oldname),
1006  errdetail_busy_db(notherbackends, npreparedxacts)));
1007 
1008  /* rename */
1010  if (!HeapTupleIsValid(newtup))
1011  elog(ERROR, "cache lookup failed for database %u", db_id);
1012  namestrcpy(&(((Form_pg_database) GETSTRUCT(newtup))->datname), newname);
1013  simple_heap_update(rel, &newtup->t_self, newtup);
1014  CatalogUpdateIndexes(rel, newtup);
1015 
1017 
1018  ObjectAddressSet(address, DatabaseRelationId, db_id);
1019 
1020  /*
1021  * Close pg_database, but keep lock till commit.
1022  */
1023  heap_close(rel, NoLock);
1024 
1025  return address;
1026 }
1027 
1028 
1029 /*
1030  * ALTER DATABASE SET TABLESPACE
1031  */
1032 static void
1033 movedb(const char *dbname, const char *tblspcname)
1034 {
1035  Oid db_id;
1036  Relation pgdbrel;
1037  int notherbackends;
1038  int npreparedxacts;
1039  HeapTuple oldtuple,
1040  newtuple;
1041  Oid src_tblspcoid,
1042  dst_tblspcoid;
1043  Datum new_record[Natts_pg_database];
1044  bool new_record_nulls[Natts_pg_database];
1045  bool new_record_repl[Natts_pg_database];
1046  ScanKeyData scankey;
1047  SysScanDesc sysscan;
1048  AclResult aclresult;
1049  char *src_dbpath;
1050  char *dst_dbpath;
1051  DIR *dstdir;
1052  struct dirent *xlde;
1053  movedb_failure_params fparms;
1054 
1055  /*
1056  * Look up the target database's OID, and get exclusive lock on it. We
1057  * need this to ensure that no new backend starts up in the database while
1058  * we are moving it, and that no one is using it as a CREATE DATABASE
1059  * template or trying to delete it.
1060  */
1062 
1063  if (!get_db_info(dbname, AccessExclusiveLock, &db_id, NULL, NULL,
1064  NULL, NULL, NULL, NULL, NULL, &src_tblspcoid, NULL, NULL))
1065  ereport(ERROR,
1066  (errcode(ERRCODE_UNDEFINED_DATABASE),
1067  errmsg("database \"%s\" does not exist", dbname)));
1068 
1069  /*
1070  * We actually need a session lock, so that the lock will persist across
1071  * the commit/restart below. (We could almost get away with letting the
1072  * lock be released at commit, except that someone could try to move
1073  * relations of the DB back into the old directory while we rmtree() it.)
1074  */
1077 
1078  /*
1079  * Permission checks
1080  */
1081  if (!pg_database_ownercheck(db_id, GetUserId()))
1083  dbname);
1084 
1085  /*
1086  * Obviously can't move the tables of my own database
1087  */
1088  if (db_id == MyDatabaseId)
1089  ereport(ERROR,
1090  (errcode(ERRCODE_OBJECT_IN_USE),
1091  errmsg("cannot change the tablespace of the currently open database")));
1092 
1093  /*
1094  * Get tablespace's oid
1095  */
1096  dst_tblspcoid = get_tablespace_oid(tblspcname, false);
1097 
1098  /*
1099  * Permission checks
1100  */
1101  aclresult = pg_tablespace_aclcheck(dst_tblspcoid, GetUserId(),
1102  ACL_CREATE);
1103  if (aclresult != ACLCHECK_OK)
1105  tblspcname);
1106 
1107  /*
1108  * pg_global must never be the default tablespace
1109  */
1110  if (dst_tblspcoid == GLOBALTABLESPACE_OID)
1111  ereport(ERROR,
1112  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1113  errmsg("pg_global cannot be used as default tablespace")));
1114 
1115  /*
1116  * No-op if same tablespace
1117  */
1118  if (src_tblspcoid == dst_tblspcoid)
1119  {
1120  heap_close(pgdbrel, NoLock);
1123  return;
1124  }
1125 
1126  /*
1127  * Check for other backends in the target database. (Because we hold the
1128  * database lock, no new ones can start after this.)
1129  *
1130  * As in CREATE DATABASE, check this after other error conditions.
1131  */
1132  if (CountOtherDBBackends(db_id, &notherbackends, &npreparedxacts))
1133  ereport(ERROR,
1134  (errcode(ERRCODE_OBJECT_IN_USE),
1135  errmsg("database \"%s\" is being accessed by other users",
1136  dbname),
1137  errdetail_busy_db(notherbackends, npreparedxacts)));
1138 
1139  /*
1140  * Get old and new database paths
1141  */
1142  src_dbpath = GetDatabasePath(db_id, src_tblspcoid);
1143  dst_dbpath = GetDatabasePath(db_id, dst_tblspcoid);
1144 
1145  /*
1146  * Force a checkpoint before proceeding. This will force all dirty
1147  * buffers, including those of unlogged tables, out to disk, to ensure
1148  * source database is up-to-date on disk for the copy.
1149  * FlushDatabaseBuffers() would suffice for that, but we also want to
1150  * process any pending unlink requests. Otherwise, the check for existing
1151  * files in the target directory might fail unnecessarily, not to mention
1152  * that the copy might fail due to source files getting deleted under it.
1153  * On Windows, this also ensures that background procs don't hold any open
1154  * files, which would cause rmdir() to fail.
1155  */
1158 
1159  /*
1160  * Now drop all buffers holding data of the target database; they should
1161  * no longer be dirty so DropDatabaseBuffers is safe.
1162  *
1163  * It might seem that we could just let these buffers age out of shared
1164  * buffers naturally, since they should not get referenced anymore. The
1165  * problem with that is that if the user later moves the database back to
1166  * its original tablespace, any still-surviving buffers would appear to
1167  * contain valid data again --- but they'd be missing any changes made in
1168  * the database while it was in the new tablespace. In any case, freeing
1169  * buffers that should never be used again seems worth the cycles.
1170  *
1171  * Note: it'd be sufficient to get rid of buffers matching db_id and
1172  * src_tblspcoid, but bufmgr.c presently provides no API for that.
1173  */
1174  DropDatabaseBuffers(db_id);
1175 
1176  /*
1177  * Check for existence of files in the target directory, i.e., objects of
1178  * this database that are already in the target tablespace. We can't
1179  * allow the move in such a case, because we would need to change those
1180  * relations' pg_class.reltablespace entries to zero, and we don't have
1181  * access to the DB's pg_class to do so.
1182  */
1183  dstdir = AllocateDir(dst_dbpath);
1184  if (dstdir != NULL)
1185  {
1186  while ((xlde = ReadDir(dstdir, dst_dbpath)) != NULL)
1187  {
1188  if (strcmp(xlde->d_name, ".") == 0 ||
1189  strcmp(xlde->d_name, "..") == 0)
1190  continue;
1191 
1192  ereport(ERROR,
1193  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1194  errmsg("some relations of database \"%s\" are already in tablespace \"%s\"",
1195  dbname, tblspcname),
1196  errhint("You must move them back to the database's default tablespace before using this command.")));
1197  }
1198 
1199  FreeDir(dstdir);
1200 
1201  /*
1202  * The directory exists but is empty. We must remove it before using
1203  * the copydir function.
1204  */
1205  if (rmdir(dst_dbpath) != 0)
1206  elog(ERROR, "could not remove directory \"%s\": %m",
1207  dst_dbpath);
1208  }
1209 
1210  /*
1211  * Use an ENSURE block to make sure we remove the debris if the copy fails
1212  * (eg, due to out-of-disk-space). This is not a 100% solution, because
1213  * of the possibility of failure during transaction commit, but it should
1214  * handle most scenarios.
1215  */
1216  fparms.dest_dboid = db_id;
1217  fparms.dest_tsoid = dst_tblspcoid;
1219  PointerGetDatum(&fparms));
1220  {
1221  /*
1222  * Copy files from the old tablespace to the new one
1223  */
1224  copydir(src_dbpath, dst_dbpath, false);
1225 
1226  /*
1227  * Record the filesystem change in XLOG
1228  */
1229  {
1230  xl_dbase_create_rec xlrec;
1231 
1232  xlrec.db_id = db_id;
1233  xlrec.tablespace_id = dst_tblspcoid;
1234  xlrec.src_db_id = db_id;
1235  xlrec.src_tablespace_id = src_tblspcoid;
1236 
1237  XLogBeginInsert();
1238  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_create_rec));
1239 
1240  (void) XLogInsert(RM_DBASE_ID,
1242  }
1243 
1244  /*
1245  * Update the database's pg_database tuple
1246  */
1247  ScanKeyInit(&scankey,
1249  BTEqualStrategyNumber, F_NAMEEQ,
1250  NameGetDatum(dbname));
1251  sysscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
1252  NULL, 1, &scankey);
1253  oldtuple = systable_getnext(sysscan);
1254  if (!HeapTupleIsValid(oldtuple)) /* shouldn't happen... */
1255  ereport(ERROR,
1256  (errcode(ERRCODE_UNDEFINED_DATABASE),
1257  errmsg("database \"%s\" does not exist", dbname)));
1258 
1259  MemSet(new_record, 0, sizeof(new_record));
1260  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1261  MemSet(new_record_repl, false, sizeof(new_record_repl));
1262 
1263  new_record[Anum_pg_database_dattablespace - 1] = ObjectIdGetDatum(dst_tblspcoid);
1264  new_record_repl[Anum_pg_database_dattablespace - 1] = true;
1265 
1266  newtuple = heap_modify_tuple(oldtuple, RelationGetDescr(pgdbrel),
1267  new_record,
1268  new_record_nulls, new_record_repl);
1269  simple_heap_update(pgdbrel, &oldtuple->t_self, newtuple);
1270 
1271  /* Update indexes */
1272  CatalogUpdateIndexes(pgdbrel, newtuple);
1273 
1275  HeapTupleGetOid(newtuple), 0);
1276 
1277  systable_endscan(sysscan);
1278 
1279  /*
1280  * Force another checkpoint here. As in CREATE DATABASE, this is to
1281  * ensure that we don't have to replay a committed XLOG_DBASE_CREATE
1282  * operation, which would cause us to lose any unlogged operations
1283  * done in the new DB tablespace before the next checkpoint.
1284  */
1286 
1287  /*
1288  * Force synchronous commit, thus minimizing the window between
1289  * copying the database files and commital of the transaction. If we
1290  * crash before committing, we'll leave an orphaned set of files on
1291  * disk, which is not fatal but not good either.
1292  */
1293  ForceSyncCommit();
1294 
1295  /*
1296  * Close pg_database, but keep lock till commit.
1297  */
1298  heap_close(pgdbrel, NoLock);
1299  }
1301  PointerGetDatum(&fparms));
1302 
1303  /*
1304  * Commit the transaction so that the pg_database update is committed. If
1305  * we crash while removing files, the database won't be corrupt, we'll
1306  * just leave some orphaned files in the old directory.
1307  *
1308  * (This is OK because we know we aren't inside a transaction block.)
1309  *
1310  * XXX would it be safe/better to do this inside the ensure block? Not
1311  * convinced it's a good idea; consider elog just after the transaction
1312  * really commits.
1313  */
1316 
1317  /* Start new transaction for the remaining work; don't need a snapshot */
1319 
1320  /*
1321  * Remove files from the old tablespace
1322  */
1323  if (!rmtree(src_dbpath, true))
1324  ereport(WARNING,
1325  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1326  src_dbpath)));
1327 
1328  /*
1329  * Record the filesystem change in XLOG
1330  */
1331  {
1332  xl_dbase_drop_rec xlrec;
1333 
1334  xlrec.db_id = db_id;
1335  xlrec.tablespace_id = src_tblspcoid;
1336 
1337  XLogBeginInsert();
1338  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1339 
1340  (void) XLogInsert(RM_DBASE_ID,
1342  }
1343 
1344  /* Now it's safe to release the database lock */
1347 }
1348 
1349 /* Error cleanup callback for movedb */
1350 static void
1352 {
1354  char *dstpath;
1355 
1356  /* Get rid of anything we managed to copy to the target directory */
1357  dstpath = GetDatabasePath(fparms->dest_dboid, fparms->dest_tsoid);
1358 
1359  (void) rmtree(dstpath, true);
1360 }
1361 
1362 
1363 /*
1364  * ALTER DATABASE name ...
1365  */
1366 Oid
1367 AlterDatabase(AlterDatabaseStmt *stmt, bool isTopLevel)
1368 {
1369  Relation rel;
1370  Oid dboid;
1371  HeapTuple tuple,
1372  newtuple;
1373  ScanKeyData scankey;
1374  SysScanDesc scan;
1375  ListCell *option;
1376  bool dbistemplate = false;
1377  bool dballowconnections = true;
1378  int dbconnlimit = -1;
1379  DefElem *distemplate = NULL;
1380  DefElem *dallowconnections = NULL;
1381  DefElem *dconnlimit = NULL;
1382  DefElem *dtablespace = NULL;
1383  Datum new_record[Natts_pg_database];
1384  bool new_record_nulls[Natts_pg_database];
1385  bool new_record_repl[Natts_pg_database];
1386 
1387  /* Extract options from the statement node tree */
1388  foreach(option, stmt->options)
1389  {
1390  DefElem *defel = (DefElem *) lfirst(option);
1391 
1392  if (strcmp(defel->defname, "is_template") == 0)
1393  {
1394  if (distemplate)
1395  ereport(ERROR,
1396  (errcode(ERRCODE_SYNTAX_ERROR),
1397  errmsg("conflicting or redundant options")));
1398  distemplate = defel;
1399  }
1400  else if (strcmp(defel->defname, "allow_connections") == 0)
1401  {
1402  if (dallowconnections)
1403  ereport(ERROR,
1404  (errcode(ERRCODE_SYNTAX_ERROR),
1405  errmsg("conflicting or redundant options")));
1406  dallowconnections = defel;
1407  }
1408  else if (strcmp(defel->defname, "connection_limit") == 0)
1409  {
1410  if (dconnlimit)
1411  ereport(ERROR,
1412  (errcode(ERRCODE_SYNTAX_ERROR),
1413  errmsg("conflicting or redundant options")));
1414  dconnlimit = defel;
1415  }
1416  else if (strcmp(defel->defname, "tablespace") == 0)
1417  {
1418  if (dtablespace)
1419  ereport(ERROR,
1420  (errcode(ERRCODE_SYNTAX_ERROR),
1421  errmsg("conflicting or redundant options")));
1422  dtablespace = defel;
1423  }
1424  else
1425  ereport(ERROR,
1426  (errcode(ERRCODE_SYNTAX_ERROR),
1427  errmsg("option \"%s\" not recognized", defel->defname)));
1428  }
1429 
1430  if (dtablespace)
1431  {
1432  /*
1433  * While the SET TABLESPACE syntax doesn't allow any other options,
1434  * somebody could write "WITH TABLESPACE ...". Forbid any other
1435  * options from being specified in that case.
1436  */
1437  if (list_length(stmt->options) != 1)
1438  ereport(ERROR,
1439  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1440  errmsg("option \"%s\" cannot be specified with other options",
1441  dtablespace->defname)));
1442  /* this case isn't allowed within a transaction block */
1443  PreventTransactionChain(isTopLevel, "ALTER DATABASE SET TABLESPACE");
1444  movedb(stmt->dbname, defGetString(dtablespace));
1445  return InvalidOid;
1446  }
1447 
1448  if (distemplate && distemplate->arg)
1449  dbistemplate = defGetBoolean(distemplate);
1450  if (dallowconnections && dallowconnections->arg)
1451  dballowconnections = defGetBoolean(dallowconnections);
1452  if (dconnlimit && dconnlimit->arg)
1453  {
1454  dbconnlimit = defGetInt32(dconnlimit);
1455  if (dbconnlimit < -1)
1456  ereport(ERROR,
1457  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1458  errmsg("invalid connection limit: %d", dbconnlimit)));
1459  }
1460 
1461  /*
1462  * Get the old tuple. We don't need a lock on the database per se,
1463  * because we're not going to do anything that would mess up incoming
1464  * connections.
1465  */
1467  ScanKeyInit(&scankey,
1469  BTEqualStrategyNumber, F_NAMEEQ,
1470  NameGetDatum(stmt->dbname));
1471  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1472  NULL, 1, &scankey);
1473  tuple = systable_getnext(scan);
1474  if (!HeapTupleIsValid(tuple))
1475  ereport(ERROR,
1476  (errcode(ERRCODE_UNDEFINED_DATABASE),
1477  errmsg("database \"%s\" does not exist", stmt->dbname)));
1478 
1479  dboid = HeapTupleGetOid(tuple);
1480 
1483  stmt->dbname);
1484 
1485  /*
1486  * In order to avoid getting locked out and having to go through
1487  * standalone mode, we refuse to disallow connections to the database
1488  * we're currently connected to. Lockout can still happen with concurrent
1489  * sessions but the likeliness of that is not high enough to worry about.
1490  */
1491  if (!dballowconnections && dboid == MyDatabaseId)
1492  ereport(ERROR,
1493  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1494  errmsg("cannot disallow connections for current database")));
1495 
1496  /*
1497  * Build an updated tuple, perusing the information just obtained
1498  */
1499  MemSet(new_record, 0, sizeof(new_record));
1500  MemSet(new_record_nulls, false, sizeof(new_record_nulls));
1501  MemSet(new_record_repl, false, sizeof(new_record_repl));
1502 
1503  if (distemplate)
1504  {
1505  new_record[Anum_pg_database_datistemplate - 1] = BoolGetDatum(dbistemplate);
1506  new_record_repl[Anum_pg_database_datistemplate - 1] = true;
1507  }
1508  if (dallowconnections)
1509  {
1510  new_record[Anum_pg_database_datallowconn - 1] = BoolGetDatum(dballowconnections);
1511  new_record_repl[Anum_pg_database_datallowconn - 1] = true;
1512  }
1513  if (dconnlimit)
1514  {
1515  new_record[Anum_pg_database_datconnlimit - 1] = Int32GetDatum(dbconnlimit);
1516  new_record_repl[Anum_pg_database_datconnlimit - 1] = true;
1517  }
1518 
1519  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), new_record,
1520  new_record_nulls, new_record_repl);
1521  simple_heap_update(rel, &tuple->t_self, newtuple);
1522 
1523  /* Update indexes */
1524  CatalogUpdateIndexes(rel, newtuple);
1525 
1527  HeapTupleGetOid(newtuple), 0);
1528 
1529  systable_endscan(scan);
1530 
1531  /* Close pg_database, but keep lock till commit */
1532  heap_close(rel, NoLock);
1533 
1534  return dboid;
1535 }
1536 
1537 
1538 /*
1539  * ALTER DATABASE name SET ...
1540  */
1541 Oid
1543 {
1544  Oid datid = get_database_oid(stmt->dbname, false);
1545 
1546  /*
1547  * Obtain a lock on the database and make sure it didn't go away in the
1548  * meantime.
1549  */
1551 
1552  if (!pg_database_ownercheck(datid, GetUserId()))
1554  stmt->dbname);
1555 
1556  AlterSetting(datid, InvalidOid, stmt->setstmt);
1557 
1559 
1560  return datid;
1561 }
1562 
1563 
1564 /*
1565  * ALTER DATABASE name OWNER TO newowner
1566  */
1568 AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
1569 {
1570  Oid db_id;
1571  HeapTuple tuple;
1572  Relation rel;
1573  ScanKeyData scankey;
1574  SysScanDesc scan;
1575  Form_pg_database datForm;
1576  ObjectAddress address;
1577 
1578  /*
1579  * Get the old tuple. We don't need a lock on the database per se,
1580  * because we're not going to do anything that would mess up incoming
1581  * connections.
1582  */
1584  ScanKeyInit(&scankey,
1586  BTEqualStrategyNumber, F_NAMEEQ,
1587  NameGetDatum(dbname));
1588  scan = systable_beginscan(rel, DatabaseNameIndexId, true,
1589  NULL, 1, &scankey);
1590  tuple = systable_getnext(scan);
1591  if (!HeapTupleIsValid(tuple))
1592  ereport(ERROR,
1593  (errcode(ERRCODE_UNDEFINED_DATABASE),
1594  errmsg("database \"%s\" does not exist", dbname)));
1595 
1596  db_id = HeapTupleGetOid(tuple);
1597  datForm = (Form_pg_database) GETSTRUCT(tuple);
1598 
1599  /*
1600  * If the new owner is the same as the existing owner, consider the
1601  * command to have succeeded. This is to be consistent with other
1602  * objects.
1603  */
1604  if (datForm->datdba != newOwnerId)
1605  {
1606  Datum repl_val[Natts_pg_database];
1607  bool repl_null[Natts_pg_database];
1608  bool repl_repl[Natts_pg_database];
1609  Acl *newAcl;
1610  Datum aclDatum;
1611  bool isNull;
1612  HeapTuple newtuple;
1613 
1614  /* Otherwise, must be owner of the existing object */
1617  dbname);
1618 
1619  /* Must be able to become new owner */
1620  check_is_member_of_role(GetUserId(), newOwnerId);
1621 
1622  /*
1623  * must have createdb rights
1624  *
1625  * NOTE: This is different from other alter-owner checks in that the
1626  * current user is checked for createdb privileges instead of the
1627  * destination owner. This is consistent with the CREATE case for
1628  * databases. Because superusers will always have this right, we need
1629  * no special case for them.
1630  */
1631  if (!have_createdb_privilege())
1632  ereport(ERROR,
1633  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1634  errmsg("permission denied to change owner of database")));
1635 
1636  memset(repl_null, false, sizeof(repl_null));
1637  memset(repl_repl, false, sizeof(repl_repl));
1638 
1639  repl_repl[Anum_pg_database_datdba - 1] = true;
1640  repl_val[Anum_pg_database_datdba - 1] = ObjectIdGetDatum(newOwnerId);
1641 
1642  /*
1643  * Determine the modified ACL for the new owner. This is only
1644  * necessary when the ACL is non-null.
1645  */
1646  aclDatum = heap_getattr(tuple,
1648  RelationGetDescr(rel),
1649  &isNull);
1650  if (!isNull)
1651  {
1652  newAcl = aclnewowner(DatumGetAclP(aclDatum),
1653  datForm->datdba, newOwnerId);
1654  repl_repl[Anum_pg_database_datacl - 1] = true;
1655  repl_val[Anum_pg_database_datacl - 1] = PointerGetDatum(newAcl);
1656  }
1657 
1658  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel), repl_val, repl_null, repl_repl);
1659  simple_heap_update(rel, &newtuple->t_self, newtuple);
1660  CatalogUpdateIndexes(rel, newtuple);
1661 
1662  heap_freetuple(newtuple);
1663 
1664  /* Update owner dependency reference */
1666  newOwnerId);
1667  }
1668 
1670 
1671  ObjectAddressSet(address, DatabaseRelationId, db_id);
1672 
1673  systable_endscan(scan);
1674 
1675  /* Close pg_database, but keep lock till commit */
1676  heap_close(rel, NoLock);
1677 
1678  return address;
1679 }
1680 
1681 
1682 /*
1683  * Helper functions
1684  */
1685 
1686 /*
1687  * Look up info about the database named "name". If the database exists,
1688  * obtain the specified lock type on it, fill in any of the remaining
1689  * parameters that aren't NULL, and return TRUE. If no such database,
1690  * return FALSE.
1691  */
1692 static bool
1693 get_db_info(const char *name, LOCKMODE lockmode,
1694  Oid *dbIdP, Oid *ownerIdP,
1695  int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP,
1696  Oid *dbLastSysOidP, TransactionId *dbFrozenXidP,
1697  MultiXactId *dbMinMultiP,
1698  Oid *dbTablespace, char **dbCollate, char **dbCtype)
1699 {
1700  bool result = false;
1701  Relation relation;
1702 
1703  AssertArg(name);
1704 
1705  /* Caller may wish to grab a better lock on pg_database beforehand... */
1707 
1708  /*
1709  * Loop covers the rare case where the database is renamed before we can
1710  * lock it. We try again just in case we can find a new one of the same
1711  * name.
1712  */
1713  for (;;)
1714  {
1715  ScanKeyData scanKey;
1716  SysScanDesc scan;
1717  HeapTuple tuple;
1718  Oid dbOid;
1719 
1720  /*
1721  * there's no syscache for database-indexed-by-name, so must do it the
1722  * hard way
1723  */
1724  ScanKeyInit(&scanKey,
1726  BTEqualStrategyNumber, F_NAMEEQ,
1727  NameGetDatum(name));
1728 
1729  scan = systable_beginscan(relation, DatabaseNameIndexId, true,
1730  NULL, 1, &scanKey);
1731 
1732  tuple = systable_getnext(scan);
1733 
1734  if (!HeapTupleIsValid(tuple))
1735  {
1736  /* definitely no database of that name */
1737  systable_endscan(scan);
1738  break;
1739  }
1740 
1741  dbOid = HeapTupleGetOid(tuple);
1742 
1743  systable_endscan(scan);
1744 
1745  /*
1746  * Now that we have a database OID, we can try to lock the DB.
1747  */
1748  if (lockmode != NoLock)
1749  LockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1750 
1751  /*
1752  * And now, re-fetch the tuple by OID. If it's still there and still
1753  * the same name, we win; else, drop the lock and loop back to try
1754  * again.
1755  */
1756  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbOid));
1757  if (HeapTupleIsValid(tuple))
1758  {
1759  Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1760 
1761  if (strcmp(name, NameStr(dbform->datname)) == 0)
1762  {
1763  /* oid of the database */
1764  if (dbIdP)
1765  *dbIdP = dbOid;
1766  /* oid of the owner */
1767  if (ownerIdP)
1768  *ownerIdP = dbform->datdba;
1769  /* character encoding */
1770  if (encodingP)
1771  *encodingP = dbform->encoding;
1772  /* allowed as template? */
1773  if (dbIsTemplateP)
1774  *dbIsTemplateP = dbform->datistemplate;
1775  /* allowing connections? */
1776  if (dbAllowConnP)
1777  *dbAllowConnP = dbform->datallowconn;
1778  /* last system OID used in database */
1779  if (dbLastSysOidP)
1780  *dbLastSysOidP = dbform->datlastsysoid;
1781  /* limit of frozen XIDs */
1782  if (dbFrozenXidP)
1783  *dbFrozenXidP = dbform->datfrozenxid;
1784  /* minimum MultixactId */
1785  if (dbMinMultiP)
1786  *dbMinMultiP = dbform->datminmxid;
1787  /* default tablespace for this database */
1788  if (dbTablespace)
1789  *dbTablespace = dbform->dattablespace;
1790  /* default locale settings for this database */
1791  if (dbCollate)
1792  *dbCollate = pstrdup(NameStr(dbform->datcollate));
1793  if (dbCtype)
1794  *dbCtype = pstrdup(NameStr(dbform->datctype));
1795  ReleaseSysCache(tuple);
1796  result = true;
1797  break;
1798  }
1799  /* can only get here if it was just renamed */
1800  ReleaseSysCache(tuple);
1801  }
1802 
1803  if (lockmode != NoLock)
1804  UnlockSharedObject(DatabaseRelationId, dbOid, 0, lockmode);
1805  }
1806 
1807  heap_close(relation, AccessShareLock);
1808 
1809  return result;
1810 }
1811 
1812 /* Check if current user has createdb privileges */
1813 static bool
1815 {
1816  bool result = false;
1817  HeapTuple utup;
1818 
1819  /* Superusers can always do everything */
1820  if (superuser())
1821  return true;
1822 
1824  if (HeapTupleIsValid(utup))
1825  {
1826  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreatedb;
1827  ReleaseSysCache(utup);
1828  }
1829  return result;
1830 }
1831 
1832 /*
1833  * Remove tablespace directories
1834  *
1835  * We don't know what tablespaces db_id is using, so iterate through all
1836  * tablespaces removing <tablespace>/db_id
1837  */
1838 static void
1840 {
1841  Relation rel;
1842  HeapScanDesc scan;
1843  HeapTuple tuple;
1844 
1846  scan = heap_beginscan_catalog(rel, 0, NULL);
1847  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1848  {
1849  Oid dsttablespace = HeapTupleGetOid(tuple);
1850  char *dstpath;
1851  struct stat st;
1852 
1853  /* Don't mess with the global tablespace */
1854  if (dsttablespace == GLOBALTABLESPACE_OID)
1855  continue;
1856 
1857  dstpath = GetDatabasePath(db_id, dsttablespace);
1858 
1859  if (lstat(dstpath, &st) < 0 || !S_ISDIR(st.st_mode))
1860  {
1861  /* Assume we can ignore it */
1862  pfree(dstpath);
1863  continue;
1864  }
1865 
1866  if (!rmtree(dstpath, true))
1867  ereport(WARNING,
1868  (errmsg("some useless files may be left behind in old database directory \"%s\"",
1869  dstpath)));
1870 
1871  /* Record the filesystem change in XLOG */
1872  {
1873  xl_dbase_drop_rec xlrec;
1874 
1875  xlrec.db_id = db_id;
1876  xlrec.tablespace_id = dsttablespace;
1877 
1878  XLogBeginInsert();
1879  XLogRegisterData((char *) &xlrec, sizeof(xl_dbase_drop_rec));
1880 
1881  (void) XLogInsert(RM_DBASE_ID,
1883  }
1884 
1885  pfree(dstpath);
1886  }
1887 
1888  heap_endscan(scan);
1890 }
1891 
1892 /*
1893  * Check for existing files that conflict with a proposed new DB OID;
1894  * return TRUE if there are any
1895  *
1896  * If there were a subdirectory in any tablespace matching the proposed new
1897  * OID, we'd get a create failure due to the duplicate name ... and then we'd
1898  * try to remove that already-existing subdirectory during the cleanup in
1899  * remove_dbtablespaces. Nuking existing files seems like a bad idea, so
1900  * instead we make this extra check before settling on the OID of the new
1901  * database. This exactly parallels what GetNewRelFileNode() does for table
1902  * relfilenode values.
1903  */
1904 static bool
1906 {
1907  bool result = false;
1908  Relation rel;
1909  HeapScanDesc scan;
1910  HeapTuple tuple;
1911 
1913  scan = heap_beginscan_catalog(rel, 0, NULL);
1914  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1915  {
1916  Oid dsttablespace = HeapTupleGetOid(tuple);
1917  char *dstpath;
1918  struct stat st;
1919 
1920  /* Don't mess with the global tablespace */
1921  if (dsttablespace == GLOBALTABLESPACE_OID)
1922  continue;
1923 
1924  dstpath = GetDatabasePath(db_id, dsttablespace);
1925 
1926  if (lstat(dstpath, &st) == 0)
1927  {
1928  /* Found a conflicting file (or directory, whatever) */
1929  pfree(dstpath);
1930  result = true;
1931  break;
1932  }
1933 
1934  pfree(dstpath);
1935  }
1936 
1937  heap_endscan(scan);
1939 
1940  return result;
1941 }
1942 
1943 /*
1944  * Issue a suitable errdetail message for a busy database
1945  */
1946 static int
1947 errdetail_busy_db(int notherbackends, int npreparedxacts)
1948 {
1949  if (notherbackends > 0 && npreparedxacts > 0)
1950 
1951  /*
1952  * We don't deal with singular versus plural here, since gettext
1953  * doesn't support multiple plurals in one string.
1954  */
1955  errdetail("There are %d other session(s) and %d prepared transaction(s) using the database.",
1956  notherbackends, npreparedxacts);
1957  else if (notherbackends > 0)
1958  errdetail_plural("There is %d other session using the database.",
1959  "There are %d other sessions using the database.",
1960  notherbackends,
1961  notherbackends);
1962  else
1963  errdetail_plural("There is %d prepared transaction using the database.",
1964  "There are %d prepared transactions using the database.",
1965  npreparedxacts,
1966  npreparedxacts);
1967  return 0; /* just to keep ereport macro happy */
1968 }
1969 
1970 /*
1971  * get_database_oid - given a database name, look up the OID
1972  *
1973  * If missing_ok is false, throw an error if database name not found. If
1974  * true, just return InvalidOid.
1975  */
1976 Oid
1977 get_database_oid(const char *dbname, bool missing_ok)
1978 {
1979  Relation pg_database;
1980  ScanKeyData entry[1];
1981  SysScanDesc scan;
1982  HeapTuple dbtuple;
1983  Oid oid;
1984 
1985  /*
1986  * There's no syscache for pg_database indexed by name, so we must look
1987  * the hard way.
1988  */
1990  ScanKeyInit(&entry[0],
1992  BTEqualStrategyNumber, F_NAMEEQ,
1993  CStringGetDatum(dbname));
1994  scan = systable_beginscan(pg_database, DatabaseNameIndexId, true,
1995  NULL, 1, entry);
1996 
1997  dbtuple = systable_getnext(scan);
1998 
1999  /* We assume that there can be at most one matching tuple */
2000  if (HeapTupleIsValid(dbtuple))
2001  oid = HeapTupleGetOid(dbtuple);
2002  else
2003  oid = InvalidOid;
2004 
2005  systable_endscan(scan);
2006  heap_close(pg_database, AccessShareLock);
2007 
2008  if (!OidIsValid(oid) && !missing_ok)
2009  ereport(ERROR,
2010  (errcode(ERRCODE_UNDEFINED_DATABASE),
2011  errmsg("database \"%s\" does not exist",
2012  dbname)));
2013 
2014  return oid;
2015 }
2016 
2017 
2018 /*
2019  * get_database_name - given a database OID, look up the name
2020  *
2021  * Returns a palloc'd string, or NULL if no such database.
2022  */
2023 char *
2025 {
2026  HeapTuple dbtuple;
2027  char *result;
2028 
2029  dbtuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(dbid));
2030  if (HeapTupleIsValid(dbtuple))
2031  {
2032  result = pstrdup(NameStr(((Form_pg_database) GETSTRUCT(dbtuple))->datname));
2033  ReleaseSysCache(dbtuple);
2034  }
2035  else
2036  result = NULL;
2037 
2038  return result;
2039 }
2040 
2041 /*
2042  * DATABASE resource manager's routines
2043  */
2044 void
2046 {
2047  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
2048 
2049  /* Backup blocks are not used in dbase records */
2050  Assert(!XLogRecHasAnyBlockRefs(record));
2051 
2052  if (info == XLOG_DBASE_CREATE)
2053  {
2055  char *src_path;
2056  char *dst_path;
2057  struct stat st;
2058 
2059  src_path = GetDatabasePath(xlrec->src_db_id, xlrec->src_tablespace_id);
2060  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2061 
2062  /*
2063  * Our theory for replaying a CREATE is to forcibly drop the target
2064  * subdirectory if present, then re-copy the source data. This may be
2065  * more work than needed, but it is simple to implement.
2066  */
2067  if (stat(dst_path, &st) == 0 && S_ISDIR(st.st_mode))
2068  {
2069  if (!rmtree(dst_path, true))
2070  /* If this failed, copydir() below is going to error. */
2071  ereport(WARNING,
2072  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2073  dst_path)));
2074  }
2075 
2076  /*
2077  * Force dirty buffers out to disk, to ensure source database is
2078  * up-to-date for the copy.
2079  */
2081 
2082  /*
2083  * Copy this subdirectory to the new location
2084  *
2085  * We don't need to copy subdirectories
2086  */
2087  copydir(src_path, dst_path, false);
2088  }
2089  else if (info == XLOG_DBASE_DROP)
2090  {
2091  xl_dbase_drop_rec *xlrec = (xl_dbase_drop_rec *) XLogRecGetData(record);
2092  char *dst_path;
2093 
2094  dst_path = GetDatabasePath(xlrec->db_id, xlrec->tablespace_id);
2095 
2096  if (InHotStandby)
2097  {
2098  /*
2099  * Lock database while we resolve conflicts to ensure that
2100  * InitPostgres() cannot fully re-execute concurrently. This
2101  * avoids backends re-connecting automatically to same database,
2102  * which can happen in some cases.
2103  */
2106  }
2107 
2108  /* Drop pages for this database that are in the shared buffer cache */
2109  DropDatabaseBuffers(xlrec->db_id);
2110 
2111  /* Also, clean out any fsync requests that might be pending in md.c */
2113 
2114  /* Clean out the xlog relcache too */
2115  XLogDropDatabase(xlrec->db_id);
2116 
2117  /* And remove the physical files */
2118  if (!rmtree(dst_path, true))
2119  ereport(WARNING,
2120  (errmsg("some useless files may be left behind in old database directory \"%s\"",
2121  dst_path)));
2122 
2123  if (InHotStandby)
2124  {
2125  /*
2126  * Release locks prior to commit. XXX There is a race condition
2127  * here that may allow backends to reconnect, but the window for
2128  * this is small because the gap between here and commit is mostly
2129  * fairly small and it is unlikely that people will be dropping
2130  * databases that we are trying to connect to anyway.
2131  */
2133  }
2134  }
2135  else
2136  elog(PANIC, "dbase_redo: unknown op code %u", info);
2137 }
#define Anum_pg_database_datdba
Definition: pg_database.h:65
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1384
#define IsA(nodeptr, _type_)
Definition: nodes.h:543
#define NameGetDatum(X)
Definition: postgres.h:603
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4485
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:178
int errhint(const char *fmt,...)
Definition: elog.c:987
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:493
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1580
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
#define XLR_SPECIAL_REL_UPDATE
Definition: xlogrecord.h:71
void check_encoding_locale_matches(int encoding, const char *collate, const char *ctype)
Definition: dbcommands.c:712
uint32 TransactionId
Definition: c.h:393
#define Anum_pg_database_datconnlimit
Definition: pg_database.h:71
Oid createdb(const CreatedbStmt *stmt)
Definition: dbcommands.c:99
#define Natts_pg_database
Definition: pg_database.h:63
#define RelationGetDescr(relation)
Definition: rel.h:383
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:282
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
#define DatumGetAclP(X)
Definition: acl.h:112
int pg_valid_server_encoding(const char *name)
Definition: encnames.c:425
#define PointerGetDatum(X)
Definition: postgres.h:564
static bool have_createdb_privilege(void)
Definition: dbcommands.c:1814
char * pstrdup(const char *in)
Definition: mcxt.c:1168
#define DatabaseRelationId
Definition: pg_database.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2743
static void createdb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:750
void AlterSetting(Oid databaseid, Oid roleid, VariableSetStmt *setstmt)
Oid AlterDatabaseSet(AlterDatabaseSetStmt *stmt)
Definition: dbcommands.c:1542
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
unsigned char uint8
Definition: c.h:263
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:259
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
void ForceSyncCommit(void)
Definition: xact.c:967
int32 defGetInt32(DefElem *def)
Definition: define.c:166
#define InHotStandby
Definition: xlog.h:74
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define MemSet(start, val, len)
Definition: c.h:849
void copydir(char *fromdir, char *todir, bool recurse)
Definition: copydir.c:37
static void remove_dbtablespaces(Oid db_id)
Definition: dbcommands.c:1839
bool directory_is_empty(const char *path)
Definition: tablespace.c:833
void PopActiveSnapshot(void)
Definition: snapmgr.c:731
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:548
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:155
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1306
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:217
static bool get_db_info(const char *name, LOCKMODE lockmode, Oid *dbIdP, Oid *ownerIdP, int *encodingP, bool *dbIsTemplateP, bool *dbAllowConnP, Oid *dbLastSysOidP, TransactionId *dbFrozenXidP, MultiXactId *dbMinMultiP, Oid *dbTablespace, char **dbCollate, char **dbCtype)
Definition: dbcommands.c:1693
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:530
#define PANIC
Definition: elog.h:53
static void movedb_failure_callback(int code, Datum arg)
Definition: dbcommands.c:1351
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:322
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
VariableSetStmt * setstmt
Definition: parsenodes.h:2773
void dbase_redo(XLogReaderState *record)
Definition: dbcommands.c:2045
ObjectAddress RenameDatabase(const char *oldname, const char *newname)
Definition: dbcommands.c:943
void LockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:913
Oid get_role_oid(const char *rolname, bool missing_ok)
Definition: acl.c:5113
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:306
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
bool defGetBoolean(DefElem *def)
Definition: define.c:111
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:410
void pfree(void *pointer)
Definition: mcxt.c:995
#define XLogRecGetData(decoder)
Definition: xlogreader.h:201
Definition: dirent.c:25
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:73
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:892
#define Anum_pg_database_datname
Definition: pg_database.h:64
#define XLOG_DBASE_DROP
char * defGetString(DefElem *def)
Definition: define.c:49
static bool check_db_file_conflict(Oid db_id)
Definition: dbcommands.c:1905
void shdepLockAndCheckObject(Oid classId, Oid objectId)
Definition: pg_shdepend.c:995
ItemPointerData t_self
Definition: htup.h:65
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2024
char * dbname
Definition: parsenodes.h:2754
void UnlockSharedObjectForSession(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:931
#define NoLock
Definition: lockdefs.h:34
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3229
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3392
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:586
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2207
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1401
#define Anum_pg_database_dattablespace
Definition: pg_database.h:75
void check_is_member_of_role(Oid member, Oid role)
Definition: acl.c:4876
#define Anum_pg_database_datistemplate
Definition: pg_database.h:69
#define CHECKPOINT_FORCE
Definition: xlog.h:177
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define AssertArg(condition)
Definition: c.h:669
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4953
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:197
static char dstpath[MAXPGPATH]
Definition: file_ops.c:31
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:108
void copyTemplateDependencies(Oid templateDbId, Oid newDbId)
Definition: pg_shdepend.c:713
#define Anum_pg_database_encoding
Definition: pg_database.h:66
void pgstat_drop_database(Oid databaseid)
Definition: pgstat.c:1166
#define Anum_pg_database_datallowconn
Definition: pg_database.h:70
Node * arg
Definition: parsenodes.h:666
#define Anum_pg_database_datacl
Definition: pg_database.h:76
#define Anum_pg_database_datctype
Definition: pg_database.h:68
#define WARNING
Definition: elog.h:40
void dropDatabaseDependencies(Oid databaseId)
Definition: pg_shdepend.c:780
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:408
#define TransactionIdGetDatum(X)
Definition: postgres.h:529
AclResult
Definition: acl.h:169
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
Oid MyDatabaseId
Definition: globals.c:76
Oid simple_heap_insert(Relation relation, HeapTuple tup)
Definition: heapam.c:2914
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1780
Oid GetNewOid(Relation relation)
Definition: catalog.c:284
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1286
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:871
void dropdb(const char *dbname, bool missing_ok)
Definition: dbcommands.c:770
#define BoolGetDatum(X)
Definition: postgres.h:410
void ForgetDatabaseFsyncRequests(Oid dbid)
Definition: md.c:1685
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:1977
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:440
#define NOTICE
Definition: elog.h:37
static char * encoding
Definition: initdb.c:125
void ResolveRecoveryConflictWithDatabase(Oid dbid)
Definition: standby.c:316
#define CHECKPOINT_WAIT
Definition: xlog.h:181
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:531
TransactionId MultiXactId
Definition: c.h:403
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define lfirst(lc)
Definition: pg_list.h:106
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:381
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2273
void CatalogUpdateIndexes(Relation heapRel, HeapTuple heapTuple)
Definition: indexing.c:157
static void movedb(const char *dbname, const char *tblspcname)
Definition: dbcommands.c:1033
void StartTransactionCommand(void)
Definition: xact.c:2673
char * dbname
Definition: streamutil.c:42
List * options
Definition: parsenodes.h:2755
static int list_length(const List *l)
Definition: pg_list.h:89
void simple_heap_delete(Relation relation, ItemPointer tid)
Definition: heapam.c:3373
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:965
void simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
Definition: heapam.c:4411
ObjectAddress AlterDatabaseOwner(const char *dbname, Oid newOwnerId)
Definition: dbcommands.c:1568
Oid AlterDatabase(AlterDatabaseStmt *stmt, bool isTopLevel)
Definition: dbcommands.c:1367
#define XLOG_DBASE_CREATE
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
#define Anum_pg_database_datlastsysoid
Definition: pg_database.h:72
#define DatabaseNameIndexId
Definition: indexing.h:134
const char * name
Definition: encode.c:521
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
bool ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
Definition: slot.c:709
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
#define DatumGetPointer(X)
Definition: postgres.h:557
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:420
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:150
#define AccessExclusiveLock
Definition: lockdefs.h:46
#define Int32GetDatum(X)
Definition: postgres.h:487
int errmsg(const char *fmt,...)
Definition: elog.c:797
void XLogDropDatabase(Oid dbid)
Definition: xlogutils.c:615
#define ShareLock
Definition: lockdefs.h:41
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:176
#define NameStr(name)
Definition: c.h:494
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void * arg
#define Anum_pg_database_datminmxid
Definition: pg_database.h:74
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:203
char * defname
Definition: parsenodes.h:665
bool CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
Definition: procarray.c:2845
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:218
static int errdetail_busy_db(int notherbackends, int npreparedxacts)
Definition: dbcommands.c:1947
#define Anum_pg_database_datfrozenxid
Definition: pg_database.h:73
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
void DropSetting(Oid databaseid, Oid roleid)
void XLogBeginInsert(void)
Definition: xloginsert.c:120
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3026
#define lstat(path, sb)
Definition: win32.h:272
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition: acl.c:1035
#define BTEqualStrategyNumber
Definition: stratnum.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2316
void RequestCheckpoint(int flags)
Definition: checkpointer.c:953
void PreventTransactionChain(bool isTopLevel, const char *stmtType)
Definition: xact.c:3150
#define Anum_pg_database_datcollate
Definition: pg_database.h:67