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)
 
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 988 of file tablespace.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, GetUserId(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_freetuple(), heap_getattr, heap_getnext(), heap_modify_tuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, AlterTableSpaceOptionsStmt::isReset, NoLock, OBJECT_TABLESPACE, AlterTableSpaceOptionsStmt::options, pg_tablespace_ownercheck(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, tablespace_reloptions(), AlterTableSpaceOptionsStmt::tablespacename, and transformRelOptions().

Referenced by standard_ProcessUtility().

989 {
990  Relation rel;
991  ScanKeyData entry[1];
992  HeapScanDesc scandesc;
993  HeapTuple tup;
994  Oid tablespaceoid;
995  Datum datum;
996  Datum newOptions;
997  Datum repl_val[Natts_pg_tablespace];
998  bool isnull;
999  bool repl_null[Natts_pg_tablespace];
1000  bool repl_repl[Natts_pg_tablespace];
1001  HeapTuple newtuple;
1002 
1003  /* Search pg_tablespace */
1004  rel = heap_open(TableSpaceRelationId, RowExclusiveLock);
1005 
1006  ScanKeyInit(&entry[0],
1007  Anum_pg_tablespace_spcname,
1008  BTEqualStrategyNumber, F_NAMEEQ,
1010  scandesc = heap_beginscan_catalog(rel, 1, entry);
1011  tup = heap_getnext(scandesc, ForwardScanDirection);
1012  if (!HeapTupleIsValid(tup))
1013  ereport(ERROR,
1014  (errcode(ERRCODE_UNDEFINED_OBJECT),
1015  errmsg("tablespace \"%s\" does not exist",
1016  stmt->tablespacename)));
1017 
1018  tablespaceoid = HeapTupleGetOid(tup);
1019 
1020  /* Must be owner of the existing object */
1023  stmt->tablespacename);
1024 
1025  /* Generate new proposed spcoptions (text array) */
1026  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1027  RelationGetDescr(rel), &isnull);
1028  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1029  stmt->options, NULL, NULL, false,
1030  stmt->isReset);
1031  (void) tablespace_reloptions(newOptions, true);
1032 
1033  /* Build new tuple. */
1034  memset(repl_null, false, sizeof(repl_null));
1035  memset(repl_repl, false, sizeof(repl_repl));
1036  if (newOptions != (Datum) 0)
1037  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1038  else
1039  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1040  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1041  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1042  repl_null, repl_repl);
1043 
1044  /* Update system catalog. */
1045  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1046 
1047  InvokeObjectPostAlterHook(TableSpaceRelationId, HeapTupleGetOid(tup), 0);
1048 
1049  heap_freetuple(newtuple);
1050 
1051  /* Conclude heap scan. */
1052  heap_endscan(scandesc);
1053  heap_close(rel, NoLock);
1054 
1055  return tablespaceoid;
1056 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1572
#define RelationGetDescr(relation)
Definition: rel.h:433
Oid GetUserId(void)
Definition: miscinit.c:379
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1558
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
unsigned int Oid
Definition: postgres_ext.h:31
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:773
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3349
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:563
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4953
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1412
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:781
uintptr_t Datum
Definition: postgres.h:367
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1835
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1173
#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, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FORKNAMECHARS, get_rolespec_oid(), get_tablespace_oid(), GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), 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(), tablespace_reloptions(), TABLESPACE_VERSION_DIRECTORY, CreateTableSpaceStmt::tablespacename, 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  * Check that there is no other tablespace by this name. (The unique
312  * index would catch this anyway, but might as well give a friendlier
313  * message.)
314  */
315  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
316  ereport(ERROR,
318  errmsg("tablespace \"%s\" already exists",
319  stmt->tablespacename)));
320 
321  /*
322  * Insert tuple into pg_tablespace. The purpose of doing this first is to
323  * lock the proposed tablename against other would-be creators. The
324  * insertion will roll back if we find problems below.
325  */
326  rel = heap_open(TableSpaceRelationId, RowExclusiveLock);
327 
328  MemSet(nulls, false, sizeof(nulls));
329 
330  values[Anum_pg_tablespace_spcname - 1] =
332  values[Anum_pg_tablespace_spcowner - 1] =
333  ObjectIdGetDatum(ownerId);
334  nulls[Anum_pg_tablespace_spcacl - 1] = true;
335 
336  /* Generate new proposed spcoptions (text array) */
337  newOptions = transformRelOptions((Datum) 0,
338  stmt->options,
339  NULL, NULL, false, false);
340  (void) tablespace_reloptions(newOptions, true);
341  if (newOptions != (Datum) 0)
342  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
343  else
344  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
345 
346  tuple = heap_form_tuple(rel->rd_att, values, nulls);
347 
348  tablespaceoid = CatalogTupleInsert(rel, tuple);
349 
350  heap_freetuple(tuple);
351 
352  /* Record dependency on owner */
353  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
354 
355  /* Post creation hook for new tablespace */
356  InvokeObjectPostCreateHook(TableSpaceRelationId, tablespaceoid, 0);
357 
358  create_tablespace_directories(location, tablespaceoid);
359 
360  /* Record the filesystem change in XLOG */
361  {
362  xl_tblspc_create_rec xlrec;
363 
364  xlrec.ts_id = tablespaceoid;
365 
366  XLogBeginInsert();
367  XLogRegisterData((char *) &xlrec,
368  offsetof(xl_tblspc_create_rec, ts_path));
369  XLogRegisterData((char *) location, strlen(location) + 1);
370 
371  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
372  }
373 
374  /*
375  * Force synchronous commit, to minimize the window between creating the
376  * symlink on-disk and marking the transaction committed. It's not great
377  * that there is any window at all, but definitely we don't want to make
378  * it larger than necessary.
379  */
380  ForceSyncCommit();
381 
382  pfree(location);
383 
384  /* We keep the lock on pg_tablespace until commit */
385  heap_close(rel, NoLock);
386 
387  return tablespaceoid;
388 #else /* !HAVE_SYMLINK */
389  ereport(ERROR,
390  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
391  errmsg("tablespaces are not supported on this platform")));
392  return InvalidOid; /* keep compiler quiet */
393 #endif /* HAVE_SYMLINK */
394 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1382
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
int errhint(const char *fmt,...)
Definition: elog.c:987
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
Oid GetUserId(void)
Definition: miscinit.c:379
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:1558
void ForceSyncCommit(void)
Definition: xact.c:962
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define MemSet(start, val, len)
Definition: c.h:908
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1074
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:590
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:194
#define OidIsValid(objectId)
Definition: c.h:605
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:773
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:163
#define MAXPGPATH
#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:873
#define is_absolute_path(filename)
Definition: port.h:86
#define CStringGetDatum(X)
Definition: postgres.h:563
#define ereport(elevel, rest)
Definition: elog.h:122
#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:565
uintptr_t Datum
Definition: postgres.h:367
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5149
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
TupleDesc rd_att
Definition: rel.h:85
bool allowSystemTableMods
Definition: globals.c:119
#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:164
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:61
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define OIDCHARS
Definition: relpath.h:30
#define offsetof(type, field)
Definition: c.h:622

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 833 of file tablespace.c.

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

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

