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/reloptions.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.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/tqual.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 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 988 of file tablespace.c.

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

Referenced by standard_ProcessUtility().

989 {
990  Relation rel;
991  ScanKeyData entry[1];
992  HeapScanDesc scandesc;
993  HeapTuple tup;
994  Oid tablespaceoid;
995  Datum datum;
996  Datum newOptions;
997  Datum repl_val[Natts_pg_tablespace];
998  bool isnull;
999  bool repl_null[Natts_pg_tablespace];
1000  bool repl_repl[Natts_pg_tablespace];
1001  HeapTuple newtuple;
1002 
1003  /* Search pg_tablespace */
1004  rel = heap_open(TableSpaceRelationId, RowExclusiveLock);
1005 
1006  ScanKeyInit(&entry[0],
1007  Anum_pg_tablespace_spcname,
1008  BTEqualStrategyNumber, F_NAMEEQ,
1010  scandesc = heap_beginscan_catalog(rel, 1, entry);
1011  tup = heap_getnext(scandesc, ForwardScanDirection);
1012  if (!HeapTupleIsValid(tup))
1013  ereport(ERROR,
1014  (errcode(ERRCODE_UNDEFINED_OBJECT),
1015  errmsg("tablespace \"%s\" does not exist",
1016  stmt->tablespacename)));
1017 
1018  tablespaceoid = HeapTupleGetOid(tup);
1019 
1020  /* Must be owner of the existing object */
1023  stmt->tablespacename);
1024 
1025  /* Generate new proposed spcoptions (text array) */
1026  datum = heap_getattr(tup, Anum_pg_tablespace_spcoptions,
1027  RelationGetDescr(rel), &isnull);
1028  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1029  stmt->options, NULL, NULL, false,
1030  stmt->isReset);
1031  (void) tablespace_reloptions(newOptions, true);
1032 
1033  /* Build new tuple. */
1034  memset(repl_null, false, sizeof(repl_null));
1035  memset(repl_repl, false, sizeof(repl_repl));
1036  if (newOptions != (Datum) 0)
1037  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1038  else
1039  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1040  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1041  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1042  repl_null, repl_repl);
1043 
1044  /* Update system catalog. */
1045  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1046 
1047  InvokeObjectPostAlterHook(TableSpaceRelationId, HeapTupleGetOid(tup), 0);
1048 
1049  heap_freetuple(newtuple);
1050 
1051  /* Conclude heap scan. */
1052  heap_endscan(scandesc);
1053  heap_close(rel, NoLock);
1054 
1055  return tablespaceoid;
1056 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1572
#define RelationGetDescr(relation)
Definition: rel.h:433
Oid GetUserId(void)
Definition: miscinit.c:379
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1558
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1773
unsigned int Oid
Definition: postgres_ext.h:31
Datum transformRelOptions(Datum oldOptions, List *defList, const char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:773
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3348
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:561
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4950
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1412
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:786
uintptr_t Datum
Definition: postgres.h:365
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1835
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1294
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:211
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:712
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1173
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ assign_temp_tablespaces()

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

Definition at line 1264 of file tablespace.c.

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

1265 {
1266  temp_tablespaces_extra *myextra = (temp_tablespaces_extra *) extra;
1267 
1268  /*
1269  * If check_temp_tablespaces was executed inside a transaction, then pass
1270  * the list it made to fd.c. Otherwise, clear fd.c's list; we must be
1271  * still outside a transaction, or else restoring during transaction exit,
1272  * and in either case we can just let the next PrepareTempTablespaces call
1273  * make things sane.
1274  */
1275  if (myextra)
1276  SetTempTablespaces(myextra->tblSpcs, myextra->numSpcs);
1277  else
1278  SetTempTablespaces(NULL, 0);
1279 }
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1154
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition: fd.c:2803

◆ check_default_tablespace()

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

Definition at line 1064 of file tablespace.c.

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

1065 {
1066  /*
1067  * If we aren't inside a transaction, we cannot do database access so
1068  * cannot verify the name. Must accept the value on faith.
1069  */
1070  if (IsTransactionState())
1071  {
1072  if (**newval != '\0' &&
1074  {
1075  /*
1076  * When source == PGC_S_TEST, don't throw a hard error for a
1077  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1078  */
1079  if (source == PGC_S_TEST)
1080  {
1081  ereport(NOTICE,
1082  (errcode(ERRCODE_UNDEFINED_OBJECT),
1083  errmsg("tablespace \"%s\" does not exist",
1084  *newval)));
1085  }
1086  else
1087  {
1088  GUC_check_errdetail("Tablespace \"%s\" does not exist.",
1089  *newval);
1090  return false;
1091  }
1092  }
1093  }
1094 
1095  return true;
1096 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1382
#define GUC_check_errdetail
Definition: guc.h:410
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:605
#define ereport(elevel, rest)
Definition: elog.h:122
#define NOTICE
Definition: elog.h:37
#define newval
bool IsTransactionState(void)
Definition: xact.c:350
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ check_temp_tablespaces()

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

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

1160 {
1161  char *rawname;
1162  List *namelist;
1163 
1164  /* Need a modifiable copy of string */
1165  rawname = pstrdup(*newval);
1166 
1167  /* Parse string into list of identifiers */
1168  if (!SplitIdentifierString(rawname, ',', &namelist))
1169  {
1170  /* syntax error in name list */
1171  GUC_check_errdetail("List syntax is invalid.");
1172  pfree(rawname);
1173  list_free(namelist);
1174  return false;
1175  }
1176 
1177  /*
1178  * If we aren't inside a transaction, we cannot do database access so
1179  * cannot verify the individual names. Must accept the list on faith.
1180  * Fortunately, there's then also no need to pass the data to fd.c.
1181  */
1182  if (IsTransactionState())
1183  {
1184  temp_tablespaces_extra *myextra;
1185  Oid *tblSpcs;
1186  int numSpcs;
1187  ListCell *l;
1188 
1189  /* temporary workspace until we are done verifying the list */
1190  tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1191  numSpcs = 0;
1192  foreach(l, namelist)
1193  {
1194  char *curname = (char *) lfirst(l);
1195  Oid curoid;
1196  AclResult aclresult;
1197 
1198  /* Allow an empty string (signifying database default) */
1199  if (curname[0] == '\0')
1200  {
1201  tblSpcs[numSpcs++] = InvalidOid;
1202  continue;
1203  }
1204 
1205  /*
1206  * In an interactive SET command, we ereport for bad info. When
1207  * source == PGC_S_TEST, don't throw a hard error for a
1208  * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1209  */
1210  curoid = get_tablespace_oid(curname, source <= PGC_S_TEST);
1211  if (curoid == InvalidOid)
1212  {
1213  if (source == PGC_S_TEST)
1214  ereport(NOTICE,
1215  (errcode(ERRCODE_UNDEFINED_OBJECT),
1216  errmsg("tablespace \"%s\" does not exist",
1217  curname)));
1218  continue;
1219  }
1220 
1221  /*
1222  * Allow explicit specification of database's default tablespace
1223  * in temp_tablespaces without triggering permissions checks.
1224  */
1225  if (curoid == MyDatabaseTableSpace)
1226  {
1227  tblSpcs[numSpcs++] = InvalidOid;
1228  continue;
1229  }
1230 
1231  /* Check permissions, similarly complaining only if interactive */
1232  aclresult = pg_tablespace_aclcheck(curoid, GetUserId(),
1233  ACL_CREATE);
1234  if (aclresult != ACLCHECK_OK)
1235  {
1236  if (source >= PGC_S_INTERACTIVE)
1237  aclcheck_error(aclresult, OBJECT_TABLESPACE, curname);
1238  continue;
1239  }
1240 
1241  tblSpcs[numSpcs++] = curoid;
1242  }
1243 
1244  /* Now prepare an "extra" struct for assign_temp_tablespaces */
1245  myextra = malloc(offsetof(temp_tablespaces_extra, tblSpcs) +
1246  numSpcs * sizeof(Oid));
1247  if (!myextra)
1248  return false;
1249  myextra->numSpcs = numSpcs;
1250  memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1251  *extra = (void *) myextra;
1252 
1253  pfree(tblSpcs);
1254  }
1255 
1256  pfree(rawname);
1257  list_free(namelist);
1258 
1259  return true;
1260 }
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1382
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4698
Oid GetUserId(void)
Definition: miscinit.c:379
#define GUC_check_errdetail
Definition: guc.h:410
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:575
unsigned int Oid
Definition: postgres_ext.h:31
Oid MyDatabaseTableSpace
Definition: globals.c:88
#define malloc(a)
Definition: header.h:50
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3348
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ACL_CREATE
Definition: parsenodes.h:84
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3290
Oid tblSpcs[FLEXIBLE_ARRAY_MEMBER]
Definition: tablespace.c:1154
#define ereport(elevel, rest)
Definition: elog.h:122
AclResult
Definition: acl.h:178
#define InvalidOid
Definition: postgres_ext.h:36
#define NOTICE
Definition: elog.h:37
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
bool IsTransactionState(void)
Definition: xact.c:350
void * palloc(Size size)
Definition: mcxt.c:924
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
Definition: pg_list.h:45
#define offsetof(type, field)
Definition: c.h:622

◆ create_tablespace_directories()

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

Definition at line 565 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, symlink, TABLESPACE_VERSION_DIRECTORY, and WARNING.

Referenced by CreateTableSpace(), and tblspc_redo().

566 {
567  char *linkloc;
568  char *location_with_version_dir;
569  struct stat st;
570 
571  linkloc = psprintf("pg_tblspc/%u", tablespaceoid);
572  location_with_version_dir = psprintf("%s/%s", location,
574 
575  /*
576  * Attempt to coerce target directory to safe permissions. If this fails,
577  * it doesn't exist or has the wrong owner.
578  */
579  if (chmod(location, pg_dir_create_mode) != 0)
580  {
581  if (errno == ENOENT)
582  ereport(ERROR,
583  (errcode(ERRCODE_UNDEFINED_FILE),
584  errmsg("directory \"%s\" does not exist", location),
585  InRecovery ? errhint("Create this directory for the tablespace before "
586  "restarting the server.") : 0));
587  else
588  ereport(ERROR,
590  errmsg("could not set permissions on directory \"%s\": %m",
591  location)));
592  }
593 
594  if (InRecovery)
595  {
596  /*
597  * Our theory for replaying a CREATE is to forcibly drop the target
598  * subdirectory if present, and then recreate it. This may be more
599  * work than needed, but it is simple to implement.
600  */
601  if (stat(location_with_version_dir, &st) == 0 && S_ISDIR(st.st_mode))
602  {
603  if (!rmtree(location_with_version_dir, true))
604  /* If this failed, MakePGDirectory() below is going to error. */
606  (errmsg("some useless files may be left behind in old database directory \"%s\"",
607  location_with_version_dir)));
608  }
609  }
610 
611  /*
612  * The creation of the version directory prevents more than one tablespace
613  * in a single location.
614  */
615  if (MakePGDirectory(location_with_version_dir) < 0)
616  {
617  if (errno == EEXIST)
618  ereport(ERROR,
619  (errcode(ERRCODE_OBJECT_IN_USE),
620  errmsg("directory \"%s\" already in use as a tablespace",
621  location_with_version_dir)));
622  else
623  ereport(ERROR,
625  errmsg("could not create directory \"%s\": %m",
626  location_with_version_dir)));
627  }
628 
629  /*
630  * In recovery, remove old symlink, in case it points to the wrong place.
631  */
632  if (InRecovery)
633  remove_tablespace_symlink(linkloc);
634 
635  /*
636  * Create the symlink under PGDATA
637  */
638  if (symlink(location, linkloc) < 0)
639  ereport(ERROR,
641  errmsg("could not create symbolic link \"%s\": %m",
642  linkloc)));
643 
644  pfree(linkloc);
645  pfree(location_with_version_dir);
646 }
int errhint(const char *fmt,...)
Definition: elog.c:987
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool InRecovery
Definition: xlog.c:194
int errcode(int sqlerrcode)
Definition: elog.c:575
void remove_tablespace_symlink(const char *linkloc)
Definition: tablespace.c:863
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:26
#define symlink(oldpath, newpath)
Definition: win32_port.h:232
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:266
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
int pg_dir_create_mode
Definition: file_perm.c:19
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3571
#define S_ISDIR(m)
Definition: win32_port.h:307
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ CreateTableSpace()

