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

1011 {
1012  Relation rel;
1013  ScanKeyData entry[1];
1014  TableScanDesc scandesc;
1015  HeapTuple tup;
1016  Oid tablespaceoid;
1017  Datum datum;
1018  Datum newOptions;
1019  Datum repl_val[Natts_pg_tablespace];
1020  bool isnull;
1021  bool repl_null[Natts_pg_tablespace];
1022  bool repl_repl[Natts_pg_tablespace];
1023  HeapTuple newtuple;
1024 
1025  /* Search pg_tablespace */
1026  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1027 
1028  ScanKeyInit(&entry[0],
1029  Anum_pg_tablespace_spcname,
1030  BTEqualStrategyNumber, F_NAMEEQ,
1032  scandesc = table_beginscan_catalog(rel, 1, entry);
1033  tup = heap_getnext(scandesc, ForwardScanDirection);
1034  if (!HeapTupleIsValid(tup))
1035  ereport(ERROR,
1036  (errcode(ERRCODE_UNDEFINED_OBJECT),
1037  errmsg("tablespace \"%s\" does not exist",
1038  stmt->tablespacename)));
1039 
1040  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1041 
1042  /* Must be owner of the existing object */
1043  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
1045  stmt->tablespacename);
1046 
1047  /* Generate new proposed spcoptions (text array) */
1048  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1049  RelationGetDescr(rel), &isnull);
1050  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1051  stmt->options, NULL, NULL, false,
1052  stmt->isReset);
1053  (void) tablespace_reloptions(newOptions, true);
1054 
1055  /* Build new tuple. */
1056  memset(repl_null, false, sizeof(repl_null));
1057  memset(repl_repl, false, sizeof(repl_repl));
1058  if (newOptions != (Datum) 0)
1059  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1060  else
1061  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1062  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1063  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1064  repl_null, repl_repl);
1065 
1066  /* Update system catalog. */
1067  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1068 
1069  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1070 
1071  heap_freetuple(newtuple);
1072 
1073  /* Conclude heap scan. */
1074  table_endscan(scandesc);
1075  table_close(rel, NoLock);
1076 
1077  return tablespaceoid;
1078 }
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:854
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
#define RelationGetDescr(relation)
Definition: rel.h:449
Oid GetUserId(void)
Definition: miscinit.c:380
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1667
int errcode(int sqlerrcode)
Definition: elog.c:608
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:3352
#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:4956
#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:822
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 233 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().

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

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 846 of file tablespace.c.

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

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

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

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

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

