PostgreSQL Source Code git master
Loading...
Searching...
No Matches
tablespace.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/binary_upgrade.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_tablespace.h"
#include "commands/comment.h"
#include "commands/seclabel.h"
#include "commands/tablespace.h"
#include "common/file_perm.h"
#include "miscadmin.h"
#include "postmaster/bgwriter.h"
#include "storage/fd.h"
#include "storage/lwlock.h"
#include "storage/procsignal.h"
#include "storage/standby.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc_hooks.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/varlena.h"
Include dependency graph for tablespace.c:

Go to the source code of this file.

Data Structures

struct  temp_tablespaces_extra
 

Functions

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

Variables

chardefault_tablespace = NULL
 
chartemp_tablespaces = NULL
 
bool allow_in_place_tablespaces = false
 
Oid binary_upgrade_next_pg_tablespace_oid = InvalidOid
 

Function Documentation

◆ AlterTableSpaceOptions()

Oid AlterTableSpaceOptions ( AlterTableSpaceOptionsStmt stmt)

Definition at line 1029 of file tablespace.c.

1030{
1031 Relation rel;
1032 ScanKeyData entry[1];
1033 TableScanDesc scandesc;
1034 HeapTuple tup;
1036 Datum datum;
1039 bool isnull;
1042 HeapTuple newtuple;
1043
1044 /* Search pg_tablespace */
1046
1047 ScanKeyInit(&entry[0],
1050 CStringGetDatum(stmt->tablespacename));
1051 scandesc = table_beginscan_catalog(rel, 1, entry);
1053 if (!HeapTupleIsValid(tup))
1054 ereport(ERROR,
1056 errmsg("tablespace \"%s\" does not exist",
1057 stmt->tablespacename)));
1058
1060
1061 /* Must be owner of the existing object */
1064 stmt->tablespacename);
1065
1066 /* Generate new proposed spcoptions (text array) */
1068 RelationGetDescr(rel), &isnull);
1069 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1071 stmt->isReset);
1073
1074 /* Build new tuple. */
1075 memset(repl_null, false, sizeof(repl_null));
1076 memset(repl_repl, false, sizeof(repl_repl));
1077 if (newOptions != (Datum) 0)
1079 else
1084
1085 /* Update system catalog. */
1086 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1087
1089
1090 heap_freetuple(newtuple);
1091
1092 /* Conclude heap scan. */
1093 table_endscan(scandesc);
1094 table_close(rel, NoLock);
1095
1096 return tablespaceoid;
1097}
@ ACLCHECK_NOT_OWNER
Definition acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1435
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
static void * GETSTRUCT(const HeapTupleData *tuple)
#define stmt
#define false
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
#define NoLock
Definition lockdefs.h:34
#define RowExclusiveLock
Definition lockdefs.h:38
Oid GetUserId(void)
Definition miscinit.c:470
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
@ OBJECT_TABLESPACE
END_CATALOG_STRUCT typedef FormData_pg_tablespace * Form_pg_tablespace
uint64_t Datum
Definition postgres.h:70
static Datum CStringGetDatum(const char *X)
Definition postgres.h:370
unsigned int Oid
static int fb(int x)
#define RelationGetDescr(relation)
Definition rel.h:542
bytea * tablespace_reloptions(Datum reloptions, bool validate)
Datum transformRelOptions(Datum oldOptions, List *defList, const char *nameSpace, const char *const validnsps[], bool acceptOidsOff, bool isReset)
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
#define BTEqualStrategyNumber
Definition stratnum.h:31
ItemPointerData t_self
Definition htup.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1061

References aclcheck_error(), ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), ereport, errcode(), errmsg, ERROR, fb(), Form_pg_tablespace, ForwardScanDirection, GETSTRUCT(), GetUserId(), heap_freetuple(), heap_getattr(), heap_getnext(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NoLock, object_ownercheck(), OBJECT_TABLESPACE, RelationGetDescr, RowExclusiveLock, ScanKeyInit(), stmt, HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), tablespace_reloptions(), and transformRelOptions().

Referenced by standard_ProcessUtility().

◆ assign_temp_tablespaces()

void assign_temp_tablespaces ( const char newval,
void extra 
)

Definition at line 1320 of file tablespace.c.

1321{
1323
1324 /*
1325 * If check_temp_tablespaces was executed inside a transaction, then pass
1326 * the list it made to fd.c. Otherwise, clear fd.c's list; we must be
1327 * still outside a transaction, or else restoring during transaction exit,
1328 * and in either case we can just let the next PrepareTempTablespaces call
1329 * make things sane.
1330 */
1331 if (myextra)
1332 SetTempTablespaces(myextra->tblSpcs, myextra->numSpcs);
1333 else
1335}
void SetTempTablespaces(Oid *tableSpaces, int numSpaces)
Definition fd.c:3097

References fb(), and SetTempTablespaces().

◆ check_default_tablespace()

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

Definition at line 1105 of file tablespace.c.

1106{
1107 /*
1108 * If we aren't inside a transaction, or connected to a database, we
1109 * cannot do the catalog accesses necessary to verify the name. Must
1110 * accept the value on faith.
1111 */
1113 {
1114 if (**newval != '\0' &&
1116 {
1117 /*
1118 * When source == PGC_S_TEST, don't throw a hard error for a
1119 * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1120 */
1121 if (source == PGC_S_TEST)
1122 {
1125 errmsg("tablespace \"%s\" does not exist",
1126 *newval)));
1127 }
1128 else
1129 {
1130 GUC_check_errdetail("Tablespace \"%s\" does not exist.",
1131 *newval);
1132 return false;
1133 }
1134 }
1135 }
1136
1137 return true;
1138}
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
#define OidIsValid(objectId)
Definition c.h:858
#define NOTICE
Definition elog.h:36
Oid MyDatabaseId
Definition globals.c:96
#define newval
#define GUC_check_errdetail
Definition guc.h:507
@ PGC_S_TEST
Definition guc.h:125
static rewind_source * source
Definition pg_rewind.c:89
#define InvalidOid
bool IsTransactionState(void)
Definition xact.c:389

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

◆ check_temp_tablespaces()

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

Definition at line 1212 of file tablespace.c.

