PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
tablespace.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/types.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 "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

Oid AlterTableSpaceOptions ( AlterTableSpaceOptionsStmt stmt)

Definition at line 987 of file tablespace.c.

References ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_NOT_OWNER, Anum_pg_tablespace_spcname, Anum_pg_tablespace_spcoptions, 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, Natts_pg_tablespace, NoLock, NULL, AlterTableSpaceOptionsStmt::options, pg_tablespace_ownercheck(), RelationGetDescr, RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, tablespace_reloptions(), AlterTableSpaceOptionsStmt::tablespacename, TableSpaceRelationId, and transformRelOptions().

Referenced by standard_ProcessUtility().

988 {
989  Relation rel;
990  ScanKeyData entry[1];
991  HeapScanDesc scandesc;
992  HeapTuple tup;
993  Oid tablespaceoid;
994  Datum datum;
995  Datum newOptions;
996  Datum repl_val[Natts_pg_tablespace];
997  bool isnull;
998  bool repl_null[Natts_pg_tablespace];
999  bool repl_repl[Natts_pg_tablespace];
1000  HeapTuple newtuple;
1001 
1002  /* Search pg_tablespace */
1004 
1005  ScanKeyInit(&entry[0],
1007  BTEqualStrategyNumber, F_NAMEEQ,
1009  scandesc = heap_beginscan_catalog(rel, 1, entry);
1010  tup = heap_getnext(scandesc, ForwardScanDirection);
1011  if (!HeapTupleIsValid(tup))
1012  ereport(ERROR,
1013  (errcode(ERRCODE_UNDEFINED_OBJECT),
1014  errmsg("tablespace \"%s\" does not exist",
1015  stmt->tablespacename)));
1016 
1017  tablespaceoid = HeapTupleGetOid(tup);
1018 
1019  /* Must be owner of the existing object */
1022  stmt->tablespacename);
1023 
1024  /* Generate new proposed spcoptions (text array) */
1026  RelationGetDescr(rel), &isnull);
1027  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1028  stmt->options, NULL, NULL, false,
1029  stmt->isReset);
1030  (void) tablespace_reloptions(newOptions, true);
1031 
1032  /* Build new tuple. */
1033  memset(repl_null, false, sizeof(repl_null));
1034  memset(repl_repl, false, sizeof(repl_repl));
1035  if (newOptions != (Datum) 0)
1036  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1037  else
1038  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1039  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1040  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1041  repl_null, repl_repl);
1042 
1043  /* Update system catalog. */
1044  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1045 
1047 
1048  heap_freetuple(newtuple);
1049 
1050  /* Conclude heap scan. */
1051  heap_endscan(scandesc);
1052  heap_close(rel, NoLock);
1053 
1054  return tablespaceoid;
1055 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
#define RelationGetDescr(relation)
Definition: rel.h:425
Oid GetUserId(void)
Definition: miscinit.c:283
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1450
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:1374
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:586
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4723
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1402
#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:769
uintptr_t Datum
Definition: postgres.h:374
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1781
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:700
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define Anum_pg_tablespace_spcname
Definition: pg_tablespace.h:55
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
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 Anum_pg_tablespace_spcoptions
Definition: pg_tablespace.h:58
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:793
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define Natts_pg_tablespace
Definition: pg_tablespace.h:54
void assign_temp_tablespaces ( const char *  newval,
void *  extra 
)

Definition at line 1263 of file tablespace.c.

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

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

Definition at line 1063 of file tablespace.c.

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

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

Definition at line 1158 of file tablespace.c.

References ACL_CREATE, ACL_KIND_TABLESPACE, 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, offsetof, palloc(), pfree(), pg_tablespace_aclcheck(), PGC_S_INTERACTIVE, PGC_S_TEST, pstrdup(), SplitIdentifierString(), and temp_tablespaces_extra::tblSpcs.

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

Definition at line 564 of file tablespace.c.

References ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, InRecovery, mkdir, pfree(), psprintf(), remove_tablespace_symlink(), rmtree(), TABLESPACE_VERSION_DIRECTORY, and WARNING.

Referenced by CreateTableSpace(), and tblspc_redo().

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

Definition at line 234 of file tablespace.c.

