PostgreSQL Source Code  git master
tablespace.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_tablespace.h"
#include "commands/comment.h"
#include "commands/seclabel.h"
#include "commands/tablecmds.h"
#include "commands/tablespace.h"
#include "common/file_perm.h"
#include "miscadmin.h"
#include "postmaster/bgwriter.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#include "storage/standby.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/varlena.h"
Include dependency graph for tablespace.c:

Go to the source code of this file.

Data Structures

struct  temp_tablespaces_extra
 

Functions

static void create_tablespace_directories (const char *location, const Oid tablespaceoid)
 
static bool destroy_tablespace_directories (Oid tablespaceoid, bool redo)
 
void TablespaceCreateDbspace (Oid spcNode, Oid dbNode, bool isRedo)
 
Oid CreateTableSpace (CreateTableSpaceStmt *stmt)
 
void DropTableSpace (DropTableSpaceStmt *stmt)
 
bool directory_is_empty (const char *path)
 
void remove_tablespace_symlink (const char *linkloc)
 
ObjectAddress RenameTableSpace (const char *oldname, const char *newname)
 
Oid AlterTableSpaceOptions (AlterTableSpaceOptionsStmt *stmt)
 
bool check_default_tablespace (char **newval, void **extra, GucSource source)
 
Oid GetDefaultTablespace (char relpersistence, bool partitioned)
 
bool check_temp_tablespaces (char **newval, void **extra, GucSource source)
 
void assign_temp_tablespaces (const char *newval, void *extra)
 
void PrepareTempTablespaces (void)
 
Oid get_tablespace_oid (const char *tablespacename, bool missing_ok)
 
char * get_tablespace_name (Oid spc_oid)
 
void tblspc_redo (XLogReaderState *record)
 

Variables

char * default_tablespace = NULL
 
char * temp_tablespaces = NULL
 

Function Documentation

◆ AlterTableSpaceOptions()

Oid AlterTableSpaceOptions ( AlterTableSpaceOptionsStmt stmt)

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

1021 {
1022  Relation rel;
1023  ScanKeyData entry[1];
1024  TableScanDesc scandesc;
1025  HeapTuple tup;
1026  Oid tablespaceoid;
1027  Datum datum;
1028  Datum newOptions;
1029  Datum repl_val[Natts_pg_tablespace];
1030  bool isnull;
1031  bool repl_null[Natts_pg_tablespace];
1032  bool repl_repl[Natts_pg_tablespace];
1033  HeapTuple newtuple;
1034 
1035  /* Search pg_tablespace */
1036  rel = table_open(TableSpaceRelationId, RowExclusiveLock);
1037 
1038  ScanKeyInit(&entry[0],
1039  Anum_pg_tablespace_spcname,
1040  BTEqualStrategyNumber, F_NAMEEQ,
1042  scandesc = table_beginscan_catalog(rel, 1, entry);
1043  tup = heap_getnext(scandesc, ForwardScanDirection);
1044  if (!HeapTupleIsValid(tup))
1045  ereport(ERROR,
1046  (errcode(ERRCODE_UNDEFINED_OBJECT),
1047  errmsg("tablespace \"%s\" does not exist",
1048  stmt->tablespacename)));
1049 
1050  tablespaceoid = ((Form_pg_tablespace) GETSTRUCT(tup))->oid;
1051 
1052  /* Must be owner of the existing object */
1053  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
1055  stmt->tablespacename);
1056 
1057  /* Generate new proposed spcoptions (text array) */
1058  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1059  RelationGetDescr(rel), &isnull);
1060  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1061  stmt->options, NULL, NULL, false,
1062  stmt->isReset);
1063  (void) tablespace_reloptions(newOptions, true);
1064 
1065  /* Build new tuple. */
1066  memset(repl_null, false, sizeof(repl_null));
1067  memset(repl_repl, false, sizeof(repl_repl));
1068  if (newOptions != (Datum) 0)
1069  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1070  else
1071  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1072  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1073  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1074  repl_null, repl_repl);
1075 
1076  /* Update system catalog. */
1077  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1078 
1079  InvokeObjectPostAlterHook(TableSpaceRelationId, tablespaceoid, 0);
1080 
1081  heap_freetuple(newtuple);
1082 
1083  /* Conclude heap scan. */
1084  table_endscan(scandesc);
1085  table_close(rel, NoLock);
1086 
1087  return tablespaceoid;
1088 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1149
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2079
int errcode(int sqlerrcode)
Definition: elog.c:698
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:3308
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:5020
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:761
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
int errmsg(const char *fmt,...)
Definition: elog.c:909
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

