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