PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2016, 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/types.h>
52 #include <sys/stat.h>
53 
54 #include "access/heapam.h"
55 #include "access/reloptions.h"
56 #include "access/htup_details.h"
57 #include "access/sysattr.h"
58 #include "access/xact.h"
59 #include "access/xlog.h"
60 #include "access/xloginsert.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 "miscadmin.h"
73 #include "postmaster/bgwriter.h"
74 #include "storage/fd.h"
75 #include "storage/lmgr.h"
76 #include "storage/standby.h"
77 #include "utils/acl.h"
78 #include "utils/builtins.h"
79 #include "utils/fmgroids.h"
80 #include "utils/guc.h"
81 #include "utils/lsyscache.h"
82 #include "utils/memutils.h"
83 #include "utils/rel.h"
84 #include "utils/tqual.h"
85 
86 
87 /* GUC variables */
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 (mkdir(dir, S_IRWXU) < 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 (mkdir(parentdir, S_IRWXU) < 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 (mkdir(parentdir, S_IRWXU) < 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 (mkdir(dir, S_IRWXU) < 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;
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 super user */
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 mkdir() uses the first two parts.
283  */
284  if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
285  OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1 + OIDCHARS > MAXPGPATH)
286  ereport(ERROR,
287  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
288  errmsg("tablespace location \"%s\" is too long",
289  location)));
290 
291  /* Warn if the tablespace is in the data directory. */
292  if (path_is_prefix_of_path(DataDir, location))
294  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
295  errmsg("tablespace location should not be inside the data directory")));
296 
297  /*
298  * Disallow creation of tablespaces named "pg_xxx"; we reserve this
299  * namespace for system purposes.
300  */
302  ereport(ERROR,
303  (errcode(ERRCODE_RESERVED_NAME),
304  errmsg("unacceptable tablespace name \"%s\"",
305  stmt->tablespacename),
306  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
307 
308  /*
309  * Check that there is no other tablespace by this name. (The unique
310  * index would catch this anyway, but might as well give a friendlier
311  * message.)
312  */
313  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
314  ereport(ERROR,
316  errmsg("tablespace \"%s\" already exists",
317  stmt->tablespacename)));
318 
319  /*
320  * Insert tuple into pg_tablespace. The purpose of doing this first is to
321  * lock the proposed tablename against other would-be creators. The
322  * insertion will roll back if we find problems below.
323  */
325 
326  MemSet(nulls, false, sizeof(nulls));
327 
328  values[Anum_pg_tablespace_spcname - 1] =
330  values[Anum_pg_tablespace_spcowner - 1] =
331  ObjectIdGetDatum(ownerId);
332  nulls[Anum_pg_tablespace_spcacl - 1] = true;
333 
334  /* Generate new proposed spcoptions (text array) */
335  newOptions = transformRelOptions((Datum) 0,
336  stmt->options,
337  NULL, NULL, false, false);
338  (void) tablespace_reloptions(newOptions, true);
339  if (newOptions != (Datum) 0)
340  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
341  else
342  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
343 
344  tuple = heap_form_tuple(rel->rd_att, values, nulls);
345 
346  tablespaceoid = simple_heap_insert(rel, tuple);
347 
348  CatalogUpdateIndexes(rel, tuple);
349 
350  heap_freetuple(tuple);
351 
352  /* Record dependency on owner */
353  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
354 
355  /* Post creation hook for new tablespace */
357 
358  create_tablespace_directories(location, tablespaceoid);
359 
360  /* Record the filesystem change in XLOG */
361  {
362  xl_tblspc_create_rec xlrec;
363 
364  xlrec.ts_id = tablespaceoid;
365 
366  XLogBeginInsert();
367  XLogRegisterData((char *) &xlrec,
368  offsetof(xl_tblspc_create_rec, ts_path));
369  XLogRegisterData((char *) location, strlen(location) + 1);
370 
371  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
372  }
373 
374  /*
375  * Force synchronous commit, to minimize the window between creating the
376  * symlink on-disk and marking the transaction committed. It's not great
377  * that there is any window at all, but definitely we don't want to make
378  * it larger than necessary.
379  */
380  ForceSyncCommit();
381 
382  pfree(location);
383 
384  /* We keep the lock on pg_tablespace until commit */
385  heap_close(rel, NoLock);
386 
387  return tablespaceoid;
388 #else /* !HAVE_SYMLINK */
389  ereport(ERROR,
390  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
391  errmsg("tablespaces are not supported on this platform")));
392  return InvalidOid; /* keep compiler quiet */
393 #endif /* HAVE_SYMLINK */
394 }
395 
396 /*
397  * Drop a table space
398  *
399  * Be careful to check that the tablespace is empty.
400  */
401 void
403 {
404 #ifdef HAVE_SYMLINK
405  char *tablespacename = stmt->tablespacename;
406  HeapScanDesc scandesc;
407  Relation rel;
408  HeapTuple tuple;
409  ScanKeyData entry[1];
410  Oid tablespaceoid;
411 
412  /*
413  * Find the target tuple
414  */
416 
417  ScanKeyInit(&entry[0],
419  BTEqualStrategyNumber, F_NAMEEQ,
420  CStringGetDatum(tablespacename));
421  scandesc = heap_beginscan_catalog(rel, 1, entry);
422  tuple = heap_getnext(scandesc, ForwardScanDirection);
423 
424  if (!HeapTupleIsValid(tuple))
425  {
426  if (!stmt->missing_ok)
427  {
428  ereport(ERROR,
429  (errcode(ERRCODE_UNDEFINED_OBJECT),
430  errmsg("tablespace \"%s\" does not exist",
431  tablespacename)));
432  }
433  else
434  {
435  ereport(NOTICE,
436  (errmsg("tablespace \"%s\" does not exist, skipping",
437  tablespacename)));
438  /* XXX I assume I need one or both of these next two calls */
439  heap_endscan(scandesc);
440  heap_close(rel, NoLock);
441  }
442  return;
443  }
444 
445  tablespaceoid = HeapTupleGetOid(tuple);
446 
447  /* Must be tablespace owner */
448  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
450  tablespacename);
451 
452  /* Disallow drop of the standard tablespaces, even by superuser */
453  if (tablespaceoid == GLOBALTABLESPACE_OID ||
454  tablespaceoid == DEFAULTTABLESPACE_OID)
456  tablespacename);
457 
458  /* DROP hook for the tablespace being removed */
459  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
460 
461  /*
462  * Remove the pg_tablespace tuple (this will roll back if we fail below)
463  */
464  simple_heap_delete(rel, &tuple->t_self);
465 
466  heap_endscan(scandesc);
467 
468  /*
469  * Remove any comments or security labels on this tablespace.
470  */
473 
474  /*
475  * Remove dependency on owner.
476  */
478 
479  /*
480  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
481  * is running concurrently.
482  */
483  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
484 
485  /*
486  * Try to remove the physical infrastructure.
487  */
488  if (!destroy_tablespace_directories(tablespaceoid, false))
489  {
490  /*
491  * Not all files deleted? However, there can be lingering empty files
492  * in the directories, left behind by for example DROP TABLE, that
493  * have been scheduled for deletion at next checkpoint (see comments
494  * in mdunlink() for details). We could just delete them immediately,
495  * but we can't tell them apart from important data files that we
496  * mustn't delete. So instead, we force a checkpoint which will clean
497  * out any lingering files, and try again.
498  *
499  * XXX On Windows, an unlinked file persists in the directory listing
500  * until no process retains an open handle for the file. The DDL
501  * commands that schedule files for unlink send invalidation messages
502  * directing other PostgreSQL processes to close the files. DROP
503  * TABLESPACE should not give up on the tablespace becoming empty
504  * until all relevant invalidation processing is complete.
505  */
507  if (!destroy_tablespace_directories(tablespaceoid, false))
508  {
509  /* Still not empty, the files must be important then */
510  ereport(ERROR,
511  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
512  errmsg("tablespace \"%s\" is not empty",
513  tablespacename)));
514  }
515  }
516 
517  /* Record the filesystem change in XLOG */
518  {
519  xl_tblspc_drop_rec xlrec;
520 
521  xlrec.ts_id = tablespaceoid;
522 
523  XLogBeginInsert();
524  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
525 
526  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
527  }
528 
529  /*
530  * Note: because we checked that the tablespace was empty, there should be
531  * no need to worry about flushing shared buffers or free space map
532  * entries for relations in the tablespace.
533  */
534 
535  /*
536  * Force synchronous commit, to minimize the window between removing the
537  * files on-disk and marking the transaction committed. It's not great
538  * that there is any window at all, but definitely we don't want to make
539  * it larger than necessary.
540  */
541  ForceSyncCommit();
542 
543  /*
544  * Allow TablespaceCreateDbspace again.
545  */
546  LWLockRelease(TablespaceCreateLock);
547 
548  /* We keep the lock on pg_tablespace until commit */
549  heap_close(rel, NoLock);
550 #else /* !HAVE_SYMLINK */
551  ereport(ERROR,
552  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
553  errmsg("tablespaces are not supported on this platform")));
554 #endif /* HAVE_SYMLINK */
555 }
556 
557 
558 /*
559  * create_tablespace_directories
560  *
561  * Attempt to create filesystem infrastructure linking $PGDATA/pg_tblspc/
562  * to the specified directory
563  */
564 static void
565 create_tablespace_directories(const char *location, const Oid tablespaceoid)
566 {
567  char *linkloc;
568  char *location_with_version_dir;
569  struct stat st;
570 
571  linkloc = psprintf("pg_tblspc/%u", tablespaceoid);
572  location_with_version_dir = psprintf("%s/%s", location,
574 
575  /*
576  * Attempt to coerce target directory to safe permissions. If this fails,
577  * it doesn't exist or has the wrong owner.
578  */
579  if (chmod(location, S_IRWXU) != 0)
580  {
581  if (errno == ENOENT)
582  ereport(ERROR,
583  (errcode(ERRCODE_UNDEFINED_FILE),
584  errmsg("directory \"%s\" does not exist", location),
585  InRecovery ? errhint("Create this directory for the tablespace before "
586  "restarting the server.") : 0));
587  else
588  ereport(ERROR,
590  errmsg("could not set permissions on directory \"%s\": %m",
591  location)));
592  }
593 
594  if (InRecovery)
595  {
596  /*
597  * Our theory for replaying a CREATE is to forcibly drop the target
598  * subdirectory if present, and then recreate it. This may be more
599  * work than needed, but it is simple to implement.
600  */
601  if (stat(location_with_version_dir, &st) == 0 && S_ISDIR(st.st_mode))
602  {
603  if (!rmtree(location_with_version_dir, true))
604  /* If this failed, mkdir() below is going to error. */
606  (errmsg("some useless files may be left behind in old database directory \"%s\"",
607  location_with_version_dir)));
608  }
609  }
610 
611  /*
612  * The creation of the version directory prevents more than one tablespace
613  * in a single location.
614  */
615  if (mkdir(location_with_version_dir, S_IRWXU) < 0)
616  {
617  if (errno == EEXIST)
618  ereport(ERROR,
619  (errcode(ERRCODE_OBJECT_IN_USE),
620  errmsg("directory \"%s\" already in use as a tablespace",
621  location_with_version_dir)));
622  else
623  ereport(ERROR,
625  errmsg("could not create directory \"%s\": %m",
626  location_with_version_dir)));
627  }
628 
629  /*
630  * In recovery, remove old symlink, in case it points to the wrong place.
631  */
632  if (InRecovery)
633  remove_tablespace_symlink(linkloc);
634 
635  /*
636  * Create the symlink under PGDATA
637  */
638  if (symlink(location, linkloc) < 0)
639  ereport(ERROR,
641  errmsg("could not create symbolic link \"%s\": %m",
642  linkloc)));
643 
644  pfree(linkloc);
645  pfree(location_with_version_dir);
646 }
647 
648 
649 /*
650  * destroy_tablespace_directories
651  *
652  * Attempt to remove filesystem infrastructure for the tablespace.
653  *
654  * 'redo' indicates we are redoing a drop from XLOG; in that case we should
655  * not throw an ERROR for problems, just LOG them. The worst consequence of
656  * not removing files here would be failure to release some disk space, which
657  * does not justify throwing an error that would require manual intervention
658  * to get the database running again.
659  *
660  * Returns TRUE if successful, FALSE if some subdirectory is not empty
661  */
662 static bool
663 destroy_tablespace_directories(Oid tablespaceoid, bool redo)
664 {
665  char *linkloc;
666  char *linkloc_with_version_dir;
667  DIR *dirdesc;
668  struct dirent *de;
669  char *subfile;
670  struct stat st;
671 
672  linkloc_with_version_dir = psprintf("pg_tblspc/%u/%s", tablespaceoid,
674 
675  /*
676  * Check if the tablespace still contains any files. We try to rmdir each
677  * per-database directory we find in it. rmdir failure implies there are
678  * still files in that subdirectory, so give up. (We do not have to worry
679  * about undoing any already completed rmdirs, since the next attempt to
680  * use the tablespace from that database will simply recreate the
681  * subdirectory via TablespaceCreateDbspace.)
682  *
683  * Since we hold TablespaceCreateLock, no one else should be creating any
684  * fresh subdirectories in parallel. It is possible that new files are
685  * being created within subdirectories, though, so the rmdir call could
686  * fail. Worst consequence is a less friendly error message.
687  *
688  * If redo is true then ENOENT is a likely outcome here, and we allow it
689  * to pass without comment. In normal operation we still allow it, but
690  * with a warning. This is because even though ProcessUtility disallows
691  * DROP TABLESPACE in a transaction block, it's possible that a previous
692  * DROP failed and rolled back after removing the tablespace directories
693  * and/or symlink. We want to allow a new DROP attempt to succeed at
694  * removing the catalog entries (and symlink if still present), so we
695  * should not give a hard error here.
696  */
697  dirdesc = AllocateDir(linkloc_with_version_dir);
698  if (dirdesc == NULL)
699  {
700  if (errno == ENOENT)
701  {
702  if (!redo)
705  errmsg("could not open directory \"%s\": %m",
706  linkloc_with_version_dir)));
707  /* The symlink might still exist, so go try to remove it */
708  goto remove_symlink;
709  }
710  else if (redo)
711  {
712  /* in redo, just log other types of error */
713  ereport(LOG,
715  errmsg("could not open directory \"%s\": %m",
716  linkloc_with_version_dir)));
717  pfree(linkloc_with_version_dir);
718  return false;
719  }
720  /* else let ReadDir report the error */
721  }
722 
723  while ((de = ReadDir(dirdesc, linkloc_with_version_dir)) != NULL)
724  {
725  if (strcmp(de->d_name, ".") == 0 ||
726  strcmp(de->d_name, "..") == 0)
727  continue;
728 
729  subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
730 
731  /* This check is just to deliver a friendlier error message */
732  if (!redo && !directory_is_empty(subfile))
733  {
734  FreeDir(dirdesc);
735  pfree(subfile);
736  pfree(linkloc_with_version_dir);
737  return false;
738  }
739 
740  /* remove empty directory */
741  if (rmdir(subfile) < 0)
742  ereport(redo ? LOG : ERROR,
744  errmsg("could not remove directory \"%s\": %m",
745  subfile)));
746 
747  pfree(subfile);
748  }
749 
750  FreeDir(dirdesc);
751 
752  /* remove version directory */
753  if (rmdir(linkloc_with_version_dir) < 0)
754  {
755  ereport(redo ? LOG : ERROR,
757  errmsg("could not remove directory \"%s\": %m",
758  linkloc_with_version_dir)));
759  pfree(linkloc_with_version_dir);
760  return false;
761  }
762 
763  /*
764  * Try to remove the symlink. We must however deal with the possibility
765  * that it's a directory instead of a symlink --- this could happen during
766  * WAL replay (see TablespaceCreateDbspace), and it is also the case on
767  * Windows where junction points lstat() as directories.
768  *
769  * Note: in the redo case, we'll return true if this final step fails;
770  * there's no point in retrying it. Also, ENOENT should provoke no more
771  * than a warning.
772  */
773 remove_symlink:
774  linkloc = pstrdup(linkloc_with_version_dir);
775  get_parent_directory(linkloc);
776  if (lstat(linkloc, &st) < 0)
777  {
778  int saved_errno = errno;
779 
780  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
782  errmsg("could not stat file \"%s\": %m",
783  linkloc)));
784  }
785  else if (S_ISDIR(st.st_mode))
786  {
787  if (rmdir(linkloc) < 0)
788  {
789  int saved_errno = errno;
790 
791  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
793  errmsg("could not remove directory \"%s\": %m",
794  linkloc)));
795  }
796  }
797 #ifdef S_ISLNK
798  else if (S_ISLNK(st.st_mode))
799  {
800  if (unlink(linkloc) < 0)
801  {
802  int saved_errno = errno;
803 
804  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
806  errmsg("could not remove symbolic link \"%s\": %m",
807  linkloc)));
808  }
809  }
810 #endif
811  else
812  {
813  /* Refuse to remove anything that's not a directory or symlink */
814  ereport(redo ? LOG : ERROR,
815  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
816  errmsg("\"%s\" is not a directory or symbolic link",
817  linkloc)));
818  }
819 
820  pfree(linkloc_with_version_dir);
821  pfree(linkloc);
822 
823  return true;
824 }
825 
826 
827 /*
828  * Check if a directory is empty.
829  *
830  * This probably belongs somewhere else, but not sure where...
831  */
832 bool
833 directory_is_empty(const char *path)
834 {
835  DIR *dirdesc;
836  struct dirent *de;
837 
838  dirdesc = AllocateDir(path);
839 
840  while ((de = ReadDir(dirdesc, path)) != NULL)
841  {
842  if (strcmp(de->d_name, ".") == 0 ||
843  strcmp(de->d_name, "..") == 0)
844  continue;
845  FreeDir(dirdesc);
846  return false;
847  }
848 
849  FreeDir(dirdesc);
850  return true;
851 }
852 
853 /*
854  * remove_tablespace_symlink
855  *
856  * This function removes symlinks in pg_tblspc. On Windows, junction points
857  * act like directories so we must be able to apply rmdir. This function
858  * works like the symlink removal code in destroy_tablespace_directories,
859  * except that failure to remove is always an ERROR. But if the file doesn't
860  * exist at all, that's OK.
861  */
862 void
863 remove_tablespace_symlink(const char *linkloc)
864 {
865  struct stat st;
866 
867  if (lstat(linkloc, &st) < 0)
868  {
869  if (errno == ENOENT)
870  return;
871  ereport(ERROR,
873  errmsg("could not stat file \"%s\": %m", linkloc)));
874  }
875 
876  if (S_ISDIR(st.st_mode))
877  {
878  /*
879  * This will fail if the directory isn't empty, but not if it's a
880  * junction point.
881  */
882  if (rmdir(linkloc) < 0 && errno != ENOENT)
883  ereport(ERROR,
885  errmsg("could not remove directory \"%s\": %m",
886  linkloc)));
887  }
888 #ifdef S_ISLNK
889  else if (S_ISLNK(st.st_mode))
890  {
891  if (unlink(linkloc) < 0 && errno != ENOENT)
892  ereport(ERROR,
894  errmsg("could not remove symbolic link \"%s\": %m",
895  linkloc)));
896  }
897 #endif
898  else
899  {
900  /* Refuse to remove anything that's not a directory or symlink */
901  ereport(ERROR,
902  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
903  errmsg("\"%s\" is not a directory or symbolic link",
904  linkloc)));
905  }
906 }
907 
908 /*
909  * Rename a tablespace
910  */
912 RenameTableSpace(const char *oldname, const char *newname)
913 {
914  Oid tspId;
915  Relation rel;
916  ScanKeyData entry[1];
917  HeapScanDesc scan;
918  HeapTuple tup;
919  HeapTuple newtuple;
920  Form_pg_tablespace newform;
921  ObjectAddress address;
922 
923  /* Search pg_tablespace */
925 
926  ScanKeyInit(&entry[0],
928  BTEqualStrategyNumber, F_NAMEEQ,
929  CStringGetDatum(oldname));
930  scan = heap_beginscan_catalog(rel, 1, entry);
931  tup = heap_getnext(scan, ForwardScanDirection);
932  if (!HeapTupleIsValid(tup))
933  ereport(ERROR,
934  (errcode(ERRCODE_UNDEFINED_OBJECT),
935  errmsg("tablespace \"%s\" does not exist",
936  oldname)));
937 
938  tspId = HeapTupleGetOid(tup);
939  newtuple = heap_copytuple(tup);
940  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
941 
942  heap_endscan(scan);
943 
944  /* Must be owner */
947 
948  /* Validate new name */
949  if (!allowSystemTableMods && IsReservedName(newname))
950  ereport(ERROR,
951  (errcode(ERRCODE_RESERVED_NAME),
952  errmsg("unacceptable tablespace name \"%s\"", newname),
953  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
954 
955  /* Make sure the new name doesn't exist */
956  ScanKeyInit(&entry[0],
958  BTEqualStrategyNumber, F_NAMEEQ,
959  CStringGetDatum(newname));
960  scan = heap_beginscan_catalog(rel, 1, entry);
961  tup = heap_getnext(scan, ForwardScanDirection);
962  if (HeapTupleIsValid(tup))
963  ereport(ERROR,
965  errmsg("tablespace \"%s\" already exists",
966  newname)));
967 
968  heap_endscan(scan);
969 
970  /* OK, update the entry */
971  namestrcpy(&(newform->spcname), newname);
972 
973  simple_heap_update(rel, &newtuple->t_self, newtuple);
974  CatalogUpdateIndexes(rel, newtuple);
975 
977 
978  ObjectAddressSet(address, TableSpaceRelationId, tspId);
979 
980  heap_close(rel, NoLock);
981 
982  return address;
983 }
984 
985 /*
986  * Alter table space options
987  */
988 Oid
990 {
991  Relation rel;
992  ScanKeyData entry[1];
993  HeapScanDesc scandesc;
994  HeapTuple tup;
995  Oid tablespaceoid;
996  Datum datum;
997  Datum newOptions;
998  Datum repl_val[Natts_pg_tablespace];
999  bool isnull;
1000  bool repl_null[Natts_pg_tablespace];
1001  bool repl_repl[Natts_pg_tablespace];
1002  HeapTuple newtuple;
1003 
1004  /* Search pg_tablespace */
1006 
1007  ScanKeyInit(&entry[0],
1009  BTEqualStrategyNumber, F_NAMEEQ,
1011  scandesc = heap_beginscan_catalog(rel, 1, entry);
1012  tup = heap_getnext(scandesc, ForwardScanDirection);
1013  if (!HeapTupleIsValid(tup))
1014  ereport(ERROR,
1015  (errcode(ERRCODE_UNDEFINED_OBJECT),
1016  errmsg("tablespace \"%s\" does not exist",
1017  stmt->tablespacename)));
1018 
1019  tablespaceoid = HeapTupleGetOid(tup);
1020 
1021  /* Must be owner of the existing object */
1024  stmt->tablespacename);
1025 
1026  /* Generate new proposed spcoptions (text array) */
1028  RelationGetDescr(rel), &isnull);
1029  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1030  stmt->options, NULL, NULL, false,
1031  stmt->isReset);
1032  (void) tablespace_reloptions(newOptions, true);
1033 
1034  /* Build new tuple. */
1035  memset(repl_null, false, sizeof(repl_null));
1036  memset(repl_repl, false, sizeof(repl_repl));
1037  if (newOptions != (Datum) 0)
1038  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1039  else
1040  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1041  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1042  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1043  repl_null, repl_repl);
1044 
1045  /* Update system catalog. */
1046  simple_heap_update(rel, &newtuple->t_self, newtuple);
1047  CatalogUpdateIndexes(rel, newtuple);
1048 
1050 
1051  heap_freetuple(newtuple);
1052 
1053  /* Conclude heap scan. */
1054  heap_endscan(scandesc);
1055  heap_close(rel, NoLock);
1056 
1057  return tablespaceoid;
1058 }
1059 
1060 /*
1061  * Routines for handling the GUC variable 'default_tablespace'.
1062  */
1063 
1064 /* check_hook: validate new default_tablespace */
1065 bool
1066 check_default_tablespace(char **newval, void **extra, GucSource source)
1067 {
1068  /*
1069  * If we aren't inside a transaction, we cannot do database access so
1070  * cannot verify the name. Must accept the value on faith.
1071  */
1072  if (IsTransactionState())
1073  {
1074  if (**newval != '\0' &&
1075  !OidIsValid(get_tablespace_oid(*newval, true)))
1076  {
1077  /*
1078  * When source == PGC_S_TEST, don't throw a hard error for a
1079  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1080  */
1081  if (source == PGC_S_TEST)
1082  {
1083  ereport(NOTICE,
1084  (errcode(ERRCODE_UNDEFINED_OBJECT),
1085  errmsg("tablespace \"%s\" does not exist",
1086  *newval)));
1087  }
1088  else
1089  {
1090  GUC_check_errdetail("Tablespace \"%s\" does not exist.",
1091  *newval);
1092  return false;
1093  }
1094  }
1095  }
1096 
1097  return true;
1098 }
1099 
1100 /*
1101  * GetDefaultTablespace -- get the OID of the current default tablespace
1102  *
1103  * Temporary objects have different default tablespaces, hence the
1104  * relpersistence parameter must be specified.
1105  *
1106  * May return InvalidOid to indicate "use the database's default tablespace".
1107  *
1108  * Note that caller is expected to check appropriate permissions for any
1109  * result other than InvalidOid.
1110  *
1111  * This exists to hide (and possibly optimize the use of) the
1112  * default_tablespace GUC variable.
1113  */
1114 Oid
1115 GetDefaultTablespace(char relpersistence)
1116 {
1117  Oid result;
1118 
1119  /* The temp-table case is handled elsewhere */
1120  if (relpersistence == RELPERSISTENCE_TEMP)
1121  {
1123  return GetNextTempTableSpace();
1124  }
1125 
1126  /* Fast path for default_tablespace == "" */
1127  if (default_tablespace == NULL || default_tablespace[0] == '\0')
1128  return InvalidOid;
1129 
1130  /*
1131  * It is tempting to cache this lookup for more speed, but then we would
1132  * fail to detect the case where the tablespace was dropped since the GUC
1133  * variable was set. Note also that we don't complain if the value fails
1134  * to refer to an existing tablespace; we just silently return InvalidOid,
1135  * causing the new object to be created in the database's tablespace.
1136  */
1137  result = get_tablespace_oid(default_tablespace, true);
1138 
1139  /*
1140  * Allow explicit specification of database's default tablespace in
1141  * default_tablespace without triggering permissions checks.
1142  */
1143  if (result == MyDatabaseTableSpace)
1144  result = InvalidOid;
1145  return result;
1146 }
1147 
1148 
1149 /*
1150  * Routines for handling the GUC variable 'temp_tablespaces'.
1151  */
1152 
1153 typedef struct
1154 {
1155  int numSpcs;
1156  Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER];
1158 
1159 /* check_hook: validate new temp_tablespaces */
1160 bool
1161 check_temp_tablespaces(char **newval, void **extra, GucSource source)
1162 {
1163  char *rawname;
1164  List *namelist;
1165 
1166  /* Need a modifiable copy of string */
1167  rawname = pstrdup(*newval);
1168 
1169  /* Parse string into list of identifiers */
1170  if (!SplitIdentifierString(rawname, ',', &namelist))
1171  {
1172  /* syntax error in name list */
1173  GUC_check_errdetail("List syntax is invalid.");
1174  pfree(rawname);
1175  list_free(namelist);
1176  return false;
1177  }
1178 
1179  /*
1180  * If we aren't inside a transaction, we cannot do database access so
1181  * cannot verify the individual names. Must accept the list on faith.
1182  * Fortunately, there's then also no need to pass the data to fd.c.
1183  */
1184  if (IsTransactionState())
1185  {
1186  temp_tablespaces_extra *myextra;
1187  Oid *tblSpcs;
1188  int numSpcs;
1189  ListCell *l;
1190 
1191  /* temporary workspace until we are done verifying the list */
1192  tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1193  numSpcs = 0;
1194  foreach(l, namelist)
1195  {
1196  char *curname = (char *) lfirst(l);
1197  Oid curoid;
1198  AclResult aclresult;
1199 
1200  /* Allow an empty string (signifying database default) */
1201  if (curname[0] == '\0')
1202  {
1203  tblSpcs[numSpcs++] = InvalidOid;
1204  continue;
1205  }
1206 
1207  /*
1208  * In an interactive SET command, we ereport for bad info. When
1209  * source == PGC_S_TEST, don't throw a hard error for a
1210  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1211  */
1212  curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
1213  if (curoid == InvalidOid)
1214  {
1215  if (source == PGC_S_TEST)
1216  ereport(NOTICE,
1217  (errcode(ERRCODE_UNDEFINED_OBJECT),
1218  errmsg("tablespace \"%s\" does not exist",
1219  curname)));
1220  continue;
1221  }
1222 
1223  /*
1224  * Allow explicit specification of database's default tablespace
1225  * in temp_tablespaces without triggering permissions checks.
1226  */
1227  if (curoid == MyDatabaseTableSpace)
1228  {
1229  tblSpcs[numSpcs++] = InvalidOid;
1230  continue;
1231  }
1232 
1233  /* Check permissions, similarly complaining only if interactive */
1234  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1235  ACL_CREATE);
1236  if (aclresult != ACLCHECK_OK)
1237  {
1238  if (source >= PGC_S_INTERACTIVE)
1239  aclcheck_error(aclresult, ACL_KIND_TABLESPACE, curname);
1240  continue;
1241  }
1242 
1243  tblSpcs[numSpcs++] = curoid;
1244  }
1245 
1246  /* Now prepare an "extra" struct for assign_temp_tablespaces */
1247  myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
1248  numSpcs * sizeof(Oid));
1249  if (!myextra)
1250  return false;
1251  myextra->numSpcs = numSpcs;
1252  memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1253  *extra = (void *) myextra;
1254 
1255  pfree(tblSpcs);
1256  }
1257 
1258  pfree(rawname);
1259  list_free(namelist);
1260 
1261  return true;
1262 }
1263 
1264 /* assign_hook: do extra actions as needed */
1265 void
1266 assign_temp_tablespaces(const char *newval, void *extra)
1267 {
1268  temp_tablespaces_extra *myextra = (temp_tablespaces_extra *) extra;
1269 
1270  /*
1271  * If check_temp_tablespaces was executed inside a transaction, then pass
1272  * the list it made to fd.c. Otherwise, clear fd.c's list; we must be
1273  * still outside a transaction, or else restoring during transaction exit,
1274  * and in either case we can just let the next PrepareTempTablespaces call
1275  * make things sane.
1276  */
1277  if (myextra)
1278  SetTempTablespaces(myextra->tblSpcs, myextra->numSpcs);
1279  else
1281 }
1282 
1283 /*
1284  * PrepareTempTablespaces -- prepare to use temp tablespaces
1285  *
1286  * If we have not already done so in the current transaction, parse the
1287  * temp_tablespaces GUC variable and tell fd.c which tablespace(s) to use
1288  * for temp files.
1289  */
1290 void
1292 {
1293  char *rawname;
1294  List *namelist;
1295  Oid *tblSpcs;
1296  int numSpcs;
1297  ListCell *l;
1298 
1299  /* No work if already done in current transaction */
1300  if (TempTablespacesAreSet())
1301  return;
1302 
1303  /*
1304  * Can't do catalog access unless within a transaction. This is just a
1305  * safety check in case this function is called by low-level code that
1306  * could conceivably execute outside a transaction. Note that in such a
1307  * scenario, fd.c will fall back to using the current database's default
1308  * tablespace, which should always be OK.
1309  */
1310  if (!IsTransactionState())
1311  return;
1312 
1313  /* Need a modifiable copy of string */
1314  rawname = pstrdup(temp_tablespaces);
1315 
1316  /* Parse string into list of identifiers */
1317  if (!SplitIdentifierString(rawname, ',', &namelist))
1318  {
1319  /* syntax error in name list */
1321  pfree(rawname);
1322  list_free(namelist);
1323  return;
1324  }
1325 
1326  /* Store tablespace OIDs in an array in TopTransactionContext */
1328  list_length(namelist) * sizeof(Oid));
1329  numSpcs = 0;
1330  foreach(l, namelist)
1331  {
1332  char *curname = (char *) lfirst(l);
1333  Oid curoid;
1334  AclResult aclresult;
1335 
1336  /* Allow an empty string (signifying database default) */
1337  if (curname[0] == '\0')
1338  {
1339  tblSpcs[numSpcs++] = InvalidOid;
1340  continue;
1341  }
1342 
1343  /* Else verify that name is a valid tablespace name */
1344  curoid = get_tablespace_oid(curname, true);
1345  if (curoid == InvalidOid)
1346  {
1347  /* Skip any bad list elements */
1348  continue;
1349  }
1350 
1351  /*
1352  * Allow explicit specification of database's default tablespace in
1353  * temp_tablespaces without triggering permissions checks.
1354  */
1355  if (curoid == MyDatabaseTableSpace)
1356  {
1357  tblSpcs[numSpcs++] = InvalidOid;
1358  continue;
1359  }
1360 
1361  /* Check permissions similarly */
1362  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1363  ACL_CREATE);
1364  if (aclresult != ACLCHECK_OK)
1365  continue;
1366 
1367  tblSpcs[numSpcs++] = curoid;
1368  }
1369 
1370  SetTempTablespaces(tblSpcs, numSpcs);
1371 
1372  pfree(rawname);
1373  list_free(namelist);
1374 }
1375 
1376 
1377 /*
1378  * get_tablespace_oid - given a tablespace name, look up the OID
1379  *
1380  * If missing_ok is false, throw an error if tablespace name not found. If
1381  * true, just return InvalidOid.
1382  */
1383 Oid
1384 get_tablespace_oid(const char *tablespacename, bool missing_ok)
1385 {
1386  Oid result;
1387  Relation rel;
1388  HeapScanDesc scandesc;
1389  HeapTuple tuple;
1390  ScanKeyData entry[1];
1391 
1392  /*
1393  * Search pg_tablespace. We use a heapscan here even though there is an
1394  * index on name, on the theory that pg_tablespace will usually have just
1395  * a few entries and so an indexed lookup is a waste of effort.
1396  */
1398 
1399  ScanKeyInit(&entry[0],
1401  BTEqualStrategyNumber, F_NAMEEQ,
1402  CStringGetDatum(tablespacename));
1403  scandesc = heap_beginscan_catalog(rel, 1, entry);
1404  tuple = heap_getnext(scandesc, ForwardScanDirection);
1405 
1406  /* We assume that there can be at most one matching tuple */
1407  if (HeapTupleIsValid(tuple))
1408  result = HeapTupleGetOid(tuple);
1409  else
1410  result = InvalidOid;
1411 
1412  heap_endscan(scandesc);
1414 
1415  if (!OidIsValid(result) && !missing_ok)
1416  ereport(ERROR,
1417  (errcode(ERRCODE_UNDEFINED_OBJECT),
1418  errmsg("tablespace \"%s\" does not exist",
1419  tablespacename)));
1420 
1421  return result;
1422 }
1423 
1424 /*
1425  * get_tablespace_name - given a tablespace OID, look up the name
1426  *
1427  * Returns a palloc'd string, or NULL if no such tablespace.
1428  */
1429 char *
1431 {
1432  char *result;
1433  Relation rel;
1434  HeapScanDesc scandesc;
1435  HeapTuple tuple;
1436  ScanKeyData entry[1];
1437 
1438  /*
1439  * Search pg_tablespace. We use a heapscan here even though there is an
1440  * index on oid, on the theory that pg_tablespace will usually have just a
1441  * few entries and so an indexed lookup is a waste of effort.
1442  */
1444 
1445  ScanKeyInit(&entry[0],
1447  BTEqualStrategyNumber, F_OIDEQ,
1448  ObjectIdGetDatum(spc_oid));
1449  scandesc = heap_beginscan_catalog(rel, 1, entry);
1450  tuple = heap_getnext(scandesc, ForwardScanDirection);
1451 
1452  /* We assume that there can be at most one matching tuple */
1453  if (HeapTupleIsValid(tuple))
1454  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1455  else
1456  result = NULL;
1457 
1458  heap_endscan(scandesc);
1460 
1461  return result;
1462 }
1463 
1464 
1465 /*
1466  * TABLESPACE resource manager's routines
1467  */
1468 void
1470 {
1471  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1472 
1473  /* Backup blocks are not used in tblspc records */
1474  Assert(!XLogRecHasAnyBlockRefs(record));
1475 
1476  if (info == XLOG_TBLSPC_CREATE)
1477  {
1479  char *location = xlrec->ts_path;
1480 
1481  create_tablespace_directories(location, xlrec->ts_id);
1482  }
1483  else if (info == XLOG_TBLSPC_DROP)
1484  {
1486 
1487  /*
1488  * If we issued a WAL record for a drop tablespace it implies that
1489  * there were no files in it at all when the DROP was done. That means
1490  * that no permanent objects can exist in it at this point.
1491  *
1492  * It is possible for standby users to be using this tablespace as a
1493  * location for their temporary files, so if we fail to remove all
1494  * files then do conflict processing and try again, if currently
1495  * enabled.
1496  *
1497  * Other possible reasons for failure include bollixed file
1498  * permissions on a standby server when they were okay on the primary,
1499  * etc etc. There's not much we can do about that, so just remove what
1500  * we can and press on.
1501  */
1502  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1503  {
1505 
1506  /*
1507  * If we did recovery processing then hopefully the backends who
1508  * wrote temp files should have cleaned up and exited by now. So
1509  * retry before complaining. If we fail again, this is just a LOG
1510  * condition, because it's not worth throwing an ERROR for (as
1511  * that would crash the database and require manual intervention
1512  * before we could get past this WAL record on restart).
1513  */
1514  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1515  ereport(LOG,
1516  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1517  errmsg("directories for tablespace %u could not be removed",
1518  xlrec->ts_id),
1519  errhint("You can remove the directories manually if necessary.")));
1520  }
1521  }
1522  else
1523  elog(PANIC, "tblspc_redo: unknown op code %u", info);
1524 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
#define Anum_pg_tablespace_spcacl
Definition: pg_tablespace.h:57
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1384
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4485
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
#define OIDCHARS
Definition: catalog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
MemoryContext TopTransactionContext
Definition: mcxt.c:48
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1580
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
char * temp_tablespaces
Definition: tablespace.c:89
#define RelationGetDescr(relation)
Definition: rel.h:383
Oid GetUserId(void)
Definition: miscinit.c:282
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:29
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
#define GUC_check_errdetail
Definition: guc.h:408
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
#define mkdir(a, b)
Definition: win32.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1168
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool InRecovery
Definition: xlog.c:187
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
unsigned char uint8
Definition: c.h:263
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1446
void ForceSyncCommit(void)
Definition: xact.c:967
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define MemSet(start, val, len)
Definition: c.h:849
bool directory_is_empty(const char *path)
Definition: tablespace.c:833
Oid get_rolespec_oid(const Node *node, bool missing_ok)
Definition: acl.c:5146
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:548
Oid CreateTableSpace(CreateTableSpaceStmt *stmt)
Definition: tablespace.c:233
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:155
#define LOG
Definition: elog.h:26
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1306
unsigned int Oid
Definition: postgres_ext.h:31
void remove_tablespace_symlink(const char *linkloc)
Definition: tablespace.c:863
bool IsReservedName(const char *name)
Definition: catalog.c:192
int namestrcpy(Name name, const char *str)
Definition: name.c:217
Definition: dirent.h:9
#define OidIsValid(objectId)
Definition: c.h:530
#define PANIC
Definition: elog.h:53
Oid GetDefaultTablespace(char relpersistence)
Definition: tablespace.c:1115
Oid MyDatabaseTableSpace
Definition: globals.c:78
GucSource
Definition: guc.h:105
#define malloc(a)
Definition: header.h:45
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1774
void assign_temp_tablespaces(const char *newval, void *extra)
Definition: tablespace.c:1266
bool TempTablespacesAreSet(void)
Definition: fd.c:2425
void pfree(void *pointer)
Definition: mcxt.c:995
#define XLogRecGetData(decoder)
Definition: xlogreader.h:201
Definition: dirent.c:25
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:73
void PrepareTempTablespaces(void)
Definition: tablespace.c:1291
#define MAXPGPATH
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
Oid GetNextTempTableSpace(void)
Definition: fd.c:2437
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3128
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3392
#define RowExclusiveLock
Definition: lockdefs.h:38
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define is_absolute_path(filename)
Definition: port.h:77
#define CStringGetDatum(X)
Definition: postgres.h:586
void get_parent_directory(char *path)
Definition: path.c:854
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:47
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4737
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2207
#define Anum_pg_tablespace_spcowner
Definition: pg_tablespace.h:56
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1401
void DropTableSpace(DropTableSpaceStmt *stmt)
Definition: tablespace.c:402
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1156
#define CHECKPOINT_FORCE
Definition: xlog.h:177
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2397
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:197
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:108
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:828
#define WARNING
Definition: elog.h:40
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:408
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:565
AclResult
Definition: acl.h:169
uintptr_t Datum
Definition: postgres.h:374
Oid simple_heap_insert(Relation relation, HeapTuple tup)
Definition: heapam.c:2914
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1780
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1286
TupleDesc rd_att
Definition: rel.h:84
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:698
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition: standby.c:288
#define CHECKPOINT_WAIT
Definition: xlog.h:181
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define lfirst(lc)
Definition: pg_list.h:106
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:381
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:663
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2273
void CatalogUpdateIndexes(Relation heapRel, HeapTuple heapTuple)
Definition: indexing.c:157
void TablespaceCreateDbspace(Oid spcNode, Oid dbNode, bool isRedo)
Definition: tablespace.c:115
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
void simple_heap_delete(Relation relation, ItemPointer tid)
Definition: heapam.c:3373
void simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup)
Definition: heapam.c:4411
bool check_default_tablespace(char **newval, void **extra, GucSource source)
Definition: tablespace.c:1066
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1167
bool IsTransactionState(void)
Definition: xact.c:347
void tblspc_redo(XLogReaderState *record)
Definition: tablespace.c:1469
#define TABLESPACE_VERSION_DIRECTORY
Definition: catalog.h:26
#define Anum_pg_tablespace_spcname
Definition: pg_tablespace.h:55
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define FORKNAMECHARS
Definition: relpath.h:41
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:420
static Datum values[MAXATTR]
Definition: bootstrap.c:160
ObjectAddress RenameTableSpace(const char *oldname, const char *newname)
Definition: tablespace.c:912
void * palloc(Size size)
Definition: mcxt.c:894
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:752
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1430
void list_free(List *list)
Definition: list.c:1133
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:176
#define NameStr(name)
Definition: c.h:494
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define Anum_pg_tablespace_spcoptions
Definition: pg_tablespace.h:58
char * DataDir
Definition: globals.c:59
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:203
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:218
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
char * default_tablespace
Definition: tablespace.c:88
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:167
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:791
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
#define lstat(path, sb)
Definition: win32.h:272
Definition: pg_list.h:45
bool check_temp_tablespaces(char **newval, void **extra, GucSource source)
Definition: tablespace.c:1161
#define BTEqualStrategyNumber
Definition: stratnum.h:31
int FreeDir(DIR *dir)
Definition: fd.c:2316
#define offsetof(type, field)
Definition: c.h:547
void RequestCheckpoint(int flags)
Definition: checkpointer.c:953
#define Natts_pg_tablespace
Definition: pg_tablespace.h:54
Oid AlterTableSpaceOptions(AlterTableSpaceOptionsStmt *stmt)
Definition: tablespace.c:989