414 {
415 #ifdef HAVE_SYMLINK
416  char *tablespacename = stmt->tablespacename;
417  TableScanDesc scandesc;
418  Relation rel;
419  HeapTuple tuple;
420  Form_pg_tablespace spcform;
421  ScanKeyData entry[1];
422  Oid tablespaceoid;
423 
424  /*
425  * Find the target tuple
426  */
427  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
428 
429  ScanKeyInit(&entry[0],
430  Anum_pg_tablespace_spcname,
431  BTEqualStrategyNumber, F_NAMEEQ,
432  CStringGetDatum(tablespacename));
433  scandesc = table_beginscan_catalog(rel, 1, entry);
434  tuple = heap_getnext(scandesc, ForwardScanDirection);
435 
436  if (!HeapTupleIsValid(tuple))
437  {
438  if (!stmt->missing_ok)
439  {
440  ereport(ERROR,
441  (errcode(ERRCODE_UNDEFINED_OBJECT),
442  errmsg("tablespace \"%s\" does not exist",
443  tablespacename)));
444  }
445  else
446  {
447  ereport(NOTICE,
448  (errmsg("tablespace \"%s\" does not exist, skipping",
449  tablespacename)));
450  /* XXX I assume I need one or both of these next two calls */
451  table_endscan(scandesc);
452  table_close(rel, NoLock);
453  }
454  return;
455  }
456 
457  spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
458  tablespaceoid = spcform->oid;
459 
460  /* Must be tablespace owner */
461  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
463  tablespacename);
464 
465  /* Disallow drop of the standard tablespaces, even by superuser */
466  if (tablespaceoid == GLOBALTABLESPACE_OID ||
467  tablespaceoid == DEFAULTTABLESPACE_OID)
469  tablespacename);
470 
471  /* DROP hook for the tablespace being removed */
472  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
473 
474  /*
475  * Remove the pg_tablespace tuple (this will roll back if we fail below)
476  */
477  CatalogTupleDelete(rel, &tuple->t_self);
478 
479  table_endscan(scandesc);
480 
481  /*
482  * Remove any comments or security labels on this tablespace.
483  */
484  DeleteSharedComments(tablespaceoid, TableSpaceRelationId);
485  DeleteSharedSecurityLabel(tablespaceoid, TableSpaceRelationId);
486 
487  /*
488  * Remove dependency on owner.
489  */
490  deleteSharedDependencyRecordsFor(TableSpaceRelationId, tablespaceoid, 0);
491 
492  /*
493  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
494  * is running concurrently.
495  */
496  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
497 
498  /*
499  * Try to remove the physical infrastructure.
500  */
501  if (!destroy_tablespace_directories(tablespaceoid, false))
502  {
503  /*
504  * Not all files deleted? However, there can be lingering empty files
505  * in the directories, left behind by for example DROP TABLE, that
506  * have been scheduled for deletion at next checkpoint (see comments
507  * in mdunlink() for details). We could just delete them immediately,
508  * but we can't tell them apart from important data files that we
509  * mustn't delete. So instead, we force a checkpoint which will clean
510  * out any lingering files, and try again.
511  *
512  * XXX On Windows, an unlinked file persists in the directory listing
513  * until no process retains an open handle for the file. The DDL
514  * commands that schedule files for unlink send invalidation messages
515  * directing other PostgreSQL processes to close the files. DROP
516  * TABLESPACE should not give up on the tablespace becoming empty
517  * until all relevant invalidation processing is complete.
518  */
520  if (!destroy_tablespace_directories(tablespaceoid, false))
521  {
522  /* Still not empty, the files must be important then */
523  ereport(ERROR,
524  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
525  errmsg("tablespace \"%s\" is not empty",
526  tablespacename)));
527  }
528  }
529 
530  /* Record the filesystem change in XLOG */
531  {
532  xl_tblspc_drop_rec xlrec;
533 
534  xlrec.ts_id = tablespaceoid;
535 
536  XLogBeginInsert();
537  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
538 
539  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
540  }
541 
542  /*
543  * Note: because we checked that the tablespace was empty, there should be
544  * no need to worry about flushing shared buffers or free space map
545  * entries for relations in the tablespace.
546  */
547 
548  /*
549  * Force synchronous commit, to minimize the window between removing the
550  * files on-disk and marking the transaction committed. It's not great
551  * that there is any window at all, but definitely we don't want to make
552  * it larger than necessary.
553  */
554  ForceSyncCommit();
555 
556  /*
557  * Allow TablespaceCreateDbspace again.
558  */
559  LWLockRelease(TablespaceCreateLock);
560 
561  /* We keep the lock on pg_tablespace until commit */
562  table_close(rel, NoLock);
563 #else /* !HAVE_SYMLINK */
564  ereport(ERROR,
565  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
566  errmsg("tablespaces are not supported on this platform")));
567 #endif /* HAVE_SYMLINK */
568 }
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:1053
int errcode(int sqlerrcode)
Definition: elog.c:608
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:3352
#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:4956
#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:907
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:676
#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:822
#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 1462 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().

1463 {
1464  char *result;
1465  Relation rel;
1466  TableScanDesc scandesc;
1467  HeapTuple tuple;
1468  ScanKeyData entry[1];
1469 
1470  /*
1471  * Search pg_tablespace. We use a heapscan here even though there is an
1472  * index on oid, on the theory that pg_tablespace will usually have just a
1473  * few entries and so an indexed lookup is a waste of effort.
1474  */
1475  rel = table_open(TableSpaceRelationId, AccessShareLock);
1476 
1477  ScanKeyInit(&entry[0],
1478  Anum_pg_tablespace_oid,
1479  BTEqualStrategyNumber, F_OIDEQ,
1480  ObjectIdGetDatum(spc_oid));
1481  scandesc = table_beginscan_catalog(rel, 1, entry);
1482  tuple = heap_getnext(scandesc, ForwardScanDirection);
1483 
1484  /* We assume that there can be at most one matching tuple */
1485  if (HeapTupleIsValid(tuple))
1486  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1487  else
1488  result = NULL;
1489 
1490  table_endscan(scandesc);
1492 
1493  return result;
1494 }
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:1186
#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:610
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 1416 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().

