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 spcNode, Oid dbNode, 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 *rptr)
 
void tblspc_desc (StringInfo buf, XLogReaderState *rptr)
 
const char * tblspc_identify (uint8 info)
 

Macro Definition Documentation

◆ XLOG_TBLSPC_CREATE

#define XLOG_TBLSPC_CREATE   0x00

Definition at line 23 of file tablespace.h.

Referenced by CreateTableSpace(), tblspc_desc(), tblspc_identify(), and tblspc_redo().

◆ XLOG_TBLSPC_DROP

#define XLOG_TBLSPC_DROP   0x10

Definition at line 24 of file tablespace.h.

Referenced by DropTableSpace(), tblspc_desc(), tblspc_identify(), and tblspc_redo().

Typedef Documentation

◆ TableSpaceOpts

◆ xl_tblspc_create_rec

◆ xl_tblspc_drop_rec

Function Documentation

◆ AlterTableSpaceOptions()

Oid AlterTableSpaceOptions ( AlterTableSpaceOptionsStmt stmt)

Definition at line 1011 of file tablespace.c.

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, AlterTableSpaceOptionsStmt::isReset, NoLock, OBJECT_TABLESPACE, AlterTableSpaceOptionsStmt::options, pg_tablespace_ownercheck(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), tablespace_reloptions(), AlterTableSpaceOptionsStmt::tablespacename, and transformRelOptions().

Referenced by standard_ProcessUtility().

1012 {
1013  Relation rel;
1014  ScanKeyData entry[1];
1015  TableScanDesc scandesc;
1016  HeapTuple tup;
1017  Oid tablespaceoid;
1018  Datum datum;
1019  Datum newOptions;
1020  Datum repl_val[Natts_pg_tablespace];
1021  bool isnull;
1022  bool repl_null[Natts_pg_tablespace];
1023  bool repl_repl[Natts_pg_tablespace];
1024  HeapTuple newtuple;
1025 
1026  /* Search pg_tablespace */
1027  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1028 
1029  ScanKeyInit(&entry[0],
1030  Anum_pg_tablespace_spcname,
1031  BTEqualStrategyNumber, F_NAMEEQ,
1033  scandesc = table_beginscan_catalog(rel, 1, entry);
1034  tup = heap_getnext(scandesc, ForwardScanDirection);
1035  if (!HeapTupleIsValid(tup))
1036  ereport(ERROR,
1037  (errcode(ERRCODE_UNDEFINED_OBJECT),
1038  errmsg("tablespace \"%s\" does not exist",
1039  stmt->tablespacename)));
1040 
1041  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1042 
1043  /* Must be owner of the existing object */
1044  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
1046  stmt->tablespacename);
1047 
1048  /* Generate new proposed spcoptions (text array) */
1049  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1050  RelationGetDescr(rel), &isnull);
1051  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1052  stmt->options, NULL, NULL, false,
1053  stmt->isReset);
1054  (void) tablespace_reloptions(newOptions, true);
1055 
1056  /* Build new tuple. */
1057  memset(repl_null, false, sizeof(repl_null));
1058  memset(repl_repl, false, sizeof(repl_repl));
1059  if (newOptions != (Datum) 0)
1060  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1061  else
1062  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1063  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1064  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1065  repl_null, repl_repl);
1066 
1067  /* Update system catalog. */
1068  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1069 
1070  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1071 
1072  heap_freetuple(newtuple);
1073 
1074  /* Conclude heap scan. */
1075  table_endscan(scandesc);
1076  table_close(rel, NoLock);
1077 
1078  return tablespaceoid;
1079 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:784
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define RelationGetDescr(relation)
Definition: rel.h:442
Oid GetUserId(void)
Definition: miscinit.c:380
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1554
int errcode(int sqlerrcode)
Definition: elog.c:570
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4957
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
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
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ CreateTableSpace()

Oid CreateTableSpace ( CreateTableSpaceStmt stmt)

Definition at line 234 of file tablespace.c.

References allowSystemTableMods, 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, IsReservedName(), CreateTableSpaceStmt::location, MAXPGPATH, MemSet, namein(), NoLock, ObjectIdGetDatum, offsetof, OIDCHARS, OidIsValid, CreateTableSpaceStmt::options, CreateTableSpaceStmt::owner, path_is_prefix_of_path(), pfree(), pstrdup(), RelationData::rd_att, recordDependencyOnOwner(), RowExclusiveLock, superuser(), table_close(), table_open(), tablespace_reloptions(), TABLESPACE_VERSION_DIRECTORY, CreateTableSpaceStmt::tablespacename, TablespaceOidIndexId, transformRelOptions(), xl_tblspc_create_rec::ts_id, values, WARNING, XLOG_TBLSPC_CREATE, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

