PostgreSQL Source Code  git master
tablespace.h File Reference
Include dependency graph for tablespace.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  xl_tblspc_create_rec
 
struct  xl_tblspc_drop_rec
 
struct  TableSpaceOpts
 

Macros

#define XLOG_TBLSPC_CREATE   0x00
 
#define XLOG_TBLSPC_DROP   0x10
 

Typedefs

typedef struct xl_tblspc_create_rec xl_tblspc_create_rec
 
typedef struct xl_tblspc_drop_rec xl_tblspc_drop_rec
 
typedef struct TableSpaceOpts TableSpaceOpts
 

Functions

Oid CreateTableSpace (CreateTableSpaceStmt *stmt)
 
void DropTableSpace (DropTableSpaceStmt *stmt)
 
ObjectAddress RenameTableSpace (const char *oldname, const char *newname)
 
Oid AlterTableSpaceOptions (AlterTableSpaceOptionsStmt *stmt)
 
void TablespaceCreateDbspace (Oid spcOid, Oid dbOid, bool isRedo)
 
Oid GetDefaultTablespace (char relpersistence, bool partitioned)
 
void PrepareTempTablespaces (void)
 
Oid get_tablespace_oid (const char *tablespacename, bool missing_ok)
 
char * get_tablespace_name (Oid spc_oid)
 
bool directory_is_empty (const char *path)
 
void remove_tablespace_symlink (const char *linkloc)
 
void tblspc_redo (XLogReaderState *record)
 
void tblspc_desc (StringInfo buf, XLogReaderState *record)
 
const char * tblspc_identify (uint8 info)
 

Variables

PGDLLIMPORT bool allow_in_place_tablespaces
 

Macro Definition Documentation

◆ XLOG_TBLSPC_CREATE

#define XLOG_TBLSPC_CREATE   0x00

Definition at line 25 of file tablespace.h.

◆ XLOG_TBLSPC_DROP

#define XLOG_TBLSPC_DROP   0x10

Definition at line 26 of file tablespace.h.

Typedef Documentation

◆ TableSpaceOpts

◆ xl_tblspc_create_rec

◆ xl_tblspc_drop_rec

Function Documentation

◆ AlterTableSpaceOptions()

Oid AlterTableSpaceOptions ( AlterTableSpaceOptionsStmt stmt)

Definition at line 1021 of file tablespace.c.

1022 {
1023  Relation rel;
1024  ScanKeyData entry[1];
1025  TableScanDesc scandesc;
1026  HeapTuple tup;
1027  Oid tablespaceoid;
1028  Datum datum;
1029  Datum newOptions;
1030  Datum repl_val[Natts_pg_tablespace];
1031  bool isnull;
1032  bool repl_null[Natts_pg_tablespace];
1033  bool repl_repl[Natts_pg_tablespace];
1034  HeapTuple newtuple;
1035 
1036  /* Search pg_tablespace */
1037  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1038 
1039  ScanKeyInit(&entry[0],
1040  Anum_pg_tablespace_spcname,
1041  BTEqualStrategyNumber, F_NAMEEQ,
1042  CStringGetDatum(stmt->tablespacename));
1043  scandesc = table_beginscan_catalog(rel, 1, entry);
1044  tup = heap_getnext(scandesc, ForwardScanDirection);
1045  if (!HeapTupleIsValid(tup))
1046  ereport(ERROR,
1047  (errcode(ERRCODE_UNDEFINED_OBJECT),
1048  errmsg("tablespace \"%s\" does not exist",
1049  stmt->tablespacename)));
1050 
1051  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1052 
1053  /* Must be owner of the existing object */
1054  if (!object_ownercheck(TableSpaceRelationId, tablespaceoid, GetUserId()))
1056  stmt->tablespacename);
1057 
1058  /* Generate new proposed spcoptions (text array) */
1059  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1060  RelationGetDescr(rel), &isnull);
1061  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1062  stmt->options, NULL, NULL, false,
1063  stmt->isReset);
1064  (void) tablespace_reloptions(newOptions, true);
1065 
1066  /* Build new tuple. */
1067  memset(repl_null, false, sizeof(repl_null));
1068  memset(repl_repl, false, sizeof(repl_repl));
1069  if (newOptions != (Datum) 0)
1070  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1071  else
1072  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1073  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1074  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1075  repl_null, repl_repl);
1076 
1077  /* Update system catalog. */
1078  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1079 
1080  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1081 
1082  heap_freetuple(newtuple);
1083 
1084  /* Conclude heap scan. */
1085  table_endscan(scandesc);
1086  table_close(rel, NoLock);
1087 
1088  return tablespaceoid;
1089 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2695
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4097
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1086
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1210
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:508
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
@ OBJECT_TABLESPACE
Definition: parsenodes.h:2138
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
uintptr_t Datum
Definition: postgres.h:64
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:530
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2088
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1158
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
#define BTEqualStrategyNumber
Definition: stratnum.h:31
ItemPointerData t_self
Definition: htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, GETSTRUCT, GetUserId(), heap_freetuple(), heap_getattr(), heap_getnext(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, object_ownercheck(), OBJECT_TABLESPACE, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), stmt, HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), tablespace_reloptions(), and transformRelOptions().

Referenced by standard_ProcessUtility().

◆ CreateTableSpace()

Oid CreateTableSpace ( CreateTableSpaceStmt stmt)

Definition at line 214 of file tablespace.c.

