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