235 {
236 #ifdef HAVE_SYMLINK
237  Relation rel;
238  Datum values[Natts_pg_tablespace];
239  bool nulls[Natts_pg_tablespace];
240  HeapTuple tuple;
241  Oid tablespaceoid;
242  char *location;
243  Oid ownerId;
244  Datum newOptions;
245 
246  /* Must be super user */
247  if (!superuser())
248  ereport(ERROR,
249  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
250  errmsg("permission denied to create tablespace \"%s\"",
251  stmt->tablespacename),
252  errhint("Must be superuser to create a tablespace.")));
253 
254  /* However, the eventual owner of the tablespace need not be */
255  if (stmt->owner)
256  ownerId = get_rolespec_oid(stmt->owner, false);
257  else
258  ownerId = GetUserId();
259 
260  /* Unix-ify the offered path, and strip any trailing slashes */
261  location = pstrdup(stmt->location);
262  canonicalize_path(location);
263 
264  /* disallow quotes, else CREATE DATABASE would be at risk */
265  if (strchr(location, '\''))
266  ereport(ERROR,
267  (errcode(ERRCODE_INVALID_NAME),
268  errmsg("tablespace location cannot contain single quotes")));
269 
270  /*
271  * Allowing relative paths seems risky
272  *
273  * this also helps us ensure that location is not empty or whitespace
274  */
275  if (!is_absolute_path(location))
276  ereport(ERROR,
277  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
278  errmsg("tablespace location must be an absolute path")));
279 
280  /*
281  * Check that location isn't too long. Remember that we're going to append
282  * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
283  * reference the whole path here, but MakePGDirectory() uses the first two
284  * parts.
285  */
286  if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
287  OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1 + OIDCHARS > MAXPGPATH)
288  ereport(ERROR,
289  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
290  errmsg("tablespace location \"%s\" is too long",
291  location)));
292 
293  /* Warn if the tablespace is in the data directory. */
294  if (path_is_prefix_of_path(DataDir, location))
296  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
297  errmsg("tablespace location should not be inside the data directory")));
298 
299  /*
300  * Disallow creation of tablespaces named "pg_xxx"; we reserve this
301  * namespace for system purposes.
302  */
304  ereport(ERROR,
305  (errcode(ERRCODE_RESERVED_NAME),
306  errmsg("unacceptable tablespace name \"%s\"",
307  stmt->tablespacename),
308  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
309 
310  /*
311  * If built with appropriate switch, whine when regression-testing
312  * conventions for tablespace names are violated.
313  */
314 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
315  if (strncmp(stmt->tablespacename, "regress_", 8) != 0)
316  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
317 #endif
318 
319  /*
320  * Check that there is no other tablespace by this name. (The unique
321  * index would catch this anyway, but might as well give a friendlier
322  * message.)
323  */
324  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
325  ereport(ERROR,
327  errmsg("tablespace \"%s\" already exists",
328  stmt->tablespacename)));
329 
330  /*
331  * Insert tuple into pg_tablespace. The purpose of doing this first is to
332  * lock the proposed tablename against other would-be creators. The
333  * insertion will roll back if we find problems below.
334  */
335  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
336 
337  MemSet(nulls, false, sizeof(nulls));
338 
339  tablespaceoid = GetNewOidWithIndex(rel, TablespaceOidIndexId,
340  Anum_pg_tablespace_oid);
341  values[Anum_pg_tablespace_oid - 1] = ObjectIdGetDatum(tablespaceoid);
342  values[Anum_pg_tablespace_spcname - 1] =
344  values[Anum_pg_tablespace_spcowner - 1] =
345  ObjectIdGetDatum(ownerId);
346  nulls[Anum_pg_tablespace_spcacl - 1] = true;
347 
348  /* Generate new proposed spcoptions (text array) */
349  newOptions = transformRelOptions((Datum) 0,
350  stmt->options,
351  NULL, NULL, false, false);
352  (void) tablespace_reloptions(newOptions, true);
353  if (newOptions != (Datum) 0)
354  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
355  else
356  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
357 
358  tuple = heap_form_tuple(rel->rd_att, values, nulls);
359 
360  CatalogTupleInsert(rel, tuple);
361 
362  heap_freetuple(tuple);
363 
364  /* Record dependency on owner */
365  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
366 
367  /* Post creation hook for new tablespace */
368  InvokeObjectPostCreateHook(TableSpaceRelationId, tablespaceoid, 0);
369 
370  create_tablespace_directories(location, tablespaceoid);
371 
372  /* Record the filesystem change in XLOG */
373  {
374  xl_tblspc_create_rec xlrec;
375 
376  xlrec.ts_id = tablespaceoid;
377 
378  XLogBeginInsert();
379  XLogRegisterData((char *) &xlrec,
380  offsetof(xl_tblspc_create_rec, ts_path));
381  XLogRegisterData((char *) location, strlen(location) + 1);
382 
383  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
384  }
385 
386  /*
387  * Force synchronous commit, to minimize the window between creating the
388  * symlink on-disk and marking the transaction committed. It's not great
389  * that there is any window at all, but definitely we don't want to make
390  * it larger than necessary.
391  */
392  ForceSyncCommit();
393 
394  pfree(location);
395 
396  /* We keep the lock on pg_tablespace until commit */
397  table_close(rel, NoLock);
398 
399  return tablespaceoid;
400 #else /* !HAVE_SYMLINK */
401  ereport(ERROR,
402  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
403  errmsg("tablespaces are not supported on this platform")));
404  return InvalidOid; /* keep compiler quiet */
405 #endif /* HAVE_SYMLINK */
406 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:323
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:974
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:784
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
Oid GetUserId(void)
Definition: miscinit.c:380
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
char * pstrdup(const char *in)
Definition: mcxt.c:1161
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1554
void ForceSyncCommit(void)
Definition: xact.c:1051
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:570
bool superuser(void)
Definition: superuser.c:47
#define MemSet(start, val, len)
Definition: c.h:955
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:617
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:214
#define OidIsValid(objectId)
Definition: c.h:638
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
#define TablespaceOidIndexId
Definition: indexing.h:244
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define is_absolute_path(filename)
Definition: port.h:86
#define CStringGetDatum(X)
Definition: postgres.h:578
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:579
uintptr_t Datum
Definition: postgres.h:367
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5225
TupleDesc rd_att
Definition: rel.h:84
bool allowSystemTableMods
Definition: globals.c:120
#define InvalidOid
Definition: postgres_ext.h:36
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define FORKNAMECHARS
Definition: relpath.h:57
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
char * DataDir
Definition: globals.c:62
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33
#define OIDCHARS
Definition: relpath.h:30
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:183
#define offsetof(type, field)
Definition: c.h:655

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 847 of file tablespace.c.

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

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