215 {
216  Relation rel;
217  Datum values[Natts_pg_tablespace];
218  bool nulls[Natts_pg_tablespace] = {0};
219  HeapTuple tuple;
220  Oid tablespaceoid;
221  char *location;
222  Oid ownerId;
223  Datum newOptions;
224  bool in_place;
225 
226  /* Must be superuser */
227  if (!superuser())
228  ereport(ERROR,
229  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
230  errmsg("permission denied to create tablespace \"%s\"",
231  stmt->tablespacename),
232  errhint("Must be superuser to create a tablespace.")));
233 
234  /* However, the eventual owner of the tablespace need not be */
235  if (stmt->owner)
236  ownerId = get_rolespec_oid(stmt->owner, false);
237  else
238  ownerId = GetUserId();
239 
240  /* Unix-ify the offered path, and strip any trailing slashes */
241  location = pstrdup(stmt->location);
242  canonicalize_path(location);
243 
244  /* disallow quotes, else CREATE DATABASE would be at risk */
245  if (strchr(location, '\''))
246  ereport(ERROR,
247  (errcode(ERRCODE_INVALID_NAME),
248  errmsg("tablespace location cannot contain single quotes")));
249 
250  in_place = allow_in_place_tablespaces && strlen(location) == 0;
251 
252  /*
253  * Allowing relative paths seems risky
254  *
255  * This also helps us ensure that location is not empty or whitespace,
256  * unless specifying a developer-only in-place tablespace.
257  */
258  if (!in_place && !is_absolute_path(location))
259  ereport(ERROR,
260  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
261  errmsg("tablespace location must be an absolute path")));
262 
263  /*
264  * Check that location isn't too long. Remember that we're going to append
265  * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
266  * reference the whole path here, but MakePGDirectory() uses the first two
267  * parts.
268  */
269  if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
270  OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1 + OIDCHARS > MAXPGPATH)
271  ereport(ERROR,
272  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
273  errmsg("tablespace location \"%s\" is too long",
274  location)));
275 
276  /* Warn if the tablespace is in the data directory. */
277  if (path_is_prefix_of_path(DataDir, location))
279  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
280  errmsg("tablespace location should not be inside the data directory")));
281 
282  /*
283  * Disallow creation of tablespaces named "pg_xxx"; we reserve this
284  * namespace for system purposes.
285  */
286  if (!allowSystemTableMods && IsReservedName(stmt->tablespacename))
287  ereport(ERROR,
288  (errcode(ERRCODE_RESERVED_NAME),
289  errmsg("unacceptable tablespace name \"%s\"",
290  stmt->tablespacename),
291  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
292 
293  /*
294  * If built with appropriate switch, whine when regression-testing
295  * conventions for tablespace names are violated.
296  */
297 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
298  if (strncmp(stmt->tablespacename, "regress_", 8) != 0)
299  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
300 #endif
301 
302  /*
303  * Check that there is no other tablespace by this name. (The unique
304  * index would catch this anyway, but might as well give a friendlier
305  * message.)
306  */
307  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
308  ereport(ERROR,
310  errmsg("tablespace \"%s\" already exists",
311  stmt->tablespacename)));
312 
313  /*
314  * Insert tuple into pg_tablespace. The purpose of doing this first is to
315  * lock the proposed tablename against other would-be creators. The
316  * insertion will roll back if we find problems below.
317  */
318  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
319 
320  if (IsBinaryUpgrade)
321  {
322  /* Use binary-upgrade override for tablespace oid */
324  ereport(ERROR,
325  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
326  errmsg("pg_tablespace OID value not set when in binary upgrade mode")));
327 
330  }
331  else
332  tablespaceoid = GetNewOidWithIndex(rel, TablespaceOidIndexId,
333  Anum_pg_tablespace_oid);
334  values[Anum_pg_tablespace_oid - 1] = ObjectIdGetDatum(tablespaceoid);
335  values[Anum_pg_tablespace_spcname - 1] =
336  DirectFunctionCall1(namein, CStringGetDatum(stmt->tablespacename));
337  values[Anum_pg_tablespace_spcowner - 1] =
338  ObjectIdGetDatum(ownerId);
339  nulls[Anum_pg_tablespace_spcacl - 1] = true;
340 
341  /* Generate new proposed spcoptions (text array) */
342  newOptions = transformRelOptions((Datum) 0,
343  stmt->options,
344  NULL, NULL, false, false);
345  (void) tablespace_reloptions(newOptions, true);
346  if (newOptions != (Datum) 0)
347  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
348  else
349  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
350 
351  tuple = heap_form_tuple(rel->rd_att, values, nulls);
352 
353  CatalogTupleInsert(rel, tuple);
354 
355  heap_freetuple(tuple);
356 
357  /* Record dependency on owner */
358  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
359 
360  /* Post creation hook for new tablespace */
361  InvokeObjectPostCreateHook(TableSpaceRelationId, tablespaceoid, 0);
362 
363  create_tablespace_directories(location, tablespaceoid);
364 
365  /* Record the filesystem change in XLOG */
366  {
367  xl_tblspc_create_rec xlrec;
368 
369  xlrec.ts_id = tablespaceoid;
370 
371  XLogBeginInsert();
372  XLogRegisterData((char *) &xlrec,
373  offsetof(xl_tblspc_create_rec, ts_path));
374  XLogRegisterData((char *) location, strlen(location) + 1);
375 
376  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
377  }
378 
379  /*
380  * Force synchronous commit, to minimize the window between creating the
381  * symlink on-disk and marking the transaction committed. It's not great
382  * that there is any window at all, but definitely we don't want to make
383  * it larger than necessary.
384  */
385  ForceSyncCommit();
386 
387  pfree(location);
388 
389  /* We keep the lock on pg_tablespace until commit */
390  table_close(rel, NoLock);
391 
392  return tablespaceoid;
393 }
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5380
Oid binary_upgrade_next_pg_tablespace_oid
Definition: tablespace.c:93
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1432
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:578
bool allow_in_place_tablespaces
Definition: tablespace.c:91
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define OidIsValid(objectId)
Definition: c.h:764
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
bool IsReservedName(const char *name)
Definition: catalog.c:219
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
#define WARNING
Definition: elog.h:36
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
bool IsBinaryUpgrade
Definition: globals.c:116
bool allowSystemTableMods
Definition: globals.c:126
char * DataDir
Definition: globals.c:66
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:233
char * pstrdup(const char *in)
Definition: mcxt.c:1644
void pfree(void *pointer)
Definition: mcxt.c:1456
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
#define MAXPGPATH
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
#define is_absolute_path(filename)
Definition: port.h:103
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:559
void canonicalize_path(char *path)
Definition: path.c:264
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
#define OIDCHARS
Definition: relpath.h:37
#define FORKNAMECHARS
Definition: relpath.h:64
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:33
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
TupleDesc rd_att
Definition: rel.h:112
bool superuser(void)
Definition: superuser.c:46
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:25
void ForceSyncCommit(void)
Definition: xact.c:1128
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:365
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:475
void XLogBeginInsert(void)
Definition: xloginsert.c:150