834 {
835  DIR *dirdesc;
836  struct dirent *de;
837 
838  dirdesc = AllocateDir(path);
839 
840  while ((de = ReadDir(dirdesc, path)) != NULL)
841  {
842  if (strcmp(de->d_name, ".") == 0 ||
843  strcmp(de->d_name, "..") == 0)
844  continue;
845  FreeDir(dirdesc);
846  return false;
847  }
848 
849  FreeDir(dirdesc);
850  return true;
851 }
Definition: dirent.h:9
Definition: dirent.c:25
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2590
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2656
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2708

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

Definition at line 402 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, GetUserId(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectDropHook, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), DropTableSpaceStmt::missing_ok, NoLock, NOTICE, OBJECT_TABLESPACE, pg_tablespace_ownercheck(), RequestCheckpoint(), RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, DropTableSpaceStmt::tablespacename, xl_tblspc_drop_rec::ts_id, XLOG_TBLSPC_DROP, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

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

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

Definition at line 1428 of file tablespace.c.

References AccessShareLock, BTEqualStrategyNumber, ForwardScanDirection, GETSTRUCT, heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleIsValid, NameStr, ObjectIdAttributeNumber, ObjectIdGetDatum, pstrdup(), and ScanKeyInit().

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

1429 {
1430  char *result;
1431  Relation rel;
1432  HeapScanDesc scandesc;
1433  HeapTuple tuple;
1434  ScanKeyData entry[1];
1435 
1436  /*
1437  * Search pg_tablespace. We use a heapscan here even though there is an
1438  * index on oid, on the theory that pg_tablespace will usually have just a
1439  * few entries and so an indexed lookup is a waste of effort.
1440  */
1441  rel = heap_open(TableSpaceRelationId, AccessShareLock);
1442 
1443  ScanKeyInit(&entry[0],
1445  BTEqualStrategyNumber, F_OIDEQ,
1446  ObjectIdGetDatum(spc_oid));
1447  scandesc = heap_beginscan_catalog(rel, 1, entry);
1448  tuple = heap_getnext(scandesc, ForwardScanDirection);
1449 
1450  /* We assume that there can be at most one matching tuple */
1451  if (HeapTupleIsValid(tuple))
1452  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1453  else
1454  result = NULL;
1455 
1456  heap_endscan(scandesc);
1458 
1459  return result;
1460 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1572
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
char * pstrdup(const char *in)
Definition: mcxt.c:1161
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:45
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1412
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1835
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define NameStr(name)
Definition: c.h:576
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char *  tablespacename,
bool  missing_ok 
)