1213{
1214 char *rawname;
1215 List *namelist;
1216
1217 /* Need a modifiable copy of string */
1219
1220 /* Parse string into list of identifiers */
1222 {
1223 /* syntax error in name list */
1224 GUC_check_errdetail("List syntax is invalid.");
1225 pfree(rawname);
1227 return false;
1228 }
1229
1230 /*
1231 * If we aren't inside a transaction, or connected to a database, we
1232 * cannot do the catalog accesses necessary to verify the name. Must
1233 * accept the value on faith. Fortunately, there's then also no need to
1234 * pass the data to fd.c.
1235 */
1237 {
1239 Oid *tblSpcs;
1240 int numSpcs;
1241 ListCell *l;
1242
1243 /* temporary workspace until we are done verifying the list */
1244 tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1245 numSpcs = 0;
1246 foreach(l, namelist)
1247 {
1248 char *curname = (char *) lfirst(l);
1249 Oid curoid;
1251
1252 /* Allow an empty string (signifying database default) */
1253 if (curname[0] == '\0')
1254 {
1255 /* InvalidOid signifies database's default tablespace */
1256 tblSpcs[numSpcs++] = InvalidOid;
1257 continue;
1258 }
1259
1260 /*
1261 * In an interactive SET command, we ereport for bad info. When
1262 * source == PGC_S_TEST, don't throw a hard error for a
1263 * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1264 */
1266 if (curoid == InvalidOid)
1267 {
1268 if (source == PGC_S_TEST)
1271 errmsg("tablespace \"%s\" does not exist",
1272 curname)));
1273 continue;
1274 }
1275
1276 /*
1277 * Allow explicit specification of database's default tablespace
1278 * in temp_tablespaces without triggering permissions checks.
1279 */
1281 {
1282 /* InvalidOid signifies database's default tablespace */
1283 tblSpcs[numSpcs++] = InvalidOid;
1284 continue;
1285 }
1286
1287 /* Check permissions, similarly complaining only if interactive */
1289 ACL_CREATE);
1290 if (aclresult != ACLCHECK_OK)
1291 {
1294 continue;
1295 }
1296
1297 tblSpcs[numSpcs++] = curoid;
1298 }
1299
1300 /* Now prepare an "extra" struct for assign_temp_tablespaces */
1302 numSpcs * sizeof(Oid));
1303 if (!myextra)
1304 return false;
1305 myextra->numSpcs = numSpcs;
1306 memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1307 *extra = myextra;
1308
1309 pfree(tblSpcs);
1310 }
1311
1312 pfree(rawname);
1314
1315 return true;
1316}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define LOG
Definition elog.h:32
Oid MyDatabaseTableSpace
Definition globals.c:98
void * guc_malloc(int elevel, size_t size)
Definition guc.c:637
@ PGC_S_INTERACTIVE
Definition guc.h:124
void list_free(List *list)
Definition list.c:1546
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define ACL_CREATE
Definition parsenodes.h:85
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
Definition pg_list.h:54
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2867

References ACL_CREATE, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg, fb(), get_tablespace_oid(), GetUserId(), GUC_check_errdetail, guc_malloc(), InvalidOid, IsTransactionState(), lfirst, list_free(), list_length(), LOG, memcpy(), MyDatabaseId, MyDatabaseTableSpace, newval, NOTICE, object_aclcheck(), OBJECT_TABLESPACE, palloc(), pfree(), PGC_S_INTERACTIVE, PGC_S_TEST, pstrdup(), source, and SplitIdentifierString().

◆ create_tablespace_directories()

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

Definition at line 580 of file tablespace.c.

