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/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 1028 of file tablespace.c.

1029{
1030 Relation rel;
1031 ScanKeyData entry[1];
1032 TableScanDesc scandesc;
1033 HeapTuple tup;
1035 Datum datum;
1038 bool isnull;
1041 HeapTuple newtuple;
1042
1043 /* Search pg_tablespace */
1045
1046 ScanKeyInit(&entry[0],
1049 CStringGetDatum(stmt->tablespacename));
1050 scandesc = table_beginscan_catalog(rel, 1, entry);
1052 if (!HeapTupleIsValid(tup))
1053 ereport(ERROR,
1055 errmsg("tablespace \"%s\" does not exist",
1056 stmt->tablespacename)));
1057
1059
1060 /* Must be owner of the existing object */
1063 stmt->tablespacename);
1064
1065 /* Generate new proposed spcoptions (text array) */
1067 RelationGetDescr(rel), &isnull);
1068 newOptions = transformRelOptions(isnull ? (Datum) 0 : datum,
1070 stmt->isReset);
1072
1073 /* Build new tuple. */
1074 memset(repl_null, false, sizeof(repl_null));
1075 memset(repl_repl, false, sizeof(repl_repl));
1076 if (newOptions != (Datum) 0)
1078 else
1083
1084 /* Update system catalog. */
1085 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1086
1088
1089 heap_freetuple(newtuple);
1090
1091 /* Conclude heap scan. */
1092 table_endscan(scandesc);
1093 table_close(rel, NoLock);
1094
1095 return tablespaceoid;
1096}
@ ACLCHECK_NOT_OWNER
Definition acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2654
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4108
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1410
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1210
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
#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:469
#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:380
unsigned int Oid
static int fb(int x)
#define RelationGetDescr(relation)
Definition rel.h:540
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:1004

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 1319 of file tablespace.c.

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

References fb(), and SetTempTablespaces().

◆ check_default_tablespace()

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

Definition at line 1104 of file tablespace.c.

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

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 1211 of file tablespace.c.

1212{
1213 char *rawname;
1214 List *namelist;
1215
1216 /* Need a modifiable copy of string */
1218
1219 /* Parse string into list of identifiers */
1221 {
1222 /* syntax error in name list */
1223 GUC_check_errdetail("List syntax is invalid.");
1224 pfree(rawname);
1226 return false;
1227 }
1228
1229 /*
1230 * If we aren't inside a transaction, or connected to a database, we
1231 * cannot do the catalog accesses necessary to verify the name. Must
1232 * accept the value on faith. Fortunately, there's then also no need to
1233 * pass the data to fd.c.
1234 */
1236 {
1238 Oid *tblSpcs;
1239 int numSpcs;
1240 ListCell *l;
1241
1242 /* temporary workspace until we are done verifying the list */
1243 tblSpcs = (Oid *) palloc(list_length(namelist) * sizeof(Oid));
1244 numSpcs = 0;
1245 foreach(l, namelist)
1246 {
1247 char *curname = (char *) lfirst(l);
1248 Oid curoid;
1250
1251 /* Allow an empty string (signifying database default) */
1252 if (curname[0] == '\0')
1253 {
1254 /* InvalidOid signifies database's default tablespace */
1255 tblSpcs[numSpcs++] = InvalidOid;
1256 continue;
1257 }
1258
1259 /*
1260 * In an interactive SET command, we ereport for bad info. When
1261 * source == PGC_S_TEST, don't throw a hard error for a
1262 * nonexistent tablespace, only a NOTICE. See comments in guc.h.
1263 */
1265 if (curoid == InvalidOid)
1266 {
1267 if (source == PGC_S_TEST)
1270 errmsg("tablespace \"%s\" does not exist",
1271 curname)));
1272 continue;
1273 }
1274
1275 /*
1276 * Allow explicit specification of database's default tablespace
1277 * in temp_tablespaces without triggering permissions checks.
1278 */
1280 {
1281 /* InvalidOid signifies database's default tablespace */
1282 tblSpcs[numSpcs++] = InvalidOid;
1283 continue;
1284 }
1285
1286 /* Check permissions, similarly complaining only if interactive */
1288 ACL_CREATE);
1289 if (aclresult != ACLCHECK_OK)
1290 {
1293 continue;
1294 }
1295
1296 tblSpcs[numSpcs++] = curoid;
1297 }
1298
1299 /* Now prepare an "extra" struct for assign_temp_tablespaces */
1301 numSpcs * sizeof(Oid));
1302 if (!myextra)
1303 return false;
1304 myextra->numSpcs = numSpcs;
1305 memcpy(myextra->tblSpcs, tblSpcs, numSpcs * sizeof(Oid));
1306 *extra = myextra;
1307
1308 pfree(tblSpcs);
1309 }
1310
1311 pfree(rawname);
1313
1314 return true;
1315}
AclResult
Definition acl.h:182
@ ACLCHECK_OK
Definition acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3854
#define LOG
Definition elog.h:31
Oid MyDatabaseTableSpace
Definition globals.c:96
void * guc_malloc(int elevel, size_t size)
Definition guc.c:636
@ 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:2775

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, 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 579 of file tablespace.c.