References allow_in_place_tablespaces, allowSystemTableMods, binary_upgrade_next_pg_tablespace_oid, canonicalize_path(), CatalogTupleInsert(), create_tablespace_directories(), CStringGetDatum(), DataDir, DirectFunctionCall1, elog(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FORKNAMECHARS, get_rolespec_oid(), get_tablespace_oid(), GetNewOidWithIndex(), GetUserId(), heap_form_tuple(), heap_freetuple(), InvalidOid, InvokeObjectPostCreateHook, is_absolute_path, IsBinaryUpgrade, IsReservedName(), MAXPGPATH, namein(), NoLock, ObjectIdGetDatum(), OIDCHARS, OidIsValid, path_is_prefix_of_path(), pfree(), pstrdup(), RelationData::rd_att, recordDependencyOnOwner(), RowExclusiveLock, stmt, superuser(), table_close(), table_open(), tablespace_reloptions(), TABLESPACE_VERSION_DIRECTORY, transformRelOptions(), xl_tblspc_create_rec::ts_id, values, WARNING, XLOG_TBLSPC_CREATE, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 859 of file tablespace.c.

860 {
861  DIR *dirdesc;
862  struct dirent *de;
863 
864  dirdesc = AllocateDir(path);
865 
866  while ((de = ReadDir(dirdesc, path)) != NULL)
867  {
868  if (strcmp(de->d_name, ".") == 0 ||
869  strcmp(de->d_name, "..") == 0)
870  continue;
871  FreeDir(dirdesc);
872  return false;
873  }
874 
875  FreeDir(dirdesc);
876  return true;
877 }
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2879
int FreeDir(DIR *dir)
Definition: fd.c:2931
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2813
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15

References AllocateDir(), dirent::d_name, FreeDir(), and ReadDir().

Referenced by CreateDatabaseUsingFileCopy(), createdb(), destroy_tablespace_directories(), and pg_tablespace_databases().

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

Definition at line 401 of file tablespace.c.

402 {
403  char *tablespacename = stmt->tablespacename;
404  TableScanDesc scandesc;
405  Relation rel;
406  HeapTuple tuple;
407  Form_pg_tablespace spcform;
408  ScanKeyData entry[1];
409  Oid tablespaceoid;
410  char *detail;
411  char *detail_log;
412 
413  /*
414  * Find the target tuple
415  */
416  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
417 
418  ScanKeyInit(&entry[0],
419  Anum_pg_tablespace_spcname,
420  BTEqualStrategyNumber, F_NAMEEQ,
421  CStringGetDatum(tablespacename));
422  scandesc = table_beginscan_catalog(rel, 1, entry);
423  tuple = heap_getnext(scandesc, ForwardScanDirection);
424 
425  if (!HeapTupleIsValid(tuple))
426  {
427  if (!stmt->missing_ok)
428  {
429  ereport(ERROR,
430  (errcode(ERRCODE_UNDEFINED_OBJECT),
431  errmsg("tablespace \"%s\" does not exist",
432  tablespacename)));
433  }
434  else
435  {
436  ereport(NOTICE,
437  (errmsg("tablespace \"%s\" does not exist, skipping",
438  tablespacename)));
439  table_endscan(scandesc);
440  table_close(rel, NoLock);
441  }
442  return;
443  }
444 
445  spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
446  tablespaceoid = spcform->oid;
447 
448  /* Must be tablespace owner */
449  if (!object_ownercheck(TableSpaceRelationId, tablespaceoid, GetUserId()))
451  tablespacename);
452 
453  /* Disallow drop of the standard tablespaces, even by superuser */
454  if (IsPinnedObject(TableSpaceRelationId, tablespaceoid))
456  tablespacename);
457 
458  /* Check for pg_shdepend entries depending on this tablespace */
459  if (checkSharedDependencies(TableSpaceRelationId, tablespaceoid,
460  &detail, &detail_log))
461  ereport(ERROR,
462  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
463  errmsg("tablespace \"%s\" cannot be dropped because some objects depend on it",
464  tablespacename),
465  errdetail_internal("%s", detail),
466  errdetail_log("%s", detail_log)));
467 
468  /* DROP hook for the tablespace being removed */
469  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
470 
471  /*
472  * Remove the pg_tablespace tuple (this will roll back if we fail below)
473  */
474  CatalogTupleDelete(rel, &tuple->t_self);
475 
476  table_endscan(scandesc);
477 
478  /*
479  * Remove any comments or security labels on this tablespace.
480  */
481  DeleteSharedComments(tablespaceoid, TableSpaceRelationId);
482  DeleteSharedSecurityLabel(tablespaceoid, TableSpaceRelationId);
483 
484  /*
485  * Remove dependency on owner.
486  */
487  deleteSharedDependencyRecordsFor(TableSpaceRelationId, tablespaceoid, 0);
488 
489  /*
490  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
491  * is running concurrently.
492  */
493  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
494 
495  /*
496  * Try to remove the physical infrastructure.
497  */
498  if (!destroy_tablespace_directories(tablespaceoid, false))
499  {
500  /*
501  * Not all files deleted? However, there can be lingering empty files
502  * in the directories, left behind by for example DROP TABLE, that
503  * have been scheduled for deletion at next checkpoint (see comments
504  * in mdunlink() for details). We could just delete them immediately,
505  * but we can't tell them apart from important data files that we
506  * mustn't delete. So instead, we force a checkpoint which will clean
507  * out any lingering files, and try again.
508  */
510 
511  /*
512  * On Windows, an unlinked file persists in the directory listing
513  * until no process retains an open handle for the file. The DDL
514  * commands that schedule files for unlink send invalidation messages
515  * directing other PostgreSQL processes to close the files, but
516  * nothing guarantees they'll be processed in time. So, we'll also
517  * use a global barrier to ask all backends to close all files, and
518  * wait until they're finished.
519  */
520  LWLockRelease(TablespaceCreateLock);
522  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
523 
524  /* And now try again. */
525  if (!destroy_tablespace_directories(tablespaceoid, false))
526  {
527  /* Still not empty, the files must be important then */
528  ereport(ERROR,
529  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
530  errmsg("tablespace \"%s\" is not empty",
531  tablespacename)));
532  }
533  }
534 
535  /* Record the filesystem change in XLOG */
536  {
537  xl_tblspc_drop_rec xlrec;
538 
539  xlrec.ts_id = tablespaceoid;
540 
541  XLogBeginInsert();
542  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
543 
544  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
545  }
546 
547  /*
548  * Note: because we checked that the tablespace was empty, there should be
549  * no need to worry about flushing shared buffers or free space map
550  * entries for relations in the tablespace.
551  */
552 
553  /*
554  * Force synchronous commit, to minimize the window between removing the
555  * files on-disk and marking the transaction committed. It's not great
556  * that there is any window at all, but definitely we don't want to make
557  * it larger than necessary.
558  */
559  ForceSyncCommit();
560 
561  /*
562  * Allow TablespaceCreateDbspace again.
563  */
564  LWLockRelease(TablespaceCreateLock);
565 
566  /* We keep the lock on pg_tablespace until commit */
567  table_close(rel, NoLock);
568 }
@ ACLCHECK_NO_PRIV
Definition: acl.h:183
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:692
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:315
void RequestCheckpoint(int flags)
Definition: checkpointer.c:921
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
int errdetail_log(const char *fmt,...)
Definition: elog.c:1250
#define NOTICE
Definition: elog.h:35
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_EXCLUSIVE
Definition: lwlock.h:116
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
bool checkSharedDependencies(Oid classId, Oid objectId, char **detail_msg, char **detail_log_msg)
Definition: pg_shdepend.c:631
void WaitForProcSignalBarrier(uint64 generation)
Definition: procsignal.c:393
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition: procsignal.c:333
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition: procsignal.h:56
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:491
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:26
#define CHECKPOINT_FORCE
Definition: xlog.h:140
#define CHECKPOINT_WAIT
Definition: xlog.h:143
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:139

References aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleDelete(), CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, checkSharedDependencies(), CStringGetDatum(), DeleteSharedComments(), deleteSharedDependencyRecordsFor(), DeleteSharedSecurityLabel(), destroy_tablespace_directories(), EmitProcSignalBarrier(), ereport, errcode(), errdetail_internal(), errdetail_log(), errmsg(), ERROR, ForceSyncCommit(), ForwardScanDirection, GETSTRUCT, GetUserId(), heap_getnext(), HeapTupleIsValid, InvokeObjectDropHook, IsPinnedObject(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), NoLock, NOTICE, object_ownercheck(), OBJECT_TABLESPACE, PROCSIGNAL_BARRIER_SMGRRELEASE, RequestCheckpoint(), RowExclusiveLock, ScanKeyInit(), stmt, HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), xl_tblspc_drop_rec::ts_id, WaitForProcSignalBarrier(), XLOG_TBLSPC_DROP, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

Definition at line 1478 of file tablespace.c.

1479 {
1480  char *result;
1481  Relation rel;
1482  TableScanDesc scandesc;
1483  HeapTuple tuple;
1484  ScanKeyData entry[1];
1485 
1486  /*
1487  * Search pg_tablespace. We use a heapscan here even though there is an
1488  * index on oid, on the theory that pg_tablespace will usually have just a
1489  * few entries and so an indexed lookup is a waste of effort.
1490  */
1491  rel = table_open(TableSpaceRelationId, AccessShareLock);
1492 
1493  ScanKeyInit(&entry[0],
1494  Anum_pg_tablespace_oid,
1495  BTEqualStrategyNumber, F_OIDEQ,
1496  ObjectIdGetDatum(spc_oid));
1497  scandesc = table_beginscan_catalog(rel, 1, entry);
1498  tuple = heap_getnext(scandesc, ForwardScanDirection);
1499 
1500  /* We assume that there can be at most one matching tuple */
1501  if (HeapTupleIsValid(tuple))
1502  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1503  else
1504  result = NULL;
1505 
1506  table_endscan(scandesc);
1508 
1509  return result;
1510 }
#define NameStr(name)
Definition: c.h:735
#define AccessShareLock
Definition: lockdefs.h:36