◆ assign_temp_tablespaces()

void assign_temp_tablespaces ( const char *  newval,
void *  extra 
)

Definition at line 1311 of file tablespace.c.

References temp_tablespaces_extra::numSpcs, SetTempTablespaces(), and temp_tablespaces_extra::tblSpcs.

1312 {
1313  temp_tablespaces_extra *myextra = (temp_tablespaces_extra *) extra;
1314 
1315  /*
1316  * If check_temp_tablespaces was executed inside a transaction, then pass
1317  * the list it made to fd.c. Otherwise, clear fd.c's list; we must be
1318  * still outside a transaction, or else restoring during transaction exit,
1319  * and in either case we can just let the next PrepareTempTablespaces call
1320  * make things sane.
1321  */
1322  if (myextra)
1323  SetTempTablespaces(myextra->tblSpcs, myextra->numSpcs);
1324  else
1325  SetTempTablespaces(NULL, 0);
1326 }
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1198
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2884

◆ check_default_tablespace()

bool check_default_tablespace ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 1096 of file tablespace.c.

References ereport, errcode(), errmsg(), get_tablespace_oid(), GUC_check_errdetail, InvalidOid, IsTransactionState(), MyDatabaseId, NOTICE, OidIsValid, and PGC_S_TEST.

1097 {
1098  /*
1099  * If we aren't inside a transaction, or connected to a database, we
1100  * cannot do the catalog accesses necessary to verify the name. Must
1101  * accept the value on faith.
1102  */
1104  {
1105  if (**newval != '\0' &&
1107  {
1108  /*
1109  * When source == PGC_S_TEST, don't throw a hard error for a
1110  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1111  */
1112  if (source == PGC_S_TEST)
1113  {
1114  ereport(NOTICE,
1115  (errcode(ERRCODE_UNDEFINED_OBJECT),
1116  errmsg("tablespace \"%s\" does not exist",
1117  *newval)));
1118  }
1119  else
1120  {
1121  GUC_check_errdetail("Tablespace \"%s\" does not exist.",
1122  *newval);
1123  return false;
1124  }
1125  }
1126  }
1127 
1128  return true;
1129 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1431
#define GUC_check_errdetail
Definition: guc.h:416
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
Oid MyDatabaseId
Definition: globals.c:88
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
static rewind_source * source
Definition: pg_rewind.c:79
#define newval
bool IsTransactionState(void)
Definition: xact.c:371
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ check_temp_tablespaces()

bool check_temp_tablespaces ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 1203 of file tablespace.c.

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg(), get_tablespace_oid(), GetUserId(), GUC_check_errdetail, InvalidOid, IsTransactionState(), lfirst, list_free(), list_length(), malloc, MyDatabaseId, MyDatabaseTableSpace, NOTICE, temp_tablespaces_extra::numSpcs, OBJECT_TABLESPACE, offsetof, palloc(), pfree(), pg_tablespace_aclcheck(), PGC_S_INTERACTIVE, PGC_S_TEST, pstrdup(), SplitIdentifierString(), and temp_tablespaces_extra::tblSpcs.

1204 {
1205  char *rawname;
1206  List *namelist;
1207 
1208  /* Need a modifiable copy of string */
1209  rawname = pstrdup(*newval);
1210 
1211  /* Parse string into list of identifiers */
1212  if (!SplitIdentifierString(rawname, ',', &namelist))
1213  {
1214  /* syntax error in name list */
1215  GUC_check_errdetail("List syntax is invalid.");
1216  pfree(rawname);
1217  list_free(namelist);
1218  return false;
1219  }
1220 
1221  /*
1222  * If we aren't inside a transaction, or connected to a database, we
1223  * cannot do the catalog accesses necessary to verify the name. Must
1224  * accept the value on faith. Fortunately, there's then also no need to
1225  * pass the data to fd.c.
1226  */
1228  {
1229  temp_tablespaces_extra *myextra;
1230  Oid *tblSpcs;
1231  int numSpcs;
1232  ListCell *l;
1233 
1234  /* temporary workspace until we are done verifying the list */
1235  tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1236  numSpcs = 0;
1237  foreach(l, namelist)
1238  {
1239  char *curname = (char *) lfirst(l);
1240  Oid curoid;
1241  AclResult aclresult;
1242 
1243  /* Allow an empty string (signifying database default) */
1244  if (curname[0] == '\0')
1245  {
1246  /* InvalidOid signifies database's default tablespace */
1247  tblSpcs[numSpcs++] = InvalidOid;
1248  continue;
1249  }
1250 
1251  /*
1252  * In an interactive SET command, we ereport for bad info. When
1253  * source == PGC_S_TEST, don't throw a hard error for a
1254  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1255  */
1256  curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
1257  if (curoid == InvalidOid)
1258  {
1259  if (source == PGC_S_TEST)
1260  ereport(NOTICE,
1261  (errcode(ERRCODE_UNDEFINED_OBJECT),
1262  errmsg("tablespace \"%s\" does not exist",
1263  curname)));
1264  continue;
1265  }
1266 
1267  /*
1268  * Allow explicit specification of database's default tablespace
1269  * in temp_tablespaces without triggering permissions checks.
1270  */
1271  if (curoid == MyDatabaseTableSpace)
1272  {
1273  /* InvalidOid signifies database's default tablespace */
1274  tblSpcs[numSpcs++] = InvalidOid;
1275  continue;
1276  }
1277 
1278  /* Check permissions, similarly complaining only if interactive */
1279  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1280  ACL_CREATE);
1281  if (aclresult != ACLCHECK_OK)
1282  {
1283  if (source >= PGC_S_INTERACTIVE)
1284  aclcheck_error(aclresult, OBJECT_TABLESPACE, curname);
1285  continue;
1286  }
1287 
1288  tblSpcs[numSpcs++] = curoid;
1289  }
1290 
1291  /* Now prepare an "extra" struct for assign_temp_tablespaces */
1292  myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
1293  numSpcs * sizeof(Oid));
1294  if (!myextra)
1295  return false;
1296  myextra->numSpcs = numSpcs;
1297  memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1298  *extra = (void *) myextra;
1299 
1300  pfree(tblSpcs);
1301  }
1302 
1303  pfree(rawname);
1304  list_free(namelist);
1305 
1306  return true;
1307 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1431
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4768
Oid GetUserId(void)
Definition: miscinit.c:478
#define GUC_check_errdetail
Definition: guc.h:416
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:90
#define malloc(a)
Definition: header.h:50
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ACL_CREATE
Definition: parsenodes.h:92
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3753
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1198
AclResult
Definition: acl.h:177
Oid MyDatabaseId
Definition: globals.c:88
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define lfirst(lc)
Definition: pg_list.h:169
static rewind_source * source
Definition: pg_rewind.c:79
static int list_length(const List *l)
Definition: pg_list.h:149
#define newval
bool IsTransactionState(void)
Definition: xact.c:371
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
Definition: pg_list.h:50
#define offsetof(type, field)
Definition: c.h:727

◆ create_tablespace_directories()

static void create_tablespace_directories ( const char *  location,
const Oid  tablespaceoid 
)
static

Definition at line 588 of file tablespace.c.

References ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, InRecovery, MakePGDirectory(), pfree(), pg_dir_create_mode, psprintf(), remove_tablespace_symlink(), rmtree(), S_ISDIR, stat::st_mode, stat, symlink, TABLESPACE_VERSION_DIRECTORY, and WARNING.

Referenced by CreateTableSpace(), and tblspc_redo().

589 {
590  char *linkloc;
591  char *location_with_version_dir;
592  struct stat st;
593 
594  linkloc = psprintf("pg_tblspc/%u", tablespaceoid);
595  location_with_version_dir = psprintf("%s/%s", location,
597 
598  /*
599  * Attempt to coerce target directory to safe permissions. If this fails,
600  * it doesn't exist or has the wrong owner.
601  */
602  if (chmod(location, pg_dir_create_mode) != 0)
603  {
604  if (errno == ENOENT)
605  ereport(ERROR,
606  (errcode(ERRCODE_UNDEFINED_FILE),
607  errmsg("directory \"%s\" does not exist", location),
608  InRecovery ? errhint("Create this directory for the tablespace before "
609  "restarting the server.") : 0));
610  else
611  ereport(ERROR,
613  errmsg("could not set permissions on directory \"%s\": %m",
614  location)));
615  }
616 
617  if (InRecovery)
618  {
619  /*
620  * Our theory for replaying a CREATE is to forcibly drop the target
621  * subdirectory if present, and then recreate it. This may be more
622  * work than needed, but it is simple to implement.
623  */
624  if (stat(location_with_version_dir, &st) == 0 && S_ISDIR(st.st_mode))
625  {
626  if (!rmtree(location_with_version_dir, true))
627  /* If this failed, MakePGDirectory() below is going to error. */
629  (errmsg("some useless files may be left behind in old database directory \"%s\"",
630  location_with_version_dir)));
631  }
632  }
633 
634  /*
635  * The creation of the version directory prevents more than one tablespace
636  * in a single location.
637  */
638  if (MakePGDirectory(location_with_version_dir) < 0)
639  {
640  if (errno == EEXIST)
641  ereport(ERROR,
642  (errcode(ERRCODE_OBJECT_IN_USE),
643  errmsg("directory \"%s\" already in use as a tablespace",
644  location_with_version_dir)));
645  else
646  ereport(ERROR,
648  errmsg("could not create directory \"%s\": %m",
649  location_with_version_dir)));
650  }
651 
652  /*
653  * In recovery, remove old symlink, in case it points to the wrong place.
654  */
655  if (InRecovery)
656  remove_tablespace_symlink(linkloc);
657 
658  /*
659  * Create the symlink under PGDATA
660  */
661  if (symlink(location, linkloc) < 0)
662  ereport(ERROR,
664  errmsg("could not create symbolic link \"%s\": %m",
665  linkloc)));
666 
667  pfree(linkloc);
668  pfree(location_with_version_dir);
669 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:698
void remove_tablespace_symlink(const char *linkloc)
Definition: tablespace.c:886
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
#define symlink(oldpath, newpath)
Definition: win32_port.h:227
int errcode_for_file_access(void)
Definition: elog.c:721
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
int pg_dir_create_mode
Definition: file_perm.c:18
#define ereport(elevel,...)
Definition: elog.h:157
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3735
bool InRecovery
Definition: xlogutils.c:52
#define S_ISDIR(m)
Definition: win32_port.h:316
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define stat
Definition: win32_port.h:275