848 {
849  DIR *dirdesc;
850  struct dirent *de;
851 
852  dirdesc = AllocateDir(path);
853 
854  while ((de = ReadDir(dirdesc, path)) != NULL)
855  {
856  if (strcmp(de->d_name, ".") == 0 ||
857  strcmp(de->d_name, "..") == 0)
858  continue;
859  FreeDir(dirdesc);
860  return false;
861  }
862 
863  FreeDir(dirdesc);
864  return true;
865 }
Definition: dirent.h:9
Definition: dirent.c:25
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2466
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2532
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2584

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

Definition at line 414 of file tablespace.c.

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

Referenced by standard_ProcessUtility().

415 {
416 #ifdef HAVE_SYMLINK
417  char *tablespacename = stmt->tablespacename;
418  TableScanDesc scandesc;
419  Relation rel;
420  HeapTuple tuple;
421  Form_pg_tablespace spcform;
422  ScanKeyData entry[1];
423  Oid tablespaceoid;
424 
425  /*
426  * Find the target tuple
427  */
428  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
429 
430  ScanKeyInit(&entry[0],
431  Anum_pg_tablespace_spcname,
432  BTEqualStrategyNumber, F_NAMEEQ,
433  CStringGetDatum(tablespacename));
434  scandesc = table_beginscan_catalog(rel, 1, entry);
435  tuple = heap_getnext(scandesc, ForwardScanDirection);
436 
437  if (!HeapTupleIsValid(tuple))
438  {
439  if (!stmt->missing_ok)
440  {
441  ereport(ERROR,
442  (errcode(ERRCODE_UNDEFINED_OBJECT),
443  errmsg("tablespace \"%s\" does not exist",
444  tablespacename)));
445  }
446  else
447  {
448  ereport(NOTICE,
449  (errmsg("tablespace \"%s\" does not exist, skipping",
450  tablespacename)));
451  /* XXX I assume I need one or both of these next two calls */
452  table_endscan(scandesc);
453  table_close(rel, NoLock);
454  }
455  return;
456  }
457 
458  spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
459  tablespaceoid = spcform->oid;
460 
461  /* Must be tablespace owner */
462  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
464  tablespacename);
465 
466  /* Disallow drop of the standard tablespaces, even by superuser */
467  if (tablespaceoid == GLOBALTABLESPACE_OID ||
468  tablespaceoid == DEFAULTTABLESPACE_OID)
470  tablespacename);
471 
472  /* DROP hook for the tablespace being removed */
473  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
474 
475  /*
476  * Remove the pg_tablespace tuple (this will roll back if we fail below)
477  */
478  CatalogTupleDelete(rel, &tuple->t_self);
479 
480  table_endscan(scandesc);
481 
482  /*
483  * Remove any comments or security labels on this tablespace.
484  */
485  DeleteSharedComments(tablespaceoid, TableSpaceRelationId);
486  DeleteSharedSecurityLabel(tablespaceoid, TableSpaceRelationId);
487 
488  /*
489  * Remove dependency on owner.
490  */
491  deleteSharedDependencyRecordsFor(TableSpaceRelationId, tablespaceoid, 0);
492 
493  /*
494  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
495  * is running concurrently.
496  */
497  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
498 
499  /*
500  * Try to remove the physical infrastructure.
501  */
502  if (!destroy_tablespace_directories(tablespaceoid, false))
503  {
504  /*
505  * Not all files deleted? However, there can be lingering empty files
506  * in the directories, left behind by for example DROP TABLE, that
507  * have been scheduled for deletion at next checkpoint (see comments
508  * in mdunlink() for details). We could just delete them immediately,
509  * but we can't tell them apart from important data files that we
510  * mustn't delete. So instead, we force a checkpoint which will clean
511  * out any lingering files, and try again.
512  *
513  * XXX On Windows, an unlinked file persists in the directory listing
514  * until no process retains an open handle for the file. The DDL
515  * commands that schedule files for unlink send invalidation messages
516  * directing other PostgreSQL processes to close the files. DROP
517  * TABLESPACE should not give up on the tablespace becoming empty
518  * until all relevant invalidation processing is complete.
519  */
521  if (!destroy_tablespace_directories(tablespaceoid, false))
522  {
523  /* Still not empty, the files must be important then */
524  ereport(ERROR,
525  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
526  errmsg("tablespace \"%s\" is not empty",
527  tablespacename)));
528  }
529  }
530 
531  /* Record the filesystem change in XLOG */
532  {
533  xl_tblspc_drop_rec xlrec;
534 
535  xlrec.ts_id = tablespaceoid;
536 
537  XLogBeginInsert();
538  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
539 
540  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
541  }
542 
543  /*
544  * Note: because we checked that the tablespace was empty, there should be
545  * no need to worry about flushing shared buffers or free space map
546  * entries for relations in the tablespace.
547  */
548 
549  /*
550  * Force synchronous commit, to minimize the window between removing the
551  * files on-disk and marking the transaction committed. It's not great
552  * that there is any window at all, but definitely we don't want to make
553  * it larger than necessary.
554  */
555  ForceSyncCommit();
556 
557  /*
558  * Allow TablespaceCreateDbspace again.
559  */
560  LWLockRelease(TablespaceCreateLock);
561 
562  /* We keep the lock on pg_tablespace until commit */
563  table_close(rel, NoLock);
564 #else /* !HAVE_SYMLINK */
565  ereport(ERROR,
566  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
567  errmsg("tablespaces are not supported on this platform")));
568 #endif /* HAVE_SYMLINK */
569 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:154
void ForceSyncCommit(void)
Definition: xact.c:1051
int errcode(int sqlerrcode)
Definition: elog.c:570
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
unsigned int Oid
Definition: postgres_ext.h:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4957
#define CHECKPOINT_FORCE
Definition: xlog.h:215
#define ereport(elevel, rest)
Definition: elog.h:141
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:908
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define NOTICE
Definition: elog.h:37
#define CHECKPOINT_WAIT
Definition: xlog.h:219
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:373
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:677
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:414
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:214
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void RequestCheckpoint(int flags)
Definition: checkpointer.c:952

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

