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

987 {
988  Relation rel;
989  ScanKeyData entry[1];
990  HeapScanDesc scandesc;
991  HeapTuple tup;
992  Oid tablespaceoid;
993  Datum datum;
994  Datum newOptions;
995  Datum repl_val[Natts_pg_tablespace];
996  bool isnull;
997  bool repl_null[Natts_pg_tablespace];
998  bool repl_repl[Natts_pg_tablespace];
999  HeapTuple newtuple;
1000 
1001  /* Search pg_tablespace */
1003 
1004  ScanKeyInit(&entry[0],
1006  BTEqualStrategyNumber, F_NAMEEQ,
1008  scandesc = heap_beginscan_catalog(rel, 1, entry);
1009  tup = heap_getnext(scandesc, ForwardScanDirection);
1010  if (!HeapTupleIsValid(tup))
1011  ereport(ERROR,
1012  (errcode(ERRCODE_UNDEFINED_OBJECT),
1013  errmsg("tablespace \"%s\" does not exist",
1014  stmt->tablespacename)));
1015 
1016  tablespaceoid = HeapTupleGetOid(tup);
1017 
1018  /* Must be owner of the existing object */
1021  stmt->tablespacename);
1022 
1023  /* Generate new proposed spcoptions (text array) */
1025  RelationGetDescr(rel), &isnull);
1026  newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1027  stmt->options, NULL, NULL, false,
1028  stmt->isReset);
1029  (void) tablespace_reloptions(newOptions, true);
1030 
1031  /* Build new tuple. */
1032  memset(repl_null, false, sizeof(repl_null));
1033  memset(repl_repl, false, sizeof(repl_repl));
1034  if (newOptions != (Datum) 0)
1035  repl_val[Anum_pg_tablespace_spcoptions - 1] = newOptions;
1036  else
1037  repl_null[Anum_pg_tablespace_spcoptions - 1] = true;
1038  repl_repl[Anum_pg_tablespace_spcoptions - 1] = true;
1039  newtuple = heap_modify_tuple(tup, RelationGetDescr(rel), repl_val,
1040  repl_null, repl_repl);
1041 
1042  /* Update system catalog. */
1043  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1044 
1046 
1047  heap_freetuple(newtuple);
1048 
1049  /* Conclude heap scan. */
1050  heap_endscan(scandesc);
1051  heap_close(rel, NoLock);
1052 
1053  return tablespaceoid;
1054 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
#define RelationGetDescr(relation)
Definition: rel.h:429
Oid GetUserId(void)
Definition: miscinit.c:283
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1493
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:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:584
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4748
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#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:372
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:745
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
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 1262 of file tablespace.c.

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

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

Definition at line 1062 of file tablespace.c.

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

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

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

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

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

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