581{
582 char *linkloc;
584 struct stat st;
585 bool in_place;
586
588
589 /*
590 * If we're asked to make an 'in place' tablespace, create the directory
591 * directly where the symlink would normally go. This is a developer-only
592 * option for now, to facilitate regression testing.
593 */
594 in_place = strlen(location) == 0;
595
596 if (in_place)
597 {
598 if (MakePGDirectory(linkloc) < 0 && errno != EEXIST)
601 errmsg("could not create directory \"%s\": %m",
602 linkloc)));
603 }
604
605 location_with_version_dir = psprintf("%s/%s", in_place ? linkloc : location,
607
608 /*
609 * Attempt to coerce target directory to safe permissions. If this fails,
610 * it doesn't exist or has the wrong owner. Not needed for in-place mode,
611 * because in that case we created the directory with the desired
612 * permissions.
613 */
614 if (!in_place && chmod(location, pg_dir_create_mode) != 0)
615 {
616 if (errno == ENOENT)
619 errmsg("directory \"%s\" does not exist", location),
620 InRecovery ? errhint("Create this directory for the tablespace before "
621 "restarting the server.") : 0));
622 else
625 errmsg("could not set permissions on directory \"%s\": %m",
626 location)));
627 }
628
629 /*
630 * The creation of the version directory prevents more than one tablespace
631 * in a single location. This imitates TablespaceCreateDbspace(), but it
632 * ignores concurrency and missing parent directories. The chmod() would
633 * have failed in the absence of a parent. pg_tablespace_spcname_index
634 * prevents concurrency.
635 */
636 if (stat(location_with_version_dir, &st) < 0)
637 {
638 if (errno != ENOENT)
641 errmsg("could not stat directory \"%s\": %m",
646 errmsg("could not create directory \"%s\": %m",
648 }
649 else if (!S_ISDIR(st.st_mode))
652 errmsg("\"%s\" exists but is not a directory",
654 else if (!InRecovery)
657 errmsg("directory \"%s\" already in use as a tablespace",
659
660 /*
661 * In recovery, remove old symlink, in case it points to the wrong place.
662 */
663 if (!in_place && InRecovery)
665
666 /*
667 * Create the symlink under PGDATA
668 */
669 if (!in_place && symlink(location, linkloc) < 0)
672 errmsg("could not create symbolic link \"%s\": %m",
673 linkloc)));
674
675 pfree(linkloc);
677}
void remove_tablespace_symlink(const char *linkloc)
Definition tablespace.c:891
int errcode_for_file_access(void)
Definition elog.c:897
int errhint(const char *fmt,...) pg_attribute_printf(1
int MakePGDirectory(const char *directoryName)
Definition fd.c:3963
int pg_dir_create_mode
Definition file_perm.c:18
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define PG_TBLSPC_DIR
Definition relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition relpath.h:33
#define stat
Definition win32_port.h:74
#define S_ISDIR(m)
Definition win32_port.h:315
#define symlink(oldpath, newpath)
Definition win32_port.h:225
bool InRecovery
Definition xlogutils.c:50

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

Referenced by CreateTableSpace(), and tblspc_redo().

◆ CreateTableSpace()

Oid CreateTableSpace ( CreateTableSpaceStmt stmt)

Definition at line 210 of file tablespace.c.

211{
212 Relation rel;
214 bool nulls[Natts_pg_tablespace] = {0};
215 HeapTuple tuple;
217 char *location;
218 Oid ownerId;
220 bool in_place;
221
222 /* Must be superuser */
223 if (!superuser())
226 errmsg("permission denied to create tablespace \"%s\"",
227 stmt->tablespacename),
228 errhint("Must be superuser to create a tablespace.")));
229
230 /* However, the eventual owner of the tablespace need not be */
231 if (stmt->owner)
232 ownerId = get_rolespec_oid(stmt->owner, false);
233 else
234 ownerId = GetUserId();
235
236 /* Unix-ify the offered path, and strip any trailing slashes */
237 location = pstrdup(stmt->location);
238 canonicalize_path(location);
239
240 /* disallow quotes, else CREATE DATABASE would be at risk */
241 if (strchr(location, '\''))
244 errmsg("tablespace location cannot contain single quotes")));
245
246 /* Report error if name has \n or \r character. */
247 if (strpbrk(stmt->tablespacename, "\n\r"))
250 errmsg("tablespace name \"%s\" contains a newline or carriage return character", stmt->tablespacename)));
251
252 in_place = allow_in_place_tablespaces && strlen(location) == 0;
253
254 /*
255 * Allowing relative paths seems risky
256 *
257 * This also helps us ensure that location is not empty or whitespace,
258 * unless specifying a developer-only in-place tablespace.
259 */
260 if (!in_place && !is_absolute_path(location))
263 errmsg("tablespace location must be an absolute path")));
264
265 /*
266 * Check that location isn't too long. Remember that we're going to append
267 * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
268 * reference the whole path here, but MakePGDirectory() uses the first two
269 * parts.
270 */
271 if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
275 errmsg("tablespace location \"%s\" is too long",
276 location)));
277
278 /* Warn if the tablespace is in the data directory. */
279 if (path_is_prefix_of_path(DataDir, location))
282 errmsg("tablespace location should not be inside the data directory")));
283
284 /*
285 * Disallow creation of tablespaces named "pg_xxx"; we reserve this
286 * namespace for system purposes.
287 */
288 if (!allowSystemTableMods && IsReservedName(stmt->tablespacename))
291 errmsg("unacceptable tablespace name \"%s\"",
292 stmt->tablespacename),
293 errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
294
295 /*
296 * If built with appropriate switch, whine when regression-testing
297 * conventions for tablespace names are violated.
298 */
299#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
300 if (strncmp(stmt->tablespacename, "regress_", 8) != 0)
301 elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
302#endif
303
304 /*
305 * Check that there is no other tablespace by this name. (The unique
306 * index would catch this anyway, but might as well give a friendlier
307 * message.)
308 */
309 if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
312 errmsg("tablespace \"%s\" already exists",
313 stmt->tablespacename)));
314
315 /*
316 * Insert tuple into pg_tablespace. The purpose of doing this first is to
317 * lock the proposed tablename against other would-be creators. The
318 * insertion will roll back if we find problems below.
319 */
321
322 if (IsBinaryUpgrade)
323 {
324 /* Use binary-upgrade override for tablespace oid */
328 errmsg("pg_tablespace OID value not set when in binary upgrade mode")));
329
332 }
333 else
340 ObjectIdGetDatum(ownerId);
341 nulls[Anum_pg_tablespace_spcacl - 1] = true;
342
343 /* Generate new proposed spcoptions (text array) */
345 stmt->options,
346 NULL, NULL, false, false);
348 if (newOptions != (Datum) 0)
350 else
351 nulls[Anum_pg_tablespace_spcoptions - 1] = true;
352
353 tuple = heap_form_tuple(rel->rd_att, values, nulls);
354
355 CatalogTupleInsert(rel, tuple);
356
357 heap_freetuple(tuple);
358
359 /* Record dependency on owner */
361
362 /* Post creation hook for new tablespace */
364
366
367 /* Record the filesystem change in XLOG */
368 {
370
372
376 XLogRegisterData(location, strlen(location) + 1);
377
379 }
380
381 /*
382 * Force synchronous commit, to minimize the window between creating the
383 * symlink on-disk and marking the transaction committed. It's not great
384 * that there is any window at all, but definitely we don't want to make
385 * it larger than necessary.
386 */
388
389 pfree(location);
390
391 /* We keep the lock on pg_tablespace until commit */
392 table_close(rel, NoLock);
393
394 return tablespaceoid;
395}
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition acl.c:5639
Oid binary_upgrade_next_pg_tablespace_oid
Definition tablespace.c:89
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition tablespace.c:580
bool allow_in_place_tablespaces
Definition tablespace.c:87
static Datum values[MAXATTR]
Definition bootstrap.c:190
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition catalog.c:448
bool IsReservedName(const char *name)
Definition catalog.c:278
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
#define elog(elevel,...)
Definition elog.h:228
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
bool IsBinaryUpgrade
Definition globals.c:123
bool allowSystemTableMods
Definition globals.c:132
char * DataDir
Definition globals.c:73
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1025
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition indexing.c:233
Datum namein(PG_FUNCTION_ARGS)
Definition name.c:48
#define InvokeObjectPostCreateHook(classId, objectId, subId)
#define MAXPGPATH
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
#define is_absolute_path(filename)
Definition port.h:104
bool path_is_prefix_of_path(const char *path1, const char *path2)
Definition path.c:637
void canonicalize_path(char *path)
Definition path.c:337
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
#define OIDCHARS
Definition relpath.h:45
#define FORKNAMECHARS
Definition relpath.h:72
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
TupleDesc rd_att
Definition rel.h:112
bool superuser(void)
Definition superuser.c:47
#define XLOG_TBLSPC_CREATE
Definition tablespace.h:27
void ForceSyncCommit(void)
Definition xact.c:1182
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:482
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:372
void XLogBeginInsert(void)
Definition xloginsert.c:153