◆ 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, 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:1431
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
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:1156
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool acceptOidsOff, bool isReset)
Definition: reloptions.c:1149
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
Oid GetUserId(void)
Definition: miscinit.c:478
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
char * pstrdup(const char *in)
Definition: mcxt.c:1299
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:2079
void ForceSyncCommit(void)
Definition: xact.c:1071
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
#define MemSet(start, val, len)
Definition: c.h:1008
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:163
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:218
#define OidIsValid(objectId)
Definition: c.h:710
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#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:1042
#define is_absolute_path(filename)
Definition: port.h:86
#define CStringGetDatum(X)
Definition: postgres.h:622
#define WARNING
Definition: elog.h:40
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:432
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition: tablespace.c:588
uintptr_t Datum
Definition: postgres.h:411
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5128
TupleDesc rd_att
Definition: rel.h:110
bool allowSystemTableMods
Definition: globals.c:123
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define FORKNAMECHARS
Definition: relpath.h:57
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
char * DataDir
Definition: globals.c:65
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:135
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define OIDCHARS
Definition: relpath.h:30
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define offsetof(type, field)
Definition: c.h:727

◆ destroy_tablespace_directories()

static bool destroy_tablespace_directories ( Oid  tablespaceoid,
bool  redo 
)
static

Definition at line 686 of file tablespace.c.