References allowSystemTableMods, Anum_pg_tablespace_spcacl, Anum_pg_tablespace_spcname, Anum_pg_tablespace_spcoptions, Anum_pg_tablespace_spcowner, 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(), Natts_pg_tablespace, NoLock, NULL, 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, TableSpaceRelationId, 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;
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 mkdir() uses the first two 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  * Check that there is no other tablespace by this name. (The unique
311  * index would catch this anyway, but might as well give a friendlier
312  * message.)
313  */
314  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
315  ereport(ERROR,
317  errmsg("tablespace \"%s\" already exists",
318  stmt->tablespacename)));
319 
320  /*
321  * Insert tuple into pg_tablespace. The purpose of doing this first is to
322  * lock the proposed tablename against other would-be creators. The
323  * insertion will roll back if we find problems below.
324  */
326 
327  MemSet(nulls, false, sizeof(nulls));
328 
329  values[Anum_pg_tablespace_spcname - 1] =
331  values[Anum_pg_tablespace_spcowner - 1] =
332  ObjectIdGetDatum(ownerId);
333  nulls[Anum_pg_tablespace_spcacl - 1] = true;
334 
335  /* Generate new proposed spcoptions (text array) */
336  newOptions = transformRelOptions((Datum) 0,
337  stmt->options,
338  NULL, NULL, false, false);
339  (void) tablespace_reloptions(newOptions, true);
340  if (newOptions != (Datum) 0)
341  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
342  else
343  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
344 
345  tuple = heap_form_tuple(rel->rd_att, values, nulls);
346 
347  tablespaceoid = CatalogTupleInsert(rel, tuple);
348 
349  heap_freetuple(tuple);
350 
351  /* Record dependency on owner */
352  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
353 
354  /* Post creation hook for new tablespace */
356 
357  create_tablespace_directories(location, tablespaceoid);
358 
359  /* Record the filesystem change in XLOG */
360  {
361  xl_tblspc_create_rec xlrec;
362 
363  xlrec.ts_id = tablespaceoid;
364 
365  XLogBeginInsert();
366  XLogRegisterData((char *) &xlrec,
367  offsetof(xl_tblspc_create_rec, ts_path));
368  XLogRegisterData((char *) location, strlen(location) + 1);
369 
370  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
371  }
372 
373  /*
374  * Force synchronous commit, to minimize the window between creating the
375  * symlink on-disk and marking the transaction committed. It's not great
376  * that there is any window at all, but definitely we don't want to make
377  * it larger than necessary.
378  */
379  ForceSyncCommit();
380 
381  pfree(location);
382 
383  /* We keep the lock on pg_tablespace until commit */
384  heap_close(rel, NoLock);
385 
386  return tablespaceoid;
387 #else /* !HAVE_SYMLINK */
388  ereport(ERROR,
389  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
390  errmsg("tablespaces are not supported on this platform")));
391  return InvalidOid; /* keep compiler quiet */
392 #endif /* HAVE_SYMLINK */
393 }
#define Anum_pg_tablespace_spcacl
Definition: pg_tablespace.h:57
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1381
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
#define OIDCHARS
Definition: catalog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:145
Oid GetUserId(void)
Definition: miscinit.c:283
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition: path.c:438
char * pstrdup(const char *in)
Definition: mcxt.c:1165
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1450
void ForceSyncCommit(void)
Definition: xact.c:969
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:853
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:158
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
bool IsReservedName(const char *name)
Definition: catalog.c:193
#define OidIsValid(objectId)
Definition: c.h:534
void pfree(void *pointer)
Definition: mcxt.c:992
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define MAXPGPATH
#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:77
#define CStringGetDatum(X)
Definition: postgres.h:586
#define Anum_pg_tablespace_spcowner
Definition: pg_tablespace.h:56
#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:564
uintptr_t Datum
Definition: postgres.h:374
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5147
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
TupleDesc rd_att
Definition: rel.h:114
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:700
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define XLOG_TBLSPC_CREATE
Definition: tablespace.h:23
#define TABLESPACE_VERSION_DIRECTORY
Definition: catalog.h:26
#define Anum_pg_tablespace_spcname
Definition: pg_tablespace.h:55
#define FORKNAMECHARS
Definition: relpath.h:41
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
static Datum values[MAXATTR]
Definition: bootstrap.c:162
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define Anum_pg_tablespace_spcoptions
Definition: pg_tablespace.h:58
char * DataDir
Definition: globals.c:59
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
#define offsetof(type, field)
Definition: c.h:551
#define Natts_pg_tablespace
Definition: pg_tablespace.h:54
static bool destroy_tablespace_directories ( Oid  tablespaceoid,
bool  redo 
)
static

Definition at line 662 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, NULL, pfree(), psprintf(), pstrdup(), ReadDir(), TABLESPACE_VERSION_DIRECTORY, unlink(), and WARNING.

Referenced by DropTableSpace(), and tblspc_redo().

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

Definition at line 832 of file tablespace.c.

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

Referenced by createdb(), and destroy_tablespace_directories().

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

Definition at line 401 of file tablespace.c.

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

Referenced by standard_ProcessUtility().

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

Definition at line 1427 of file tablespace.c.

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

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

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

Definition at line 1381 of file tablespace.c.

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

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