References allow_in_place_tablespaces, allowSystemTableMods, binary_upgrade_next_pg_tablespace_oid, canonicalize_path(), CatalogTupleInsert(), create_tablespace_directories(), CStringGetDatum(), DataDir, DirectFunctionCall1, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg, ERROR, fb(), ForceSyncCommit(), FORKNAMECHARS, get_rolespec_oid(), get_tablespace_oid(), GetNewOidWithIndex(), GetUserId(), heap_form_tuple(), heap_freetuple(), InvalidOid, InvokeObjectPostCreateHook, is_absolute_path, IsBinaryUpgrade, IsReservedName(), MAXPGPATH, namein(), NoLock, ObjectIdGetDatum(), OIDCHARS, OidIsValid, path_is_prefix_of_path(), pfree(), pstrdup(), RelationData::rd_att, recordDependencyOnOwner(), RowExclusiveLock, stmt, superuser(), table_close(), table_open(), tablespace_reloptions(), TABLESPACE_VERSION_DIRECTORY, transformRelOptions(), xl_tblspc_create_rec::ts_id, values, WARNING, XLOG_TBLSPC_CREATE, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

◆ destroy_tablespace_directories()

static bool destroy_tablespace_directories ( Oid  tablespaceoid,
bool  redo 
)
static

Definition at line 694 of file tablespace.c.

695{
696 char *linkloc;
698 DIR *dirdesc;
699 struct dirent *de;
700 char *subfile;
701 struct stat st;
702
705
706 /*
707 * Check if the tablespace still contains any files. We try to rmdir each
708 * per-database directory we find in it. rmdir failure implies there are
709 * still files in that subdirectory, so give up. (We do not have to worry
710 * about undoing any already completed rmdirs, since the next attempt to
711 * use the tablespace from that database will simply recreate the
712 * subdirectory via TablespaceCreateDbspace.)
713 *
714 * Since we hold TablespaceCreateLock, no one else should be creating any
715 * fresh subdirectories in parallel. It is possible that new files are
716 * being created within subdirectories, though, so the rmdir call could
717 * fail. Worst consequence is a less friendly error message.
718 *
719 * If redo is true then ENOENT is a likely outcome here, and we allow it
720 * to pass without comment. In normal operation we still allow it, but
721 * with a warning. This is because even though ProcessUtility disallows
722 * DROP TABLESPACE in a transaction block, it's possible that a previous
723 * DROP failed and rolled back after removing the tablespace directories
724 * and/or symlink. We want to allow a new DROP attempt to succeed at
725 * removing the catalog entries (and symlink if still present), so we
726 * should not give a hard error here.
727 */
729 if (dirdesc == NULL)
730 {
731 if (errno == ENOENT)
732 {
733 if (!redo)
736 errmsg("could not open directory \"%s\": %m",
738 /* The symlink might still exist, so go try to remove it */
739 goto remove_symlink;
740 }
741 else if (redo)
742 {
743 /* in redo, just log other types of error */
744 ereport(LOG,
746 errmsg("could not open directory \"%s\": %m",
749 return false;
750 }
751 /* else let ReadDir report the error */
752 }
753
754 while ((de = ReadDir(dirdesc, linkloc_with_version_dir)) != NULL)
755 {
756 if (strcmp(de->d_name, ".") == 0 ||
757 strcmp(de->d_name, "..") == 0)
758 continue;
759
760 subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
761
762 /* This check is just to deliver a friendlier error message */
763 if (!redo && !directory_is_empty(subfile))
764 {
765 FreeDir(dirdesc);
766 pfree(subfile);
768 return false;
769 }
770
771 /* remove empty directory */
772 if (rmdir(subfile) < 0)
773 ereport(redo ? LOG : ERROR,
775 errmsg("could not remove directory \"%s\": %m",
776 subfile)));
777
778 pfree(subfile);
779 }
780
781 FreeDir(dirdesc);
782
783 /* remove version directory */
785 {
786 ereport(redo ? LOG : ERROR,
788 errmsg("could not remove directory \"%s\": %m",
791 return false;
792 }
793
794 /*
795 * Try to remove the symlink. We must however deal with the possibility
796 * that it's a directory instead of a symlink --- this could happen during
797 * WAL replay (see TablespaceCreateDbspace).
798 *
799 * Note: in the redo case, we'll return true if this final step fails;
800 * there's no point in retrying it. Also, ENOENT should provoke no more
801 * than a warning.
802 */
806 if (lstat(linkloc, &st) < 0)
807 {
808 int saved_errno = errno;
809
810 ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
812 errmsg("could not stat file \"%s\": %m",
813 linkloc)));
814 }
815 else if (S_ISDIR(st.st_mode))
816 {
817 if (rmdir(linkloc) < 0)
818 {
819 int saved_errno = errno;
820
821 ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
823 errmsg("could not remove directory \"%s\": %m",
824 linkloc)));
825 }
826 }
827 else if (S_ISLNK(st.st_mode))
828 {
829 if (unlink(linkloc) < 0)
830 {
831 int saved_errno = errno;
832
833 ereport(redo ? LOG : (saved_errno == ENOENT ? WARNING : ERROR),
835 errmsg("could not remove symbolic link \"%s\": %m",
836 linkloc)));
837 }
838 }
839 else
840 {
841 /* Refuse to remove anything that's not a directory or symlink */
842 ereport(redo ? LOG : ERROR,
844 errmsg("\"%s\" is not a directory or symbolic link",
845 linkloc)));
846 }
847
849 pfree(linkloc);
850
851 return true;
852}
bool directory_is_empty(const char *path)
Definition tablespace.c:861
int FreeDir(DIR *dir)
Definition fd.c:3009
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
void get_parent_directory(char *path)
Definition path.c:1068
Definition dirent.c:26
#define lstat(path, sb)
Definition win32_port.h:275
#define S_ISLNK(m)
Definition win32_port.h:334

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