References AllocateDir(), dirent::d_name, directory_is_empty(), ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FreeDir(), get_parent_directory(), LOG, lstat, pfree(), psprintf(), pstrdup(), ReadDir(), S_ISDIR, stat::st_mode, TABLESPACE_VERSION_DIRECTORY, and WARNING.

Referenced by DropTableSpace(), and tblspc_redo().

687 {
688  char *linkloc;
689  char *linkloc_with_version_dir;
690  DIR *dirdesc;
691  struct dirent *de;
692  char *subfile;
693  struct stat st;
694 
695  linkloc_with_version_dir = psprintf("pg_tblspc/%u/%s", tablespaceoid,
697 
698  /*
699  * Check if the tablespace still contains any files. We try to rmdir each
700  * per-database directory we find in it. rmdir failure implies there are
701  * still files in that subdirectory, so give up. (We do not have to worry
702  * about undoing any already completed rmdirs, since the next attempt to
703  * use the tablespace from that database will simply recreate the
704  * subdirectory via TablespaceCreateDbspace.)
705  *
706  * Since we hold TablespaceCreateLock, no one else should be creating any
707  * fresh subdirectories in parallel. It is possible that new files are
708  * being created within subdirectories, though, so the rmdir call could
709  * fail. Worst consequence is a less friendly error message.
710  *
711  * If redo is true then ENOENT is a likely outcome here, and we allow it
712  * to pass without comment. In normal operation we still allow it, but
713  * with a warning. This is because even though ProcessUtility disallows
714  * DROP TABLESPACE in a transaction block, it's possible that a previous
715  * DROP failed and rolled back after removing the tablespace directories
716  * and/or symlink. We want to allow a new DROP attempt to succeed at
717  * removing the catalog entries (and symlink if still present), so we
718  * should not give a hard error here.
719  */
720  dirdesc = AllocateDir(linkloc_with_version_dir);
721  if (dirdesc == NULL)
722  {
723  if (errno == ENOENT)
724  {
725  if (!redo)
728  errmsg("could not open directory \"%s\": %m",
729  linkloc_with_version_dir)));
730  /* The symlink might still exist, so go try to remove it */
731  goto remove_symlink;
732  }
733  else if (redo)
734  {
735  /* in redo, just log other types of error */
736  ereport(LOG,
738  errmsg("could not open directory \"%s\": %m",
739  linkloc_with_version_dir)));
740  pfree(linkloc_with_version_dir);
741  return false;
742  }
743  /* else let ReadDir report the error */
744  }
745 
746  while ((de = ReadDir(dirdesc, linkloc_with_version_dir)) != NULL)
747  {
748  if (strcmp(de->d_name, ".") == 0 ||
749  strcmp(de->d_name, "..") == 0)
750  continue;
751 
752  subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
753 
754  /* This check is just to deliver a friendlier error message */
755  if (!redo && !directory_is_empty(subfile))
756  {
757  FreeDir(dirdesc);
758  pfree(subfile);
759  pfree(linkloc_with_version_dir);
760  return false;
761  }
762 
763  /* remove empty directory */
764  if (rmdir(subfile) < 0)
765  ereport(redo ? LOG : ERROR,
767  errmsg("could not remove directory \"%s\": %m",
768  subfile)));
769 
770  pfree(subfile);
771  }
772 
773  FreeDir(dirdesc);
774 
775  /* remove version directory */
776  if (rmdir(linkloc_with_version_dir) < 0)
777  {
778  ereport(redo ? LOG : ERROR,
780  errmsg("could not remove directory \"%s\": %m",
781  linkloc_with_version_dir)));
782  pfree(linkloc_with_version_dir);
783  return false;
784  }
785 
786  /*
787  * Try to remove the symlink. We must however deal with the possibility
788  * that it's a directory instead of a symlink --- this could happen during
789  * WAL replay (see TablespaceCreateDbspace), and it is also the case on
790  * Windows where junction points lstat() as directories.
791  *
792  * Note: in the redo case, we'll return true if this final step fails;
793  * there's no point in retrying it. Also, ENOENT should provoke no more
794  * than a warning.
795  */
796 remove_symlink:
797  linkloc = pstrdup(linkloc_with_version_dir);
798  get_parent_directory(linkloc);
799  if (lstat(linkloc, &st) < 0)
800  {
801  int saved_errno = errno;
802 
803  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
805  errmsg("could not stat file \"%s\": %m",
806  linkloc)));
807  }
808  else if (S_ISDIR(st.st_mode))
809  {
810  if (rmdir(linkloc) < 0)
811  {
812  int saved_errno = errno;
813 
814  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
816  errmsg("could not remove directory \"%s\": %m",
817  linkloc)));
818  }
819  }
820 #ifdef S_ISLNK
821  else if (S_ISLNK(st.st_mode))
822  {
823  if (unlink(linkloc) < 0)
824  {
825  int saved_errno = errno;
826 
827  ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
829  errmsg("could not remove symbolic link \"%s\": %m",
830  linkloc)));
831  }
832  }
833 #endif
834  else
835  {
836  /* Refuse to remove anything that's not a directory or symlink */
837  ereport(redo ? LOG : ERROR,
838  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
839  errmsg("\"%s\" is not a directory or symbolic link",
840  linkloc)));
841  }
842 
843  pfree(linkloc_with_version_dir);
844  pfree(linkloc);
845 
846  return true;
847 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:698
bool directory_is_empty(const char *path)
Definition: tablespace.c:856
#define LOG
Definition: elog.h:26
Definition: dirent.h:9
void pfree(void *pointer)
Definition: mcxt.c:1169
Definition: dirent.c:25
#define ERROR
Definition: elog.h:46
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
int errcode_for_file_access(void)
Definition: elog.c:721
void get_parent_directory(char *path)
Definition: path.c:854
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2678
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2744
#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:909
char d_name[MAX_PATH]
Definition: dirent.h:15
int FreeDir(DIR *dir)
Definition: fd.c:2796

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 856 of file tablespace.c.

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

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

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