Definition at line 1382 of file tablespace.c.

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum, ereport, errcode(), errmsg(), ERROR, ForwardScanDirection, heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, OidIsValid, and ScanKeyInit().

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().

1383 {
1384  Oid result;
1385  Relation rel;
1386  HeapScanDesc scandesc;
1387  HeapTuple tuple;
1388  ScanKeyData entry[1];
1389 
1390  /*
1391  * Search pg_tablespace. We use a heapscan here even though there is an
1392  * index on name, on the theory that pg_tablespace will usually have just
1393  * a few entries and so an indexed lookup is a waste of effort.
1394  */
1395  rel = heap_open(TableSpaceRelationId, AccessShareLock);
1396 
1397  ScanKeyInit(&entry[0],
1398  Anum_pg_tablespace_spcname,
1399  BTEqualStrategyNumber, F_NAMEEQ,
1400  CStringGetDatum(tablespacename));
1401  scandesc = heap_beginscan_catalog(rel, 1, entry);
1402  tuple = heap_getnext(scandesc, ForwardScanDirection);
1403 
1404  /* We assume that there can be at most one matching tuple */
1405  if (HeapTupleIsValid(tuple))
1406  result = HeapTupleGetOid(tuple);
1407  else
1408  result = InvalidOid;
1409 
1410  heap_endscan(scandesc);
1412 
1413  if (!OidIsValid(result) && !missing_ok)
1414  ereport(ERROR,
1415  (errcode(ERRCODE_UNDEFINED_OBJECT),
1416  errmsg("tablespace \"%s\" does not exist",
1417  tablespacename)));
1418 
1419  return result;
1420 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1572
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:605
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:563
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1412
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1835
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence)

Definition at line 1113 of file tablespace.c.

References default_tablespace, get_tablespace_oid(), GetNextTempTableSpace(), InvalidOid, MyDatabaseTableSpace, and PrepareTempTablespaces().

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