Referenced by DropTableSpace(), and tblspc_redo().

◆ directory_is_empty()

bool directory_is_empty ( const char path)

Definition at line 861 of file tablespace.c.

862{
863 DIR *dirdesc;
864 struct dirent *de;
865
866 dirdesc = AllocateDir(path);
867
868 while ((de = ReadDir(dirdesc, path)) != NULL)
869 {
870 if (strcmp(de->d_name, ".") == 0 ||
871 strcmp(de->d_name, "..") == 0)
872 continue;
873 FreeDir(dirdesc);
874 return false;
875 }
876
877 FreeDir(dirdesc);
878 return true;
879}

References AllocateDir(), fb(), FreeDir(), and ReadDir().

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

◆ DropTableSpace()

void DropTableSpace ( DropTableSpaceStmt stmt)

Definition at line 403 of file tablespace.c.

404{
405 char *tablespacename = stmt->tablespacename;
406 TableScanDesc scandesc;
407 Relation rel;
408 HeapTuple tuple;
410 ScanKeyData entry[1];
412 char *detail;
413 char *detail_log;
414
415 /*
416 * Find the target tuple
417 */
419
420 ScanKeyInit(&entry[0],
423 CStringGetDatum(tablespacename));
424 scandesc = table_beginscan_catalog(rel, 1, entry);
425 tuple = heap_getnext(scandesc, ForwardScanDirection);
426
427 if (!HeapTupleIsValid(tuple))
428 {
429 if (!stmt->missing_ok)
430 {
433 errmsg("tablespace \"%s\" does not exist",
434 tablespacename)));
435 }
436 else
437 {
439 (errmsg("tablespace \"%s\" does not exist, skipping",
440 tablespacename)));
441 table_endscan(scandesc);
442 table_close(rel, NoLock);
443 }
444 return;
445 }
446
448 tablespaceoid = spcform->oid;
449
450 /* Must be tablespace owner */
453 tablespacename);
454
455 /* Disallow drop of the standard tablespaces, even by superuser */
458 tablespacename);
459
460 /* Check for pg_shdepend entries depending on this tablespace */
462 &detail, &detail_log))
465 errmsg("tablespace \"%s\" cannot be dropped because some objects depend on it",
466 tablespacename),
467 errdetail_internal("%s", detail),
468 errdetail_log("%s", detail_log)));
469
470 /* DROP hook for the tablespace being removed */
472
473 /*
474 * Remove the pg_tablespace tuple (this will roll back if we fail below)
475 */
476 CatalogTupleDelete(rel, &tuple->t_self);
477
478 table_endscan(scandesc);
479
480 /*
481 * Remove any comments or security labels on this tablespace.
482 */
485
486 /*
487 * Remove dependency on owner.
488 */
490
491 /*
492 * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
493 * is running concurrently.
494 */
496
497 /*
498 * Try to remove the physical infrastructure.
499 */
501 {
502 /*
503 * Not all files deleted? However, there can be lingering empty files
504 * in the directories, left behind by for example DROP TABLE, that
505 * have been scheduled for deletion at next checkpoint (see comments
506 * in mdunlink() for details). We could just delete them immediately,
507 * but we can't tell them apart from important data files that we
508 * mustn't delete. So instead, we force a checkpoint which will clean
509 * out any lingering files, and try again.
510 */
512
513 /*
514 * On Windows, an unlinked file persists in the directory listing
515 * until no process retains an open handle for the file. The DDL
516 * commands that schedule files for unlink send invalidation messages
517 * directing other PostgreSQL processes to close the files, but
518 * nothing guarantees they'll be processed in time. So, we'll also
519 * use a global barrier to ask all backends to close all files, and
520 * wait until they're finished.
521 */
525
526 /* And now try again. */
528 {
529 /* Still not empty, the files must be important then */
532 errmsg("tablespace \"%s\" is not empty",
533 tablespacename)));
534 }
535 }
536
537 /* Record the filesystem change in XLOG */
538 {
540
542
545
547 }
548
549 /*
550 * Note: because we checked that the tablespace was empty, there should be
551 * no need to worry about flushing shared buffers or free space map
552 * entries for relations in the tablespace.
553 */
554
555 /*
556 * Force synchronous commit, to minimize the window between removing the
557 * files on-disk and marking the transaction committed. It's not great
558 * that there is any window at all, but definitely we don't want to make
559 * it larger than necessary.
560 */
562
563 /*
564 * Allow TablespaceCreateDbspace again.
565 */
567
568 /* We keep the lock on pg_tablespace until commit */
569 table_close(rel, NoLock);
570}
@ ACLCHECK_NO_PRIV
Definition acl.h:185
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition tablespace.c:694
bool IsPinnedObject(Oid classId, Oid objectId)
Definition catalog.c:370
void RequestCheckpoint(int flags)
void DeleteSharedComments(Oid oid, Oid classoid)
Definition comment.c:384
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
int int int errdetail_log(const char *fmt,...) pg_attribute_printf(1
void CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
Definition indexing.c:365
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_EXCLUSIVE
Definition lwlock.h:104
#define InvokeObjectDropHook(classId, objectId, subId)
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
bool checkSharedDependencies(Oid classId, Oid objectId, char **detail_msg, char **detail_log_msg)
void WaitForProcSignalBarrier(uint64 generation)
Definition procsignal.c:428
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition procsignal.c:360
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition procsignal.h:50
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition seclabel.c:502
#define XLOG_TBLSPC_DROP
Definition tablespace.h:28
#define CHECKPOINT_FORCE
Definition xlog.h:154
#define CHECKPOINT_WAIT
Definition xlog.h:157
#define CHECKPOINT_FAST
Definition xlog.h:153

References aclcheck_error(), ACLCHECK_NO_PRIV, ACLCHECK_NOT_OWNER, BTEqualStrategyNumber, CatalogTupleDelete(), CHECKPOINT_FAST, CHECKPOINT_FORCE, CHECKPOINT_WAIT, checkSharedDependencies(), CStringGetDatum(), DeleteSharedComments(), deleteSharedDependencyRecordsFor(), DeleteSharedSecurityLabel(), destroy_tablespace_directories(), EmitProcSignalBarrier(), ereport, errcode(), errdetail_internal(), errdetail_log(), errmsg, ERROR, fb(), ForceSyncCommit(), Form_pg_tablespace, ForwardScanDirection, GETSTRUCT(), GetUserId(), heap_getnext(), HeapTupleIsValid, InvokeObjectDropHook, IsPinnedObject(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), NoLock, NOTICE, object_ownercheck(), OBJECT_TABLESPACE, PROCSIGNAL_BARRIER_SMGRRELEASE, RequestCheckpoint(), RowExclusiveLock, ScanKeyInit(), stmt, HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), xl_tblspc_drop_rec::ts_id, WaitForProcSignalBarrier(), XLOG_TBLSPC_DROP, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by standard_ProcessUtility().