◆ 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, IsPinnedObject(), 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  table_endscan(scandesc);
453  table_close(rel, NoLock);
454  }
455  return;
456  }
457 
458  spcform = (Form_pg_tablespace) GETSTRUCT(tuple);
459  tablespaceoid = spcform->oid;
460 
461  /* Must be tablespace owner */
462  if (!pg_tablespace_ownercheck(tablespaceoid, GetUserId()))
464  tablespacename);
465 
466  /* Disallow drop of the standard tablespaces, even by superuser */
467  if (IsPinnedObject(TableSpaceRelationId, tablespaceoid))
469  tablespacename);
470 
471  /* Check for pg_shdepend entries depending on this tablespace */
472  if (checkSharedDependencies(TableSpaceRelationId, tablespaceoid,
473  &detail, &detail_log))
474  ereport(ERROR,
475  (errcode(ERRCODE_DEPENDENT_OBJECTS_STILL_EXIST),
476  errmsg("tablespace \"%s\" cannot be dropped because some objects depend on it",
477  tablespacename),
478  errdetail_internal("%s", detail),
479  errdetail_log("%s", detail_log)));
480 
481  /* DROP hook for the tablespace being removed */
482  InvokeObjectDropHook(TableSpaceRelationId, tablespaceoid, 0);
483 
484  /*
485  * Remove the pg_tablespace tuple (this will roll back if we fail below)
486  */
487  CatalogTupleDelete(rel, &tuple->t_self);
488 
489  table_endscan(scandesc);
490 
491  /*
492  * Remove any comments or security labels on this tablespace.
493  */
494  DeleteSharedComments(tablespaceoid, TableSpaceRelationId);
495  DeleteSharedSecurityLabel(tablespaceoid, TableSpaceRelationId);
496 
497  /*
498  * Remove dependency on owner.
499  */
500  deleteSharedDependencyRecordsFor(TableSpaceRelationId, tablespaceoid, 0);
501 
502  /*
503  * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
504  * is running concurrently.
505  */
506  LWLockAcquire(TablespaceCreateLock, LW_EXCLUSIVE);
507 
508  /*
509  * Try to remove the physical infrastructure.
510  */
511  if (!destroy_tablespace_directories(tablespaceoid, false))
512  {
513  /*
514  * Not all files deleted? However, there can be lingering empty files
515  * in the directories, left behind by for example DROP TABLE, that
516  * have been scheduled for deletion at next checkpoint (see comments
517  * in mdunlink() for details). We could just delete them immediately,
518  * but we can't tell them apart from important data files that we
519  * mustn't delete. So instead, we force a checkpoint which will clean
520  * out any lingering files, and try again.
521  *
522  * XXX On Windows, an unlinked file persists in the directory listing
523  * until no process retains an open handle for the file. The DDL
524  * commands that schedule files for unlink send invalidation messages
525  * directing other PostgreSQL processes to close the files. DROP
526  * TABLESPACE should not give up on the tablespace becoming empty
527  * until all relevant invalidation processing is complete.
528  */
530  if (!destroy_tablespace_directories(tablespaceoid, false))
531  {
532  /* Still not empty, the files must be important then */
533  ereport(ERROR,
534  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
535  errmsg("tablespace \"%s\" is not empty",
536  tablespacename)));
537  }
538  }
539 
540  /* Record the filesystem change in XLOG */
541  {
542  xl_tblspc_drop_rec xlrec;
543 
544  xlrec.ts_id = tablespaceoid;
545 
546  XLogBeginInsert();
547  XLogRegisterData((char *) &xlrec, sizeof(xl_tblspc_drop_rec));
548 
549  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP);
550  }
551 
552  /*
553  * Note: because we checked that the tablespace was empty, there should be
554  * no need to worry about flushing shared buffers or free space map
555  * entries for relations in the tablespace.
556  */
557 
558  /*
559  * Force synchronous commit, to minimize the window between removing the
560  * files on-disk and marking the transaction committed. It's not great
561  * that there is any window at all, but definitely we don't want to make
562  * it larger than necessary.
563  */
564  ForceSyncCommit();
565 
566  /*
567  * Allow TablespaceCreateDbspace again.
568  */
569  LWLockRelease(TablespaceCreateLock);
570 
571  /* We keep the lock on pg_tablespace until commit */
572  table_close(rel, NoLock);
573 #else /* !HAVE_SYMLINK */
574  ereport(ERROR,
575  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
576  errmsg("tablespaces are not supported on this platform")));
577 #endif /* HAVE_SYMLINK */
578 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
Oid GetUserId(void)
Definition: miscinit.c:478
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
void ForceSyncCommit(void)
Definition: xact.c:1071
int errcode(int sqlerrcode)
Definition: elog.c:698
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
unsigned int Oid
Definition: postgres_ext.h:31
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
bool IsPinnedObject(Oid classId, Oid objectId)
Definition: catalog.c:307
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:48
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:5020
int errdetail_log(const char *fmt,...)
Definition: elog.c:1090
#define CHECKPOINT_FORCE
Definition: xlog.h:200
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:997
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:432
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define CHECKPOINT_WAIT
Definition: xlog.h:204
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void DeleteSharedComments(Oid oid, Oid classoid)
Definition: comment.c:374
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition: tablespace.c:686
#define XLOG_TBLSPC_DROP
Definition: tablespace.h:24
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition: seclabel.c:489
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199
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:629
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void XLogBeginInsert(void)
Definition: xloginsert.c:135
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void RequestCheckpoint(int flags)
Definition: checkpointer.c:924

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