234 {
235 #ifdef HAVE_SYMLINK
236  Relation rel;
238  bool nulls[Natts_pg_tablespace];
239  HeapTuple tuple;
240  Oid tablespaceoid;
241  char *location;
242  Oid ownerId;
243  Datum newOptions;
244 
245  /* Must be super user */
246  if (!superuser())
247  ereport(ERROR,
248  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
249  errmsg("permission denied to create tablespace \"%s\"",
250  stmt->tablespacename),
251  errhint("Must be superuser to create a tablespace.")));
252 
253  /* However, the eventual owner of the tablespace need not be */
254  if (stmt->owner)
255  ownerId = get_rolespec_oid(stmt->owner, false);
256  else
257  ownerId = GetUserId();
258 
259  /* Unix-ify the offered path, and strip any trailing slashes */
260  location = pstrdup(stmt->location);
261  canonicalize_path(location);
262 
263  /* disallow quotes, else CREATE DATABASE would be at risk */
264  if (strchr(location, '\''))
265  ereport(ERROR,
266  (errcode(ERRCODE_INVALID_NAME),
267  errmsg("tablespace location cannot contain single quotes")));
268 
269  /*
270  * Allowing relative paths seems risky
271  *
272  * this also helps us ensure that location is not empty or whitespace
273  */
274  if (!is_absolute_path(location))
275  ereport(ERROR,
276  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
277  errmsg("tablespace location must be an absolute path")));
278 
279  /*
280  * Check that location isn't too long. Remember that we're going to append
281  * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
282  * reference the whole path here, but mkdir() uses the first two parts.
283  */
284  if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
285  OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1 + OIDCHARS > MAXPGPATH)
286  ereport(ERROR,
287  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
288  errmsg("tablespace location \"%s\" is too long",
289  location)));
290 
291  /* Warn if the tablespace is in the data directory. */
292  if (path_is_prefix_of_path(DataDir, location))
294  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
295  errmsg("tablespace location should not be inside the data directory")));
296 
297  /*
298  * Disallow creation of tablespaces named "pg_xxx"; we reserve this
299  * namespace for system purposes.
300  */
302  ereport(ERROR,
303  (errcode(ERRCODE_RESERVED_NAME),
304  errmsg("unacceptable tablespace name \"%s\"",
305  stmt->tablespacename),
306  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
307 
308  /*
309  * Check that there is no other tablespace by this name. (The unique
310  * index would catch this anyway, but might as well give a friendlier
311  * message.)
312  */
313  if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
314  ereport(ERROR,
316  errmsg("tablespace \"%s\" already exists",
317  stmt->tablespacename)));
318 
319  /*
320  * Insert tuple into pg_tablespace. The purpose of doing this first is to
321  * lock the proposed tablename against other would-be creators. The
322  * insertion will roll back if we find problems below.
323  */
325 
326  MemSet(nulls, false, sizeof(nulls));
327 
328  values[Anum_pg_tablespace_spcname - 1] =
330  values[Anum_pg_tablespace_spcowner - 1] =
331  ObjectIdGetDatum(ownerId);
332  nulls[Anum_pg_tablespace_spcacl - 1] = true;
333 
334  /* Generate new proposed spcoptions (text array) */
335  newOptions = transformRelOptions((Datum) 0,
336  stmt->options,
337  NULL, NULL, false, false);
338  (void) tablespace_reloptions(newOptions, true);
339  if (newOptions != (Datum) 0)
340  values[Anum_pg_tablespace_spcoptions - 1] = newOptions;
341  else
342  nulls[Anum_pg_tablespace_spcoptions - 1] = true;
343 
344  tuple = heap_form_tuple(rel->rd_att, values, nulls);
345 
346  tablespaceoid = CatalogTupleInsert(rel, tuple);
347 
348  heap_freetuple(tuple);
349 
350  /* Record dependency on owner */
351  recordDependencyOnOwner(TableSpaceRelationId, tablespaceoid, ownerId);
352 
353  /* Post creation hook for new tablespace */
355 
356  create_tablespace_directories(location, tablespaceoid);
357 
358  /* Record the filesystem change in XLOG */
359  {
360  xl_tblspc_create_rec xlrec;
361 
362  xlrec.ts_id = tablespaceoid;
363 
364  XLogBeginInsert();
365  XLogRegisterData((char *) &xlrec,
366  offsetof(xl_tblspc_create_rec, ts_path));
367  XLogRegisterData((char *) location, strlen(location) + 1);
368 
369  (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_CREATE);
370  }
371 
372  /*
373  * Force synchronous commit, to minimize the window between creating the
374  * symlink on-disk and marking the transaction committed. It's not great
375  * that there is any window at all, but definitely we don't want to make
376  * it larger than necessary.
377  */
378  ForceSyncCommit();
379 
380  pfree(location);
381 
382  /* We keep the lock on pg_tablespace until commit */
383  heap_close(rel, NoLock);
384 
385  return tablespaceoid;
386 #else /* !HAVE_SYMLINK */
387  ereport(ERROR,
388  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
389  errmsg("tablespaces are not supported on this platform")));
390  return InvalidOid; /* keep compiler quiet */
391 #endif /* HAVE_SYMLINK */
392 }
#define Anum_pg_tablespace_spcacl
Definition: pg_tablespace.h:57
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
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:1077
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Definition: reloptions.c:1493
void ForceSyncCommit(void)
Definition: xact.c:970
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:857
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:584
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:159
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:538
void pfree(void *pointer)
Definition: mcxt.c:950
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:584
#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:563
uintptr_t Datum
Definition: postgres.h:372
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition: acl.c:5129
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
TupleDesc rd_att
Definition: rel.h:115
Datum transformRelOptions(Datum oldOptions, List *defList, char *namspace, char *validnsps[], bool ignoreOids, bool isReset)
Definition: reloptions.c:745
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#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:163
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:31
#define offsetof(type, field)
Definition: c.h:555
#define Natts_pg_tablespace
Definition: pg_tablespace.h:54
static bool destroy_tablespace_directories ( Oid  tablespaceoid,
bool  redo 
)
static

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

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