◆ get_tablespace_name()

char * get_tablespace_name ( Oid  spc_oid)

Definition at line 1486 of file tablespace.c.

1487{
1488 char *result;
1489 Relation rel;
1490 TableScanDesc scandesc;
1491 HeapTuple tuple;
1492 ScanKeyData entry[1];
1493
1494 /*
1495 * Search pg_tablespace. We use a heapscan here even though there is an
1496 * index on oid, on the theory that pg_tablespace will usually have just a
1497 * few entries and so an indexed lookup is a waste of effort.
1498 */
1500
1501 ScanKeyInit(&entry[0],
1505 scandesc = table_beginscan_catalog(rel, 1, entry);
1506 tuple = heap_getnext(scandesc, ForwardScanDirection);
1507
1508 /* We assume that there can be at most one matching tuple */
1509 if (HeapTupleIsValid(tuple))
1511 else
1512 result = NULL;
1513
1514 table_endscan(scandesc);
1516
1517 return result;
1518}
#define NameStr(name)
Definition c.h:835
uint32 result
#define AccessShareLock
Definition lockdefs.h:36

References AccessShareLock, BTEqualStrategyNumber, fb(), Form_pg_tablespace, ForwardScanDirection, GETSTRUCT(), heap_getnext(), HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), result, ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

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

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char tablespacename,
bool  missing_ok 
)

Definition at line 1440 of file tablespace.c.

1441{
1442 Oid result;
1443 Relation rel;
1444 TableScanDesc scandesc;
1445 HeapTuple tuple;
1446 ScanKeyData entry[1];
1447
1448 /*
1449 * Search pg_tablespace. We use a heapscan here even though there is an
1450 * index on name, on the theory that pg_tablespace will usually have just
1451 * a few entries and so an indexed lookup is a waste of effort.
1452 */
1454
1455 ScanKeyInit(&entry[0],
1458 CStringGetDatum(tablespacename));
1459 scandesc = table_beginscan_catalog(rel, 1, entry);
1460 tuple = heap_getnext(scandesc, ForwardScanDirection);
1461
1462 /* We assume that there can be at most one matching tuple */
1463 if (HeapTupleIsValid(tuple))
1464 result = ((Form_pg_tablespace) GETSTRUCT(tuple))->oid;
1465 else
1467
1468 table_endscan(scandesc);
1470
1471 if (!OidIsValid(result) && !missing_ok)
1472 ereport(ERROR,
1474 errmsg("tablespace \"%s\" does not exist",
1475 tablespacename)));
1476
1477 return result;
1478}

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum(), ereport, errcode(), errmsg, ERROR, fb(), Form_pg_tablespace, ForwardScanDirection, GETSTRUCT(), heap_getnext(), HeapTupleIsValid, InvalidOid, OidIsValid, result, ScanKeyInit(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

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

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence,
bool  partitioned 
)

Definition at line 1157 of file tablespace.c.

1158{
1159 Oid result;
1160
1161 /* The temp-table case is handled elsewhere */
1162 if (relpersistence == RELPERSISTENCE_TEMP)
1163 {
1165 return GetNextTempTableSpace();
1166 }
1167
1168 /* Fast path for default_tablespace == "" */
1169 if (default_tablespace == NULL || default_tablespace[0] == '\0')
1170 return InvalidOid;
1171
1172 /*
1173 * It is tempting to cache this lookup for more speed, but then we would
1174 * fail to detect the case where the tablespace was dropped since the GUC
1175 * variable was set. Note also that we don't complain if the value fails
1176 * to refer to an existing tablespace; we just silently return InvalidOid,
1177 * causing the new object to be created in the database's tablespace.
1178 */
1180
1181 /*
1182 * Allow explicit specification of database's default tablespace in
1183 * default_tablespace without triggering permissions checks. Don't allow
1184 * specifying that when creating a partitioned table, however, since the
1185 * result is confusing.
1186 */
1188 {
1189 if (partitioned)
1190 ereport(ERROR,
1192 errmsg("cannot specify default tablespace for partitioned relations")));
1194 }
1195 return result;
1196}
void PrepareTempTablespaces(void)
char * default_tablespace
Definition tablespace.c:85
Oid GetNextTempTableSpace(void)
Definition fd.c:3159

References default_tablespace, ereport, errcode(), errmsg, ERROR, fb(), get_tablespace_oid(), GetNextTempTableSpace(), InvalidOid, MyDatabaseTableSpace, PrepareTempTablespaces(), and result.

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1345 of file tablespace.c.