Definition at line 1463 of file tablespace.c.

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(), generateClonedIndexStmt(), getObjectDescription(), getObjectIdentityParts(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), and shdepLockAndCheckObject().

1464 {
1465  char *result;
1466  Relation rel;
1467  TableScanDesc scandesc;
1468  HeapTuple tuple;
1469  ScanKeyData entry[1];
1470 
1471  /*
1472  * Search pg_tablespace. We use a heapscan here even though there is an
1473  * index on oid, on the theory that pg_tablespace will usually have just a
1474  * few entries and so an indexed lookup is a waste of effort.
1475  */
1476  rel = table_open(TableSpaceRelationId, AccessShareLock);
1477 
1478  ScanKeyInit(&entry[0],
1479  Anum_pg_tablespace_oid,
1480  BTEqualStrategyNumber, F_OIDEQ,
1481  ObjectIdGetDatum(spc_oid));
1482  scandesc = table_beginscan_catalog(rel, 1, entry);
1483  tuple = heap_getnext(scandesc, ForwardScanDirection);
1484 
1485  /* We assume that there can be at most one matching tuple */
1486  if (HeapTupleIsValid(tuple))
1487  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1488  else
1489  result = NULL;
1490 
1491  table_endscan(scandesc);
1493 
1494  return result;
1495 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define AccessShareLock
Definition: lockdefs.h:36
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
#define NameStr(name)
Definition: c.h:609
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char *  tablespacename,
bool  missing_ok 
)

