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

1023 {
1024  Relation rel;
1025  ScanKeyData entry[1];
1026  TableScanDesc scandesc;
1027  HeapTuple tup;
1028  Oid tablespaceoid;
1029  Datum datum;
1030  Datum newOptions;
1031  Datum repl_val[Natts_pg_tablespace];
1032  bool isnull;
1033  bool repl_null[Natts_pg_tablespace];
1034  bool repl_repl[Natts_pg_tablespace];
1035  HeapTuple newtuple;
1036 
1037  /* Search pg_tablespace */
1038  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1039 
1040  ScanKeyInit(&entry[0],
1041  Anum_pg_tablespace_spcname,
1042  BTEqualStrategyNumber, F_NAMEEQ,
1044  scandesc = table_beginscan_catalog(rel, 1, entry);
1045  tup = heap_getnext(scandesc, ForwardScanDirection);
1046  if (!HeapTupleIsValid(tup))
1047  ereport(ERROR,
1048  (errcode(ERRCODE_UNDEFINED_OBJECT),
1049  errmsg("tablespace \"%s\" does not exist",
1050  stmt->tablespacename)));
1051 
1052  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1053 
1054  /* Must be owner of the existing object */
1055  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
1057  stmt->tablespacename);
1058 
1059  /* Generate new proposed spcoptions (text array) */
1060  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1061  RelationGetDescr(rel), &isnull);
1062  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1063  stmt->options, NULL, NULL, false,
1064  stmt->isReset);
1065  (void) tablespace_reloptions(newOptions, true);
1066 
1067  /* Build new tuple. */
1068  memset(repl_null, false, sizeof(repl_null));
1069  memset(repl_repl, false, sizeof(repl_repl));
1070  if (newOptions != (Datum) 0)
1071  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1072  else
1073  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1074  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1075  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1076  repl_null, repl_repl);
1077 
1078  /* Update system catalog. */
1079  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1080 
1081  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1082 
1083  heap_freetuple(newtuple);
1084 
1085  /* Conclude heap scan. */
1086  table_endscan(scandesc);
1087  table_close(rel, NoLock);
1088 
1089  return tablespaceoid;
1090 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#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:1132
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
#define RelationGetDescr(relation)
Definition: rel.h:483
Oid GetUserId(void)
Definition: miscinit.c:476
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2063
int errcode(int sqlerrcode)
Definition: elog.c:704
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:3294
#define ERROR
Definition: elog.h:45
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
#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:4889
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:1433
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:315
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1162
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1132
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
Oid GetUserId(void)
Definition: miscinit.c:476
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2063
void ForceSyncCommit(void)
Definition: xact.c:1071
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:704
bool superuser(void)
Definition: superuser.c:46
#define MemSet(start, val, len)
Definition: c.h:996
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:210
#define OidIsValid(objectId)
Definition: c.h:698
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
#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:1048
#define is_absolute_path(filename)
Definition: port.h:86
#define CStringGetDatum(X)
Definition: postgres.h:578
#define WARNING
Definition: elog.h:40
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:330
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:422
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:590
#define TablespaceOidIndexId
Definition: pg_tablespace.h:53
uintptr_t Datum
Definition: postgres.h:367
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5212
TupleDesc rd_att
Definition: rel.h:111
bool allowSystemTableMods
Definition: globals.c:121
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define FORKNAMECHARS
Definition: relpath.h:57
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
char * DataDir
Definition: globals.c:63
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:123
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define OIDCHARS
Definition: relpath.h:30
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:222
#define offsetof(type, field)
Definition: c.h:715

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 858 of file tablespace.c.

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

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

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

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

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

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