1346{
1347 char *rawname;
1348 List *namelist;
1349 Oid *tblSpcs;
1350 int numSpcs;
1351 ListCell *l;
1352
1353 /* No work if already done in current transaction */
1355 return;
1356
1357 /*
1358 * Can't do catalog access unless within a transaction. This is just a
1359 * safety check in case this function is called by low-level code that
1360 * could conceivably execute outside a transaction. Note that in such a
1361 * scenario, fd.c will fall back to using the current database's default
1362 * tablespace, which should always be OK.
1363 */
1364 if (!IsTransactionState())
1365 return;
1366
1367 /* Need a modifiable copy of string */
1369
1370 /* Parse string into list of identifiers */
1372 {
1373 /* syntax error in name list */
1375 pfree(rawname);
1377 return;
1378 }
1379
1380 /* Store tablespace OIDs in an array in TopTransactionContext */
1382 list_length(namelist) * sizeof(Oid));
1383 numSpcs = 0;
1384 foreach(l, namelist)
1385 {
1386 char *curname = (char *) lfirst(l);
1387 Oid curoid;
1389
1390 /* Allow an empty string (signifying database default) */
1391 if (curname[0] == '\0')
1392 {
1393 /* InvalidOid signifies database's default tablespace */
1394 tblSpcs[numSpcs++] = InvalidOid;
1395 continue;
1396 }
1397
1398 /* Else verify that name is a valid tablespace name */
1400 if (curoid == InvalidOid)
1401 {
1402 /* Skip any bad list elements */
1403 continue;
1404 }
1405
1406 /*
1407 * Allow explicit specification of database's default tablespace in
1408 * temp_tablespaces without triggering permissions checks.
1409 */
1411 {
1412 /* InvalidOid signifies database's default tablespace */
1413 tblSpcs[numSpcs++] = InvalidOid;
1414 continue;
1415 }
1416
1417 /* Check permissions similarly */
1419 ACL_CREATE);
1420 if (aclresult != ACLCHECK_OK)
1421 continue;
1422
1423 tblSpcs[numSpcs++] = curoid;
1424 }
1425
1426 SetTempTablespaces(tblSpcs, numSpcs);
1427
1428 pfree(rawname);
1430}
char * temp_tablespaces
Definition tablespace.c:86
bool TempTablespacesAreSet(void)
Definition fd.c:3126
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
MemoryContext TopTransactionContext
Definition mcxt.c:171

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

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

◆ remove_tablespace_symlink()

void remove_tablespace_symlink ( const char linkloc)

Definition at line 891 of file tablespace.c.

892{
893 struct stat st;
894
895 if (lstat(linkloc, &st) < 0)
896 {
897 if (errno == ENOENT)
898 return;
901 errmsg("could not stat file \"%s\": %m", linkloc)));
902 }
903
904 if (S_ISDIR(st.st_mode))
905 {
906 /*
907 * This will fail if the directory isn't empty, but not if it's a
908 * junction point.
909 */
910 if (rmdir(linkloc) < 0 && errno != ENOENT)
913 errmsg("could not remove directory \"%s\": %m",
914 linkloc)));
915 }
916 else if (S_ISLNK(st.st_mode))
917 {
918 if (unlink(linkloc) < 0 && errno != ENOENT)
921 errmsg("could not remove symbolic link \"%s\": %m",
922 linkloc)));
923 }
924 else
925 {
926 /* Refuse to remove anything that's not a directory or symlink */
929 errmsg("\"%s\" is not a directory or symbolic link",
930 linkloc)));
931 }
932}

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

Referenced by create_tablespace_directories(), and InitWalRecovery().

◆ RenameTableSpace()

ObjectAddress RenameTableSpace ( const char oldname,
const char newname 
)

Definition at line 938 of file tablespace.c.

939{
940 Oid tspId;
941 Relation rel;
942 ScanKeyData entry[1];
943 TableScanDesc scan;
945 HeapTuple newtuple;
947 ObjectAddress address;
948
949 /* Search pg_tablespace */
951
952 ScanKeyInit(&entry[0],
956 scan = table_beginscan_catalog(rel, 1, entry);
958 if (!HeapTupleIsValid(tup))
961 errmsg("tablespace \"%s\" does not exist",
962 oldname)));
963
964 newtuple = heap_copytuple(tup);
966 tspId = newform->oid;
967
968 table_endscan(scan);
969
970 /* Must be owner */
973
974 /* Validate new name */
975 if (!allowSystemTableMods && IsReservedName(newname))
978 errmsg("unacceptable tablespace name \"%s\"", newname),
979 errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
980
981 /* Report error if name has \n or \r character. */
982 if (strpbrk(newname, "\n\r"))
985 errmsg("tablespace name \"%s\" contains a newline or carriage return character", newname)));
986
987 /*
988 * If built with appropriate switch, whine when regression-testing
989 * conventions for tablespace names are violated.
990 */
991#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
992 if (strncmp(newname, "regress_", 8) != 0)
993 elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
994#endif
995
996 /* Make sure the new name doesn't exist */
997 ScanKeyInit(&entry[0],
1000 CStringGetDatum(newname));
1001 scan = table_beginscan_catalog(rel, 1, entry);
1003 if (HeapTupleIsValid(tup))
1004 ereport(ERROR,
1006 errmsg("tablespace \"%s\" already exists",
1007 newname)));
1008
1009 table_endscan(scan);
1010
1011 /* OK, update the entry */
1012 namestrcpy(&(newform->spcname), newname);
1013
1014 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1015
1017
1019
1020 table_close(rel, NoLock);
1021
1022 return address;
1023}
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:686
void namestrcpy(Name name, const char *str)
Definition name.c:233
#define ObjectAddressSet(addr, class_id, object_id)

References aclcheck_error(), ACLCHECK_NO_PRIV, allowSystemTableMods, BTEqualStrategyNumber, CatalogTupleUpdate(), CStringGetDatum(), elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errmsg, ERROR, fb(), Form_pg_tablespace, ForwardScanDirection, GETSTRUCT(), GetUserId(), heap_copytuple(), heap_getnext(), HeapTupleIsValid, InvokeObjectPostAlterHook, IsReservedName(), namestrcpy(), NoLock, object_ownercheck(), OBJECT_TABLESPACE, ObjectAddressSet, RowExclusiveLock, ScanKeyInit(), HeapTupleData::t_self, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and WARNING.

Referenced by ExecRenameStmt().

◆ TablespaceCreateDbspace()

void TablespaceCreateDbspace ( Oid  spcOid,
Oid  dbOid,
bool  isRedo 
)

Definition at line 114 of file tablespace.c.