Definition at line 831 of file tablespace.c.

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

Referenced by createdb(), and destroy_tablespace_directories().

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

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

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

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

1427 {
1428  char *result;
1429  Relation rel;
1430  HeapScanDesc scandesc;
1431  HeapTuple tuple;
1432  ScanKeyData entry[1];
1433 
1434  /*
1435  * Search pg_tablespace. We use a heapscan here even though there is an
1436  * index on oid, on the theory that pg_tablespace will usually have just a
1437  * few entries and so an indexed lookup is a waste of effort.
1438  */
1440 
1441  ScanKeyInit(&entry[0],
1443  BTEqualStrategyNumber, F_OIDEQ,
1444  ObjectIdGetDatum(spc_oid));
1445  scandesc = heap_beginscan_catalog(rel, 1, entry);
1446  tuple = heap_getnext(scandesc, ForwardScanDirection);
1447 
1448  /* We assume that there can be at most one matching tuple */
1449  if (HeapTupleIsValid(tuple))
1450  result = pstrdup(NameStr(((Form_pg_tablespace) GETSTRUCT(tuple))->spcname));
1451  else
1452  result = NULL;
1453 
1454  heap_endscan(scandesc);
1456 
1457  return result;
1458 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
#define ObjectIdAttributeNumber
Definition: sysattr.h:22
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define AccessShareLock
Definition: lockdefs.h:36
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:47
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define TableSpaceRelationId
Definition: pg_tablespace.h:29
#define NameStr(name)
Definition: c.h:499
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 1380 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, result, 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().

1381 {
1382  Oid result;
1383  Relation rel;
1384  HeapScanDesc scandesc;
1385  HeapTuple tuple;
1386  ScanKeyData entry[1];
1387 
1388  /*
1389  * Search pg_tablespace. We use a heapscan here even though there is an
1390  * index on name, on the theory that pg_tablespace will usually have just
1391  * a few entries and so an indexed lookup is a waste of effort.
1392  */
1394 
1395  ScanKeyInit(&entry[0],
1397  BTEqualStrategyNumber, F_NAMEEQ,
1398  CStringGetDatum(tablespacename));
1399  scandesc = heap_beginscan_catalog(rel, 1, entry);
1400  tuple = heap_getnext(scandesc, ForwardScanDirection);
1401 
1402  /* We assume that there can be at most one matching tuple */
1403  if (HeapTupleIsValid(tuple))
1404  result = HeapTupleGetOid(tuple);
1405  else
1406  result = InvalidOid;
1407 
1408  heap_endscan(scandesc);
1410 
1411  if (!OidIsValid(result) && !missing_ok)
1412  ereport(ERROR,
1413  (errcode(ERRCODE_UNDEFINED_OBJECT),
1414  errmsg("tablespace \"%s\" does not exist",
1415  tablespacename)));
1416 
1417  return result;
1418 }
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:584
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#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 1111 of file tablespace.c.

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

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

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

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

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

Definition at line 861 of file tablespace.c.

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

Referenced by create_tablespace_directories(), and StartupXLOG().

862 {
863  struct stat st;
864 
865  if (lstat(linkloc, &st) < 0)
866  {
867  if (errno == ENOENT)
868  return;
869  ereport(ERROR,
871  errmsg("could not stat file \"%s\": %m", linkloc)));
872  }
873 
874  if (S_ISDIR(st.st_mode))
875  {
876  /*
877  * This will fail if the directory isn't empty, but not if it's a
878  * junction point.
879  */
880  if (rmdir(linkloc) < 0 && errno != ENOENT)
881  ereport(ERROR,
883  errmsg("could not remove directory \"%s\": %m",
884  linkloc)));
885  }
886 #ifdef S_ISLNK
887  else if (S_ISLNK(st.st_mode))
888  {
889  if (unlink(linkloc) < 0 && errno != ENOENT)
890  ereport(ERROR,
892  errmsg("could not remove symbolic link \"%s\": %m",
893  linkloc)));
894  }
895 #endif
896  else
897  {
898  /* Refuse to remove anything that's not a directory or symlink */
899  ereport(ERROR,
900  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
901  errmsg("\"%s\" is not a directory or symbolic link",
902  linkloc)));
903  }
904 }
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:262
ObjectAddress RenameTableSpace ( const char *  oldname,
const char *  newname 
)

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