580{
581 char *linkloc;
583 struct stat st;
584 bool in_place;
585
587
588 /*
589 * If we're asked to make an 'in place' tablespace, create the directory
590 * directly where the symlink would normally go. This is a developer-only
591 * option for now, to facilitate regression testing.
592 */
593 in_place = strlen(location) == 0;
594
595 if (in_place)
596 {
597 if (MakePGDirectory(linkloc) < 0 && errno != EEXIST)
600 errmsg("could not create directory \"%s\": %m",
601 linkloc)));
602 }
603
604 location_with_version_dir = psprintf("%s/%s", in_place ? linkloc : location,
606
607 /*
608 * Attempt to coerce target directory to safe permissions. If this fails,
609 * it doesn't exist or has the wrong owner. Not needed for in-place mode,
610 * because in that case we created the directory with the desired
611 * permissions.
612 */
613 if (!in_place && chmod(location, pg_dir_create_mode) != 0)
614 {
615 if (errno == ENOENT)
618 errmsg("directory \"%s\" does not exist", location),
619 InRecovery ? errhint("Create this directory for the tablespace before "
620 "restarting the server.") : 0));
621 else
624 errmsg("could not set permissions on directory \"%s\": %m",
625 location)));
626 }
627
628 /*
629 * The creation of the version directory prevents more than one tablespace
630 * in a single location. This imitates TablespaceCreateDbspace(), but it
631 * ignores concurrency and missing parent directories. The chmod() would
632 * have failed in the absence of a parent. pg_tablespace_spcname_index
633 * prevents concurrency.
634 */
635 if (stat(location_with_version_dir, &st) < 0)
636 {
637 if (errno != ENOENT)
640 errmsg("could not stat directory \"%s\": %m",
645 errmsg("could not create directory \"%s\": %m",
647 }
648 else if (!S_ISDIR(st.st_mode))
651 errmsg("\"%s\" exists but is not a directory",
653 else if (!InRecovery)
656 errmsg("directory \"%s\" already in use as a tablespace",
658
659 /*
660 * In recovery, remove old symlink, in case it points to the wrong place.
661 */
662 if (!in_place && InRecovery)
664
665 /*
666 * Create the symlink under PGDATA
667 */
668 if (!in_place && symlink(location, linkloc) < 0)
671 errmsg("could not create symbolic link \"%s\": %m",
672 linkloc)));
673
674 pfree(linkloc);
676}
void remove_tablespace_symlink(const char *linkloc)
Definition tablespace.c:890
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:3962
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 209 of file tablespace.c.

210{
211 Relation rel;
213 bool nulls[Natts_pg_tablespace] = {0};
214 HeapTuple tuple;
216 char *location;
217 Oid ownerId;
219 bool in_place;
220
221 /* Must be superuser */
222 if (!superuser())
225 errmsg("permission denied to create tablespace \"%s\"",
226 stmt->tablespacename),
227 errhint("Must be superuser to create a tablespace.")));
228
229 /* However, the eventual owner of the tablespace need not be */
230 if (stmt->owner)
231 ownerId = get_rolespec_oid(stmt->owner, false);
232 else
233 ownerId = GetUserId();
234
235 /* Unix-ify the offered path, and strip any trailing slashes */
236 location = pstrdup(stmt->location);
237 canonicalize_path(location);
238
239 /* disallow quotes, else CREATE DATABASE would be at risk */
240 if (strchr(location, '\''))
243 errmsg("tablespace location cannot contain single quotes")));
244
245 /* Report error if name has \n or \r character. */
246 if (strpbrk(stmt->tablespacename, "\n\r"))
249 errmsg("tablespace name \"%s\" contains a newline or carriage return character", stmt->tablespacename)));
250
251 in_place = allow_in_place_tablespaces && strlen(location) == 0;
252
253 /*
254 * Allowing relative paths seems risky
255 *
256 * This also helps us ensure that location is not empty or whitespace,
257 * unless specifying a developer-only in-place tablespace.
258 */
259 if (!in_place && !is_absolute_path(location))
262 errmsg("tablespace location must be an absolute path")));
263
264 /*
265 * Check that location isn't too long. Remember that we're going to append
266 * 'PG_XXX/<dboid>/<relid>_<fork>.<nnn>'. FYI, we never actually
267 * reference the whole path here, but MakePGDirectory() uses the first two
268 * parts.
269 */
270 if (strlen(location) + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + 1 +
274 errmsg("tablespace location \"%s\" is too long",
275 location)));
276
277 /* Warn if the tablespace is in the data directory. */
278 if (path_is_prefix_of_path(DataDir, location))
281 errmsg("tablespace location should not be inside the data directory")));
282
283 /*
284 * Disallow creation of tablespaces named "pg_xxx"; we reserve this
285 * namespace for system purposes.
286 */
287 if (!allowSystemTableMods && IsReservedName(stmt->tablespacename))
290 errmsg("unacceptable tablespace name \"%s\"",
291 stmt->tablespacename),
292 errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
293
294 /*
295 * If built with appropriate switch, whine when regression-testing
296 * conventions for tablespace names are violated.
297 */
298#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
299 if (strncmp(stmt->tablespacename, "regress_", 8) != 0)
300 elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
301#endif
302
303 /*
304 * Check that there is no other tablespace by this name. (The unique
305 * index would catch this anyway, but might as well give a friendlier
306 * message.)
307 */
308 if (OidIsValid(get_tablespace_oid(stmt->tablespacename, true)))
311 errmsg("tablespace \"%s\" already exists",
312 stmt->tablespacename)));
313
314 /*
315 * Insert tuple into pg_tablespace. The purpose of doing this first is to
316 * lock the proposed tablename against other would-be creators. The
317 * insertion will roll back if we find problems below.
318 */
320
321 if (IsBinaryUpgrade)
322 {
323 /* Use binary-upgrade override for tablespace oid */
327 errmsg("pg_tablespace OID value not set when in binary upgrade mode")));
328
331 }
332 else
339 ObjectIdGetDatum(ownerId);
340 nulls[Anum_pg_tablespace_spcacl - 1] = true;
341
342 /* Generate new proposed spcoptions (text array) */
344 stmt->options,
345 NULL, NULL, false, false);
347 if (newOptions != (Datum) 0)
349 else
350 nulls[Anum_pg_tablespace_spcoptions - 1] = true;
351
352 tuple = heap_form_tuple(rel->rd_att, values, nulls);
353
354 CatalogTupleInsert(rel, tuple);
355
356 heap_freetuple(tuple);
357
358 /* Record dependency on owner */
360
361 /* Post creation hook for new tablespace */
363
365
366 /* Record the filesystem change in XLOG */
367 {
369
371
375 XLogRegisterData(location, strlen(location) + 1);
376
378 }
379
380 /*
381 * Force synchronous commit, to minimize the window between creating the
382 * symlink on-disk and marking the transaction committed. It's not great
383 * that there is any window at all, but definitely we don't want to make
384 * it larger than necessary.
385 */
387
388 pfree(location);
389
390 /* We keep the lock on pg_tablespace until commit */
391 table_close(rel, NoLock);
392
393 return tablespaceoid;
394}
Oid get_rolespec_oid(const RoleSpec *role, bool missing_ok)
Definition acl.c:5588
Oid binary_upgrade_next_pg_tablespace_oid
Definition tablespace.c:88
static void create_tablespace_directories(const char *location, const Oid tablespaceoid)
Definition tablespace.c:579
bool allow_in_place_tablespaces
Definition tablespace.c:86
static Datum values[MAXATTR]
Definition bootstrap.c:147
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:36
#define elog(elevel,...)
Definition elog.h:226
#define DirectFunctionCall1(func, arg1)
Definition fmgr.h:684
bool IsBinaryUpgrade
Definition globals.c:121
bool allowSystemTableMods
Definition globals.c:130
char * DataDir
Definition globals.c:71
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1117
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:262
#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:1153
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:478
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:368
void XLogBeginInsert(void)
Definition xloginsert.c:152

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 693 of file tablespace.c.

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

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

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 402 of file tablespace.c.