115{
116 struct stat st;
117 char *dir;
118
119 /*
120 * The global tablespace doesn't have per-database subdirectories, so
121 * nothing to do for it.
122 */
123 if (spcOid == GLOBALTABLESPACE_OID)
124 return;
125
126 Assert(OidIsValid(spcOid));
127 Assert(OidIsValid(dbOid));
128
129 dir = GetDatabasePath(dbOid, spcOid);
130
131 if (stat(dir, &st) < 0)
132 {
133 /* Directory does not exist? */
134 if (errno == ENOENT)
135 {
136 /*
137 * Acquire TablespaceCreateLock to ensure that no DROP TABLESPACE
138 * or TablespaceCreateDbspace is running concurrently.
139 */
141
142 /*
143 * Recheck to see if someone created the directory while we were
144 * waiting for lock.
145 */
146 if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode))
147 {
148 /* Directory was created */
149 }
150 else
151 {
152 /* Directory creation failed? */
153 if (MakePGDirectory(dir) < 0)
154 {
155 /* Failure other than not exists or not in WAL replay? */
156 if (errno != ENOENT || !isRedo)
159 errmsg("could not create directory \"%s\": %m",
160 dir)));
161
162 /*
163 * During WAL replay, it's conceivable that several levels
164 * of directories are missing if tablespaces are dropped
165 * further ahead of the WAL stream than we're currently
166 * replaying. An easy way forward is to create them as
167 * plain directories and hope they are removed by further
168 * WAL replay if necessary. If this also fails, there is
169 * trouble we cannot get out of, so just report that and
170 * bail out.
171 */
172 if (pg_mkdir_p(dir, pg_dir_create_mode) < 0)
175 errmsg("could not create directory \"%s\": %m",
176 dir)));
177 }
178 }
179
181 }
182 else
183 {
186 errmsg("could not stat directory \"%s\": %m", dir)));
187 }
188 }
189 else
190 {
191 /* Is it not a directory? */
192 if (!S_ISDIR(st.st_mode))
195 errmsg("\"%s\" exists but is not a directory",
196 dir)));
197 }
198
199 pfree(dir);
200}
#define Assert(condition)
Definition c.h:943
int pg_mkdir_p(char *path, int omode)
Definition pgmkdirp.c:57
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition relpath.c:110

References Assert, ereport, errcode(), errcode_for_file_access(), errmsg, ERROR, fb(), GetDatabasePath(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MakePGDirectory(), OidIsValid, pfree(), pg_dir_create_mode, pg_mkdir_p(), S_ISDIR, stat::st_mode, and stat.

Referenced by mdcreate().

◆ tblspc_redo()

void tblspc_redo ( XLogReaderState record)

Definition at line 1525 of file tablespace.c.

1526{
1527 uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
1528
1529 /* Backup blocks are not used in tblspc records */
1531
1532 if (info == XLOG_TBLSPC_CREATE)
1533 {
1535 char *location = xlrec->ts_path;
1536
1537 create_tablespace_directories(location, xlrec->ts_id);
1538 }
1539 else if (info == XLOG_TBLSPC_DROP)
1540 {
1542
1543 /* Close all smgr fds in all backends. */
1545
1546 /*
1547 * If we issued a WAL record for a drop tablespace it implies that
1548 * there were no files in it at all when the DROP was done. That means
1549 * that no permanent objects can exist in it at this point.
1550 *
1551 * It is possible for standby users to be using this tablespace as a
1552 * location for their temporary files, so if we fail to remove all
1553 * files then do conflict processing and try again, if currently
1554 * enabled.
1555 *
1556 * Other possible reasons for failure include bollixed file
1557 * permissions on a standby server when they were okay on the primary,
1558 * etc etc. There's not much we can do about that, so just remove what
1559 * we can and press on.
1560 */
1561 if (!destroy_tablespace_directories(xlrec->ts_id, true))
1562 {
1564
1565 /*
1566 * If we did recovery processing then hopefully the backends who
1567 * wrote temp files should have cleaned up and exited by now. So
1568 * retry before complaining. If we fail again, this is just a LOG
1569 * condition, because it's not worth throwing an ERROR for (as
1570 * that would crash the database and require manual intervention
1571 * before we could get past this WAL record on restart).
1572 */
1573 if (!destroy_tablespace_directories(xlrec->ts_id, true))
1574 ereport(LOG,
1576 errmsg("directories for tablespace %u could not be removed",
1577 xlrec->ts_id),
1578 errhint("You can remove the directories manually if necessary.")));
1579 }
1580 }
1581 else
1582 elog(PANIC, "tblspc_redo: unknown op code %u", info);
1583}
uint8_t uint8
Definition c.h:622
#define PANIC
Definition elog.h:44
void ResolveRecoveryConflictWithTablespace(Oid tsid)
Definition standby.c:542
char ts_path[FLEXIBLE_ARRAY_MEMBER]
Definition tablespace.h:33
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:410
#define XLogRecGetData(decoder)
Definition xlogreader.h:415
#define XLogRecHasAnyBlockRefs(decoder)
Definition xlogreader.h:417

References Assert, create_tablespace_directories(), destroy_tablespace_directories(), elog, EmitProcSignalBarrier(), ereport, errcode(), errhint(), errmsg, fb(), LOG, PANIC, PROCSIGNAL_BARRIER_SMGRRELEASE, ResolveRecoveryConflictWithTablespace(), xl_tblspc_create_rec::ts_path, WaitForProcSignalBarrier(), XLOG_TBLSPC_CREATE, XLOG_TBLSPC_DROP, XLogRecGetData, XLogRecGetInfo, and XLogRecHasAnyBlockRefs.

Variable Documentation

◆ allow_in_place_tablespaces

bool allow_in_place_tablespaces = false

Definition at line 87 of file tablespace.c.

Referenced by CheckTablespaceDirectory(), CreateTableSpace(), and recovery_create_dbdir().

◆ binary_upgrade_next_pg_tablespace_oid

Oid binary_upgrade_next_pg_tablespace_oid = InvalidOid

Definition at line 89 of file tablespace.c.

Referenced by binary_upgrade_set_next_pg_tablespace_oid(), and CreateTableSpace().

◆ default_tablespace

char* default_tablespace = NULL

Definition at line 85 of file tablespace.c.

Referenced by GetDefaultTablespace().

◆ temp_tablespaces

char* temp_tablespaces = NULL

Definition at line 86 of file tablespace.c.

Referenced by PrepareTempTablespaces().