Definition at line 1417 of file tablespace.c.

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(), get_object_address_unqualified(), GetDefaultTablespace(), movedb(), objectNamesToOids(), pg_tablespace_size_name(), and PrepareTempTablespaces().

1418 {
1419  Oid result;
1420  Relation rel;
1421  TableScanDesc scandesc;
1422  HeapTuple tuple;
1423  ScanKeyData entry[1];
1424 
1425  /*
1426  * Search pg_tablespace. We use a heapscan here even though there is an
1427  * index on name, on the theory that pg_tablespace will usually have just
1428  * a few entries and so an indexed lookup is a waste of effort.
1429  */
1430  rel = table_open(TableSpaceRelationId, AccessShareLock);
1431 
1432  ScanKeyInit(&entry[0],
1433  Anum_pg_tablespace_spcname,
1434  BTEqualStrategyNumber, F_NAMEEQ,
1435  CStringGetDatum(tablespacename));
1436  scandesc = table_beginscan_catalog(rel, 1, entry);
1437  tuple = heap_getnext(scandesc, ForwardScanDirection);
1438 
1439  /* We assume that there can be at most one matching tuple */
1440  if (HeapTupleIsValid(tuple))
1441  result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1442  else
1443  result = InvalidOid;
1444 
1445  table_endscan(scandesc);
1447 
1448  if (!OidIsValid(result) && !missing_ok)
1449  ereport(ERROR,
1450  (errcode(ERRCODE_UNDEFINED_OBJECT),
1451  errmsg("tablespace \"%s\" does not exist",
1452  tablespacename)));
1453 
1454  return result;
1455 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
#define ERROR
Definition: elog.h:43
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
int errmsg(const char *fmt,...)
Definition: elog.c:784
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence,
bool  partitioned 
)

Definition at line 1139 of file tablespace.c.

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

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

1140 {
1141  Oid result;
1142 
1143  /* The temp-table case is handled elsewhere */
1144  if (relpersistence == RELPERSISTENCE_TEMP)
1145  {
1147  return GetNextTempTableSpace();
1148  }
1149 
1150  /* Fast path for default_tablespace == "" */
1151  if (default_tablespace == NULL || default_tablespace[0] == '\0')
1152  return InvalidOid;
1153 
1154  /*
1155  * It is tempting to cache this lookup for more speed, but then we would
1156  * fail to detect the case where the tablespace was dropped since the GUC
1157  * variable was set. Note also that we don't complain if the value fails
1158  * to refer to an existing tablespace; we just silently return InvalidOid,
1159  * causing the new object to be created in the database's tablespace.
1160  */
1161  result = get_tablespace_oid(default_tablespace, true);
1162 
1163  /*
1164  * Allow explicit specification of database's default tablespace in
1165  * default_tablespace without triggering permissions checks. Don't allow
1166  * specifying that when creating a partitioned table, however, since the
1167  * result is confusing.
1168  */
1169  if (result == MyDatabaseTableSpace)
1170  {
1171  if (partitioned)
1172  ereport(ERROR,
1173  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1174  errmsg("cannot specify default tablespace for partitioned relations")));
1175  result = InvalidOid;
1176  }
1177  return result;
1178 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:87
#define ERROR
Definition: elog.h:43
void PrepareTempTablespaces(void)
Definition: tablespace.c:1324
char relpersistence
Definition: pg_class.h:78
Oid GetNextTempTableSpace(void)
Definition: fd.c:2727
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * default_tablespace
Definition: tablespace.c:89

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1324 of file tablespace.c.

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

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