1382 {
1383  Oid result;
1384  Relation rel;
1385  HeapScanDesc scandesc;
1386  HeapTuple tuple;
1387  ScanKeyData entry[1];
1388 
1389  /*
1390  * Search pg_tablespace. We use a heapscan here even though there is an
1391  * index on name, on the theory that pg_tablespace will usually have just
1392  * a few entries and so an indexed lookup is a waste of effort.
1393  */
1395 
1396  ScanKeyInit(&entry[0],
1398  BTEqualStrategyNumber, F_NAMEEQ,
1399  CStringGetDatum(tablespacename));
1400  scandesc = heap_beginscan_catalog(rel, 1, entry);
1401  tuple = heap_getnext(scandesc, ForwardScanDirection);
1402 
1403  /* We assume that there can be at most one matching tuple */
1404  if (HeapTupleIsValid(tuple))
1405  result = HeapTupleGetOid(tuple);
1406  else
1407  result = InvalidOid;
1408 
1409  heap_endscan(scandesc);
1411 
1412  if (!OidIsValid(result) && !missing_ok)
1413  ereport(ERROR,
1414  (errcode(ERRCODE_UNDEFINED_OBJECT),
1415  errmsg("tablespace \"%s\" does not exist",
1416  tablespacename)));
1417 
1418  return result;
1419 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
#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:534
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:586
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1402
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1781
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define Anum_pg_tablespace_spcname
Definition: pg_tablespace.h:55
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
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:695
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Oid GetDefaultTablespace ( char  relpersistence)

Definition at line 1112 of file tablespace.c.

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

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

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

Definition at line 1288 of file tablespace.c.

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

Referenced by ExecHashIncreaseNumBatches(), ExecHashTableCreate(), GetDefaultTablespace(), inittapes(), and tuplestore_puttuple_common().

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

Definition at line 862 of file tablespace.c.

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

Referenced by create_tablespace_directories(), and StartupXLOG().

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

Definition at line 911 of file tablespace.c.

References ACL_KIND_TABLESPACE, aclcheck_error(), ACLCHECK_NO_PRIV, allowSystemTableMods, Anum_pg_tablespace_spcname, 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, ObjectAddressSet, pg_tablespace_ownercheck(), RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, and TableSpaceRelationId.

Referenced by ExecRenameStmt().

912 {
913  Oid tspId;
914  Relation rel;
915  ScanKeyData entry[1];
916  HeapScanDesc scan;
917  HeapTuple tup;
918  HeapTuple newtuple;
919  Form_pg_tablespace newform;
920  ObjectAddress address;
921 
922  /* Search pg_tablespace */
924 
925  ScanKeyInit(&entry[0],
927  BTEqualStrategyNumber, F_NAMEEQ,
928  CStringGetDatum(oldname));
929  scan = heap_beginscan_catalog(rel, 1, entry);
930  tup = heap_getnext(scan, ForwardScanDirection);
931  if (!HeapTupleIsValid(tup))
932  ereport(ERROR,
933  (errcode(ERRCODE_UNDEFINED_OBJECT),
934  errmsg("tablespace \"%s\" does not exist",
935  oldname)));
936 
937  tspId = HeapTupleGetOid(tup);
938  newtuple = heap_copytuple(tup);
939  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
940 
941  heap_endscan(scan);
942 
943  /* Must be owner */
946 
947  /* Validate new name */
948  if (!allowSystemTableMods && IsReservedName(newname))
949  ereport(ERROR,
950  (errcode(ERRCODE_RESERVED_NAME),
951  errmsg("unacceptable tablespace name \"%s\"", newname),
952  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
953 
954  /* Make sure the new name doesn't exist */
955  ScanKeyInit(&entry[0],
957  BTEqualStrategyNumber, F_NAMEEQ,
958  CStringGetDatum(newname));
959  scan = heap_beginscan_catalog(rel, 1, entry);
960  tup = heap_getnext(scan, ForwardScanDirection);
961  if (HeapTupleIsValid(tup))
962  ereport(ERROR,
964  errmsg("tablespace \"%s\" already exists",
965  newname)));
966 
967  heap_endscan(scan);
968 
969  /* OK, update the entry */
970  namestrcpy(&(newform->spcname), newname);
971 
972  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
973 
975 
976  ObjectAddressSet(address, TableSpaceRelationId, tspId);
977 
978  heap_close(rel, NoLock);
979 
980  return address;
981 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
Oid GetUserId(void)
Definition: miscinit.c:283
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:193
int namestrcpy(Name name, const char *str)
Definition: name.c:217
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3378
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:586
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:47
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4723
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1402
#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:1781
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
bool allowSystemTableMods
Definition: globals.c:111
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
#define Anum_pg_tablespace_spcname
Definition: pg_tablespace.h:55
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
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:695
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
#define BTEqualStrategyNumber
Definition: stratnum.h:31
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(), GLOBALTABLESPACE_OID, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), mkdir, OidIsValid, pfree(), and pstrdup().

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 (mkdir(dir, S_IRWXU) < 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 (mkdir(parentdir, S_IRWXU) < 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 (mkdir(parentdir, S_IRWXU) < 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 (mkdir(dir, S_IRWXU) < 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 }
#define mkdir(a, b)
Definition: win32.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:534
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
void pfree(void *pointer)
Definition: mcxt.c:992
#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:108
#define Assert(condition)
Definition: c.h:671
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
int errmsg(const char *fmt,...)
Definition: elog.c:797
void tblspc_redo ( XLogReaderState record)

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

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

Variable Documentation

char* default_tablespace = NULL

Definition at line 89 of file tablespace.c.

Referenced by GetDefaultTablespace().

char* temp_tablespaces = NULL

Definition at line 90 of file tablespace.c.

Referenced by PrepareTempTablespaces().