403{
404 char *tablespacename = stmt->tablespacename;
405 TableScanDesc scandesc;
406 Relation rel;
407 HeapTuple tuple;
409 ScanKeyData entry[1];
411 char *detail;
412 char *detail_log;
413
414 /*
415 * Find the target tuple
416 */
418
419 ScanKeyInit(&entry[0],
422 CStringGetDatum(tablespacename));
423 scandesc = table_beginscan_catalog(rel, 1, entry);
424 tuple = heap_getnext(scandesc, ForwardScanDirection);
425
426 if (!HeapTupleIsValid(tuple))
427 {
428 if (!stmt->missing_ok)
429 {
432 errmsg("tablespace \"%s\" does not exist",
433 tablespacename)));
434 }
435 else
436 {
438 (errmsg("tablespace \"%s\" does not exist, skipping",
439 tablespacename)));
440 table_endscan(scandesc);
441 table_close(rel, NoLock);
442 }
443 return;
444 }
445
447 tablespaceoid = spcform->oid;
448
449 /* Must be tablespace owner */
452 tablespacename);
453
454 /* Disallow drop of the standard tablespaces, even by superuser */
457 tablespacename);
458
459 /* Check for pg_shdepend entries depending on this tablespace */
461 &detail, &detail_log))
464 errmsg("tablespace \"%s\" cannot be dropped because some objects depend on it",
465 tablespacename),
466 errdetail_internal("%s", detail),
467 errdetail_log("%s", detail_log)));
468
469 /* DROP hook for the tablespace being removed */
471
472 /*
473 * Remove the pg_tablespace tuple (this will roll back if we fail below)
474 */
475 CatalogTupleDelete(rel, &tuple->t_self);
476
477 table_endscan(scandesc);
478
479 /*
480 * Remove any comments or security labels on this tablespace.
481 */
484
485 /*
486 * Remove dependency on owner.
487 */
489
490 /*
491 * Acquire TablespaceCreateLock to ensure that no TablespaceCreateDbspace
492 * is running concurrently.
493 */
495
496 /*
497 * Try to remove the physical infrastructure.
498 */
500 {
501 /*
502 * Not all files deleted? However, there can be lingering empty files
503 * in the directories, left behind by for example DROP TABLE, that
504 * have been scheduled for deletion at next checkpoint (see comments
505 * in mdunlink() for details). We could just delete them immediately,
506 * but we can't tell them apart from important data files that we
507 * mustn't delete. So instead, we force a checkpoint which will clean
508 * out any lingering files, and try again.
509 */
511
512 /*
513 * On Windows, an unlinked file persists in the directory listing
514 * until no process retains an open handle for the file. The DDL
515 * commands that schedule files for unlink send invalidation messages
516 * directing other PostgreSQL processes to close the files, but
517 * nothing guarantees they'll be processed in time. So, we'll also
518 * use a global barrier to ask all backends to close all files, and
519 * wait until they're finished.
520 */
524
525 /* And now try again. */
527 {
528 /* Still not empty, the files must be important then */
531 errmsg("tablespace \"%s\" is not empty",
532 tablespacename)));
533 }
534 }
535
536 /* Record the filesystem change in XLOG */
537 {
539
541
544
546 }
547
548 /*
549 * Note: because we checked that the tablespace was empty, there should be
550 * no need to worry about flushing shared buffers or free space map
551 * entries for relations in the tablespace.
552 */
553
554 /*
555 * Force synchronous commit, to minimize the window between removing the
556 * files on-disk and marking the transaction committed. It's not great
557 * that there is any window at all, but definitely we don't want to make
558 * it larger than necessary.
559 */
561
562 /*
563 * Allow TablespaceCreateDbspace again.
564 */
566
567 /* We keep the lock on pg_tablespace until commit */
568 table_close(rel, NoLock);
569}
@ ACLCHECK_NO_PRIV
Definition acl.h:184
static bool destroy_tablespace_directories(Oid tablespaceoid, bool redo)
Definition tablespace.c:693
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:1176
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
@ LW_EXCLUSIVE
Definition lwlock.h:112
#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:426
uint64 EmitProcSignalBarrier(ProcSignalBarrierType type)
Definition procsignal.c:358
@ PROCSIGNAL_BARRIER_SMGRRELEASE
Definition procsignal.h:48
void DeleteSharedSecurityLabel(Oid objectId, Oid classId)
Definition seclabel.c:501
#define XLOG_TBLSPC_DROP
Definition tablespace.h:28
#define CHECKPOINT_FORCE
Definition xlog.h:153
#define CHECKPOINT_WAIT
Definition xlog.h:156
#define CHECKPOINT_FAST
Definition xlog.h:152

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 1485 of file tablespace.c.

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

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

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