Oid CreateTableSpace ( CreateTableSpaceStmt stmt)

Definition at line 234 of file tablespace.c.

References allowSystemTableMods, canonicalize_path(), CatalogTupleInsert(), create_tablespace_directories(), CStringGetDatum, DataDir, DirectFunctionCall1, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, ForceSyncCommit(), FORKNAMECHARS, get_rolespec_oid(), get_tablespace_oid(), GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), InvalidOid, InvokeObjectPostCreateHook, is_absolute_path, IsReservedName(), CreateTableSpaceStmt::location, MAXPGPATH, MemSet, namein(), NoLock, ObjectIdGetDatum, offsetof, OIDCHARS, OidIsValid, CreateTableSpaceStmt::options, CreateTableSpaceStmt::owner, path_is_prefix_of_path(), pfree(), pstrdup(), RelationData::rd_att, recordDependencyOnOwner(), RowExclusiveLock, superuser(), tablespace_reloptions(), TABLESPACE_VERSION_DIRECTORY, CreateTableSpaceStmt::tablespacename, transformRelOptions(), xl_tblspc_create_rec::ts_id, values, WARNING, XLOG_TBLSPC_CREATE, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

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

◆ destroy_tablespace_directories()

static bool destroy_tablespace_directories ( Oid  tablespaceoid,
bool  redo 
)
static