References AccessShareLock, BTEqualStrategyNumber, ForwardScanDirection, GETSTRUCT, heap_getnext(), HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by AlterTableMoveAll(), calculate_tablespace_size(), DefineIndex(), DefineRelation(), ExecReindex(), generateClonedIndexStmt(), getObjectDescription(), getObjectIdentityParts(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), ReindexMultipleInternal(), ReindexRelationConcurrently(), and shdepLockAndCheckObject().

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char *  tablespacename,
bool  missing_ok 
)

Definition at line 1432 of file tablespace.c.

1433 {
1434  Oid result;
1435  Relation rel;
1436  TableScanDesc scandesc;
1437  HeapTuple tuple;
1438  ScanKeyData entry[1];
1439 
1440  /*
1441  * Search pg_tablespace. We use a heapscan here even though there is an
1442  * index on name, on the theory that pg_tablespace will usually have just
1443  * a few entries and so an indexed lookup is a waste of effort.
1444  */
1445  rel = table_open(TableSpaceRelationId, AccessShareLock);
1446 
1447  ScanKeyInit(&entry[0],
1448  Anum_pg_tablespace_spcname,
1449  BTEqualStrategyNumber, F_NAMEEQ,
1450  CStringGetDatum(tablespacename));
1451  scandesc = table_beginscan_catalog(rel, 1, entry);
1452  tuple = heap_getnext(scandesc, ForwardScanDirection);
1453 
1454  /* We assume that there can be at most one matching tuple */
1455  if (HeapTupleIsValid(tuple))
1456  result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1457  else
1458  result = InvalidOid;
1459 
1460  table_endscan(scandesc);
1462 
1463  if (!OidIsValid(result) && !missing_ok)
1464  ereport(ERROR,
1465  (errcode(ERRCODE_UNDEFINED_OBJECT),
1466  errmsg("tablespace \"%s\" does not exist",
1467  tablespacename)));
1468 
1469  return result;
1470 }

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, GETSTRUCT, heap_getnext(), HeapTupleIsValid, InvalidOid, OidIsValid, ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by AlterTableMoveAll(), ATPrepSetTableSpace(), check_default_tablespace(), check_temp_tablespaces(), convert_tablespace_name(), createdb(), CreateTableSpace(), DefineIndex(), DefineRelation(), ExecReindex(), get_object_address_unqualified(), GetDefaultTablespace(), movedb(), objectNamesToOids(), pg_tablespace_size_name(), and PrepareTempTablespaces().

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence,
bool  partitioned 
)

Definition at line 1149 of file tablespace.c.

1150 {
1151  Oid result;
1152 
1153  /* The temp-table case is handled elsewhere */
1154  if (relpersistence == RELPERSISTENCE_TEMP)
1155  {
1157  return GetNextTempTableSpace();
1158  }
1159 
1160  /* Fast path for default_tablespace == "" */
1161  if (default_tablespace == NULL || default_tablespace[0] == '\0')
1162  return InvalidOid;
1163 
1164  /*
1165  * It is tempting to cache this lookup for more speed, but then we would
1166  * fail to detect the case where the tablespace was dropped since the GUC
1167  * variable was set. Note also that we don't complain if the value fails
1168  * to refer to an existing tablespace; we just silently return InvalidOid,
1169  * causing the new object to be created in the database's tablespace.
1170  */
1171  result = get_tablespace_oid(default_tablespace, true);
1172 
1173  /*
1174  * Allow explicit specification of database's default tablespace in
1175  * default_tablespace without triggering permissions checks. Don't allow
1176  * specifying that when creating a partitioned table, however, since the
1177  * result is confusing.
1178  */
1179  if (result == MyDatabaseTableSpace)
1180  {
1181  if (partitioned)
1182  ereport(ERROR,
1183  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1184  errmsg("cannot specify default tablespace for partitioned relations")));
1185  result = InvalidOid;
1186  }
1187  return result;
1188 }
void PrepareTempTablespaces(void)
Definition: tablespace.c:1337
char * default_tablespace
Definition: tablespace.c:89
Oid GetNextTempTableSpace(void)
Definition: fd.c:3081
Oid MyDatabaseTableSpace
Definition: globals.c:91