◆ get_tablespace_oid()

Oid get_tablespace_oid ( const char tablespacename,
bool  missing_ok 
)

Definition at line 1439 of file tablespace.c.

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

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

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

◆ GetDefaultTablespace()

Oid GetDefaultTablespace ( char  relpersistence,
bool  partitioned 
)

Definition at line 1156 of file tablespace.c.

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

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

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

◆ PrepareTempTablespaces()

void PrepareTempTablespaces ( void  )

Definition at line 1344 of file tablespace.c.

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

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

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 937 of file tablespace.c.

938{
939 Oid tspId;
940 Relation rel;
941 ScanKeyData entry[1];
942 TableScanDesc scan;
944 HeapTuple newtuple;
946 ObjectAddress address;
947
948 /* Search pg_tablespace */
950
951 ScanKeyInit(&entry[0],
955 scan = table_beginscan_catalog(rel, 1, entry);
957 if (!HeapTupleIsValid(tup))
960 errmsg("tablespace \"%s\" does not exist",
961 oldname)));
962
963 newtuple = heap_copytuple(tup);
965 tspId = newform->oid;
966
967 table_endscan(scan);
968
969 /* Must be owner */
972
973 /* Validate new name */
974 if (!allowSystemTableMods && IsReservedName(newname))
977 errmsg("unacceptable tablespace name \"%s\"", newname),
978 errdetail("The prefix \"pg_\" is reserved for system tablespaces.")));
979
980 /* Report error if name has \n or \r character. */
981 if (strpbrk(newname, "\n\r"))
984 errmsg("tablespace name \"%s\" contains a newline or carriage return character", newname)));
985
986 /*
987 * If built with appropriate switch, whine when regression-testing
988 * conventions for tablespace names are violated.
989 */
990#ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
991 if (strncmp(newname, "regress_", 8) != 0)
992 elog(WARNING, "tablespaces created by regression test cases should have names starting with \"regress_\"");
993#endif
994
995 /* Make sure the new name doesn't exist */
996 ScanKeyInit(&entry[0],
999 CStringGetDatum(newname));
1000 scan = table_beginscan_catalog(rel, 1, entry);
1002 if (HeapTupleIsValid(tup))
1003 ereport(ERROR,
1005 errmsg("tablespace \"%s\" already exists",
1006 newname)));
1007
1008 table_endscan(scan);
1009
1010 /* OK, update the entry */
1011 namestrcpy(&(newform->spcname), newname);
1012
1013 CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1014
1016
1018
1019 table_close(rel, NoLock);
1020
1021 return address;
1022}
HeapTuple heap_copytuple(HeapTuple tuple)
Definition heaptuple.c:778
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 113 of file tablespace.c.

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

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

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 86 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 88 of file tablespace.c.

Referenced by binary_upgrade_set_next_pg_tablespace_oid(), and CreateTableSpace().

◆ default_tablespace

char* default_tablespace = NULL

Definition at line 84 of file tablespace.c.

Referenced by GetDefaultTablespace().

◆ temp_tablespaces

char* temp_tablespaces = NULL

Definition at line 85 of file tablespace.c.

Referenced by PrepareTempTablespaces().