1114 {
1115  Oid result;
1116 
1117  /* The temp-table case is handled elsewhere */
1118  if (relpersistence == RELPERSISTENCE_TEMP)
1119  {
1121  return GetNextTempTableSpace();
1122  }
1123 
1124  /* Fast path for default_tablespace == "" */
1125  if (default_tablespace == NULL || default_tablespace[0] == '\0')
1126  return InvalidOid;
1127 
1128  /*
1129  * It is tempting to cache this lookup for more speed, but then we would
1130  * fail to detect the case where the tablespace was dropped since the GUC
1131  * variable was set. Note also that we don't complain if the value fails
1132  * to refer to an existing tablespace; we just silently return InvalidOid,
1133  * causing the new object to be created in the database's tablespace.
1134  */
1135  result = get_tablespace_oid(default_tablespace, true);
1136 
1137  /*
1138  * Allow explicit specification of database's default tablespace in
1139  * default_tablespace without triggering permissions checks.
1140  */
1141  if (result == MyDatabaseTableSpace)
1142  result = InvalidOid;
1143  return result;
1144 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1382
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:86
void PrepareTempTablespaces(void)
Definition: tablespace.c:1289
char relpersistence
Definition: pg_class.h:50
Oid GetNextTempTableSpace(void)
Definition: fd.c:2851
#define InvalidOid
Definition: postgres_ext.h:36
char * default_tablespace
Definition: tablespace.c:89

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1289 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 ExecHashIncreaseNumBatches(), ExecHashTableCreate(), GetDefaultTablespace(), inittapestate(), SharedFileSetInit(), and tuplestore_puttuple_common().

1290 {
1291  char *rawname;
1292  List *namelist;
1293  Oid *tblSpcs;
1294  int numSpcs;
1295  ListCell *l;
1296 
1297  /* No work if already done in current transaction */
1298  if (TempTablespacesAreSet())
1299  return;
1300 
1301  /*
1302  * Can't do catalog access unless within a transaction. This is just a
1303  * safety check in case this function is called by low-level code that
1304  * could conceivably execute outside a transaction. Note that in such a
1305  * scenario, fd.c will fall back to using the current database's default
1306  * tablespace, which should always be OK.
1307  */
1308  if (!IsTransactionState())
1309  return;
1310 
1311  /* Need a modifiable copy of string */
1312  rawname = pstrdup(temp_tablespaces);
1313 
1314  /* Parse string into list of identifiers */
1315  if (!SplitIdentifierString(rawname, ',', &namelist))
1316  {
1317  /* syntax error in name list */
1318  SetTempTablespaces(NULL, 0);
1319  pfree(rawname);
1320  list_free(namelist);
1321  return;
1322  }
1323 
1324  /* Store tablespace OIDs in an array in TopTransactionContext */
1326  list_length(namelist) * sizeof(Oid));
1327  numSpcs = 0;
1328  foreach(l, namelist)
1329  {
1330  char *curname = (char *) lfirst(l);
1331  Oid curoid;
1332  AclResult aclresult;
1333 
1334  /* Allow an empty string (signifying database default) */
1335  if (curname[0] == '\0')
1336  {
1337  tblSpcs[numSpcs++] = InvalidOid;
1338  continue;
1339  }
1340 
1341  /* Else verify that name is a valid tablespace name */
1342  curoid = get_tablespace_oid(curname, true);
1343  if (curoid == InvalidOid)
1344  {
1345  /* Skip any bad list elements */
1346  continue;
1347  }
1348 
1349  /*
1350  * Allow explicit specification of database's default tablespace in
1351  * temp_tablespaces without triggering permissions checks.
1352  */
1353  if (curoid == MyDatabaseTableSpace)
1354  {
1355  tblSpcs[numSpcs++] = InvalidOid;
1356  continue;
1357  }
1358 
1359  /* Check permissions similarly */
1360  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1361  ACL_CREATE);
1362  if (aclresult != ACLCHECK_OK)
1363  continue;
1364 
1365  tblSpcs[numSpcs++] = curoid;
1366  }
1367 
1368  SetTempTablespaces(tblSpcs, numSpcs);
1369 
1370  pfree(rawname);
1371  list_free(namelist);
1372 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1382
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4701
MemoryContext TopTransactionContext
Definition: mcxt.c:49
char * temp_tablespaces
Definition: tablespace.c:90
Oid GetUserId(void)
Definition: miscinit.c:379
char * pstrdup(const char *in)
Definition: mcxt.c:1161
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:86
bool TempTablespacesAreSet(void)
Definition: fd.c:2821
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:3290
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2793
AclResult
Definition: acl.h:178
#define InvalidOid
Definition: postgres_ext.h:36
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
bool IsTransactionState(void)
Definition: xact.c:350
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
void list_free(List *list)
Definition: list.c:1133
Definition: pg_list.h:45

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