911 {
912  Oid tspId;
913  Relation rel;
914  ScanKeyData entry[1];
915  HeapScanDesc scan;
916  HeapTuple tup;
917  HeapTuple newtuple;
918  Form_pg_tablespace newform;
919  ObjectAddress address;
920 
921  /* Search pg_tablespace */
923 
924  ScanKeyInit(&entry[0],
926  BTEqualStrategyNumber, F_NAMEEQ,
927  CStringGetDatum(oldname));
928  scan = heap_beginscan_catalog(rel, 1, entry);
929  tup = heap_getnext(scan, ForwardScanDirection);
930  if (!HeapTupleIsValid(tup))
931  ereport(ERROR,
932  (errcode(ERRCODE_UNDEFINED_OBJECT),
933  errmsg("tablespace \"%s\" does not exist",
934  oldname)));
935 
936  tspId = HeapTupleGetOid(tup);
937  newtuple = heap_copytuple(tup);
938  newform = (Form_pg_tablespace) GETSTRUCT(newtuple);
939 
940  heap_endscan(scan);
941 
942  /* Must be owner */
945 
946  /* Validate new name */
947  if (!allowSystemTableMods && IsReservedName(newname))
948  ereport(ERROR,
949  (errcode(ERRCODE_RESERVED_NAME),
950  errmsg("unacceptable tablespace name \"%s\"", newname),
951  errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
952 
953  /* Make sure the new name doesn't exist */
954  ScanKeyInit(&entry[0],
956  BTEqualStrategyNumber, F_NAMEEQ,
957  CStringGetDatum(newname));
958  scan = heap_beginscan_catalog(rel, 1, entry);
959  tup = heap_getnext(scan, ForwardScanDirection);
960  if (HeapTupleIsValid(tup))
961  ereport(ERROR,
963  errmsg("tablespace \"%s\" already exists",
964  newname)));
965 
966  heap_endscan(scan);
967 
968  /* OK, update the entry */
969  namestrcpy(&(newform->spcname), newname);
970 
971  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
972 
974 
975  ObjectAddressSet(address, TableSpaceRelationId, tspId);
976 
977  heap_close(rel, NoLock);
978 
979  return address;
980 }
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:1578
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:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:584
FormData_pg_tablespace * Form_pg_tablespace
Definition: pg_tablespace.h:47
bool pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
Definition: aclchk.c:4748
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
#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:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
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:31
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void TablespaceCreateDbspace ( Oid  spcNode,
Oid  dbNode,
bool  isRedo 
)

Definition at line 115 of file tablespace.c.

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

Referenced by smgrcreate().

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

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

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

Variable Documentation

char* default_tablespace = NULL

Definition at line 88 of file tablespace.c.

Referenced by GetDefaultTablespace().

char* temp_tablespaces = NULL

Definition at line 89 of file tablespace.c.

Referenced by PrepareTempTablespaces().