PostgreSQL Source Code  git master
tablespace.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * tablespace.c
4  * Commands to manipulate table spaces
5  *
6  * Tablespaces in PostgreSQL are designed to allow users to determine
7  * where the data file(s) for a given database object reside on the file
8  * system.
9  *
10  * A tablespace represents a directory on the file system. At tablespace
11  * creation time, the directory must be empty. To simplify things and
12  * remove the possibility of having file name conflicts, we isolate
13  * files within a tablespace into database-specific subdirectories.
14  *
15  * To support file access via the information given in RelFileNode, we
16  * maintain a symbolic-link map in $PGDATA/pg_tblspc. The symlinks are
17  * named by tablespace OIDs and point to the actual tablespace directories.
18  * There is also a per-cluster version directory in each tablespace.
19  * Thus the full path to an arbitrary file is
20  * $PGDATA/pg_tblspc/spcoid/PG_MAJORVER_CATVER/dboid/relfilenode
21  * e.g.
22  * $PGDATA/pg_tblspc/20981/PG_9.0_201002161/719849/83292814
23  *
24  * There are two tablespaces created at initdb time: pg_global (for shared
25  * tables) and pg_default (for everything else). For backwards compatibility
26  * and to remain functional on platforms without symlinks, these tablespaces
27  * are accessed specially: they are respectively
28  * $PGDATA/global/relfilenode
29  * $PGDATA/base/dboid/relfilenode
30  *
31  * To allow CREATE DATABASE to give a new database a default tablespace
32  * that's different from the template database's default, we make the
33  * provision that a zero in pg_class.reltablespace means the database's
34  * default tablespace. Without this, CREATE DATABASE would have to go in
35  * and munge the system catalogs of the new database.
36  *
37  *
38  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
39  * Portions Copyright (c) 1994, Regents of the University of California
40  *
41  *
42  * IDENTIFICATION
43  * src/backend/commands/tablespace.c
44  *
45  *-------------------------------------------------------------------------
46  */
47 #include "postgres.h"
48 
49 #include <unistd.h>
50 #include <dirent.h>
51 #include <sys/stat.h>
52 
53 #include "access/heapam.h"
54 #include "access/htup_details.h"
55 #include "access/reloptions.h"
56 #include "access/sysattr.h"
57 #include "access/tableam.h"
58 #include "access/xact.h"
59 #include "access/xloginsert.h"
60 #include "access/xlogutils.h"
61 #include "catalog/catalog.h"
62 #include "catalog/dependency.h"
63 #include "catalog/indexing.h"
64 #include "catalog/namespace.h"
65 #include "catalog/objectaccess.h"
66 #include "catalog/pg_namespace.h"
67 #include "catalog/pg_tablespace.h"
68 #include "commands/comment.h"
69 #include "commands/seclabel.h"
70 #include "commands/tablecmds.h"
71 #include "commands/tablespace.h"
72 #include "common/file_perm.h"
73 #include "miscadmin.h"
74 #include "postmaster/bgwriter.h"
75 #include "storage/fd.h"
76 #include "storage/lmgr.h"
77 #include "storage/standby.h"
78 #include "utils/acl.h"
79 #include "utils/builtins.h"
80 #include "utils/fmgroids.h"
81 #include "utils/guc.h"
82 #include "utils/lsyscache.h"
83 #include "utils/memutils.h"
84 #include "utils/rel.h"
85 #include "utils/varlena.h"
86 
87 /* GUC variables */
88 char *default_tablespace = NULL;
89 char *temp_tablespaces = NULL;
90 
91 
92 static void create_tablespace_directories(const char *location,
93  const Oid tablespaceoid);
94 static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo);
95 
96 
97 /*
98  * Each database using a table space is isolated into its own name space
99  * by a subdirectory named for the database OID. On first creation of an
100  * object in the tablespace, create the subdirectory. If the subdirectory
101  * already exists, fall through quietly.
102  *
103  * isRedo indicates that we are creating an object during WAL replay.
104  * In this case we will cope with the possibility of the tablespace
105  * directory not being there either --- this could happen if we are
106  * replaying an operation on a table in a subsequently-dropped tablespace.
107  * We handle this by making a directory in the place where the tablespace
108  * symlink would normally be. This isn't an exact replay of course, but
109  * it's the best we can do given the available information.
110  *
111  * If tablespaces are not supported, we still need it in case we have to
112  * re-create a database subdirectory (of $PGDATA/base) during WAL replay.
113  */
114 void
115 TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
116 {
117  struct stat st;
118  char *dir;
119 
120  /*
121  * The global tablespace doesn't have per-database subdirectories, so
122  * nothing to do for it.
123  */
124  if (spcNode == GLOBALTABLESPACE_OID)
125  return;
126 
127  Assert(OidIsValid(spcNode));
128  Assert(OidIsValid(dbNode));
129 
130  dir = GetDatabasePath(dbNode, spcNode);
131 
132  if (stat(dir, &st) < 0)
133  {
134  /* Directory does not exist? */
135  if (errno == ENOENT)
136  {
137  /*
138  * Acquire TablespaceCreateLock to ensure that no DROP TABLESPACE
139  * or TablespaceCreateDbspace is running concurrently.
140  */
141  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
142 
143  /*
144  * Recheck to see if someone created the directory while we were
145  * waiting for lock.
146  */
147  if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode))
148  {
149  /* Directory was created */
150  }
151  else
152  {
153  /* Directory creation failed? */
154  if (MakePGDirectory(dir) < 0)
155  {
156  char *parentdir;
157 
158  /* Failure other than not exists or not in WAL replay? */
159  if (errno != ENOENT || !isRedo)
160  ereport(ERROR,
162  errmsg("could not create directory \"%s\": %m",
163  dir)));
164 
165  /*
166  * Parent directories are missing during WAL replay, so
167  * continue by creating simple parent directories rather
168  * than a symlink.
169  */
170 
171  /* create two parents up if not exist */
172  parentdir = pstrdup(dir);
173  get_parent_directory(parentdir);
174  get_parent_directory(parentdir);
175  /* Can't create parent and it doesn't already exist? */
176  if (MakePGDirectory(parentdir) < 0 && errno != EEXIST)
177  ereport(ERROR,
179  errmsg("could not create directory \"%s\": %m",
180  parentdir)));
181  pfree(parentdir);
182 
183  /* create one parent up if not exist */
184  parentdir = pstrdup(dir);
185  get_parent_directory(parentdir);
186  /* Can't create parent and it doesn't already exist? */
187  if (MakePGDirectory(parentdir) < 0 && errno != EEXIST)
188  ereport(ERROR,
190  errmsg("could not create directory \"%s\": %m",
191  parentdir)));
192  pfree(parentdir);
193 
194  /* Create database directory */
195  if (MakePGDirectory(dir) < 0)
196  ereport(ERROR,
198  errmsg("could not create directory \"%s\": %m",
199  dir)));
200  }
201  }
202 
203  LWLockRelease(TablespaceCreateLock);
204  }
205  else
206  {
207  ereport(ERROR,
209  errmsg("could not stat directory \"%s\": %m", dir)));
210  }
211  }
212  else
213  {
214  /* Is it not a directory? */
215  if (!S_ISDIR(st.st_mode))
216  ereport(ERROR,
217  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
218  errmsg("\"%s\" exists but is not a directory",
219  dir)));
220  }
221 
222  pfree(dir);
223 }
224 
225 /*
226  * Create a table space
227  *
228  * Only superusers can create a tablespace. This seems a reasonable restriction
229  * since we're determining the system layout and, anyway, we probably have
230  * root if we're doing this kind of activity
231  */
232 Oid
234 {
235 #ifdef HAVE_SYMLINK
236  Relation rel;
237  Datum values[Natts_pg_tablespace];
238  bool nulls[Natts_pg_tablespace];
239  HeapTuple tuple;
240  Oid tablespaceoid;
241  char *location;
242  Oid ownerId;
243  Datum newOptions;
244 
245  /* Must be superuser */
246  if (!superuser())
247  ereport(ERROR,
248  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
249  errmsg("permission denied to create tablespace \"%s\"",
250  stmt->tablespacename),
251  errhint("Must be superuser to create a tablespace.")));
252 
253  /* However, the eventual owner of the tablespace need not be */
254  if (stmt->owner)
255  ownerId = get_rolespec_oid(stmt->owner, false);
256  else
257  ownerId = GetUserId();
258 
259  /* Unix-ify the offered path, and strip any trailing slashes */
260  location = pstrdup(stmt->location);
261  canonicalize_path(location);
262 
263  /* disallow quotes, else CREATE DATABASE would be at risk */
264  if (strchr(location, '\''))
265  ereport(ERROR,
266  (errcode(ERRCODE_INVALID_NAME),
267  errmsg("tablespace location cannot contain single quotes")));
268 
269  /*
270  * Allowing relative paths seems risky
271  *
272  * this also helps us ensure that location is not empty or whitespace
273  */
274  if (!is_absolute_path(location))
275  ereport(ERROR,
276  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
277  errmsg("tablespace location must be an absolute path")));
278 
279  /*
280  * Check that location isn't too long. Remember that we're going to append
281  * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
282  * reference the whole path here, but MakePGDirectory() uses the first two
283  * parts.
284  */
285  if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
286  OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1 + OIDCHARS > MAXPGPATH)
287  ereport(ERROR,
288  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
289  errmsg("tablespace location \"%s\" is too long",
290  location)));
291 
292  /* Warn if the tablespace is in the data directory. */
293  if (path_is_prefix_of_path(DataDir, location))
295  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
296  errmsg("tablespace location should not be inside the data directory")));
297 
298  /*
299  * Disallow creation of tablespaces named "pg_xxx"; we reserve this
300  * namespace for system purposes.
301  */
303  ereport(ERROR,
304  (errcode(ERRCODE_RESERVED_NAME),
305  errmsg("unacceptable tablespace name \"%s\"",
306  stmt->tablespacename),
307  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
308 
309  /*
310  * If built with appropriate switch, whine when regression-testing
311  * conventions for tablespace names are violated.
312  */
313 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
314  if (strncmp(stmt->tablespacename, "regress_", 8) != 0)
315  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
316 #endif
317 
318  /*
319  * Check that there is no other tablespace by this name. (The unique
320  * index would catch this anyway, but might as well give a friendlier
321  * message.)
322  */
323  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
324  ereport(ERROR,
326  errmsg("tablespace \"%s\" already exists",
327  stmt->tablespacename)));
328 
329  /*
330  * Insert tuple into pg_tablespace. The purpose of doing this first is to
331  * lock the proposed tablename against other would-be creators. The
332  * insertion will roll back if we find problems below.
333  */
334  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
335 
336  MemSet(nulls, false, sizeof(nulls));
337 
338  tablespaceoid = GetNewOidWithIndex(rel, TablespaceOidIndexId,
339  Anum_pg_tablespace_oid);
340  values[Anum_pg_tablespace_oid - 1] = ObjectIdGetDatum(tablespaceoid);
341  values[Anum_pg_tablespace_spcname - 1] =
343  values[Anum_pg_tablespace_spcowner - 1] =
344  ObjectIdGetDatum(ownerId);
345  nulls[Anum_pg_tablespace_spcacl - 1] = true;
346 
347  /* Generate new proposed spcoptions (text array) */
348  newOptions = transformRelOptions((Datum) 0,
349  stmt->options,
350  NULL, NULL, false, false);
351  (void) tablespace_reloptions(newOptions, true);
352  if (newOptions != (Datum) 0)
353  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
354  else
355  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
356 
357  tuple = heap_form_tuple(rel->rd_att, values, nulls);
358 
359  CatalogTupleInsert(rel, tuple);
360 
361  heap_freetuple(tuple);
362 
363  /* Record dependency on owner */
364  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
365 
366  /* Post creation hook for new tablespace */
367  InvokeObjectPostCreateHook(TableSpaceRelationId, tablespaceoid, 0);
368 
369  create_tablespace_directories(location, tablespaceoid);
370 
371  /* Record the filesystem change in XLOG */
372  {
373  xl_tblspc_create_rec xlrec;
374 
375  xlrec.ts_id = tablespaceoid;
376 
377  XLogBeginInsert();
378  XLogRegisterData((char *) &xlrec,
379  offsetof(xl_tblspc_create_rec, ts_path));
380  XLogRegisterData((char *) location, strlen(location) + 1);
381 
382  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
383  }
384 
385  /*
386  * Force synchronous commit, to minimize the window between creating the
387  * symlink on-disk and marking the transaction committed. It's not great
388  * that there is any window at all, but definitely we don't want to make
389  * it larger than necessary.
390  */
391  ForceSyncCommit();
392 
393  pfree(location);
394 
395  /* We keep the lock on pg_tablespace until commit */
396  table_close(rel, NoLock);
397 
398  return tablespaceoid;
399 #else /* !HAVE_SYMLINK */
400  ereport(ERROR,
401  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
402  errmsg("tablespaces are not supported on this platform")));
403  return InvalidOid; /* keep compiler quiet */
404 #endif /* HAVE_SYMLINK */
405 }
406 
407 /*
408  * Drop a table space
409  *
410  * Be careful to check that the tablespace is empty.
411  */
412 void
414 {
415 #ifdef HAVE_SYMLINK
416  char *tablespacename = stmt->tablespacename;
417  TableScanDesc scandesc;
418  Relation rel;
419  HeapTuple tuple;
420  Form_pg_tablespace spcform;
421  ScanKeyData entry[1];
422  Oid tablespaceoid;
423  char *detail;
424  char *detail_log;
425 
426  /*
427  * Find the target tuple
428  */
429  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
430 
431  ScanKeyInit(&entry[0],
432  Anum_pg_tablespace_spcname,
433  BTEqualStrategyNumber, F_NAMEEQ,
434  CStringGetDatum(tablespacename));
435  scandesc = table_beginscan_catalog(rel, 1, entry);
436  tuple = heap_getnext(scandesc, ForwardScanDirection);
437 
438  if (!HeapTupleIsValid(tuple))
439  {
440  if (!stmt->missing_ok)
441  {
442  ereport(ERROR,
443  (errcode(ERRCODE_UNDEFINED_OBJECT),
444  errmsg("tablespace \"%s\" does not exist",
445  tablespacename)));
446  }
447  else
448  {
449  ereport(NOTICE,
450  (errmsg("tablespace \"%s\" does not exist, skipping",
451  tablespacename)));
452  table_endscan(scandesc);
453  table_close(rel, NoLock);
454  }
455  return;
456  }
457 
458  spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
459  tablespaceoid = spcform->oid;
460 
461  /* Must be tablespace owner */
462  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
464  tablespacename);
465 
466  /* Disallow drop of the standard tablespaces, even by superuser */
467  if (IsPinnedObject(TableSpaceRelationId, tablespaceoid))
469  tablespacename);
470 
471  /* Check for pg_shdepend entries depending on this tablespace */
472  if (checkSharedDependencies(TableSpaceRelationId, tablespaceoid,
473  &detail, &detail_log))
474  ereport(ERROR,
475  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
476  errmsg("tablespace \"%s\" cannot be dropped because some objects depend on it",
477  tablespacename),
478  errdetail_internal("%s", detail),
479  errdetail_log("%s", detail_log)));
480 
481  /* DROP hook for the tablespace being removed */
482  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
483 
484  /*
485  * Remove the pg_tablespace tuple (this will roll back if we fail below)
486  */
487  CatalogTupleDelete(rel, &tuple->t_self);
488 
489  table_endscan(scandesc);
490 
491  /*
492  * Remove any comments or security labels on this tablespace.
493  */
494  DeleteSharedComments(tablespaceoid, TableSpaceRelationId);
495  DeleteSharedSecurityLabel(tablespaceoid, TableSpaceRelationId);
496 
497  /*
498  * Remove dependency on owner.
499  */
500  deleteSharedDependencyRecordsFor(TableSpaceRelationId, tablespaceoid, 0);
501 
502  /*
503  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
504  * is running concurrently.
505  */
506  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
507 
508  /*
509  * Try to remove the physical infrastructure.
510  */
511  if (!destroy_tablespace_directories(tablespaceoid, false))
512  {
513  /*
514  * Not all files deleted? However, there can be lingering empty files
515  * in the directories, left behind by for example DROP TABLE, that
516  * have been scheduled for deletion at next checkpoint (see comments
517  * in mdunlink() for details). We could just delete them immediately,
518  * but we can't tell them apart from important data files that we
519  * mustn't delete. So instead, we force a checkpoint which will clean
520  * out any lingering files, and try again.
521  *
522  * XXX On Windows, an unlinked file persists in the directory listing
523  * until no process retains an open handle for the file. The DDL
524  * commands that schedule files for unlink send invalidation messages
525  * directing other PostgreSQL processes to close the files. DROP
526  * TABLESPACE should not give up on the tablespace becoming empty
527  * until all relevant invalidation processing is complete.
528  */
530  if (!destroy_tablespace_directories(tablespaceoid, false))
531  {
532  /* Still not empty, the files must be important then */
533  ereport(ERROR,
534  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
535  errmsg("tablespace \"%s\" is not empty",
536  tablespacename)));
537  }
538  }
539 
540  /* Record the filesystem change in XLOG */
541  {
542  xl_tblspc_drop_rec xlrec;
543 
544  xlrec.ts_id = tablespaceoid;
545 
546  XLogBeginInsert();
547  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
548 
549  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
550  }
551 
552  /*
553  * Note: because we checked that the tablespace was empty, there should be
554  * no need to worry about flushing shared buffers or free space map
555  * entries for relations in the tablespace.
556  */
557 
558  /*
559  * Force synchronous commit, to minimize the window between removing the
560  * files on-disk and marking the transaction committed. It's not great
561  * that there is any window at all, but definitely we don't want to make
562  * it larger than necessary.
563  */
564  ForceSyncCommit();
565 
566  /*
567  * Allow TablespaceCreateDbspace again.
568  */
569  LWLockRelease(TablespaceCreateLock);
570 
571  /* We keep the lock on pg_tablespace until commit */
572  table_close(rel, NoLock);
573 #else /* !HAVE_SYMLINK */
574  ereport(ERROR,
575  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
576  errmsg("tablespaces are not supported on this platform")));
577 #endif /* HAVE_SYMLINK */
578 }
579 
580 
581 /*
582  * create_tablespace_directories
583  *
584  * Attempt to create filesystem infrastructure linking $PGDATA/pg_tblspc/
585  * to the specified directory
586  */
587 static void
588 create_tablespace_directories(const char *location, const Oid tablespaceoid)
589 {
590  char *linkloc;
591  char *location_with_version_dir;
592  struct stat st;
593 
594  linkloc = psprintf("pg_tblspc/%u", tablespaceoid);
595  location_with_version_dir = psprintf("%s/%s", location,
597 
598  /*
599  * Attempt to coerce target directory to safe permissions. If this fails,
600  * it doesn't exist or has the wrong owner.
601  */
602  if (chmod(location, pg_dir_create_mode) != 0)
603  {
604  if (errno == ENOENT)
605  ereport(ERROR,
606  (errcode(ERRCODE_UNDEFINED_FILE),
607  errmsg("directory \"%s\" does not exist", location),
608  InRecovery ? errhint("Create this directory for the tablespace before "
609  "restarting the server.") : 0));
610  else
611  ereport(ERROR,
613  errmsg("could not set permissions on directory \"%s\": %m",
614  location)));
615  }
616 
617  /*
618  * The creation of the version directory prevents more than one tablespace
619  * in a single location. This imitates TablespaceCreateDbspace(), but it
620  * ignores concurrency and missing parent directories. The chmod() would
621  * have failed in the absence of a parent. pg_tablespace_spcname_index
622  * prevents concurrency.
623  */
624  if (stat(location_with_version_dir, &st) < 0)
625  {
626  if (errno != ENOENT)
627  ereport(ERROR,
629  errmsg("could not stat directory \"%s\": %m",
630  location_with_version_dir)));
631  else if (MakePGDirectory(location_with_version_dir) < 0)
632  ereport(ERROR,
634  errmsg("could not create directory \"%s\": %m",
635  location_with_version_dir)));
636  }
637  else if (!S_ISDIR(st.st_mode))
638  ereport(ERROR,
639  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
640  errmsg("\"%s\" exists but is not a directory",
641  location_with_version_dir)));
642  else if (!InRecovery)
643  ereport(ERROR,
644  (errcode(ERRCODE_OBJECT_IN_USE),
645  errmsg("directory \"%s\" already in use as a tablespace",
646  location_with_version_dir)));
647 
648  /*
649  * In recovery, remove old symlink, in case it points to the wrong place.
650  */
651  if (InRecovery)
652  remove_tablespace_symlink(linkloc);
653 
654  /*
655  * Create the symlink under PGDATA
656  */
657  if (symlink(location, linkloc) < 0)
658  ereport(ERROR,
660  errmsg("could not create symbolic link \"%s\": %m",
661  linkloc)));
662 
663  pfree(linkloc);
664  pfree(location_with_version_dir);
665 }
666 
667 
668 /*
669  * destroy_tablespace_directories
670  *
671  * Attempt to remove filesystem infrastructure for the tablespace.
672  *
673  * 'redo' indicates we are redoing a drop from XLOG; in that case we should
674  * not throw an ERROR for problems, just LOG them. The worst consequence of
675  * not removing files here would be failure to release some disk space, which
676  * does not justify throwing an error that would require manual intervention
677  * to get the database running again.
678  *
679  * Returns true if successful, false if some subdirectory is not empty
680  */
681 static bool
682 destroy_tablespace_directories(Oid tablespaceoid, bool redo)
683 {
684  char *linkloc;
685  char *linkloc_with_version_dir;
686  DIR *dirdesc;
687  struct dirent *de;
688  char *subfile;
689  struct stat st;
690 
691  linkloc_with_version_dir = psprintf("pg_tblspc/%u/%s", tablespaceoid,
693 
694  /*
695  * Check if the tablespace still contains any files. We try to rmdir each
696  * per-database directory we find in it. rmdir failure implies there are
697  * still files in that subdirectory, so give up. (We do not have to worry
698  * about undoing any already completed rmdirs, since the next attempt to
699  * use the tablespace from that database will simply recreate the
700  * subdirectory via TablespaceCreateDbspace.)
701  *
702  * Since we hold TablespaceCreateLock, no one else should be creating any
703  * fresh subdirectories in parallel. It is possible that new files are
704  * being created within subdirectories, though, so the rmdir call could
705  * fail. Worst consequence is a less friendly error message.
706  *
707  * If redo is true then ENOENT is a likely outcome here, and we allow it
708  * to pass without comment. In normal operation we still allow it, but
709  * with a warning. This is because even though ProcessUtility disallows
710  * DROP TABLESPACE in a transaction block, it's possible that a previous
711  * DROP failed and rolled back after removing the tablespace directories
712  * and/or symlink. We want to allow a new DROP attempt to succeed at
713  * removing the catalog entries (and symlink if still present), so we
714  * should not give a hard error here.
715  */
716  dirdesc = AllocateDir(linkloc_with_version_dir);
717  if (dirdesc == NULL)
718  {
719  if (errno == ENOENT)
720  {
721  if (!redo)
724  errmsg("could not open directory \"%s\": %m",
725  linkloc_with_version_dir)));
726  /* The symlink might still exist, so go try to remove it */
727  goto remove_symlink;
728  }
729  else if (redo)
730  {
731  /* in redo, just log other types of error */
732  ereport(LOG,
734  errmsg("could not open directory \"%s\": %m",
735  linkloc_with_version_dir)));
736  pfree(linkloc_with_version_dir);
737  return false;
738  }
739  /* else let ReadDir report the error */
740  }
741 
742  while ((de = ReadDir(dirdesc, linkloc_with_version_dir)) != NULL)
743  {
744  if (strcmp(de->d_name, ".") == 0 ||
745  strcmp(de->d_name, "..") == 0)
746  continue;
747 
748  subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
749 
750  /* This check is just to deliver a friendlier error message */
751  if (!redo && !directory_is_empty(subfile))
752  {
753  FreeDir(dirdesc);
754  pfree(subfile);
755  pfree(linkloc_with_version_dir);
756  return false;
757  }
758 
759  /* remove empty directory */
760  if (rmdir(subfile) < 0)
761  ereport(redo ? LOG : ERROR,
763  errmsg("could not remove directory \"%s\": %m",
764  subfile)));
765 
766  pfree(subfile);
767  }
768 
769  FreeDir(dirdesc);
770 
771  /* remove version directory */
772  if (rmdir(linkloc_with_version_dir) < 0)
773  {
774  ereport(redo ? LOG : ERROR,
776  errmsg("could not remove directory \"%s\": %m",
777  linkloc_with_version_dir)));
778  pfree(linkloc_with_version_dir);
779  return false;
780  }
781 
782  /*
783  * Try to remove the symlink. We must however deal with the possibility
784  * that it's a directory instead of a symlink --- this could happen during
785  * WAL replay (see TablespaceCreateDbspace), and it is also the case on
786  * Windows where junction points lstat() as directories.
787  *
788  * Note: in the redo case, we'll return true if this final step fails;
789  * there's no point in retrying it. Also, ENOENT should provoke no more
790  * than a warning.
791  */
792 remove_symlink:
793  linkloc = pstrdup(linkloc_with_version_dir);
794  get_parent_directory(linkloc);
795  if (lstat(linkloc, &st) < 0)
796  {
797  int saved_errno = errno;
798 
799  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
801  errmsg("could not stat file \"%s\": %m",
802  linkloc)));
803  }
804  else if (S_ISDIR(st.st_mode))
805  {
806  if (rmdir(linkloc) < 0)
807  {
808  int saved_errno = errno;
809 
810  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
812  errmsg("could not remove directory \"%s\": %m",
813  linkloc)));
814  }
815  }
816 #ifdef S_ISLNK
817  else if (S_ISLNK(st.st_mode))
818  {
819  if (unlink(linkloc) < 0)
820  {
821  int saved_errno = errno;
822 
823  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
825  errmsg("could not remove symbolic link \"%s\": %m",
826  linkloc)));
827  }
828  }
829 #endif
830  else
831  {
832  /* Refuse to remove anything that's not a directory or symlink */
833  ereport(redo ? LOG : ERROR,
834  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
835  errmsg("\"%s\" is not a directory or symbolic link",
836  linkloc)));
837  }
838 
839  pfree(linkloc_with_version_dir);
840  pfree(linkloc);
841 
842  return true;
843 }
844 
845 
846 /*
847  * Check if a directory is empty.
848  *
849  * This probably belongs somewhere else, but not sure where...
850  */
851 bool
852 directory_is_empty(const char *path)
853 {
854  DIR *dirdesc;
855  struct dirent *de;
856 
857  dirdesc = AllocateDir(path);
858 
859  while ((de = ReadDir(dirdesc, path)) != NULL)
860  {
861  if (strcmp(de->d_name, ".") == 0 ||
862  strcmp(de->d_name, "..") == 0)
863  continue;
864  FreeDir(dirdesc);
865  return false;
866  }
867 
868  FreeDir(dirdesc);
869  return true;
870 }
871 
872 /*
873  * remove_tablespace_symlink
874  *
875  * This function removes symlinks in pg_tblspc. On Windows, junction points
876  * act like directories so we must be able to apply rmdir. This function
877  * works like the symlink removal code in destroy_tablespace_directories,
878  * except that failure to remove is always an ERROR. But if the file doesn't
879  * exist at all, that's OK.
880  */
881 void
882 remove_tablespace_symlink(const char *linkloc)
883 {
884  struct stat st;
885 
886  if (lstat(linkloc, &st) < 0)
887  {
888  if (errno == ENOENT)
889  return;
890  ereport(ERROR,
892  errmsg("could not stat file \"%s\": %m", linkloc)));
893  }
894 
895  if (S_ISDIR(st.st_mode))
896  {
897  /*
898  * This will fail if the directory isn't empty, but not if it's a
899  * junction point.
900  */
901  if (rmdir(linkloc) < 0 && errno != ENOENT)
902  ereport(ERROR,
904  errmsg("could not remove directory \"%s\": %m",
905  linkloc)));
906  }
907 #ifdef S_ISLNK
908  else if (S_ISLNK(st.st_mode))
909  {
910  if (unlink(linkloc) < 0 && errno != ENOENT)
911  ereport(ERROR,
913  errmsg("could not remove symbolic link \"%s\": %m",
914  linkloc)));
915  }
916 #endif
917  else
918  {
919  /* Refuse to remove anything that's not a directory or symlink */
920  ereport(ERROR,
921  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
922  errmsg("\"%s\" is not a directory or symbolic link",
923  linkloc)));
924  }
925 }
926 
927 /*
928  * Rename a tablespace
929  */
931 RenameTableSpace(const char *oldname, const char *newname)
932 {
933  Oid tspId;
934  Relation rel;
935  ScanKeyData entry[1];
936  TableScanDesc scan;
937  HeapTuple tup;
938  HeapTuple newtuple;
939  Form_pg_tablespace newform;
940  ObjectAddress address;
941 
942  /* Search pg_tablespace */
943  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
944 
945  ScanKeyInit(&entry[0],
946  Anum_pg_tablespace_spcname,
947  BTEqualStrategyNumber, F_NAMEEQ,
948  CStringGetDatum(oldname));
949  scan = table_beginscan_catalog(rel, 1, entry);
950  tup = heap_getnext(scan, ForwardScanDirection);
951  if (!HeapTupleIsValid(tup))
952  ereport(ERROR,
953  (errcode(ERRCODE_UNDEFINED_OBJECT),
954  errmsg("tablespace \"%s\" does not exist",
955  oldname)));
956 
957  newtuple = heap_copytuple(tup);
958  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
959  tspId = newform->oid;
960 
961  table_endscan(scan);
962 
963  /* Must be owner */
964  if (!pg_tablespace_ownercheck(tspId, GetUserId()))
966 
967  /* Validate new name */
968  if (!allowSystemTableMods && IsReservedName(newname))
969  ereport(ERROR,
970  (errcode(ERRCODE_RESERVED_NAME),
971  errmsg("unacceptable tablespace name \"%s\"", newname),
972  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
973 
974  /*
975  * If built with appropriate switch, whine when regression-testing
976  * conventions for tablespace names are violated.
977  */
978 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
979  if (strncmp(newname, "regress_", 8) != 0)
980  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
981 #endif
982 
983  /* Make sure the new name doesn't exist */
984  ScanKeyInit(&entry[0],
985  Anum_pg_tablespace_spcname,
986  BTEqualStrategyNumber, F_NAMEEQ,
987  CStringGetDatum(newname));
988  scan = table_beginscan_catalog(rel, 1, entry);
989  tup = heap_getnext(scan, ForwardScanDirection);
990  if (HeapTupleIsValid(tup))
991  ereport(ERROR,
993  errmsg("tablespace \"%s\" already exists",
994  newname)));
995 
996  table_endscan(scan);
997 
998  /* OK, update the entry */
999  namestrcpy(&(newform->spcname), newname);
1000 
1001  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1002 
1003  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
1004 
1005  ObjectAddressSet(address, TableSpaceRelationId, tspId);
1006 
1007  table_close(rel, NoLock);
1008 
1009  return address;
1010 }
1011 
1012 /*
1013  * Alter table space options
1014  */
1015 Oid
1017 {
1018  Relation rel;
1019  ScanKeyData entry[1];
1020  TableScanDesc scandesc;
1021  HeapTuple tup;
1022  Oid tablespaceoid;
1023  Datum datum;
1024  Datum newOptions;
1025  Datum repl_val[Natts_pg_tablespace];
1026  bool isnull;
1027  bool repl_null[Natts_pg_tablespace];
1028  bool repl_repl[Natts_pg_tablespace];
1029  HeapTuple newtuple;
1030 
1031  /* Search pg_tablespace */
1032  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1033 
1034  ScanKeyInit(&entry[0],
1035  Anum_pg_tablespace_spcname,
1036  BTEqualStrategyNumber, F_NAMEEQ,
1038  scandesc = table_beginscan_catalog(rel, 1, entry);
1039  tup = heap_getnext(scandesc, ForwardScanDirection);
1040  if (!HeapTupleIsValid(tup))
1041  ereport(ERROR,
1042  (errcode(ERRCODE_UNDEFINED_OBJECT),
1043  errmsg("tablespace \"%s\" does not exist",
1044  stmt->tablespacename)));
1045 
1046  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1047 
1048  /* Must be owner of the existing object */
1049  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
1051  stmt->tablespacename);
1052 
1053  /* Generate new proposed spcoptions (text array) */
1054  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1055  RelationGetDescr(rel), &isnull);
1056  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1057  stmt->options, NULL, NULL, false,
1058  stmt->isReset);
1059  (void) tablespace_reloptions(newOptions, true);
1060 
1061  /* Build new tuple. */
1062  memset(repl_null, false, sizeof(repl_null));
1063  memset(repl_repl, false, sizeof(repl_repl));
1064  if (newOptions != (Datum) 0)
1065  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1066  else
1067  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1068  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1069  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1070  repl_null, repl_repl);
1071 
1072  /* Update system catalog. */
1073  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1074 
1075  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1076 
1077  heap_freetuple(newtuple);
1078 
1079  /* Conclude heap scan. */
1080  table_endscan(scandesc);
1081  table_close(rel, NoLock);
1082 
1083  return tablespaceoid;
1084 }
1085 
1086 /*
1087  * Routines for handling the GUC variable 'default_tablespace'.
1088  */
1089 
1090 /* check_hook: validate new default_tablespace */
1091 bool
1093 {
1094  /*
1095  * If we aren't inside a transaction, or connected to a database, we
1096  * cannot do the catalog accesses necessary to verify the name. Must
1097  * accept the value on faith.
1098  */
1100  {
1101  if (**newval != '\0' &&
1102  !OidIsValid(get_tablespace_oid(*newval, true)))
1103  {
1104  /*
1105  * When source == PGC_S_TEST, don't throw a hard error for a
1106  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1107  */
1108  if (source == PGC_S_TEST)
1109  {
1110  ereport(NOTICE,
1111  (errcode(ERRCODE_UNDEFINED_OBJECT),
1112  errmsg("tablespace \"%s\" does not exist",
1113  *newval)));
1114  }
1115  else
1116  {
1117  GUC_check_errdetail("Tablespace \"%s\" does not exist.",
1118  *newval);
1119  return false;
1120  }
1121  }
1122  }
1123 
1124  return true;
1125 }
1126 
1127 /*
1128  * GetDefaultTablespace -- get the OID of the current default tablespace
1129  *
1130  * Temporary objects have different default tablespaces, hence the
1131  * relpersistence parameter must be specified. Also, for partitioned tables,
1132  * we disallow specifying the database default, so that needs to be specified
1133  * too.
1134  *
1135  * May return InvalidOid to indicate "use the database's default tablespace".
1136  *
1137  * Note that caller is expected to check appropriate permissions for any
1138  * result other than InvalidOid.
1139  *
1140  * This exists to hide (and possibly optimize the use of) the
1141  * default_tablespace GUC variable.
1142  */
1143 Oid
1144 GetDefaultTablespace(char relpersistence, bool partitioned)
1145 {
1146  Oid result;
1147 
1148  /* The temp-table case is handled elsewhere */
1149  if (relpersistence == RELPERSISTENCE_TEMP)
1150  {
1152  return GetNextTempTableSpace();
1153  }
1154 
1155  /* Fast path for default_tablespace == "" */
1156  if (default_tablespace == NULL || default_tablespace[0] == '\0')
1157  return InvalidOid;
1158 
1159  /*
1160  * It is tempting to cache this lookup for more speed, but then we would
1161  * fail to detect the case where the tablespace was dropped since the GUC
1162  * variable was set. Note also that we don't complain if the value fails
1163  * to refer to an existing tablespace; we just silently return InvalidOid,
1164  * causing the new object to be created in the database's tablespace.
1165  */
1166  result = get_tablespace_oid(default_tablespace, true);
1167 
1168  /*
1169  * Allow explicit specification of database's default tablespace in
1170  * default_tablespace without triggering permissions checks. Don't allow
1171  * specifying that when creating a partitioned table, however, since the
1172  * result is confusing.
1173  */
1174  if (result == MyDatabaseTableSpace)
1175  {
1176  if (partitioned)
1177  ereport(ERROR,
1178  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1179  errmsg("cannot specify default tablespace for partitioned relations")));
1180  result = InvalidOid;
1181  }
1182  return result;
1183 }
1184 
1185 
1186 /*
1187  * Routines for handling the GUC variable 'temp_tablespaces'.
1188  */
1189 
1190 typedef struct
1191 {
1192  /* Array of OIDs to be passed to SetTempTablespaces() */
1193  int numSpcs;
1196 
1197 /* check_hook: validate new temp_tablespaces */
1198 bool
1200 {
1201  char *rawname;
1202  List *namelist;
1203 
1204  /* Need a modifiable copy of string */
1205  rawname = pstrdup(*newval);
1206 
1207  /* Parse string into list of identifiers */
1208  if (!SplitIdentifierString(rawname, ',', &namelist))
1209  {
1210  /* syntax error in name list */
1211  GUC_check_errdetail("List syntax is invalid.");
1212  pfree(rawname);
1213  list_free(namelist);
1214  return false;
1215  }
1216 
1217  /*
1218  * If we aren't inside a transaction, or connected to a database, we
1219  * cannot do the catalog accesses necessary to verify the name. Must
1220  * accept the value on faith. Fortunately, there's then also no need to
1221  * pass the data to fd.c.
1222  */
1224  {
1225  temp_tablespaces_extra *myextra;
1226  Oid *tblSpcs;
1227  int numSpcs;
1228  ListCell *l;
1229 
1230  /* temporary workspace until we are done verifying the list */
1231  tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1232  numSpcs = 0;
1233  foreach(l, namelist)
1234  {
1235  char *curname = (char *) lfirst(l);
1236  Oid curoid;
1237  AclResult aclresult;
1238 
1239  /* Allow an empty string (signifying database default) */
1240  if (curname[0] == '\0')
1241  {
1242  /* InvalidOid signifies database's default tablespace */
1243  tblSpcs[numSpcs++] = InvalidOid;
1244  continue;
1245  }
1246 
1247  /*
1248  * In an interactive SET command, we ereport for bad info. When
1249  * source == PGC_S_TEST, don't throw a hard error for a
1250  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1251  */
1252  curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
1253  if (curoid == InvalidOid)
1254  {
1255  if (source == PGC_S_TEST)
1256  ereport(NOTICE,
1257  (errcode(ERRCODE_UNDEFINED_OBJECT),
1258  errmsg("tablespace \"%s\" does not exist",
1259  curname)));
1260  continue;
1261  }
1262 
1263  /*
1264  * Allow explicit specification of database's default tablespace
1265  * in temp_tablespaces without triggering permissions checks.
1266  */
1267  if (curoid == MyDatabaseTableSpace)
1268  {
1269  /* InvalidOid signifies database's default tablespace */
1270  tblSpcs[numSpcs++] = InvalidOid;
1271  continue;
1272  }
1273 
1274  /* Check permissions, similarly complaining only if interactive */
1275  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1276  ACL_CREATE);
1277  if (aclresult != ACLCHECK_OK)
1278  {
1279  if (source >= PGC_S_INTERACTIVE)
1280  aclcheck_error(aclresult, OBJECT_TABLESPACE, curname);
1281  continue;
1282  }
1283 
1284  tblSpcs[numSpcs++] = curoid;
1285  }
1286 
1287  /* Now prepare an "extra" struct for assign_temp_tablespaces */
1288  myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
1289  numSpcs * sizeof(Oid));
1290  if (!myextra)
1291  return false;
1292  myextra->numSpcs = numSpcs;
1293  memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1294  *extra = (void *) myextra;
1295 
1296  pfree(tblSpcs);
1297  }
1298 
1299  pfree(rawname);
1300  list_free(namelist);
1301 
1302  return true;
1303 }
1304 
1305 /* assign_hook: do extra actions as needed */
1306 void
1307 assign_temp_tablespaces(const char *newval, void *extra)
1308 {
1309  temp_tablespaces_extra *myextra = (temp_tablespaces_extra *) extra;
1310 
1311  /*
1312  * If check_temp_tablespaces was executed inside a transaction, then pass
1313  * the list it made to fd.c. Otherwise, clear fd.c's list; we must be
1314  * still outside a transaction, or else restoring during transaction exit,
1315  * and in either case we can just let the next PrepareTempTablespaces call
1316  * make things sane.
1317  */
1318  if (myextra)
1319  SetTempTablespaces(myextra->tblSpcs, myextra->numSpcs);
1320  else
1321  SetTempTablespaces(NULL, 0);
1322 }
1323 
1324 /*
1325  * PrepareTempTablespaces -- prepare to use temp tablespaces
1326  *
1327  * If we have not already done so in the current transaction, parse the
1328  * temp_tablespaces GUC variable and tell fd.c which tablespace(s) to use
1329  * for temp files.
1330  */
1331 void
1333 {
1334  char *rawname;
1335  List *namelist;
1336  Oid *tblSpcs;
1337  int numSpcs;
1338  ListCell *l;
1339 
1340  /* No work if already done in current transaction */
1341  if (TempTablespacesAreSet())
1342  return;
1343 
1344  /*
1345  * Can't do catalog access unless within a transaction. This is just a
1346  * safety check in case this function is called by low-level code that
1347  * could conceivably execute outside a transaction. Note that in such a
1348  * scenario, fd.c will fall back to using the current database's default
1349  * tablespace, which should always be OK.
1350  */
1351  if (!IsTransactionState())
1352  return;
1353 
1354  /* Need a modifiable copy of string */
1355  rawname = pstrdup(temp_tablespaces);
1356 
1357  /* Parse string into list of identifiers */
1358  if (!SplitIdentifierString(rawname, ',', &namelist))
1359  {
1360  /* syntax error in name list */
1361  SetTempTablespaces(NULL, 0);
1362  pfree(rawname);
1363  list_free(namelist);
1364  return;
1365  }
1366 
1367  /* Store tablespace OIDs in an array in TopTransactionContext */
1369  list_length(namelist) * sizeof(Oid));
1370  numSpcs = 0;
1371  foreach(l, namelist)
1372  {
1373  char *curname = (char *) lfirst(l);
1374  Oid curoid;
1375  AclResult aclresult;
1376 
1377  /* Allow an empty string (signifying database default) */
1378  if (curname[0] == '\0')
1379  {
1380  /* InvalidOid signifies database's default tablespace */
1381  tblSpcs[numSpcs++] = InvalidOid;
1382  continue;
1383  }
1384 
1385  /* Else verify that name is a valid tablespace name */
1386  curoid = get_tablespace_oid(curname, true);
1387  if (curoid == InvalidOid)
1388  {
1389  /* Skip any bad list elements */
1390  continue;
1391  }
1392 
1393  /*
1394  * Allow explicit specification of database's default tablespace in
1395  * temp_tablespaces without triggering permissions checks.
1396  */
1397  if (curoid == MyDatabaseTableSpace)
1398  {
1399  /* InvalidOid signifies database's default tablespace */
1400  tblSpcs[numSpcs++] = InvalidOid;
1401  continue;
1402  }
1403 
1404  /* Check permissions similarly */
1405  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1406  ACL_CREATE);
1407  if (aclresult != ACLCHECK_OK)
1408  continue;
1409 
1410  tblSpcs[numSpcs++] = curoid;
1411  }
1412 
1413  SetTempTablespaces(tblSpcs, numSpcs);
1414 
1415  pfree(rawname);
1416  list_free(namelist);
1417 }
1418 
1419 
1420 /*
1421  * get_tablespace_oid - given a tablespace name, look up the OID
1422  *
1423  * If missing_ok is false, throw an error if tablespace name not found. If
1424  * true, just return InvalidOid.
1425  */
1426 Oid
1427 get_tablespace_oid(const char *tablespacename, bool missing_ok)
1428 {
1429  Oid result;
1430  Relation rel;
1431  TableScanDesc scandesc;
1432  HeapTuple tuple;
1433  ScanKeyData entry[1];
1434 
1435  /*
1436  * Search pg_tablespace. We use a heapscan here even though there is an
1437  * index on name, on the theory that pg_tablespace will usually have just
1438  * a few entries and so an indexed lookup is a waste of effort.
1439  */
1440  rel = table_open(TableSpaceRelationId, AccessShareLock);
1441 
1442  ScanKeyInit(&entry[0],
1443  Anum_pg_tablespace_spcname,
1444  BTEqualStrategyNumber, F_NAMEEQ,
1445  CStringGetDatum(tablespacename));
1446  scandesc = table_beginscan_catalog(rel, 1, entry);
1447  tuple = heap_getnext(scandesc, ForwardScanDirection);
1448 
1449  /* We assume that there can be at most one matching tuple */
1450  if (HeapTupleIsValid(tuple))
1451  result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1452  else
1453  result = InvalidOid;
1454 
1455  table_endscan(scandesc);
1457 
1458  if (!OidIsValid(result) && !missing_ok)
1459  ereport(ERROR,
1460  (errcode(ERRCODE_UNDEFINED_OBJECT),
1461  errmsg("tablespace \"%s\" does not exist",
1462  tablespacename)));
1463 
1464  return result;
1465 }
1466 
1467 /*
1468  * get_tablespace_name - given a tablespace OID, look up the name
1469  *
1470  * Returns a palloc'd string, or NULL if no such tablespace.
1471  */
1472 char *
1474 {
1475  char *result;
1476  Relation rel;
1477  TableScanDesc scandesc;
1478  HeapTuple tuple;
1479  ScanKeyData entry[1];
1480 
1481  /*
1482  * Search pg_tablespace. We use a heapscan here even though there is an
1483  * index on oid, on the theory that pg_tablespace will usually have just a
1484  * few entries and so an indexed lookup is a waste of effort.
1485  */
1486  rel = table_open(TableSpaceRelationId, AccessShareLock);
1487 
1488  ScanKeyInit(&entry[0],
1489  Anum_pg_tablespace_oid,
1490  BTEqualStrategyNumber, F_OIDEQ,
1491  ObjectIdGetDatum(spc_oid));
1492  scandesc = table_beginscan_catalog(rel, 1, entry);
1493  tuple = heap_getnext(scandesc, ForwardScanDirection);
1494 
1495  /* We assume that there can be at most one matching tuple */
1496  if (HeapTupleIsValid(tuple))
1497  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1498  else
1499  result = NULL;
1500 
1501  table_endscan(scandesc);
1503 
1504  return result;
1505 }
1506 
1507 
1508 /*
1509  * TABLESPACE resource manager's routines
1510  */
1511 void
1513 {
1514  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1515 
1516  /* Backup blocks are not used in tblspc records */
1517  Assert(!XLogRecHasAnyBlockRefs(record));
1518 
1519  if (info == XLOG_TBLSPC_CREATE)
1520  {
1522  char *location = xlrec->ts_path;
1523 
1524  create_tablespace_directories(location, xlrec->ts_id);
1525  }
1526  else if (info == XLOG_TBLSPC_DROP)
1527  {
1529 
1530  /*
1531  * If we issued a WAL record for a drop tablespace it implies that
1532  * there were no files in it at all when the DROP was done. That means
1533  * that no permanent objects can exist in it at this point.
1534  *
1535  * It is possible for standby users to be using this tablespace as a
1536  * location for their temporary files, so if we fail to remove all
1537  * files then do conflict processing and try again, if currently
1538  * enabled.
1539  *
1540  * Other possible reasons for failure include bollixed file
1541  * permissions on a standby server when they were okay on the primary,
1542  * etc etc. There's not much we can do about that, so just remove what
1543  * we can and press on.
1544  */
1545  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1546  {
1548 
1549  /*
1550  * If we did recovery processing then hopefully the backends who
1551  * wrote temp files should have cleaned up and exited by now. So
1552  * retry before complaining. If we fail again, this is just a LOG
1553  * condition, because it's not worth throwing an ERROR for (as
1554  * that would crash the database and require manual intervention
1555  * before we could get past this WAL record on restart).
1556  */
1557  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1558  ereport(LOG,
1559  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1560  errmsg("directories for tablespace %u could not be removed",
1561  xlrec->ts_id),
1562  errhint("You can remove the directories manually if necessary.")));
1563  }
1564  }
1565  else
1566  elog(PANIC, "tblspc_redo: unknown op code %u", info);
1567 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1427
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4768
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
MemoryContext TopTransactionContext
Definition: mcxt.c:53
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1149
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
char * temp_tablespaces
Definition: tablespace.c:89
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:495
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:29
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define GUC_check_errdetail
Definition: guc.h:422
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
char * pstrdup(const char *in)
Definition: mcxt.c:1299
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
unsigned char uint8
Definition: c.h:439
#define AccessShareLock
Definition: lockdefs.h:36
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2080
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:350
void ForceSyncCommit(void)
Definition: xact.c:1072
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
#define MemSet(start, val, len)
Definition: c.h:1008
bool directory_is_empty(const char *path)
Definition: tablespace.c:852
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
Oid CreateTableSpace(CreateTableSpaceStmt *stmt)
Definition: tablespace.c:233
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:163
#define LOG
Definition: elog.h:26
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void remove_tablespace_symlink(const char *linkloc)
Definition: tablespace.c:882
bool IsReservedName(const char *name)
Definition: catalog.c:218
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:710
#define PANIC
Definition: elog.h:50
Oid MyDatabaseTableSpace
Definition: globals.c:90
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
GucSource
Definition: guc.h:104
#define malloc(a)
Definition: header.h:50
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void assign_temp_tablespaces(const char *newval, void *extra)
Definition: tablespace.c:1307
bool TempTablespacesAreSet(void)
Definition: fd.c:2954
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
void pfree(void *pointer)
Definition: mcxt.c:1169
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:307
#define XLogRecGetData(decoder)
Definition: xlogreader.h:320
Definition: dirent.c:25
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define ACL_CREATE
Definition: parsenodes.h:92
void PrepareTempTablespaces(void)
Definition: tablespace.c:1332
#define MAXPGPATH
ItemPointerData t_self
Definition: htup.h:65
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
Definition: tablespace.c:1144
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
#define NoLock
Definition: lockdefs.h:34
Oid GetNextTempTableSpace(void)
Definition: fd.c:2987
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
#define symlink(oldpath, newpath)
Definition: win32_port.h:235
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3746
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
#define is_absolute_path(filename)
Definition: port.h:86
#define CStringGetDatum(X)
Definition: postgres.h:622
void get_parent_directory(char *path)
Definition: path.c:854
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:5020
int errdetail_log(const char *fmt,...)
Definition: elog.c:1090
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2720
void DropTableSpace(DropTableSpaceStmt *stmt)
Definition: tablespace.c:413
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1194
#define CHECKPOINT_FORCE
Definition: xlog.h:200
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2926
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:315
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:997
#define WARNING
Definition: elog.h:40
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:761
int pg_dir_create_mode
Definition: file_perm.c:18
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:434
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:588
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
unsigned short st_mode
Definition: win32_port.h:268
Oid MyDatabaseId
Definition: globals.c:88
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5128
TupleDesc rd_att
Definition: rel.h:110
bool allowSystemTableMods
Definition: globals.c:123
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3782
#define NOTICE
Definition: elog.h:37
bool InRecovery
Definition: xlogutils.c:52
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition: standby.c:499
#define CHECKPOINT_WAIT
Definition: xlog.h:204
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define lfirst(lc)
Definition: pg_list.h:169
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:682
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2786
void TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
Definition: tablespace.c:115
static rewind_source * source
Definition: pg_rewind.c:79
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static int list_length(const List *l)
Definition: pg_list.h:149
#define newval
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
bool check_default_tablespace(char **newval, void **extra, GucSource source)
Definition: tablespace.c:1092
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
bool IsTransactionState(void)
Definition: xact.c:372
void tblspc_redo(XLogReaderState *record)
Definition: tablespace.c:1512
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define FORKNAMECHARS
Definition: relpath.h:57
#define S_ISDIR(m)
Definition: win32_port.h:324
#define lstat(path, sb)
Definition: win32_port.h:284
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:489
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
static Datum values[MAXATTR]
Definition: bootstrap.c:156
ObjectAddress RenameTableSpace(const char *oldname, const char *newname)
Definition: tablespace.c:931
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1473
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
char * DataDir
Definition: globals.c:65
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:322
char d_name[MAX_PATH]
Definition: dirent.h:15
bool checkSharedDependencies(Oid classId, Oid objectId, char **detail_msg, char **detail_log_msg)
Definition: pg_shdepend.c:629
char * default_tablespace
Definition: tablespace.c:88
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void XLogBeginInsert(void)
Definition: xloginsert.c:135
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
bool check_temp_tablespaces(char **newval, void **extra, GucSource source)
Definition: tablespace.c:1199
#define OIDCHARS
Definition: relpath.h:30
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define BTEqualStrategyNumber
Definition: stratnum.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2838
#define offsetof(type, field)
Definition: c.h:727
#define stat
Definition: win32_port.h:283
void RequestCheckpoint(int flags)
Definition: checkpointer.c:920
Oid AlterTableSpaceOptions(AlterTableSpaceOptionsStmt *stmt)
Definition: tablespace.c:1016