References default_tablespace, ereport, errcode(), errmsg(), ERROR, get_tablespace_oid(), GetNextTempTableSpace(), InvalidOid, MyDatabaseTableSpace, and PrepareTempTablespaces().

Referenced by DefineIndex(), DefineRelation(), and ExecRefreshMatView().

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1337 of file tablespace.c.

1338 {
1339  char *rawname;
1340  List *namelist;
1341  Oid *tblSpcs;
1342  int numSpcs;
1343  ListCell *l;
1344 
1345  /* No work if already done in current transaction */
1346  if (TempTablespacesAreSet())
1347  return;
1348 
1349  /*
1350  * Can't do catalog access unless within a transaction. This is just a
1351  * safety check in case this function is called by low-level code that
1352  * could conceivably execute outside a transaction. Note that in such a
1353  * scenario, fd.c will fall back to using the current database's default
1354  * tablespace, which should always be OK.
1355  */
1356  if (!IsTransactionState())
1357  return;
1358 
1359  /* Need a modifiable copy of string */
1360  rawname = pstrdup(temp_tablespaces);
1361 
1362  /* Parse string into list of identifiers */
1363  if (!SplitIdentifierString(rawname, ',', &namelist))
1364  {
1365  /* syntax error in name list */
1366  SetTempTablespaces(NULL, 0);
1367  pfree(rawname);
1368  list_free(namelist);
1369  return;
1370  }
1371 
1372  /* Store tablespace OIDs in an array in TopTransactionContext */
1374  list_length(namelist) * sizeof(Oid));
1375  numSpcs = 0;
1376  foreach(l, namelist)
1377  {
1378  char *curname = (char *) lfirst(l);
1379  Oid curoid;
1380  AclResult aclresult;
1381 
1382  /* Allow an empty string (signifying database default) */
1383  if (curname[0] == '\0')
1384  {
1385  /* InvalidOid signifies database's default tablespace */
1386  tblSpcs[numSpcs++] = InvalidOid;
1387  continue;
1388  }
1389 
1390  /* Else verify that name is a valid tablespace name */
1391  curoid = get_tablespace_oid(curname, true);
1392  if (curoid == InvalidOid)
1393  {
1394  /* Skip any bad list elements */
1395  continue;
1396  }
1397 
1398  /*
1399  * Allow explicit specification of database's default tablespace in
1400  * temp_tablespaces without triggering permissions checks.
1401  */
1402  if (curoid == MyDatabaseTableSpace)
1403  {
1404  /* InvalidOid signifies database's default tablespace */
1405  tblSpcs[numSpcs++] = InvalidOid;
1406  continue;
1407  }
1408 
1409  /* Check permissions similarly */
1410  aclresult = object_aclcheck(TableSpaceRelationId, curoid, GetUserId(),
1411  ACL_CREATE);
1412  if (aclresult != ACLCHECK_OK)
1413  continue;
1414 
1415  tblSpcs[numSpcs++] = curoid;
1416  }
1417 
1418  SetTempTablespaces(tblSpcs, numSpcs);
1419 
1420  pfree(rawname);
1421  list_free(namelist);
1422 }
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3843
char * temp_tablespaces
Definition: tablespace.c:90
bool TempTablespacesAreSet(void)
Definition: fd.c:3048
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:3019
void list_free(List *list)
Definition: list.c:1545
MemoryContext TopTransactionContext
Definition: mcxt.c:146
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021
#define ACL_CREATE
Definition: parsenodes.h:85
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
Definition: pg_list.h:54
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3456
bool IsTransactionState(void)
Definition: xact.c:378

References ACL_CREATE, ACLCHECK_OK, get_tablespace_oid(), GetUserId(), InvalidOid, IsTransactionState(), lfirst, list_free(), list_length(), MemoryContextAlloc(), MyDatabaseTableSpace, object_aclcheck(), pfree(), pstrdup(), SetTempTablespaces(), SplitIdentifierString(), temp_tablespaces, TempTablespacesAreSet(), and TopTransactionContext.

Referenced by BufFileCreateTemp(), ExecHashIncreaseNumBatches(), ExecHashTableCreate(), FileSetInit(), GetDefaultTablespace(), inittapestate(), and tuplestore_puttuple_common().

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

Definition at line 889 of file tablespace.c.

890 {
891  struct stat st;
892 
893  if (lstat(linkloc, &st) < 0)
894  {
895  if (errno == ENOENT)
896  return;
897  ereport(ERROR,
899  errmsg("could not stat file \"%s\": %m", linkloc)));
900  }
901 
902  if (S_ISDIR(st.st_mode))
903  {
904  /*
905  * This will fail if the directory isn't empty, but not if it's a
906  * junction point.
907  */
908  if (rmdir(linkloc) < 0 && errno != ENOENT)
909  ereport(ERROR,
911  errmsg("could not remove directory \"%s\": %m",
912  linkloc)));
913  }
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  else
923  {
924  /* Refuse to remove anything that's not a directory or symlink */
925  ereport(ERROR,
926  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
927  errmsg("\"%s\" is not a directory or symbolic link",
928  linkloc)));
929  }
930 }
int errcode_for_file_access(void)
Definition: elog.c:881
#define lstat(path, sb)
Definition: win32_port.h:285
#define S_ISDIR(m)
Definition: win32_port.h:325
#define S_ISLNK(m)
Definition: win32_port.h:344

References ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, lstat, S_ISDIR, S_ISLNK, and stat::st_mode.