1480 {
1481  char *result;
1482  Relation rel;
1483  TableScanDesc scandesc;
1484  HeapTuple tuple;
1485  ScanKeyData entry[1];
1486 
1487  /*
1488  * Search pg_tablespace. We use a heapscan here even though there is an
1489  * index on oid, on the theory that pg_tablespace will usually have just a
1490  * few entries and so an indexed lookup is a waste of effort.
1491  */
1492  rel = table_open(TableSpaceRelationId, AccessShareLock);
1493 
1494  ScanKeyInit(&entry[0],
1495  Anum_pg_tablespace_oid,
1496  BTEqualStrategyNumber, F_OIDEQ,
1497  ObjectIdGetDatum(spc_oid));
1498  scandesc = table_beginscan_catalog(rel, 1, entry);
1499  tuple = heap_getnext(scandesc, ForwardScanDirection);
1500 
1501  /* We assume that there can be at most one matching tuple */
1502  if (HeapTupleIsValid(tuple))
1503  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1504  else
1505  result = NULL;
1506 
1507  table_endscan(scandesc);
1509 
1510  return result;
1511 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define AccessShareLock
Definition: lockdefs.h:36
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
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:962
#define NameStr(name)
Definition: c.h:669
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 1433 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().

1434 {
1435  Oid result;
1436  Relation rel;
1437  TableScanDesc scandesc;
1438  HeapTuple tuple;
1439  ScanKeyData entry[1];
1440 
1441  /*
1442  * Search pg_tablespace. We use a heapscan here even though there is an
1443  * index on name, on the theory that pg_tablespace will usually have just
1444  * a few entries and so an indexed lookup is a waste of effort.
1445  */
1446  rel = table_open(TableSpaceRelationId, AccessShareLock);
1447 
1448  ScanKeyInit(&entry[0],
1449  Anum_pg_tablespace_spcname,
1450  BTEqualStrategyNumber, F_NAMEEQ,
1451  CStringGetDatum(tablespacename));
1452  scandesc = table_beginscan_catalog(rel, 1, entry);
1453  tuple = heap_getnext(scandesc, ForwardScanDirection);
1454 
1455  /* We assume that there can be at most one matching tuple */
1456  if (HeapTupleIsValid(tuple))
1457  result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1458  else
1459  result = InvalidOid;
1460 
1461  table_endscan(scandesc);
1463 
1464  if (!OidIsValid(result) && !missing_ok)
1465  ereport(ERROR,
1466  (errcode(ERRCODE_UNDEFINED_OBJECT),
1467  errmsg("tablespace \"%s\" does not exist",
1468  tablespacename)));
1469 
1470  return result;
1471 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
#define ERROR
Definition: elog.h:45
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
#define CStringGetDatum(X)
Definition: postgres.h:578
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:46
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
int errmsg(const char *fmt,...)
Definition: elog.c:915
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 1150 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().

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

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

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

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

Definition at line 888 of file tablespace.c.

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

Referenced by create_tablespace_directories(), and StartupXLOG().

889 {
890  struct stat st;
891 
892  if (lstat(linkloc, &st) < 0)
893  {
894  if (errno == ENOENT)
895  return;
896  ereport(ERROR,
898  errmsg("could not stat file \"%s\": %m", linkloc)));
899  }
900 
901  if (S_ISDIR(st.st_mode))
902  {
903  /*
904  * This will fail if the directory isn't empty, but not if it's a
905  * junction point.
906  */
907  if (rmdir(linkloc) < 0 && errno != ENOENT)
908  ereport(ERROR,
910  errmsg("could not remove directory \"%s\": %m",
911  linkloc)));
912  }
913 #ifdef S_ISLNK
914  else if (S_ISLNK(st.st_mode))
915  {
916  if (unlink(linkloc) < 0 && errno != ENOENT)
917  ereport(ERROR,
919  errmsg("could not remove symbolic link \"%s\": %m",
920  linkloc)));
921  }
922 #endif
923  else
924  {
925  /* Refuse to remove anything that's not a directory or symlink */
926  ereport(ERROR,
927  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
928  errmsg("\"%s\" is not a directory or symbolic link",
929  linkloc)));
930  }
931 }
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
int errcode_for_file_access(void)
Definition: elog.c:727
#define ereport(elevel,...)
Definition: elog.h:155
#define S_ISDIR(m)
Definition: win32_port.h:316
#define lstat(path, sb)
Definition: win32_port.h:276
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ RenameTableSpace()

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

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