Definition at line 863 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().

864 {
865  struct stat st;
866 
867  if (lstat(linkloc, &st) < 0)
868  {
869  if (errno == ENOENT)
870  return;
871  ereport(ERROR,
873  errmsg("could not stat file \"%s\": %m", linkloc)));
874  }
875 
876  if (S_ISDIR(st.st_mode))
877  {
878  /*
879  * This will fail if the directory isn't empty, but not if it's a
880  * junction point.
881  */
882  if (rmdir(linkloc) < 0 && errno != ENOENT)
883  ereport(ERROR,
885  errmsg("could not remove directory \"%s\": %m",
886  linkloc)));
887  }
888 #ifdef S_ISLNK
889  else if (S_ISLNK(st.st_mode))
890  {
891  if (unlink(linkloc) < 0 && errno != ENOENT)
892  ereport(ERROR,
894  errmsg("could not remove symbolic link \"%s\": %m",
895  linkloc)));
896  }
897 #endif
898  else
899  {
900  /* Refuse to remove anything that's not a directory or symlink */
901  ereport(ERROR,
902  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
903  errmsg("\"%s\" is not a directory or symbolic link",
904  linkloc)));
905  }
906 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define stat(a, b)
Definition: win32_port.h:266
#define S_ISDIR(m)
Definition: win32_port.h:307
#define lstat(path, sb)
Definition: win32_port.h:255
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ RenameTableSpace()

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

Definition at line 912 of file tablespace.c.

References aclcheck_error(), ACLCHECK_NO_PRIV, allowSystemTableMods, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errmsg(), ERROR, ForwardScanDirection, GETSTRUCT, GetUserId(), heap_beginscan_catalog(), heap_close, heap_copytuple(), heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, IsReservedName(), namestrcpy(), NoLock, OBJECT_TABLESPACE, ObjectAddressSet, pg_tablespace_ownercheck(), RowExclusiveLock, ScanKeyInit(), and HeapTupleData::t_self.

Referenced by ExecRenameStmt().