Referenced by create_tablespace_directories(), and InitWalRecovery().

◆ RenameTableSpace()

ObjectAddress RenameTableSpace ( const char *  oldname,
const char *  newname 
)

Definition at line 936 of file tablespace.c.

937 {
938  Oid tspId;
939  Relation rel;
940  ScanKeyData entry[1];
941  TableScanDesc scan;
942  HeapTuple tup;
943  HeapTuple newtuple;
944  Form_pg_tablespace newform;
945  ObjectAddress address;
946 
947  /* Search pg_tablespace */
948  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
949 
950  ScanKeyInit(&entry[0],
951  Anum_pg_tablespace_spcname,
952  BTEqualStrategyNumber, F_NAMEEQ,
953  CStringGetDatum(oldname));
954  scan = table_beginscan_catalog(rel, 1, entry);
955  tup = heap_getnext(scan, ForwardScanDirection);
956  if (!HeapTupleIsValid(tup))
957  ereport(ERROR,
958  (errcode(ERRCODE_UNDEFINED_OBJECT),
959  errmsg("tablespace \"%s\" does not exist",
960  oldname)));
961 
962  newtuple = heap_copytuple(tup);
963  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
964  tspId = newform->oid;
965 
966  table_endscan(scan);
967 
968  /* Must be owner */
969  if (!object_ownercheck(TableSpaceRelationId, tspId, GetUserId()))
971 
972  /* Validate new name */
973  if (!allowSystemTableMods && IsReservedName(newname))
974  ereport(ERROR,
975  (errcode(ERRCODE_RESERVED_NAME),
976  errmsg("unacceptable tablespace name \"%s\"", newname),
977  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
978 
979  /*
980  * If built with appropriate switch, whine when regression-testing
981  * conventions for tablespace names are violated.
982  */
983 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
984  if (strncmp(newname, "regress_", 8) != 0)
985  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
986 #endif
987 
988  /* Make sure the new name doesn't exist */
989  ScanKeyInit(&entry[0],
990  Anum_pg_tablespace_spcname,
991  BTEqualStrategyNumber, F_NAMEEQ,
992  CStringGetDatum(newname));
993  scan = table_beginscan_catalog(rel, 1, entry);
994  tup = heap_getnext(scan, ForwardScanDirection);
995  if (HeapTupleIsValid(tup))
996  ereport(ERROR,
998  errmsg("tablespace \"%s\" already exists",
999  newname)));
1000 
1001  table_endscan(scan);
1002 
1003  /* OK, update the entry */
1004  namestrcpy(&(newform->spcname), newname);
1005 
1006  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1007 
1008  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
1009 
1010  ObjectAddressSet(address, TableSpaceRelationId, tspId);
1011 
1012  table_close(rel, NoLock);
1013 
1014  return address;
1015 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:777
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40

References aclcheck_error(), ACLCHECK_NO_PRIV, allowSystemTableMods, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), elog(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errmsg(), ERROR, ForwardScanDirection, GETSTRUCT, GetUserId(), heap_copytuple(), heap_getnext(), HeapTupleIsValid, InvokeObjectPostAlterHook, IsReservedName(), namestrcpy(), NoLock, object_ownercheck(), OBJECT_TABLESPACE, ObjectAddressSet, RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by ExecRenameStmt().

◆ TablespaceCreateDbspace()

void TablespaceCreateDbspace ( Oid  spcOid,
Oid  dbOid,
bool  isRedo 
)

Definition at line 118 of file tablespace.c.

119 {
120  struct stat st;
121  char *dir;
122 
123  /*
124  * The global tablespace doesn't have per-database subdirectories, so
125  * nothing to do for it.
126  */
127  if (spcOid == GLOBALTABLESPACE_OID)
128  return;
129 
130  Assert(OidIsValid(spcOid));
131  Assert(OidIsValid(dbOid));
132 
133  dir = GetDatabasePath(dbOid, spcOid);
134 
135  if (stat(dir, &st) < 0)
136  {
137  /* Directory does not exist? */
138  if (errno == ENOENT)
139  {
140  /*
141  * Acquire TablespaceCreateLock to ensure that no DROP TABLESPACE
142  * or TablespaceCreateDbspace is running concurrently.
143  */
144  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
145 
146  /*
147  * Recheck to see if someone created the directory while we were
148  * waiting for lock.
149  */
150  if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode))
151  {
152  /* Directory was created */
153  }
154  else
155  {
156  /* Directory creation failed? */
157  if (MakePGDirectory(dir) < 0)
158  {
159  /* Failure other than not exists or not in WAL replay? */
160  if (errno != ENOENT || !isRedo)
161  ereport(ERROR,
163  errmsg("could not create directory \"%s\": %m",
164  dir)));
165 
166  /*
167  * During WAL replay, it's conceivable that several levels
168  * of directories are missing if tablespaces are dropped
169  * further ahead of the WAL stream than we're currently
170  * replaying. An easy way forward is to create them as
171  * plain directories and hope they are removed by further
172  * WAL replay if necessary. If this also fails, there is
173  * trouble we cannot get out of, so just report that and
174  * bail out.
175  */
176  if (pg_mkdir_p(dir, pg_dir_create_mode) < 0)
177  ereport(ERROR,
179  errmsg("could not create directory \"%s\": %m",
180  dir)));
181  }
182  }
183 
184  LWLockRelease(TablespaceCreateLock);
185  }
186  else
187  {
188  ereport(ERROR,
190  errmsg("could not stat directory \"%s\": %m", dir)));
191  }
192  }
193  else
194  {
195  /* Is it not a directory? */
196  if (!S_ISDIR(st.st_mode))
197  ereport(ERROR,
198  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
199  errmsg("\"%s\" exists but is not a directory",
200  dir)));
201  }
202 
203  pfree(dir);
204 }
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3883
int pg_dir_create_mode
Definition: file_perm.c:18
Assert(fmt[strlen(fmt) - 1] !='\n')
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition: relpath.c:110
#define stat
Definition: win32_port.h:284