938 {
939  Oid tspId;
940  Relation rel;
941  ScanKeyData entry[1];
942  TableScanDesc scan;
943  HeapTuple tup;
944  HeapTuple newtuple;
945  Form_pg_tablespace newform;
946  ObjectAddress address;
947 
948  /* Search pg_tablespace */
949  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
950 
951  ScanKeyInit(&entry[0],
952  Anum_pg_tablespace_spcname,
953  BTEqualStrategyNumber, F_NAMEEQ,
954  CStringGetDatum(oldname));
955  scan = table_beginscan_catalog(rel, 1, entry);
956  tup = heap_getnext(scan, ForwardScanDirection);
957  if (!HeapTupleIsValid(tup))
958  ereport(ERROR,
959  (errcode(ERRCODE_UNDEFINED_OBJECT),
960  errmsg("tablespace \"%s\" does not exist",
961  oldname)));
962 
963  newtuple = heap_copytuple(tup);
964  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
965  tspId = newform->oid;
966 
967  table_endscan(scan);
968 
969  /* Must be owner */
970  if (!pg_tablespace_ownercheck(tspId, GetUserId()))
972 
973  /* Validate new name */
974  if (!allowSystemTableMods && IsReservedName(newname))
975  ereport(ERROR,
976  (errcode(ERRCODE_RESERVED_NAME),
977  errmsg("unacceptable tablespace name \"%s\"", newname),
978  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
979 
980  /*
981  * If built with appropriate switch, whine when regression-testing
982  * conventions for tablespace names are violated.
983  */
984 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
985  if (strncmp(newname, "regress_", 8) != 0)
986  elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
987 #endif
988 
989  /* Make sure the new name doesn't exist */
990  ScanKeyInit(&entry[0],
991  Anum_pg_tablespace_spcname,
992  BTEqualStrategyNumber, F_NAMEEQ,
993  CStringGetDatum(newname));
994  scan = table_beginscan_catalog(rel, 1, entry);
995  tup = heap_getnext(scan, ForwardScanDirection);
996  if (HeapTupleIsValid(tup))
997  ereport(ERROR,
999  errmsg("tablespace \"%s\" already exists",
1000  newname)));
1001 
1002  table_endscan(scan);
1003 
1004  /* OK, update the entry */
1005  namestrcpy(&(newform->spcname), newname);
1006 
1007  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1008 
1009  InvokeObjectPostAlterHook(TableSpaceRelationId, tspId, 0);
1010 
1011  ObjectAddressSet(address, TableSpaceRelationId, tspId);
1012 
1013  table_close(rel, NoLock);
1014 
1015  return address;
1016 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
Oid GetUserId(void)
Definition: miscinit.c:476
void namestrcpy(Name name, const char *str)
Definition: name.c:233
int errcode(int sqlerrcode)
Definition: elog.c:704
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:210
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define ERROR
Definition: elog.h:45
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1304
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#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:4889
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define WARNING
Definition: elog.h:40
bool allowSystemTableMods
Definition: globals.c:121
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:962
int errmsg(const char *fmt,...)
Definition: elog.c:915
#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:32
#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, stat::st_mode, 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:1187
int errcode(int sqlerrcode)
Definition: elog.c:704
#define OidIsValid(objectId)
Definition: c.h:698
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1810
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
int errcode_for_file_access(void)
Definition: elog.c:727
void get_parent_directory(char *path)
Definition: path.c:854
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
#define ereport(elevel,...)
Definition: elog.h:155
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3612
#define Assert(condition)
Definition: c.h:792
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
#define S_ISDIR(m)
Definition: win32_port.h:316
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define stat
Definition: win32_port.h:275

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

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