1325 {
1326  char *rawname;
1327  List *namelist;
1328  Oid *tblSpcs;
1329  int numSpcs;
1330  ListCell *l;
1331 
1332  /* No work if already done in current transaction */
1333  if (TempTablespacesAreSet())
1334  return;
1335 
1336  /*
1337  * Can't do catalog access unless within a transaction. This is just a
1338  * safety check in case this function is called by low-level code that
1339  * could conceivably execute outside a transaction. Note that in such a
1340  * scenario, fd.c will fall back to using the current database's default
1341  * tablespace, which should always be OK.
1342  */
1343  if (!IsTransactionState())
1344  return;
1345 
1346  /* Need a modifiable copy of string */
1347  rawname = pstrdup(temp_tablespaces);
1348 
1349  /* Parse string into list of identifiers */
1350  if (!SplitIdentifierString(rawname, ',', &namelist))
1351  {
1352  /* syntax error in name list */
1353  SetTempTablespaces(NULL, 0);
1354  pfree(rawname);
1355  list_free(namelist);
1356  return;
1357  }
1358 
1359  /* Store tablespace OIDs in an array in TopTransactionContext */
1361  list_length(namelist) * sizeof(Oid));
1362  numSpcs = 0;
1363  foreach(l, namelist)
1364  {
1365  char *curname = (char *) lfirst(l);
1366  Oid curoid;
1367  AclResult aclresult;
1368 
1369  /* Allow an empty string (signifying database default) */
1370  if (curname[0] == '\0')
1371  {
1372  tblSpcs[numSpcs++] = InvalidOid;
1373  continue;
1374  }
1375 
1376  /* Else verify that name is a valid tablespace name */
1377  curoid = get_tablespace_oid(curname, true);
1378  if (curoid == InvalidOid)
1379  {
1380  /* Skip any bad list elements */
1381  continue;
1382  }
1383 
1384  /*
1385  * Allow explicit specification of database's default tablespace in
1386  * temp_tablespaces without triggering permissions checks.
1387  */
1388  if (curoid == MyDatabaseTableSpace)
1389  {
1390  tblSpcs[numSpcs++] = InvalidOid;
1391  continue;
1392  }
1393 
1394  /* Check permissions similarly */
1395  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1396  ACL_CREATE);
1397  if (aclresult != ACLCHECK_OK)
1398  continue;
1399 
1400  tblSpcs[numSpcs++] = curoid;
1401  }
1402 
1403  SetTempTablespaces(tblSpcs, numSpcs);
1404 
1405  pfree(rawname);
1406  list_free(namelist);
1407 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1417
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4705
MemoryContext TopTransactionContext
Definition: mcxt.c:49
char * temp_tablespaces
Definition: tablespace.c:90
Oid GetUserId(void)
Definition: miscinit.c:380
char * pstrdup(const char *in)
Definition: mcxt.c:1161
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:87
bool TempTablespacesAreSet(void)
Definition: fd.c:2697
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ACL_CREATE
Definition: parsenodes.h:84
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3669
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2669
AclResult
Definition: acl.h:177
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
bool IsTransactionState(void)
Definition: xact.c:356
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
void list_free(List *list)
Definition: list.c:1373
Definition: pg_list.h:50

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

Definition at line 877 of file tablespace.c.

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

Referenced by create_tablespace_directories(), and StartupXLOG().

878 {
879  struct stat st;
880 
881  if (lstat(linkloc, &st) < 0)
882  {
883  if (errno == ENOENT)
884  return;
885  ereport(ERROR,
887  errmsg("could not stat file \"%s\": %m", linkloc)));
888  }
889 
890  if (S_ISDIR(st.st_mode))
891  {
892  /*
893  * This will fail if the directory isn't empty, but not if it's a
894  * junction point.
895  */
896  if (rmdir(linkloc) < 0 && errno != ENOENT)
897  ereport(ERROR,
899  errmsg("could not remove directory \"%s\": %m",
900  linkloc)));
901  }
902 #ifdef S_ISLNK
903  else if (S_ISLNK(st.st_mode))
904  {
905  if (unlink(linkloc) < 0 && errno != ENOENT)
906  ereport(ERROR,
908  errmsg("could not remove symbolic link \"%s\": %m",
909  linkloc)));
910  }
911 #endif
912  else
913  {
914  /* Refuse to remove anything that's not a directory or symlink */
915  ereport(ERROR,
916  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
917  errmsg("\"%s\" is not a directory or symbolic link",
918  linkloc)));
919  }
920 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
#define stat(a, b)
Definition: win32_port.h:264
#define S_ISDIR(m)
Definition: win32_port.h:305
#define lstat(path, sb)
Definition: win32_port.h:253
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ RenameTableSpace()

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

Definition at line 926 of file tablespace.c.

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_TABLESPACE, ObjectAddressSet, pg_tablespace_ownercheck(), RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by ExecRenameStmt().

