Debian Codegraph @

src/backend/catalog/pg_attrdef.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * pg_attrdef.c
4 * routines to support manipulation of the pg_attrdef relation
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/catalog/pg_attrdef.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include "access/relation.h"
18 #include "access/table.h"
19 #include "catalog/dependency.h"
20 #include "catalog/indexing.h"
21 #include "catalog/objectaccess.h"
22 #include "catalog/pg_attrdef.h"
23 #include "utils/builtins.h"
24 #include "utils/fmgroids.h"
25 #include "utils/rel.h"
26 #include "utils/syscache.h"
27
28
29 /*
30 * Store a default expression for column attnum of relation rel.
31 *
32 * Returns the OID of the new pg_attrdef tuple.
33 *
34 * NB: Caller is responsible for ensuring the user has USAGE on all types expr
35 * depends on.
36 */
37 Oid
38 StoreAttrDefault(Relation rel, AttrNumber attnum,
39 Node *expr, bool is_internal)
40 {
41 char *adbin;
42 Relation adrel;
43 HeapTuple tuple;
44 Datum values[Natts_pg_attrdef];
45 static bool nulls[Natts_pg_attrdef] = {false, false, false, false};
46 Relation attrrel;
47 HeapTuple atttup;
48 Form_pg_attribute attStruct;
49 Datum valuesAtt[Natts_pg_attribute] = {0};
50 bool nullsAtt[Natts_pg_attribute] = {0};
51 bool replacesAtt[Natts_pg_attribute] = {0};
52 char attgenerated;
53 Oid attrdefOid;
54 ObjectAddress colobject,
55 defobject;
56
57 adrel = table_open(AttrDefaultRelationId, RowExclusiveLock);
58
59 /*
60 * Flatten expression to string form for storage.
61 */
62 adbin = nodeToString(expr);
63
64 /*
65 * Make the pg_attrdef entry.
66 */
67 attrdefOid = GetNewOidWithIndex(adrel, AttrDefaultOidIndexId,
68 Anum_pg_attrdef_oid);
69 values[Anum_pg_attrdef_oid - 1] = ObjectIdGetDatum(attrdefOid);
70 values[Anum_pg_attrdef_adrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
71 values[Anum_pg_attrdef_adnum - 1] = Int16GetDatum(attnum);
72 values[Anum_pg_attrdef_adbin - 1] = CStringGetTextDatum(adbin);
73
74 tuple = heap_form_tuple(adrel->rd_att, values, nulls);
75 CatalogTupleInsert(adrel, tuple);
76
77 defobject.classId = AttrDefaultRelationId;
78 defobject.objectId = attrdefOid;
79 defobject.objectSubId = 0;
80
81 table_close(adrel, RowExclusiveLock);
82
83 /* now can free some of the stuff allocated above */
84 pfree(DatumGetPointer(values[Anum_pg_attrdef_adbin - 1]));
85 heap_freetuple(tuple);
86 pfree(adbin);
87
88 /*
89 * Update the pg_attribute entry for the column to show that a default
90 * exists.
91 */
92 attrrel = table_open(AttributeRelationId, RowExclusiveLock);
93 atttup = SearchSysCacheCopy2(ATTNUM,
94 ObjectIdGetDatum(RelationGetRelid(rel)),
95 Int16GetDatum(attnum));
96 if (!HeapTupleIsValid(atttup))
97 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
98 attnum, RelationGetRelid(rel));
99 attStruct = (Form_pg_attribute) GETSTRUCT(atttup);
100 attgenerated = attStruct->attgenerated;
101
102 valuesAtt[Anum_pg_attribute_atthasdef - 1] = BoolGetDatum(true);
103 replacesAtt[Anum_pg_attribute_atthasdef - 1] = true;
104
105 atttup = heap_modify_tuple(atttup, RelationGetDescr(attrrel),
106 valuesAtt, nullsAtt, replacesAtt);
107
108 CatalogTupleUpdate(attrrel, &atttup->t_self, atttup);
109
110 table_close(attrrel, RowExclusiveLock);
111 heap_freetuple(atttup);
112
113 /*
114 * Make a dependency so that the pg_attrdef entry goes away if the column
115 * (or whole table) is deleted. In the case of a generated column, make
116 * it an internal dependency to prevent the default expression from being
117 * deleted separately.
118 */
119 colobject.classId = RelationRelationId;
120 colobject.objectId = RelationGetRelid(rel);
121 colobject.objectSubId = attnum;
122
123 recordDependencyOn(&defobject, &colobject,
124 attgenerated ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO);
125
126 /*
127 * Record dependencies on objects used in the expression, too.
128 */
129 recordDependencyOnSingleRelExpr(&defobject, expr, RelationGetRelid(rel),
130 DEPENDENCY_NORMAL,
131 DEPENDENCY_NORMAL, false);
132
133 /*
134 * Post creation hook for attribute defaults.
135 *
136 * XXX. ALTER TABLE ALTER COLUMN SET/DROP DEFAULT is implemented with a
137 * couple of deletion/creation of the attribute's default entry, so the
138 * callee should check existence of an older version of this entry if it
139 * needs to distinguish.
140 */
141 InvokeObjectPostCreateHookArg(AttrDefaultRelationId,
142 RelationGetRelid(rel), attnum, is_internal);
143
144 return attrdefOid;
145 }
146
147
148 /*
149 * RemoveAttrDefault
150 *
151 * If the specified relation/attribute has a default, remove it.
152 * (If no default, raise error if complain is true, else return quietly.)
153 */
154 void
155 RemoveAttrDefault(Oid relid, AttrNumber attnum,
156 DropBehavior behavior, bool complain, bool internal)
157 {
158 Relation attrdef_rel;
159 ScanKeyData scankeys[2];
160 SysScanDesc scan;
161 HeapTuple tuple;
162 bool found = false;
163
164 attrdef_rel = table_open(AttrDefaultRelationId, RowExclusiveLock);
165
166 ScanKeyInit(&scankeys[0],
167 Anum_pg_attrdef_adrelid,
168 BTEqualStrategyNumber, F_OIDEQ,
169 ObjectIdGetDatum(relid));
170 ScanKeyInit(&scankeys[1],
171 Anum_pg_attrdef_adnum,
172 BTEqualStrategyNumber, F_INT2EQ,
173 Int16GetDatum(attnum));
174
175 scan = systable_beginscan(attrdef_rel, AttrDefaultIndexId, true,
176 NULL, 2, scankeys);
177
178 /* There should be at most one matching tuple, but we loop anyway */
179 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
180 {
181 ObjectAddress object;
182 Form_pg_attrdef attrtuple = (Form_pg_attrdef) GETSTRUCT(tuple);
183
184 object.classId = AttrDefaultRelationId;
185 object.objectId = attrtuple->oid;
186 object.objectSubId = 0;
187
188 performDeletion(&object, behavior,
189 internal ? PERFORM_DELETION_INTERNAL : 0);
190
191 found = true;
192 }
193
194 systable_endscan(scan);
195 table_close(attrdef_rel, RowExclusiveLock);
196
197 if (complain && !found)
198 elog(ERROR, "could not find attrdef tuple for relation %u attnum %d",
199 relid, attnum);
200 }
201
202 /*
203 * RemoveAttrDefaultById
204 *
205 * Remove a pg_attrdef entry specified by OID. This is the guts of
206 * attribute-default removal. Note it should be called via performDeletion,
207 * not directly.
208 */
209 void
210 RemoveAttrDefaultById(Oid attrdefId)
211 {
212 Relation attrdef_rel;
213 Relation attr_rel;
214 Relation myrel;
215 ScanKeyData scankeys[1];
216 SysScanDesc scan;
217 HeapTuple tuple;
218 Oid myrelid;
219 AttrNumber myattnum;
220
221 /* Grab an appropriate lock on the pg_attrdef relation */
222 attrdef_rel = table_open(AttrDefaultRelationId, RowExclusiveLock);
223
224 /* Find the pg_attrdef tuple */
225 ScanKeyInit(&scankeys[0],
226 Anum_pg_attrdef_oid,
227 BTEqualStrategyNumber, F_OIDEQ,
228 ObjectIdGetDatum(attrdefId));
229
230 scan = systable_beginscan(attrdef_rel, AttrDefaultOidIndexId, true,
231 NULL, 1, scankeys);
232
233 tuple = systable_getnext(scan);
234 if (!HeapTupleIsValid(tuple))
235 elog(ERROR, "could not find tuple for attrdef %u", attrdefId);
236
237 myrelid = ((Form_pg_attrdef) GETSTRUCT(tuple))->adrelid;
238 myattnum = ((Form_pg_attrdef) GETSTRUCT(tuple))->adnum;
239
240 /* Get an exclusive lock on the relation owning the attribute */
241 myrel = relation_open(myrelid, AccessExclusiveLock);
242
243 /* Now we can delete the pg_attrdef row */
244 CatalogTupleDelete(attrdef_rel, &tuple->t_self);
245
246 systable_endscan(scan);
247 table_close(attrdef_rel, RowExclusiveLock);
248
249 /* Fix the pg_attribute row */
250 attr_rel = table_open(AttributeRelationId, RowExclusiveLock);
251
252 tuple = SearchSysCacheCopy2(ATTNUM,
253 ObjectIdGetDatum(myrelid),
254 Int16GetDatum(myattnum));
255 if (!HeapTupleIsValid(tuple)) /* shouldn't happen */
256 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
257 myattnum, myrelid);
258
259 ((Form_pg_attribute) GETSTRUCT(tuple))->atthasdef = false;
260
261 CatalogTupleUpdate(attr_rel, &tuple->t_self, tuple);
262
263 /*
264 * Our update of the pg_attribute row will force a relcache rebuild, so
265 * there's nothing else to do here.
266 */
267 table_close(attr_rel, RowExclusiveLock);
268
269 /* Keep lock on attribute's rel until end of xact */
270 relation_close(myrel, NoLock);
271 }
272
273
274 /*
275 * Get the pg_attrdef OID of the default expression for a column
276 * identified by relation OID and column number.
277 *
278 * Returns InvalidOid if there is no such pg_attrdef entry.
279 */
280 Oid
281 GetAttrDefaultOid(Oid relid, AttrNumber attnum)
282 {
283 Oid result = InvalidOid;
284 Relation attrdef;
285 ScanKeyData keys[2];
286 SysScanDesc scan;
287 HeapTuple tup;
288
289 attrdef = table_open(AttrDefaultRelationId, AccessShareLock);
290 ScanKeyInit(&keys[0],
291 Anum_pg_attrdef_adrelid,
292 BTEqualStrategyNumber,
293 F_OIDEQ,
294 ObjectIdGetDatum(relid));
295 ScanKeyInit(&keys[1],
296 Anum_pg_attrdef_adnum,
297 BTEqualStrategyNumber,
298 F_INT2EQ,
299 Int16GetDatum(attnum));
300 scan = systable_beginscan(attrdef, AttrDefaultIndexId, true,
301 NULL, 2, keys);
302
303 if (HeapTupleIsValid(tup = systable_getnext(scan)))
304 {
305 Form_pg_attrdef atdform = (Form_pg_attrdef) GETSTRUCT(tup);
306
307 result = atdform->oid;
308 }
309
310 systable_endscan(scan);
311 table_close(attrdef, AccessShareLock);
312
313 return result;
314 }
315
316 /*
317 * Given a pg_attrdef OID, return the relation OID and column number of
318 * the owning column (represented as an ObjectAddress for convenience).
319 *
320 * Returns InvalidObjectAddress if there is no such pg_attrdef entry.
321 */
322 ObjectAddress
323 GetAttrDefaultColumnAddress(Oid attrdefoid)
324 {
325 ObjectAddress result = InvalidObjectAddress;
326 Relation attrdef;
327 ScanKeyData skey[1];
328 SysScanDesc scan;
329 HeapTuple tup;
330
331 attrdef = table_open(AttrDefaultRelationId, AccessShareLock);
332 ScanKeyInit(&skey[0],
333 Anum_pg_attrdef_oid,
334 BTEqualStrategyNumber, F_OIDEQ,
335 ObjectIdGetDatum(attrdefoid));
336 scan = systable_beginscan(attrdef, AttrDefaultOidIndexId, true,
337 NULL, 1, skey);
338
339 if (HeapTupleIsValid(tup = systable_getnext(scan)))
340 {
341 Form_pg_attrdef atdform = (Form_pg_attrdef) GETSTRUCT(tup);
342
343 result.classId = RelationRelationId;
344 result.objectId = atdform->adrelid;
345 result.objectSubId = atdform->adnum;
346 }
347
348 systable_endscan(scan);
349 table_close(attrdef, AccessShareLock);
350
351 return result;
352 }