References Assert(), ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, GetDatabasePath(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MakePGDirectory(), OidIsValid, pfree(), pg_dir_create_mode, pg_mkdir_p(), S_ISDIR, stat::st_mode, and stat.

Referenced by mdcreate().

◆ tblspc_desc()

void tblspc_desc ( StringInfo  buf,
XLogReaderState record 
)

Definition at line 21 of file tblspcdesc.c.

22 {
23  char *rec = XLogRecGetData(record);
24  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
25 
26  if (info == XLOG_TBLSPC_CREATE)
27  {
29 
30  appendStringInfo(buf, "%u \"%s\"", xlrec->ts_id, xlrec->ts_path);
31  }
32  else if (info == XLOG_TBLSPC_DROP)
33  {
34  xl_tblspc_drop_rec *xlrec = (xl_tblspc_drop_rec *) rec;
35 
36  appendStringInfo(buf, "%u", xlrec->ts_id);
37  }
38 }
unsigned char uint8
Definition: c.h:493
static char * buf
Definition: pg_test_fsync.c:73
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:31
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

References appendStringInfo(), buf, xl_tblspc_create_rec::ts_id, xl_tblspc_drop_rec::ts_id, xl_tblspc_create_rec::ts_path, XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, XLogRecGetData, XLogRecGetInfo, and XLR_INFO_MASK.

◆ tblspc_identify()

const char* tblspc_identify ( uint8  info)

Definition at line 41 of file tblspcdesc.c.

42 {
43  const char *id = NULL;
44 
45  switch (info & ~XLR_INFO_MASK)
46  {
47  case XLOG_TBLSPC_CREATE:
48  id = "CREATE";
49  break;
50  case XLOG_TBLSPC_DROP:
51  id = "DROP";
52  break;
53  }
54 
55  return id;
56 }

References XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, and XLR_INFO_MASK.

◆ tblspc_redo()

void tblspc_redo ( XLogReaderState record)

Definition at line 1517 of file tablespace.c.

1518 {
1519  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1520 
1521  /* Backup blocks are not used in tblspc records */
1522  Assert(!XLogRecHasAnyBlockRefs(record));
1523 
1524  if (info == XLOG_TBLSPC_CREATE)
1525  {
1527  char *location = xlrec->ts_path;
1528 
1529  create_tablespace_directories(location, xlrec->ts_id);
1530  }
1531  else if (info == XLOG_TBLSPC_DROP)
1532  {
1534 
1535  /* Close all smgr fds in all backends. */
1537 
1538  /*
1539  * If we issued a WAL record for a drop tablespace it implies that
1540  * there were no files in it at all when the DROP was done. That means
1541  * that no permanent objects can exist in it at this point.
1542  *
1543  * It is possible for standby users to be using this tablespace as a
1544  * location for their temporary files, so if we fail to remove all
1545  * files then do conflict processing and try again, if currently
1546  * enabled.
1547  *
1548  * Other possible reasons for failure include bollixed file
1549  * permissions on a standby server when they were okay on the primary,
1550  * etc etc. There's not much we can do about that, so just remove what
1551  * we can and press on.
1552  */
1553  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1554  {
1556 
1557  /*
1558  * If we did recovery processing then hopefully the backends who
1559  * wrote temp files should have cleaned up and exited by now. So
1560  * retry before complaining. If we fail again, this is just a LOG
1561  * condition, because it's not worth throwing an ERROR for (as
1562  * that would crash the database and require manual intervention
1563  * before we could get past this WAL record on restart).
1564  */
1565  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1566  ereport(LOG,
1567  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1568  errmsg("directories for tablespace %u could not be removed",
1569  xlrec->ts_id),
1570  errhint("You can remove the directories manually if necessary.")));
1571  }
1572  }
1573  else
1574  elog(PANIC, "tblspc_redo: unknown op code %u", info);
1575 }
#define LOG
Definition: elog.h:31
#define PANIC
Definition: elog.h:42
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition: standby.c:539
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:417

References Assert(), create_tablespace_directories(), destroy_tablespace_directories(), elog(), EmitProcSignalBarrier(), ereport, errcode(), errhint(), errmsg(), LOG, PANIC, PROCSIGNAL_BARRIER_SMGRRELEASE, ResolveRecoveryConflictWithTablespace(), xl_tblspc_create_rec::ts_id, xl_tblspc_drop_rec::ts_id, xl_tblspc_create_rec::ts_path, WaitForProcSignalBarrier(), XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, XLogRecGetData, XLogRecGetInfo, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

Variable Documentation

◆ allow_in_place_tablespaces

PGDLLIMPORT bool allow_in_place_tablespaces
extern

Definition at line 91 of file tablespace.c.

Referenced by CheckTablespaceDirectory(), CreateTableSpace(), and recovery_create_dbdir().