927 {
928  Oid tspId;
929  Relation rel;
930  ScanKeyData entry[1];
931  TableScanDesc scan;
932  HeapTuple tup;
933  HeapTuple newtuple;
934  Form_pg_tablespace newform;
935  ObjectAddress address;
936 
937  /* Search pg_tablespace */
938  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
939 
940  ScanKeyInit(&entry[0],
941  Anum_pg_tablespace_spcname,
942  BTEqualStrategyNumber, F_NAMEEQ,
943  CStringGetDatum(oldname));
944  scan = table_beginscan_catalog(rel, 1, entry);
945  tup = heap_getnext(scan, ForwardScanDirection);
946  if (!HeapTupleIsValid(tup))
947  ereport(ERROR,
948  (errcode(ERRCODE_UNDEFINED_OBJECT),
949  errmsg("tablespace \"%s\" does not exist",
950  oldname)));
951 
952  newtuple = heap_copytuple(tup);
953  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
954  tspId = newform->oid;
955 
956  table_endscan(scan);
957 
958  /* Must be owner */
959  if (!pg_tablespace_ownercheck(tspId, GetUserId()))
961 
962  /* Validate new name */
963  if (!allowSystemTableMods && IsReservedName(newname))
964  ereport(ERROR,
965  (errcode(ERRCODE_RESERVED_NAME),
966  errmsg("unacceptable tablespace name \"%s\"", newname),
967  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
968 
969  /*
970  * If built with appropriate switch, whine when regression-testing
971  * conventions for tablespace names are violated.
972  */
973 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
974  if (strncmp(newname, "regress_", 8) != 0)
975  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
976 #endif
977 
978  /* Make sure the new name doesn't exist */
979  ScanKeyInit(&entry[0],
980  Anum_pg_tablespace_spcname,
981  BTEqualStrategyNumber, F_NAMEEQ,
982  CStringGetDatum(newname));
983  scan = table_beginscan_catalog(rel, 1, entry);
984  tup = heap_getnext(scan, ForwardScanDirection);
985  if (HeapTupleIsValid(tup))
986  ereport(ERROR,
988  errmsg("tablespace \"%s\" already exists",
989  newname)));
990 
991  table_endscan(scan);
992 
993  /* OK, update the entry */
994  namestrcpy(&(newform->spcname), newname);
995 
996  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
997 
998  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
999 
1000  ObjectAddressSet(address, TableSpaceRelationId, tspId);
1001 
1002  table_close(rel, NoLock);
1003 
1004  return address;
1005 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
Oid GetUserId(void)
Definition: miscinit.c:380
int errcode(int sqlerrcode)
Definition: elog.c:570
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:214
int namestrcpy(Name name, const char *str)
Definition: name.c:250
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3353
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4957
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define WARNING
Definition: elog.h:40
bool allowSystemTableMods
Definition: globals.c:120
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ TablespaceCreateDbspace()

void TablespaceCreateDbspace ( Oid  spcNode,
Oid  dbNode,
bool  isRedo 
)

Definition at line 116 of file tablespace.c.

References Assert, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, get_parent_directory(), GetDatabasePath(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MakePGDirectory(), OidIsValid, pfree(), pstrdup(), S_ISDIR, and stat.

Referenced by mdcreate().

117 {
118  struct stat st;
119  char *dir;
120 
121  /*
122  * The global tablespace doesn't have per-database subdirectories, so
123  * nothing to do for it.
124  */
125  if (spcNode == GLOBALTABLESPACE_OID)
126  return;
127 
128  Assert(OidIsValid(spcNode));
129  Assert(OidIsValid(dbNode));
130 
131  dir = GetDatabasePath(dbNode, spcNode);
132 
133  if (stat(dir, &st) < 0)
134  {
135  /* Directory does not exist? */
136  if (errno == ENOENT)
137  {
138  /*
139  * Acquire TablespaceCreateLock to ensure that no DROP TABLESPACE
140  * or TablespaceCreateDbspace is running concurrently.
141  */
142  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
143 
144  /*
145  * Recheck to see if someone created the directory while we were
146  * waiting for lock.
147  */
148  if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode))
149  {
150  /* Directory was created */
151  }
152  else
153  {
154  /* Directory creation failed? */
155  if (MakePGDirectory(dir) < 0)
156  {
157  char *parentdir;
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  * Parent directories are missing during WAL replay, so
168  * continue by creating simple parent directories rather
169  * than a symlink.
170  */
171 
172  /* create two parents up if not exist */
173  parentdir = pstrdup(dir);
174  get_parent_directory(parentdir);
175  get_parent_directory(parentdir);
176  /* Can't create parent and it doesn't already exist? */
177  if (MakePGDirectory(parentdir) < 0 && errno != EEXIST)
178  ereport(ERROR,
180  errmsg("could not create directory \"%s\": %m",
181  parentdir)));
182  pfree(parentdir);
183 
184  /* create one parent up if not exist */
185  parentdir = pstrdup(dir);
186  get_parent_directory(parentdir);
187  /* Can't create parent and it doesn't already exist? */
188  if (MakePGDirectory(parentdir) < 0 && errno != EEXIST)
189  ereport(ERROR,
191  errmsg("could not create directory \"%s\": %m",
192  parentdir)));
193  pfree(parentdir);
194 
195  /* Create database directory */
196  if (MakePGDirectory(dir) < 0)
197  ereport(ERROR,
199  errmsg("could not create directory \"%s\": %m",
200  dir)));
201  }
202  }
203 
204  LWLockRelease(TablespaceCreateLock);
205  }
206  else
207  {
208  ereport(ERROR,
210  errmsg("could not stat directory \"%s\": %m", dir)));
211  }
212  }
213  else
214  {
215  /* Is it not a directory? */
216  if (!S_ISDIR(st.st_mode))
217  ereport(ERROR,
218  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
219  errmsg("\"%s\" exists but is not a directory",
220  dir)));
221  }
222 
223  pfree(dir);
224 }
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:570
#define OidIsValid(objectId)
Definition: c.h:638
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:593
void get_parent_directory(char *path)
Definition: path.c:854
#define ereport(elevel, rest)
Definition: elog.h:141
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define stat(a, b)
Definition: win32_port.h:264
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3459
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define S_ISDIR(m)
Definition: win32_port.h:305
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ tblspc_desc()