Definition at line 663 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, TABLESPACE_VERSION_DIRECTORY, and WARNING.

Referenced by DropTableSpace(), and tblspc_redo().

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

◆ directory_is_empty()

bool directory_is_empty ( const char *  path)

Definition at line 833 of file tablespace.c.

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

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

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

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

Definition at line 402 of file tablespace.c.

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

Referenced by standard_ProcessUtility().

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

◆ get_tablespace_name()

char* get_tablespace_name ( Oid  spc_oid)

Definition at line 1428 of file tablespace.c.

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

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

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

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char *  tablespacename,
bool  missing_ok 
)

Definition at line 1382 of file tablespace.c.

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

Referenced by AlterTableMoveAll(), ATPrepSetTableSpace(), check_default_tablespace(), check_temp_tablespaces(), convert_tablespace_name(), createdb(), CreateTableSpace(), DefineIndex(), DefineRelation(), get_object_address_unqualified(), GetDefaultTablespace(), movedb(), objectNamesToOids(), pg_tablespace_size_name(), and PrepareTempTablespaces().

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

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence)

Definition at line 1113 of file tablespace.c.

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

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

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1289 of file tablespace.c.

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

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

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

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char *  linkloc)

Definition at line 863 of file tablespace.c.

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

Referenced by create_tablespace_directories(), and StartupXLOG().

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

◆ RenameTableSpace()

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

Definition at line 912 of file tablespace.c.

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

Referenced by ExecRenameStmt().

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

◆ TablespaceCreateDbspace()

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

Definition at line 116 of file tablespace.c.

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

Referenced by smgrcreate().

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

◆ tblspc_redo()

void tblspc_redo ( XLogReaderState record)

Definition at line 1467 of file tablespace.c.

References Assert, create_tablespace_directories(), destroy_tablespace_directories(), elog, ereport, errcode(), errhint(), errmsg(), LOG, PANIC, ResolveRecoveryConflictWithTablespace(), xl_tblspc_create_rec::ts_id, xl_tblspc_drop_rec::ts_id, xl_tblspc_create_rec::ts_path, XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, XLogRecGetData, XLogRecGetInfo, XLogRecHasAnyBlockRefs, and XLR_INFO_MASK.

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

Variable Documentation

◆ default_tablespace

char* default_tablespace = NULL

Definition at line 89 of file tablespace.c.

Referenced by GetDefaultTablespace().

◆ temp_tablespaces

char* temp_tablespaces = NULL

Definition at line 90 of file tablespace.c.

Referenced by PrepareTempTablespaces().