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