Definition at line 1477 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(), ExecReindex(), generateClonedIndexStmt(), getObjectDescription(), getObjectIdentityParts(), pg_get_constraintdef_worker(), pg_get_indexdef_worker(), ReindexMultipleInternal(), ReindexRelationConcurrently(), and shdepLockAndCheckObject().

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

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

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

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

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

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

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

887 {
888  struct stat st;
889 
890  if (lstat(linkloc, &st) < 0)
891  {
892  if (errno == ENOENT)
893  return;
894  ereport(ERROR,
896  errmsg("could not stat file \"%s\": %m", linkloc)));
897  }
898 
899  if (S_ISDIR(st.st_mode))
900  {
901  /*
902  * This will fail if the directory isn't empty, but not if it's a
903  * junction point.
904  */
905  if (rmdir(linkloc) < 0 && errno != ENOENT)
906  ereport(ERROR,
908  errmsg("could not remove directory \"%s\": %m",
909  linkloc)));
910  }
911 #ifdef S_ISLNK
912  else if (S_ISLNK(st.st_mode))
913  {
914  if (unlink(linkloc) < 0 && errno != ENOENT)
915  ereport(ERROR,
917  errmsg("could not remove symbolic link \"%s\": %m",
918  linkloc)));
919  }
920 #endif
921  else
922  {
923  /* Refuse to remove anything that's not a directory or symlink */
924  ereport(ERROR,
925  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
926  errmsg("\"%s\" is not a directory or symbolic link",
927  linkloc)));
928  }
929 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
#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:909

◆ RenameTableSpace()

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

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

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

◆ tblspc_redo()

void tblspc_redo ( XLogReaderState record)

Definition at line 1516 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.

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

Variable Documentation

◆ default_tablespace

char* default_tablespace = NULL

Definition at line 88 of file tablespace.c.

Referenced by GetDefaultTablespace().

◆ temp_tablespaces

char* temp_tablespaces = NULL

Definition at line 89 of file tablespace.c.

Referenced by PrepareTempTablespaces().