void tblspc_desc ( StringInfo  buf,
XLogReaderState rptr 
)

Definition at line 21 of file tblspcdesc.c.

References appendStringInfo(), 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.

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 }
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:29
unsigned char uint8
Definition: c.h:356
#define XLogRecGetData(decoder)
Definition: xlogreader.h:233
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:229
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24

◆ tblspc_identify()

const char* tblspc_identify ( uint8  info)

Definition at line 41 of file tblspcdesc.c.

References XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, and XLR_INFO_MASK.

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 }
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24

◆ tblspc_redo()

void tblspc_redo ( XLogReaderState rptr)

Definition at line 1502 of file tablespace.c.

References Assert, create_tablespace_directories(), destroy_tablespace_directories(), elog, ereport, errcode(), errhint(), errmsg(), LOG, PANIC, ResolveRecoveryConflictWithTablespace(), 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, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

1503 {
1504  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1505 
1506  /* Backup blocks are not used in tblspc records */
1507  Assert(!XLogRecHasAnyBlockRefs(record));
1508 
1509  if (info == XLOG_TBLSPC_CREATE)
1510  {
1512  char *location = xlrec->ts_path;
1513 
1514  create_tablespace_directories(location, xlrec->ts_id);
1515  }
1516  else if (info == XLOG_TBLSPC_DROP)
1517  {
1519 
1520  /*
1521  * If we issued a WAL record for a drop tablespace it implies that
1522  * there were no files in it at all when the DROP was done. That means
1523  * that no permanent objects can exist in it at this point.
1524  *
1525  * It is possible for standby users to be using this tablespace as a
1526  * location for their temporary files, so if we fail to remove all
1527  * files then do conflict processing and try again, if currently
1528  * enabled.
1529  *
1530  * Other possible reasons for failure include bollixed file
1531  * permissions on a standby server when they were okay on the primary,
1532  * etc etc. There's not much we can do about that, so just remove what
1533  * we can and press on.
1534  */
1535  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1536  {
1538 
1539  /*
1540  * If we did recovery processing then hopefully the backends who
1541  * wrote temp files should have cleaned up and exited by now. So
1542  * retry before complaining. If we fail again, this is just a LOG
1543  * condition, because it's not worth throwing an ERROR for (as
1544  * that would crash the database and require manual intervention
1545  * before we could get past this WAL record on restart).
1546  */
1547  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1548  ereport(LOG,
1549  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1550  errmsg("directories for tablespace %u could not be removed",
1551  xlrec->ts_id),
1552  errhint("You can remove the directories manually if necessary.")));
1553  }
1554  }
1555  else
1556  elog(PANIC, "tblspc_redo: unknown op code %u", info);
1557 }
int errhint(const char *fmt,...)
Definition: elog.c:974
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:29
unsigned char uint8
Definition: c.h:356
int errcode(int sqlerrcode)
Definition: elog.c:570
#define LOG
Definition: elog.h:26
#define PANIC
Definition: elog.h:53
#define XLogRecGetData(decoder)
Definition: xlogreader.h:233
#define ereport(elevel, rest)
Definition: elog.h:141
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:229
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:579
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition: standby.c:318
#define Assert(condition)
Definition: c.h:732
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:677
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:235