913 {
914  Oid tspId;
915  Relation rel;
916  ScanKeyData entry[1];
917  HeapScanDesc scan;
918  HeapTuple tup;
919  HeapTuple newtuple;
920  Form_pg_tablespace newform;
921  ObjectAddress address;
922 
923  /* Search pg_tablespace */
924  rel = heap_open(TableSpaceRelationId, RowExclusiveLock);
925 
926  ScanKeyInit(&entry[0],
927  Anum_pg_tablespace_spcname,
928  BTEqualStrategyNumber, F_NAMEEQ,
929  CStringGetDatum(oldname));
930  scan = heap_beginscan_catalog(rel, 1, entry);
931  tup = heap_getnext(scan, ForwardScanDirection);
932  if (!HeapTupleIsValid(tup))
933  ereport(ERROR,
934  (errcode(ERRCODE_UNDEFINED_OBJECT),
935  errmsg("tablespace \"%s\" does not exist",
936  oldname)));
937 
938  tspId = HeapTupleGetOid(tup);
939  newtuple = heap_copytuple(tup);
940  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
941 
942  heap_endscan(scan);
943 
944  /* Must be owner */
947 
948  /* Validate new name */
949  if (!allowSystemTableMods && IsReservedName(newname))
950  ereport(ERROR,
951  (errcode(ERRCODE_RESERVED_NAME),
952  errmsg("unacceptable tablespace name \"%s\"", newname),
953  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
954 
955  /* Make sure the new name doesn't exist */
956  ScanKeyInit(&entry[0],
957  Anum_pg_tablespace_spcname,
958  BTEqualStrategyNumber, F_NAMEEQ,
959  CStringGetDatum(newname));
960  scan = heap_beginscan_catalog(rel, 1, entry);
961  tup = heap_getnext(scan, ForwardScanDirection);
962  if (HeapTupleIsValid(tup))
963  ereport(ERROR,
965  errmsg("tablespace \"%s\" already exists",
966  newname)));
967 
968  heap_endscan(scan);
969 
970  /* OK, update the entry */
971  namestrcpy(&(newform->spcname), newname);
972 
973  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
974 
975  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
976 
977  ObjectAddressSet(address, TableSpaceRelationId, tspId);
978 
979  heap_close(rel, NoLock);
980 
981  return address;
982 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:722
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1572
Oid GetUserId(void)
Definition: miscinit.c:379
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:194
int namestrcpy(Name name, const char *str)
Definition: name.c:216
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3349
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:563
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:45
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4953
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1412
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1835
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
bool allowSystemTableMods
Definition: globals.c:119
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#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 smgrcreate().

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:575
#define OidIsValid(objectId)
Definition: c.h:605
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:598
void get_parent_directory(char *path)
Definition: path.c:854
#define ereport(elevel, rest)
Definition: elog.h:122
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:107
#define stat(a, b)
Definition: win32_port.h:266
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3571
#define Assert(condition)
Definition: c.h:699
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
#define S_ISDIR(m)
Definition: win32_port.h:307
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ 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:323
#define XLogRecGetData(decoder)
Definition: xlogreader.h:230
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:226
#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 1467 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.

1468 {
1469  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1470 
1471  /* Backup blocks are not used in tblspc records */
1472  Assert(!XLogRecHasAnyBlockRefs(record));
1473 
1474  if (info == XLOG_TBLSPC_CREATE)
1475  {
1477  char *location = xlrec->ts_path;
1478 
1479  create_tablespace_directories(location, xlrec->ts_id);
1480  }
1481  else if (info == XLOG_TBLSPC_DROP)
1482  {
1484 
1485  /*
1486  * If we issued a WAL record for a drop tablespace it implies that
1487  * there were no files in it at all when the DROP was done. That means
1488  * that no permanent objects can exist in it at this point.
1489  *
1490  * It is possible for standby users to be using this tablespace as a
1491  * location for their temporary files, so if we fail to remove all
1492  * files then do conflict processing and try again, if currently
1493  * enabled.
1494  *
1495  * Other possible reasons for failure include bollixed file
1496  * permissions on a standby server when they were okay on the primary,
1497  * etc etc. There's not much we can do about that, so just remove what
1498  * we can and press on.
1499  */
1500  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1501  {
1503 
1504  /*
1505  * If we did recovery processing then hopefully the backends who
1506  * wrote temp files should have cleaned up and exited by now. So
1507  * retry before complaining. If we fail again, this is just a LOG
1508  * condition, because it's not worth throwing an ERROR for (as
1509  * that would crash the database and require manual intervention
1510  * before we could get past this WAL record on restart).
1511  */
1512  if (!destroy_tablespace_directories(xlrec->ts_id, true))
1513  ereport(LOG,
1514  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1515  errmsg("directories for tablespace %u could not be removed",
1516  xlrec->ts_id),
1517  errhint("You can remove the directories manually if necessary.")));
1518  }
1519  }
1520  else
1521  elog(PANIC, "tblspc_redo: unknown op code %u", info);
1522 }
int errhint(const char *fmt,...)
Definition: elog.c:987
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.h:29
unsigned char uint8
Definition: c.h:323
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
#define PANIC
Definition: elog.h:53
#define XLogRecGetData(decoder)
Definition: xlogreader.h:230
#define ereport(elevel, rest)
Definition: elog.h:122
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:226
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:565
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition: standby.c:291
#define Assert(condition)
Definition: c.h:699
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:663
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:232
#define elog
Definition: elog.h:219