1417 {
1418  Oid result;
1419  Relation rel;
1420  TableScanDesc scandesc;
1421  HeapTuple tuple;
1422  ScanKeyData entry[1];
1423 
1424  /*
1425  * Search pg_tablespace. We use a heapscan here even though there is an
1426  * index on name, on the theory that pg_tablespace will usually have just
1427  * a few entries and so an indexed lookup is a waste of effort.
1428  */
1429  rel = table_open(TableSpaceRelationId, AccessShareLock);
1430 
1431  ScanKeyInit(&entry[0],
1432  Anum_pg_tablespace_spcname,
1433  BTEqualStrategyNumber, F_NAMEEQ,
1434  CStringGetDatum(tablespacename));
1435  scandesc = table_beginscan_catalog(rel, 1, entry);
1436  tuple = heap_getnext(scandesc, ForwardScanDirection);
1437 
1438  /* We assume that there can be at most one matching tuple */
1439  if (HeapTupleIsValid(tuple))
1440  result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1441  else
1442  result = InvalidOid;
1443 
1444  table_endscan(scandesc);
1446 
1447  if (!OidIsValid(result) && !missing_ok)
1448  ereport(ERROR,
1449  (errcode(ERRCODE_UNDEFINED_OBJECT),
1450  errmsg("tablespace \"%s\" does not exist",
1451  tablespacename)));
1452 
1453  return result;
1454 }
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:608
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:639
#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:822
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 1138 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().

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

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

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

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

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

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

◆ RenameTableSpace()

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

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

926 {
927  Oid tspId;
928  Relation rel;
929  ScanKeyData entry[1];
930  TableScanDesc scan;
931  HeapTuple tup;
932  HeapTuple newtuple;
933  Form_pg_tablespace newform;
934  ObjectAddress address;
935 
936  /* Search pg_tablespace */
937  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
938 
939  ScanKeyInit(&entry[0],
940  Anum_pg_tablespace_spcname,
941  BTEqualStrategyNumber, F_NAMEEQ,
942  CStringGetDatum(oldname));
943  scan = table_beginscan_catalog(rel, 1, entry);
944  tup = heap_getnext(scan, ForwardScanDirection);
945  if (!HeapTupleIsValid(tup))
946  ereport(ERROR,
947  (errcode(ERRCODE_UNDEFINED_OBJECT),
948  errmsg("tablespace \"%s\" does not exist",
949  oldname)));
950 
951  newtuple = heap_copytuple(tup);
952  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
953  tspId = newform->oid;
954 
955  table_endscan(scan);
956 
957  /* Must be owner */
958  if (!pg_tablespace_ownercheck(tspId, GetUserId()))
960 
961  /* Validate new name */
962  if (!allowSystemTableMods && IsReservedName(newname))
963  ereport(ERROR,
964  (errcode(ERRCODE_RESERVED_NAME),
965  errmsg("unacceptable tablespace name \"%s\"", newname),
966  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
967 
968  /*
969  * If built with appropriate switch, whine when regression-testing
970  * conventions for tablespace names are violated.
971  */
972 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
973  if (strncmp(newname, "regress_", 8) != 0)
974  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
975 #endif
976 
977  /* Make sure the new name doesn't exist */
978  ScanKeyInit(&entry[0],
979  Anum_pg_tablespace_spcname,
980  BTEqualStrategyNumber, F_NAMEEQ,
981  CStringGetDatum(newname));
982  scan = table_beginscan_catalog(rel, 1, entry);
983  tup = heap_getnext(scan, ForwardScanDirection);
984  if (HeapTupleIsValid(tup))
985  ereport(ERROR,
987  errmsg("tablespace \"%s\" already exists",
988  newname)));
989 
990  table_endscan(scan);
991 
992  /* OK, update the entry */
993  namestrcpy(&(newform->spcname), newname);
994 
995  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
996 
997  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
998 
999  ObjectAddressSet(address, TableSpaceRelationId, tspId);
1000 
1001  table_close(rel, NoLock);
1002 
1003  return address;
1004 }
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:608
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:213
int namestrcpy(Name name, const char *str)
Definition: name.c:250
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3352
#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:957
#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:4956
#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:822
#define elog(elevel,...)
Definition: elog.h:228
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:31
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ TablespaceCreateDbspace()

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

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

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

◆ 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:357
#define XLogRecGetData(decoder)
Definition: xlogreader.h:246
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:242
#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 1501 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.

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