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