Debian Codegraph @

src/backend/catalog/pg_constraint.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * pg_constraint.c
4 * routines to support manipulation of the pg_constraint 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_constraint.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include "access/genam.h"
18 #include "access/gist.h"
19 #include "access/htup_details.h"
20 #include "access/sysattr.h"
21 #include "access/table.h"
22 #include "catalog/catalog.h"
23 #include "catalog/dependency.h"
24 #include "catalog/heap.h"
25 #include "catalog/indexing.h"
26 #include "catalog/objectaccess.h"
27 #include "catalog/pg_constraint.h"
28 #include "catalog/pg_operator.h"
29 #include "catalog/pg_type.h"
30 #include "commands/defrem.h"
31 #include "common/int.h"
32 #include "utils/array.h"
33 #include "utils/builtins.h"
34 #include "utils/fmgroids.h"
35 #include "utils/lsyscache.h"
36 #include "utils/rel.h"
37 #include "utils/syscache.h"
38
39
40 /*
41 * CreateConstraintEntry
42 * Create a constraint table entry.
43 *
44 * Subsidiary records (such as triggers or indexes to implement the
45 * constraint) are *not* created here. But we do make dependency links
46 * from the constraint to the things it depends on.
47 *
48 * The new constraint's OID is returned.
49 *
50 * NB: Caller is responsible for ensuring the user has USAGE on all types
51 * conExpr depends on.
52 */
53 Oid
54 CreateConstraintEntry(const char *constraintName,
55 Oid constraintNamespace,
56 char constraintType,
57 bool isDeferrable,
58 bool isDeferred,
59 bool isEnforced,
60 bool isValidated,
61 Oid parentConstrId,
62 Oid relId,
63 const int16 *constraintKey,
64 int constraintNKeys,
65 int constraintNTotalKeys,
66 Oid domainId,
67 Oid indexRelId,
68 Oid foreignRelId,
69 const int16 *foreignKey,
70 const Oid *pfEqOp,
71 const Oid *ppEqOp,
72 const Oid *ffEqOp,
73 int foreignNKeys,
74 char foreignUpdateType,
75 char foreignDeleteType,
76 const int16 *fkDeleteSetCols,
77 int numFkDeleteSetCols,
78 char foreignMatchType,
79 const Oid *exclOp,
80 Node *conExpr,
81 const char *conBin,
82 bool conIsLocal,
83 int16 conInhCount,
84 bool conNoInherit,
85 bool conPeriod,
86 bool is_internal)
87 {
88 Relation conDesc;
89 Oid conOid;
90 HeapTuple tup;
91 bool nulls[Natts_pg_constraint];
92 Datum values[Natts_pg_constraint];
93 ArrayType *conkeyArray;
94 ArrayType *confkeyArray;
95 ArrayType *conpfeqopArray;
96 ArrayType *conppeqopArray;
97 ArrayType *conffeqopArray;
98 ArrayType *conexclopArray;
99 ArrayType *confdelsetcolsArray;
100 NameData cname;
101 int i;
102 ObjectAddress conobject;
103 ObjectAddresses *addrs_auto;
104 ObjectAddresses *addrs_normal;
105
106 /* Only CHECK or FOREIGN KEY constraint can be not enforced */
107 Assert(isEnforced || constraintType == CONSTRAINT_CHECK ||
108 constraintType == CONSTRAINT_FOREIGN);
109 /* NOT ENFORCED constraint must be NOT VALID */
110 Assert(isEnforced || !isValidated);
111
112 conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
113
114 Assert(constraintName);
115 namestrcpy(&cname, constraintName);
116
117 /*
118 * Convert C arrays into Postgres arrays.
119 */
120 if (constraintNKeys > 0)
121 {
122 Datum *conkey;
123
124 conkey = (Datum *) palloc(constraintNKeys * sizeof(Datum));
125 for (i = 0; i < constraintNKeys; i++)
126 conkey[i] = Int16GetDatum(constraintKey[i]);
127 conkeyArray = construct_array_builtin(conkey, constraintNKeys, INT2OID);
128 }
129 else
130 conkeyArray = NULL;
131
132 if (foreignNKeys > 0)
133 {
134 Datum *fkdatums;
135 int nkeys = Max(foreignNKeys, numFkDeleteSetCols);
136
137 fkdatums = (Datum *) palloc(nkeys * sizeof(Datum));
138 for (i = 0; i < foreignNKeys; i++)
139 fkdatums[i] = Int16GetDatum(foreignKey[i]);
140 confkeyArray = construct_array_builtin(fkdatums, foreignNKeys, INT2OID);
141 for (i = 0; i < foreignNKeys; i++)
142 fkdatums[i] = ObjectIdGetDatum(pfEqOp[i]);
143 conpfeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
144 for (i = 0; i < foreignNKeys; i++)
145 fkdatums[i] = ObjectIdGetDatum(ppEqOp[i]);
146 conppeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
147 for (i = 0; i < foreignNKeys; i++)
148 fkdatums[i] = ObjectIdGetDatum(ffEqOp[i]);
149 conffeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
150
151 if (numFkDeleteSetCols > 0)
152 {
153 for (i = 0; i < numFkDeleteSetCols; i++)
154 fkdatums[i] = Int16GetDatum(fkDeleteSetCols[i]);
155 confdelsetcolsArray = construct_array_builtin(fkdatums, numFkDeleteSetCols, INT2OID);
156 }
157 else
158 confdelsetcolsArray = NULL;
159 }
160 else
161 {
162 confkeyArray = NULL;
163 conpfeqopArray = NULL;
164 conppeqopArray = NULL;
165 conffeqopArray = NULL;
166 confdelsetcolsArray = NULL;
167 }
168
169 if (exclOp != NULL)
170 {
171 Datum *opdatums;
172
173 opdatums = (Datum *) palloc(constraintNKeys * sizeof(Datum));
174 for (i = 0; i < constraintNKeys; i++)
175 opdatums[i] = ObjectIdGetDatum(exclOp[i]);
176 conexclopArray = construct_array_builtin(opdatums, constraintNKeys, OIDOID);
177 }
178 else
179 conexclopArray = NULL;
180
181 /* initialize nulls and values */
182 for (i = 0; i < Natts_pg_constraint; i++)
183 {
184 nulls[i] = false;
185 values[i] = (Datum) NULL;
186 }
187
188 conOid = GetNewOidWithIndex(conDesc, ConstraintOidIndexId,
189 Anum_pg_constraint_oid);
190 values[Anum_pg_constraint_oid - 1] = ObjectIdGetDatum(conOid);
191 values[Anum_pg_constraint_conname - 1] = NameGetDatum(&cname);
192 values[Anum_pg_constraint_connamespace - 1] = ObjectIdGetDatum(constraintNamespace);
193 values[Anum_pg_constraint_contype - 1] = CharGetDatum(constraintType);
194 values[Anum_pg_constraint_condeferrable - 1] = BoolGetDatum(isDeferrable);
195 values[Anum_pg_constraint_condeferred - 1] = BoolGetDatum(isDeferred);
196 values[Anum_pg_constraint_conenforced - 1] = BoolGetDatum(isEnforced);
197 values[Anum_pg_constraint_convalidated - 1] = BoolGetDatum(isValidated);
198 values[Anum_pg_constraint_conrelid - 1] = ObjectIdGetDatum(relId);
199 values[Anum_pg_constraint_contypid - 1] = ObjectIdGetDatum(domainId);
200 values[Anum_pg_constraint_conindid - 1] = ObjectIdGetDatum(indexRelId);
201 values[Anum_pg_constraint_conparentid - 1] = ObjectIdGetDatum(parentConstrId);
202 values[Anum_pg_constraint_confrelid - 1] = ObjectIdGetDatum(foreignRelId);
203 values[Anum_pg_constraint_confupdtype - 1] = CharGetDatum(foreignUpdateType);
204 values[Anum_pg_constraint_confdeltype - 1] = CharGetDatum(foreignDeleteType);
205 values[Anum_pg_constraint_confmatchtype - 1] = CharGetDatum(foreignMatchType);
206 values[Anum_pg_constraint_conislocal - 1] = BoolGetDatum(conIsLocal);
207 values[Anum_pg_constraint_coninhcount - 1] = Int16GetDatum(conInhCount);
208 values[Anum_pg_constraint_connoinherit - 1] = BoolGetDatum(conNoInherit);
209 values[Anum_pg_constraint_conperiod - 1] = BoolGetDatum(conPeriod);
210
211 if (conkeyArray)
212 values[Anum_pg_constraint_conkey - 1] = PointerGetDatum(conkeyArray);
213 else
214 nulls[Anum_pg_constraint_conkey - 1] = true;
215
216 if (confkeyArray)
217 values[Anum_pg_constraint_confkey - 1] = PointerGetDatum(confkeyArray);
218 else
219 nulls[Anum_pg_constraint_confkey - 1] = true;
220
221 if (conpfeqopArray)
222 values[Anum_pg_constraint_conpfeqop - 1] = PointerGetDatum(conpfeqopArray);
223 else
224 nulls[Anum_pg_constraint_conpfeqop - 1] = true;
225
226 if (conppeqopArray)
227 values[Anum_pg_constraint_conppeqop - 1] = PointerGetDatum(conppeqopArray);
228 else
229 nulls[Anum_pg_constraint_conppeqop - 1] = true;
230
231 if (conffeqopArray)
232 values[Anum_pg_constraint_conffeqop - 1] = PointerGetDatum(conffeqopArray);
233 else
234 nulls[Anum_pg_constraint_conffeqop - 1] = true;
235
236 if (confdelsetcolsArray)
237 values[Anum_pg_constraint_confdelsetcols - 1] = PointerGetDatum(confdelsetcolsArray);
238 else
239 nulls[Anum_pg_constraint_confdelsetcols - 1] = true;
240
241 if (conexclopArray)
242 values[Anum_pg_constraint_conexclop - 1] = PointerGetDatum(conexclopArray);
243 else
244 nulls[Anum_pg_constraint_conexclop - 1] = true;
245
246 if (conBin)
247 values[Anum_pg_constraint_conbin - 1] = CStringGetTextDatum(conBin);
248 else
249 nulls[Anum_pg_constraint_conbin - 1] = true;
250
251 tup = heap_form_tuple(RelationGetDescr(conDesc), values, nulls);
252
253 CatalogTupleInsert(conDesc, tup);
254
255 ObjectAddressSet(conobject, ConstraintRelationId, conOid);
256
257 table_close(conDesc, RowExclusiveLock);
258
259 /* Handle set of auto dependencies */
260 addrs_auto = new_object_addresses();
261
262 if (OidIsValid(relId))
263 {
264 /*
265 * Register auto dependency from constraint to owning relation, or to
266 * specific column(s) if any are mentioned.
267 */
268 ObjectAddress relobject;
269
270 if (constraintNTotalKeys > 0)
271 {
272 for (i = 0; i < constraintNTotalKeys; i++)
273 {
274 ObjectAddressSubSet(relobject, RelationRelationId, relId,
275 constraintKey[i]);
276 add_exact_object_address(&relobject, addrs_auto);
277 }
278 }
279 else
280 {
281 ObjectAddressSet(relobject, RelationRelationId, relId);
282 add_exact_object_address(&relobject, addrs_auto);
283 }
284 }
285
286 if (OidIsValid(domainId))
287 {
288 /*
289 * Register auto dependency from constraint to owning domain
290 */
291 ObjectAddress domobject;
292
293 ObjectAddressSet(domobject, TypeRelationId, domainId);
294 add_exact_object_address(&domobject, addrs_auto);
295 }
296
297 record_object_address_dependencies(&conobject, addrs_auto,
298 DEPENDENCY_AUTO);
299 free_object_addresses(addrs_auto);
300
301 /* Handle set of normal dependencies */
302 addrs_normal = new_object_addresses();
303
304 if (OidIsValid(foreignRelId))
305 {
306 /*
307 * Register normal dependency from constraint to foreign relation, or
308 * to specific column(s) if any are mentioned.
309 */
310 ObjectAddress relobject;
311
312 if (foreignNKeys > 0)
313 {
314 for (i = 0; i < foreignNKeys; i++)
315 {
316 ObjectAddressSubSet(relobject, RelationRelationId,
317 foreignRelId, foreignKey[i]);
318 add_exact_object_address(&relobject, addrs_normal);
319 }
320 }
321 else
322 {
323 ObjectAddressSet(relobject, RelationRelationId, foreignRelId);
324 add_exact_object_address(&relobject, addrs_normal);
325 }
326 }
327
328 if (OidIsValid(indexRelId) && constraintType == CONSTRAINT_FOREIGN)
329 {
330 /*
331 * Register normal dependency on the unique index that supports a
332 * foreign-key constraint. (Note: for indexes associated with unique
333 * or primary-key constraints, the dependency runs the other way, and
334 * is not made here.)
335 */
336 ObjectAddress relobject;
337
338 ObjectAddressSet(relobject, RelationRelationId, indexRelId);
339 add_exact_object_address(&relobject, addrs_normal);
340 }
341
342 if (foreignNKeys > 0)
343 {
344 /*
345 * Register normal dependencies on the equality operators that support
346 * a foreign-key constraint. If the PK and FK types are the same then
347 * all three operators for a column are the same; otherwise they are
348 * different.
349 */
350 ObjectAddress oprobject;
351
352 oprobject.classId = OperatorRelationId;
353 oprobject.objectSubId = 0;
354
355 for (i = 0; i < foreignNKeys; i++)
356 {
357 oprobject.objectId = pfEqOp[i];
358 add_exact_object_address(&oprobject, addrs_normal);
359 if (ppEqOp[i] != pfEqOp[i])
360 {
361 oprobject.objectId = ppEqOp[i];
362 add_exact_object_address(&oprobject, addrs_normal);
363 }
364 if (ffEqOp[i] != pfEqOp[i])
365 {
366 oprobject.objectId = ffEqOp[i];
367 add_exact_object_address(&oprobject, addrs_normal);
368 }
369 }
370 }
371
372 record_object_address_dependencies(&conobject, addrs_normal,
373 DEPENDENCY_NORMAL);
374 free_object_addresses(addrs_normal);
375
376 /*
377 * We don't bother to register dependencies on the exclusion operators of
378 * an exclusion constraint. We assume they are members of the opclass
379 * supporting the index, so there's an indirect dependency via that. (This
380 * would be pretty dicey for cross-type operators, but exclusion operators
381 * can never be cross-type.)
382 */
383
384 if (conExpr != NULL)
385 {
386 /*
387 * Register dependencies from constraint to objects mentioned in CHECK
388 * expression.
389 */
390 recordDependencyOnSingleRelExpr(&conobject, conExpr, relId,
391 DEPENDENCY_NORMAL,
392 DEPENDENCY_NORMAL, false);
393 }
394
395 /* Post creation hook for new constraint */
396 InvokeObjectPostCreateHookArg(ConstraintRelationId, conOid, 0,
397 is_internal);
398
399 return conOid;
400 }
401
402 /*
403 * Test whether given name is currently used as a constraint name
404 * for the given object (relation or domain).
405 *
406 * This is used to decide whether to accept a user-specified constraint name.
407 * It is deliberately not the same test as ChooseConstraintName uses to decide
408 * whether an auto-generated name is OK: here, we will allow it unless there
409 * is an identical constraint name in use *on the same object*.
410 *
411 * NB: Caller should hold exclusive lock on the given object, else
412 * this test can be fooled by concurrent additions.
413 */
414 bool
415 ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId,
416 const char *conname)
417 {
418 bool found;
419 Relation conDesc;
420 SysScanDesc conscan;
421 ScanKeyData skey[3];
422
423 conDesc = table_open(ConstraintRelationId, AccessShareLock);
424
425 ScanKeyInit(&skey[0],
426 Anum_pg_constraint_conrelid,
427 BTEqualStrategyNumber, F_OIDEQ,
428 ObjectIdGetDatum((conCat == CONSTRAINT_RELATION)
429 ? objId : InvalidOid));
430 ScanKeyInit(&skey[1],
431 Anum_pg_constraint_contypid,
432 BTEqualStrategyNumber, F_OIDEQ,
433 ObjectIdGetDatum((conCat == CONSTRAINT_DOMAIN)
434 ? objId : InvalidOid));
435 ScanKeyInit(&skey[2],
436 Anum_pg_constraint_conname,
437 BTEqualStrategyNumber, F_NAMEEQ,
438 CStringGetDatum(conname));
439
440 conscan = systable_beginscan(conDesc, ConstraintRelidTypidNameIndexId,
441 true, NULL, 3, skey);
442
443 /* There can be at most one matching row */
444 found = (HeapTupleIsValid(systable_getnext(conscan)));
445
446 systable_endscan(conscan);
447 table_close(conDesc, AccessShareLock);
448
449 return found;
450 }
451
452 /*
453 * Does any constraint of the given name exist in the given namespace?
454 *
455 * This is used for code that wants to match ChooseConstraintName's rule
456 * that we should avoid autogenerating duplicate constraint names within a
457 * namespace.
458 */
459 bool
460 ConstraintNameExists(const char *conname, Oid namespaceid)
461 {
462 bool found;
463 Relation conDesc;
464 SysScanDesc conscan;
465 ScanKeyData skey[2];
466
467 conDesc = table_open(ConstraintRelationId, AccessShareLock);
468
469 ScanKeyInit(&skey[0],
470 Anum_pg_constraint_conname,
471 BTEqualStrategyNumber, F_NAMEEQ,
472 CStringGetDatum(conname));
473
474 ScanKeyInit(&skey[1],
475 Anum_pg_constraint_connamespace,
476 BTEqualStrategyNumber, F_OIDEQ,
477 ObjectIdGetDatum(namespaceid));
478
479 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
480 NULL, 2, skey);
481
482 found = (HeapTupleIsValid(systable_getnext(conscan)));
483
484 systable_endscan(conscan);
485 table_close(conDesc, AccessShareLock);
486
487 return found;
488 }
489
490 /*
491 * Select a nonconflicting name for a new constraint.
492 *
493 * The objective here is to choose a name that is unique within the
494 * specified namespace. Postgres does not require this, but the SQL
495 * spec does, and some apps depend on it. Therefore we avoid choosing
496 * default names that so conflict.
497 *
498 * name1, name2, and label are used the same way as for makeObjectName(),
499 * except that the label can't be NULL; digits will be appended to the label
500 * if needed to create a name that is unique within the specified namespace.
501 * If the given label is empty, we only consider names that include at least
502 * one added digit.
503 *
504 * 'others' can be a list of string names already chosen within the current
505 * command (but not yet reflected into the catalogs); we will not choose
506 * a duplicate of one of these either.
507 *
508 * Note: it is theoretically possible to get a collision anyway, if someone
509 * else chooses the same name concurrently. This is fairly unlikely to be
510 * a problem in practice, especially if one is holding an exclusive lock on
511 * the relation identified by name1.
512 *
513 * Returns a palloc'd string.
514 */
515 char *
516 ChooseConstraintName(const char *name1, const char *name2,
517 const char *label, Oid namespaceid,
518 List *others)
519 {
520 int pass = 0;
521 char *conname = NULL;
522 char modlabel[NAMEDATALEN];
523 Relation conDesc;
524 SysScanDesc conscan;
525 ScanKeyData skey[2];
526 bool found;
527 ListCell *l;
528
529 conDesc = table_open(ConstraintRelationId, AccessShareLock);
530
531 /* try the unmodified label first, unless it's empty */
532 if (label[0] != '\0')
533 strlcpy(modlabel, label, sizeof(modlabel));
534 else
535 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
536
537 for (;;)
538 {
539 conname = makeObjectName(name1, name2, modlabel);
540
541 found = false;
542
543 foreach(l, others)
544 {
545 if (strcmp((char *) lfirst(l), conname) == 0)
546 {
547 found = true;
548 break;
549 }
550 }
551
552 if (!found)
553 {
554 ScanKeyInit(&skey[0],
555 Anum_pg_constraint_conname,
556 BTEqualStrategyNumber, F_NAMEEQ,
557 CStringGetDatum(conname));
558
559 ScanKeyInit(&skey[1],
560 Anum_pg_constraint_connamespace,
561 BTEqualStrategyNumber, F_OIDEQ,
562 ObjectIdGetDatum(namespaceid));
563
564 conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
565 NULL, 2, skey);
566
567 found = (HeapTupleIsValid(systable_getnext(conscan)));
568
569 systable_endscan(conscan);
570 }
571
572 if (!found)
573 break;
574
575 /* found a conflict, so try a new name component */
576 pfree(conname);
577 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
578 }
579
580 table_close(conDesc, AccessShareLock);
581
582 return conname;
583 }
584
585 /*
586 * Find and return a copy of the pg_constraint tuple that implements a
587 * (possibly not valid) not-null constraint for the given column of the
588 * given relation. If no such constraint exists, return NULL.
589 *
590 * XXX This would be easier if we had pg_attribute.notnullconstr with the OID
591 * of the constraint that implements the not-null constraint for that column.
592 * I'm not sure it's worth the catalog bloat and de-normalization, however.
593 */
594 HeapTuple
595 findNotNullConstraintAttnum(Oid relid, AttrNumber attnum)
596 {
597 Relation pg_constraint;
598 HeapTuple conTup,
599 retval = NULL;
600 SysScanDesc scan;
601 ScanKeyData key;
602
603 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
604 ScanKeyInit(&key,
605 Anum_pg_constraint_conrelid,
606 BTEqualStrategyNumber, F_OIDEQ,
607 ObjectIdGetDatum(relid));
608 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
609 true, NULL, 1, &key);
610
611 while (HeapTupleIsValid(conTup = systable_getnext(scan)))
612 {
613 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(conTup);
614 AttrNumber conkey;
615
616 /*
617 * We're looking for a NOTNULL constraint with the column we're
618 * looking for as the sole element in conkey.
619 */
620 if (con->contype != CONSTRAINT_NOTNULL)
621 continue;
622
623 conkey = extractNotNullColumn(conTup);
624 if (conkey != attnum)
625 continue;
626
627 /* Found it */
628 retval = heap_copytuple(conTup);
629 break;
630 }
631
632 systable_endscan(scan);
633 table_close(pg_constraint, AccessShareLock);
634
635 return retval;
636 }
637
638 /*
639 * Find and return a copy of the pg_constraint tuple that implements a
640 * (possibly not valid) not-null constraint for the given column of the
641 * given relation.
642 * If no such column or no such constraint exists, return NULL.
643 */
644 HeapTuple
645 findNotNullConstraint(Oid relid, const char *colname)
646 {
647 AttrNumber attnum;
648
649 attnum = get_attnum(relid, colname);
650 if (attnum <= InvalidAttrNumber)
651 return NULL;
652
653 return findNotNullConstraintAttnum(relid, attnum);
654 }
655
656 /*
657 * Find and return the pg_constraint tuple that implements a validated
658 * not-null constraint for the given domain.
659 */
660 HeapTuple
661 findDomainNotNullConstraint(Oid typid)
662 {
663 Relation pg_constraint;
664 HeapTuple conTup,
665 retval = NULL;
666 SysScanDesc scan;
667 ScanKeyData key;
668
669 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
670 ScanKeyInit(&key,
671 Anum_pg_constraint_contypid,
672 BTEqualStrategyNumber, F_OIDEQ,
673 ObjectIdGetDatum(typid));
674 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
675 true, NULL, 1, &key);
676
677 while (HeapTupleIsValid(conTup = systable_getnext(scan)))
678 {
679 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(conTup);
680
681 /*
682 * We're looking for a NOTNULL constraint that's marked validated.
683 */
684 if (con->contype != CONSTRAINT_NOTNULL)
685 continue;
686 if (!con->convalidated)
687 continue;
688
689 /* Found it */
690 retval = heap_copytuple(conTup);
691 break;
692 }
693
694 systable_endscan(scan);
695 table_close(pg_constraint, AccessShareLock);
696
697 return retval;
698 }
699
700 /*
701 * Given a pg_constraint tuple for a not-null constraint, return the column
702 * number it is for.
703 */
704 AttrNumber
705 extractNotNullColumn(HeapTuple constrTup)
706 {
707 Datum adatum;
708 ArrayType *arr;
709
710 /* only tuples for not-null constraints should be given */
711 Assert(((Form_pg_constraint) GETSTRUCT(constrTup))->contype == CONSTRAINT_NOTNULL);
712
713 adatum = SysCacheGetAttrNotNull(CONSTROID, constrTup,
714 Anum_pg_constraint_conkey);
715 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
716 if (ARR_NDIM(arr) != 1 ||
717 ARR_HASNULL(arr) ||
718 ARR_ELEMTYPE(arr) != INT2OID ||
719 ARR_DIMS(arr)[0] != 1)
720 elog(ERROR, "conkey is not a 1-D smallint array");
721
722 /* We leak the detoasted datum, but we don't care */
723
724 return ((AttrNumber *) ARR_DATA_PTR(arr))[0];
725 }
726
727 /*
728 * AdjustNotNullInheritance
729 * Adjust inheritance status for a single not-null constraint
730 *
731 * If no not-null constraint is found for the column, return false.
732 * Caller can create one.
733 *
734 * If a constraint exists but the connoinherit flag is not what the caller
735 * wants, throw an error about the incompatibility. If the desired
736 * constraint is valid but the existing constraint is not valid, also
737 * throw an error about that (the opposite case is acceptable). If
738 * the proposed constraint has a different name, also throw an error.
739 *
740 * If everything checks out, we adjust conislocal/coninhcount and return
741 * true. If is_local is true we flip conislocal true, or do nothing if
742 * it's already true; otherwise we increment coninhcount by 1.
743 */
744 bool
745 AdjustNotNullInheritance(Oid relid, AttrNumber attnum, const char *new_conname,
746 bool is_local, bool is_no_inherit, bool is_notvalid)
747 {
748 HeapTuple tup;
749
750 tup = findNotNullConstraintAttnum(relid, attnum);
751 if (HeapTupleIsValid(tup))
752 {
753 Relation pg_constraint;
754 Form_pg_constraint conform;
755 bool changed = false;
756
757 pg_constraint = table_open(ConstraintRelationId, RowExclusiveLock);
758 conform = (Form_pg_constraint) GETSTRUCT(tup);
759
760 /*
761 * If the NO INHERIT flag we're asked for doesn't match what the
762 * existing constraint has, throw an error.
763 */
764 if (is_no_inherit != conform->connoinherit)
765 ereport(ERROR,
766 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
767 errmsg("cannot change NO INHERIT status of NOT NULL constraint \"%s\" on relation \"%s\"",
768 NameStr(conform->conname), get_rel_name(relid)),
769 errhint("You might need to make the existing constraint inheritable using %s.",
770 "ALTER TABLE ... ALTER CONSTRAINT ... INHERIT"));
771
772 /*
773 * Throw an error if the existing constraint is NOT VALID and caller
774 * wants a valid one.
775 */
776 if (!is_notvalid && !conform->convalidated)
777 ereport(ERROR,
778 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
779 errmsg("incompatible NOT VALID constraint \"%s\" on relation \"%s\"",
780 NameStr(conform->conname), get_rel_name(relid)),
781 errhint("You might need to validate it using %s.",
782 "ALTER TABLE ... VALIDATE CONSTRAINT"));
783
784 /*
785 * If, for a new constraint that is being defined locally (i.e., not
786 * being passed down via inheritance), a name was specified, then
787 * verify that the existing constraint has the same name. Otherwise
788 * throw an error. Names of inherited constraints are ignored because
789 * they are not directly user-specified, so matching is not important.
790 */
791 if (is_local && new_conname &&
792 strcmp(new_conname, NameStr(conform->conname)) != 0)
793 ereport(ERROR,
794 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
795 errmsg("cannot create not-null constraint \"%s\" on column \"%s\" of table \"%s\"",
796 new_conname, get_attname(relid, attnum, false), get_rel_name(relid)),
797 errdetail("A not-null constraint named \"%s\" already exists for this column.",
798 NameStr(conform->conname)));
799
800 if (!is_local)
801 {
802 if (pg_add_s16_overflow(conform->coninhcount, 1,
803 &conform->coninhcount))
804 ereport(ERROR,
805 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
806 errmsg("too many inheritance parents"));
807 changed = true;
808 }
809 else if (!conform->conislocal)
810 {
811 conform->conislocal = true;
812 changed = true;
813 }
814
815 if (changed)
816 CatalogTupleUpdate(pg_constraint, &tup->t_self, tup);
817
818 table_close(pg_constraint, RowExclusiveLock);
819
820 return true;
821 }
822
823 return false;
824 }
825
826 /*
827 * RelationGetNotNullConstraints
828 * Return the list of not-null constraints for the given rel
829 *
830 * Caller can request cooked constraints, or raw.
831 *
832 * This is seldom needed, so we just scan pg_constraint each time.
833 *
834 * 'include_noinh' determines whether to include NO INHERIT constraints or not.
835 */
836 List *
837 RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
838 {
839 List *notnulls = NIL;
840 Relation constrRel;
841 HeapTuple htup;
842 SysScanDesc conscan;
843 ScanKeyData skey;
844
845 constrRel = table_open(ConstraintRelationId, AccessShareLock);
846 ScanKeyInit(&skey,
847 Anum_pg_constraint_conrelid,
848 BTEqualStrategyNumber, F_OIDEQ,
849 ObjectIdGetDatum(relid));
850 conscan = systable_beginscan(constrRel, ConstraintRelidTypidNameIndexId, true,
851 NULL, 1, &skey);
852
853 while (HeapTupleIsValid(htup = systable_getnext(conscan)))
854 {
855 Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(htup);
856 AttrNumber colnum;
857
858 if (conForm->contype != CONSTRAINT_NOTNULL)
859 continue;
860 if (conForm->connoinherit && !include_noinh)
861 continue;
862
863 colnum = extractNotNullColumn(htup);
864
865 if (cooked)
866 {
867 CookedConstraint *cooked;
868
869 cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
870
871 cooked->contype = CONSTR_NOTNULL;
872 cooked->conoid = conForm->oid;
873 cooked->name = pstrdup(NameStr(conForm->conname));
874 cooked->attnum = colnum;
875 cooked->expr = NULL;
876 cooked->is_enforced = true;
877 cooked->skip_validation = !conForm->convalidated;
878 cooked->is_local = true;
879 cooked->inhcount = 0;
880 cooked->is_no_inherit = conForm->connoinherit;
881
882 notnulls = lappend(notnulls, cooked);
883 }
884 else
885 {
886 Constraint *constr;
887
888 constr = makeNode(Constraint);
889 constr->contype = CONSTR_NOTNULL;
890 constr->conname = pstrdup(NameStr(conForm->conname));
891 constr->deferrable = false;
892 constr->initdeferred = false;
893 constr->location = -1;
894 constr->keys = list_make1(makeString(get_attname(relid, colnum,
895 false)));
896 constr->is_enforced = true;
897 constr->skip_validation = !conForm->convalidated;
898 constr->initially_valid = true;
899 constr->is_no_inherit = conForm->connoinherit;
900 notnulls = lappend(notnulls, constr);
901 }
902 }
903
904 systable_endscan(conscan);
905 table_close(constrRel, AccessShareLock);
906
907 return notnulls;
908 }
909
910
911 /*
912 * Delete a single constraint record.
913 */
914 void
915 RemoveConstraintById(Oid conId)
916 {
917 Relation conDesc;
918 HeapTuple tup;
919 Form_pg_constraint con;
920
921 conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
922
923 tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conId));
924 if (!HeapTupleIsValid(tup)) /* should not happen */
925 elog(ERROR, "cache lookup failed for constraint %u", conId);
926 con = (Form_pg_constraint) GETSTRUCT(tup);
927
928 /*
929 * Special processing depending on what the constraint is for.
930 */
931 if (OidIsValid(con->conrelid))
932 {
933 Relation rel;
934
935 /*
936 * If the constraint is for a relation, open and exclusive-lock the
937 * relation it's for.
938 */
939 rel = table_open(con->conrelid, AccessExclusiveLock);
940
941 /*
942 * We need to update the relchecks count if it is a check constraint
943 * being dropped. This update will force backends to rebuild relcache
944 * entries when we commit.
945 */
946 if (con->contype == CONSTRAINT_CHECK)
947 {
948 Relation pgrel;
949 HeapTuple relTup;
950 Form_pg_class classForm;
951
952 pgrel = table_open(RelationRelationId, RowExclusiveLock);
953 relTup = SearchSysCacheCopy1(RELOID,
954 ObjectIdGetDatum(con->conrelid));
955 if (!HeapTupleIsValid(relTup))
956 elog(ERROR, "cache lookup failed for relation %u",
957 con->conrelid);
958 classForm = (Form_pg_class) GETSTRUCT(relTup);
959
960 if (classForm->relchecks == 0) /* should not happen */
961 elog(ERROR, "relation \"%s\" has relchecks = 0",
962 RelationGetRelationName(rel));
963 classForm->relchecks--;
964
965 CatalogTupleUpdate(pgrel, &relTup->t_self, relTup);
966
967 heap_freetuple(relTup);
968
969 table_close(pgrel, RowExclusiveLock);
970 }
971
972 /* Keep lock on constraint's rel until end of xact */
973 table_close(rel, NoLock);
974 }
975 else if (OidIsValid(con->contypid))
976 {
977 /*
978 * XXX for now, do nothing special when dropping a domain constraint
979 *
980 * Probably there should be some form of locking on the domain type,
981 * but we have no such concept at the moment.
982 */
983 }
984 else
985 elog(ERROR, "constraint %u is not of a known type", conId);
986
987 /* Fry the constraint itself */
988 CatalogTupleDelete(conDesc, &tup->t_self);
989
990 /* Clean up */
991 ReleaseSysCache(tup);
992 table_close(conDesc, RowExclusiveLock);
993 }
994
995 /*
996 * RenameConstraintById
997 * Rename a constraint.
998 *
999 * Note: this isn't intended to be a user-exposed function; it doesn't check
1000 * permissions etc. Currently this is only invoked when renaming an index
1001 * that is associated with a constraint, but it's made a little more general
1002 * than that with the expectation of someday having ALTER TABLE RENAME
1003 * CONSTRAINT.
1004 */
1005 void
1006 RenameConstraintById(Oid conId, const char *newname)
1007 {
1008 Relation conDesc;
1009 HeapTuple tuple;
1010 Form_pg_constraint con;
1011
1012 conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
1013
1014 tuple = SearchSysCacheCopy1(CONSTROID, ObjectIdGetDatum(conId));
1015 if (!HeapTupleIsValid(tuple))
1016 elog(ERROR, "cache lookup failed for constraint %u", conId);
1017 con = (Form_pg_constraint) GETSTRUCT(tuple);
1018
1019 /*
1020 * For user-friendliness, check whether the name is already in use.
1021 */
1022 if (OidIsValid(con->conrelid) &&
1023 ConstraintNameIsUsed(CONSTRAINT_RELATION,
1024 con->conrelid,
1025 newname))
1026 ereport(ERROR,
1027 (errcode(ERRCODE_DUPLICATE_OBJECT),
1028 errmsg("constraint \"%s\" for relation \"%s\" already exists",
1029 newname, get_rel_name(con->conrelid))));
1030 if (OidIsValid(con->contypid) &&
1031 ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
1032 con->contypid,
1033 newname))
1034 ereport(ERROR,
1035 (errcode(ERRCODE_DUPLICATE_OBJECT),
1036 errmsg("constraint \"%s\" for domain %s already exists",
1037 newname, format_type_be(con->contypid))));
1038
1039 /* OK, do the rename --- tuple is a copy, so OK to scribble on it */
1040 namestrcpy(&(con->conname), newname);
1041
1042 CatalogTupleUpdate(conDesc, &tuple->t_self, tuple);
1043
1044 InvokeObjectPostAlterHook(ConstraintRelationId, conId, 0);
1045
1046 heap_freetuple(tuple);
1047 table_close(conDesc, RowExclusiveLock);
1048 }
1049
1050 /*
1051 * AlterConstraintNamespaces
1052 * Find any constraints belonging to the specified object,
1053 * and move them to the specified new namespace.
1054 *
1055 * isType indicates whether the owning object is a type or a relation.
1056 */
1057 void
1058 AlterConstraintNamespaces(Oid ownerId, Oid oldNspId,
1059 Oid newNspId, bool isType, ObjectAddresses *objsMoved)
1060 {
1061 Relation conRel;
1062 ScanKeyData key[2];
1063 SysScanDesc scan;
1064 HeapTuple tup;
1065
1066 conRel = table_open(ConstraintRelationId, RowExclusiveLock);
1067
1068 ScanKeyInit(&key[0],
1069 Anum_pg_constraint_conrelid,
1070 BTEqualStrategyNumber, F_OIDEQ,
1071 ObjectIdGetDatum(isType ? InvalidOid : ownerId));
1072 ScanKeyInit(&key[1],
1073 Anum_pg_constraint_contypid,
1074 BTEqualStrategyNumber, F_OIDEQ,
1075 ObjectIdGetDatum(isType ? ownerId : InvalidOid));
1076
1077 scan = systable_beginscan(conRel, ConstraintRelidTypidNameIndexId, true,
1078 NULL, 2, key);
1079
1080 while (HeapTupleIsValid((tup = systable_getnext(scan))))
1081 {
1082 Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(tup);
1083 ObjectAddress thisobj;
1084
1085 ObjectAddressSet(thisobj, ConstraintRelationId, conform->oid);
1086
1087 if (object_address_present(&thisobj, objsMoved))
1088 continue;
1089
1090 /* Don't update if the object is already part of the namespace */
1091 if (conform->connamespace == oldNspId && oldNspId != newNspId)
1092 {
1093 tup = heap_copytuple(tup);
1094 conform = (Form_pg_constraint) GETSTRUCT(tup);
1095
1096 conform->connamespace = newNspId;
1097
1098 CatalogTupleUpdate(conRel, &tup->t_self, tup);
1099
1100 /*
1101 * Note: currently, the constraint will not have its own
1102 * dependency on the namespace, so we don't need to do
1103 * changeDependencyFor().
1104 */
1105 }
1106
1107 InvokeObjectPostAlterHook(ConstraintRelationId, thisobj.objectId, 0);
1108
1109 add_exact_object_address(&thisobj, objsMoved);
1110 }
1111
1112 systable_endscan(scan);
1113
1114 table_close(conRel, RowExclusiveLock);
1115 }
1116
1117 /*
1118 * ConstraintSetParentConstraint
1119 * Set a partition's constraint as child of its parent constraint,
1120 * or remove the linkage if parentConstrId is InvalidOid.
1121 *
1122 * This updates the constraint's pg_constraint row to show it as inherited, and
1123 * adds PARTITION dependencies to prevent the constraint from being deleted
1124 * on its own. Alternatively, reverse that.
1125 */
1126 void
1127 ConstraintSetParentConstraint(Oid childConstrId,
1128 Oid parentConstrId,
1129 Oid childTableId)
1130 {
1131 Relation constrRel;
1132 Form_pg_constraint constrForm;
1133 HeapTuple tuple,
1134 newtup;
1135 ObjectAddress depender;
1136 ObjectAddress referenced;
1137
1138 constrRel = table_open(ConstraintRelationId, RowExclusiveLock);
1139 tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(childConstrId));
1140 if (!HeapTupleIsValid(tuple))
1141 elog(ERROR, "cache lookup failed for constraint %u", childConstrId);
1142 newtup = heap_copytuple(tuple);
1143 constrForm = (Form_pg_constraint) GETSTRUCT(newtup);
1144 if (OidIsValid(parentConstrId))
1145 {
1146 /* don't allow setting parent for a constraint that already has one */
1147 Assert(constrForm->coninhcount == 0);
1148 if (constrForm->conparentid != InvalidOid)
1149 elog(ERROR, "constraint %u already has a parent constraint",
1150 childConstrId);
1151
1152 constrForm->conislocal = false;
1153 if (pg_add_s16_overflow(constrForm->coninhcount, 1,
1154 &constrForm->coninhcount))
1155 ereport(ERROR,
1156 errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1157 errmsg("too many inheritance parents"));
1158
1159 constrForm->conparentid = parentConstrId;
1160
1161 CatalogTupleUpdate(constrRel, &tuple->t_self, newtup);
1162
1163 ObjectAddressSet(depender, ConstraintRelationId, childConstrId);
1164
1165 ObjectAddressSet(referenced, ConstraintRelationId, parentConstrId);
1166 recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_PRI);
1167
1168 ObjectAddressSet(referenced, RelationRelationId, childTableId);
1169 recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_SEC);
1170 }
1171 else
1172 {
1173 constrForm->coninhcount--;
1174 constrForm->conislocal = true;
1175 constrForm->conparentid = InvalidOid;
1176
1177 /* Make sure there's no further inheritance. */
1178 Assert(constrForm->coninhcount == 0);
1179
1180 CatalogTupleUpdate(constrRel, &tuple->t_self, newtup);
1181
1182 deleteDependencyRecordsForClass(ConstraintRelationId, childConstrId,
1183 ConstraintRelationId,
1184 DEPENDENCY_PARTITION_PRI);
1185 deleteDependencyRecordsForClass(ConstraintRelationId, childConstrId,
1186 RelationRelationId,
1187 DEPENDENCY_PARTITION_SEC);
1188 }
1189
1190 ReleaseSysCache(tuple);
1191 table_close(constrRel, RowExclusiveLock);
1192 }
1193
1194
1195 /*
1196 * get_relation_constraint_oid
1197 * Find a constraint on the specified relation with the specified name.
1198 * Returns constraint's OID.
1199 */
1200 Oid
1201 get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
1202 {
1203 Relation pg_constraint;
1204 HeapTuple tuple;
1205 SysScanDesc scan;
1206 ScanKeyData skey[3];
1207 Oid conOid = InvalidOid;
1208
1209 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
1210
1211 ScanKeyInit(&skey[0],
1212 Anum_pg_constraint_conrelid,
1213 BTEqualStrategyNumber, F_OIDEQ,
1214 ObjectIdGetDatum(relid));
1215 ScanKeyInit(&skey[1],
1216 Anum_pg_constraint_contypid,
1217 BTEqualStrategyNumber, F_OIDEQ,
1218 ObjectIdGetDatum(InvalidOid));
1219 ScanKeyInit(&skey[2],
1220 Anum_pg_constraint_conname,
1221 BTEqualStrategyNumber, F_NAMEEQ,
1222 CStringGetDatum(conname));
1223
1224 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
1225 NULL, 3, skey);
1226
1227 /* There can be at most one matching row */
1228 if (HeapTupleIsValid(tuple = systable_getnext(scan)))
1229 conOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
1230
1231 systable_endscan(scan);
1232
1233 /* If no such constraint exists, complain */
1234 if (!OidIsValid(conOid) && !missing_ok)
1235 ereport(ERROR,
1236 (errcode(ERRCODE_UNDEFINED_OBJECT),
1237 errmsg("constraint \"%s\" for table \"%s\" does not exist",
1238 conname, get_rel_name(relid))));
1239
1240 table_close(pg_constraint, AccessShareLock);
1241
1242 return conOid;
1243 }
1244
1245 /*
1246 * get_relation_constraint_attnos
1247 * Find a constraint on the specified relation with the specified name
1248 * and return the constrained columns.
1249 *
1250 * Returns a Bitmapset of the column attnos of the constrained columns, with
1251 * attnos being offset by FirstLowInvalidHeapAttributeNumber so that system
1252 * columns can be represented.
1253 *
1254 * *constraintOid is set to the OID of the constraint, or InvalidOid on
1255 * failure.
1256 */
1257 Bitmapset *
1258 get_relation_constraint_attnos(Oid relid, const char *conname,
1259 bool missing_ok, Oid *constraintOid)
1260 {
1261 Bitmapset *conattnos = NULL;
1262 Relation pg_constraint;
1263 HeapTuple tuple;
1264 SysScanDesc scan;
1265 ScanKeyData skey[3];
1266
1267 /* Set *constraintOid, to avoid complaints about uninitialized vars */
1268 *constraintOid = InvalidOid;
1269
1270 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
1271
1272 ScanKeyInit(&skey[0],
1273 Anum_pg_constraint_conrelid,
1274 BTEqualStrategyNumber, F_OIDEQ,
1275 ObjectIdGetDatum(relid));
1276 ScanKeyInit(&skey[1],
1277 Anum_pg_constraint_contypid,
1278 BTEqualStrategyNumber, F_OIDEQ,
1279 ObjectIdGetDatum(InvalidOid));
1280 ScanKeyInit(&skey[2],
1281 Anum_pg_constraint_conname,
1282 BTEqualStrategyNumber, F_NAMEEQ,
1283 CStringGetDatum(conname));
1284
1285 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
1286 NULL, 3, skey);
1287
1288 /* There can be at most one matching row */
1289 if (HeapTupleIsValid(tuple = systable_getnext(scan)))
1290 {
1291 Datum adatum;
1292 bool isNull;
1293
1294 *constraintOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
1295
1296 /* Extract the conkey array, ie, attnums of constrained columns */
1297 adatum = heap_getattr(tuple, Anum_pg_constraint_conkey,
1298 RelationGetDescr(pg_constraint), &isNull);
1299 if (!isNull)
1300 {
1301 ArrayType *arr;
1302 int numcols;
1303 int16 *attnums;
1304 int i;
1305
1306 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1307 numcols = ARR_DIMS(arr)[0];
1308 if (ARR_NDIM(arr) != 1 ||
1309 numcols < 0 ||
1310 ARR_HASNULL(arr) ||
1311 ARR_ELEMTYPE(arr) != INT2OID)
1312 elog(ERROR, "conkey is not a 1-D smallint array");
1313 attnums = (int16 *) ARR_DATA_PTR(arr);
1314
1315 /* Construct the result value */
1316 for (i = 0; i < numcols; i++)
1317 {
1318 conattnos = bms_add_member(conattnos,
1319 attnums[i] - FirstLowInvalidHeapAttributeNumber);
1320 }
1321 }
1322 }
1323
1324 systable_endscan(scan);
1325
1326 /* If no such constraint exists, complain */
1327 if (!OidIsValid(*constraintOid) && !missing_ok)
1328 ereport(ERROR,
1329 (errcode(ERRCODE_UNDEFINED_OBJECT),
1330 errmsg("constraint \"%s\" for table \"%s\" does not exist",
1331 conname, get_rel_name(relid))));
1332
1333 table_close(pg_constraint, AccessShareLock);
1334
1335 return conattnos;
1336 }
1337
1338 /*
1339 * Return the OID of the constraint enforced by the given index in the
1340 * given relation; or InvalidOid if no such index is cataloged.
1341 *
1342 * Much like get_constraint_index, this function is concerned only with the
1343 * one constraint that "owns" the given index. Therefore, constraints of
1344 * types other than unique, primary-key, and exclusion are ignored.
1345 */
1346 Oid
1347 get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
1348 {
1349 Relation pg_constraint;
1350 SysScanDesc scan;
1351 ScanKeyData key;
1352 HeapTuple tuple;
1353 Oid constraintId = InvalidOid;
1354
1355 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
1356
1357 ScanKeyInit(&key,
1358 Anum_pg_constraint_conrelid,
1359 BTEqualStrategyNumber,
1360 F_OIDEQ,
1361 ObjectIdGetDatum(relationId));
1362 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
1363 true, NULL, 1, &key);
1364 while ((tuple = systable_getnext(scan)) != NULL)
1365 {
1366 Form_pg_constraint constrForm;
1367
1368 constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
1369
1370 /* See above */
1371 if (constrForm->contype != CONSTRAINT_PRIMARY &&
1372 constrForm->contype != CONSTRAINT_UNIQUE &&
1373 constrForm->contype != CONSTRAINT_EXCLUSION)
1374 continue;
1375
1376 if (constrForm->conindid == indexId)
1377 {
1378 constraintId = constrForm->oid;
1379 break;
1380 }
1381 }
1382 systable_endscan(scan);
1383
1384 table_close(pg_constraint, AccessShareLock);
1385 return constraintId;
1386 }
1387
1388 /*
1389 * get_domain_constraint_oid
1390 * Find a constraint on the specified domain with the specified name.
1391 * Returns constraint's OID.
1392 */
1393 Oid
1394 get_domain_constraint_oid(Oid typid, const char *conname, bool missing_ok)
1395 {
1396 Relation pg_constraint;
1397 HeapTuple tuple;
1398 SysScanDesc scan;
1399 ScanKeyData skey[3];
1400 Oid conOid = InvalidOid;
1401
1402 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
1403
1404 ScanKeyInit(&skey[0],
1405 Anum_pg_constraint_conrelid,
1406 BTEqualStrategyNumber, F_OIDEQ,
1407 ObjectIdGetDatum(InvalidOid));
1408 ScanKeyInit(&skey[1],
1409 Anum_pg_constraint_contypid,
1410 BTEqualStrategyNumber, F_OIDEQ,
1411 ObjectIdGetDatum(typid));
1412 ScanKeyInit(&skey[2],
1413 Anum_pg_constraint_conname,
1414 BTEqualStrategyNumber, F_NAMEEQ,
1415 CStringGetDatum(conname));
1416
1417 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
1418 NULL, 3, skey);
1419
1420 /* There can be at most one matching row */
1421 if (HeapTupleIsValid(tuple = systable_getnext(scan)))
1422 conOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
1423
1424 systable_endscan(scan);
1425
1426 /* If no such constraint exists, complain */
1427 if (!OidIsValid(conOid) && !missing_ok)
1428 ereport(ERROR,
1429 (errcode(ERRCODE_UNDEFINED_OBJECT),
1430 errmsg("constraint \"%s\" for domain %s does not exist",
1431 conname, format_type_be(typid))));
1432
1433 table_close(pg_constraint, AccessShareLock);
1434
1435 return conOid;
1436 }
1437
1438 /*
1439 * get_primary_key_attnos
1440 * Identify the columns in a relation's primary key, if any.
1441 *
1442 * Returns a Bitmapset of the column attnos of the primary key's columns,
1443 * with attnos being offset by FirstLowInvalidHeapAttributeNumber so that
1444 * system columns can be represented.
1445 *
1446 * If there is no primary key, return NULL. We also return NULL if the pkey
1447 * constraint is deferrable and deferrableOk is false.
1448 *
1449 * *constraintOid is set to the OID of the pkey constraint, or InvalidOid
1450 * on failure.
1451 */
1452 Bitmapset *
1453 get_primary_key_attnos(Oid relid, bool deferrableOk, Oid *constraintOid)
1454 {
1455 Bitmapset *pkattnos = NULL;
1456 Relation pg_constraint;
1457 HeapTuple tuple;
1458 SysScanDesc scan;
1459 ScanKeyData skey[1];
1460
1461 /* Set *constraintOid, to avoid complaints about uninitialized vars */
1462 *constraintOid = InvalidOid;
1463
1464 /* Scan pg_constraint for constraints of the target rel */
1465 pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
1466
1467 ScanKeyInit(&skey[0],
1468 Anum_pg_constraint_conrelid,
1469 BTEqualStrategyNumber, F_OIDEQ,
1470 ObjectIdGetDatum(relid));
1471
1472 scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
1473 NULL, 1, skey);
1474
1475 while (HeapTupleIsValid(tuple = systable_getnext(scan)))
1476 {
1477 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
1478 Datum adatum;
1479 bool isNull;
1480 ArrayType *arr;
1481 int16 *attnums;
1482 int numkeys;
1483 int i;
1484
1485 /* Skip constraints that are not PRIMARY KEYs */
1486 if (con->contype != CONSTRAINT_PRIMARY)
1487 continue;
1488
1489 /*
1490 * If the primary key is deferrable, but we've been instructed to
1491 * ignore deferrable constraints, then we might as well give up
1492 * searching, since there can only be a single primary key on a table.
1493 */
1494 if (con->condeferrable && !deferrableOk)
1495 break;
1496
1497 /* Extract the conkey array, ie, attnums of PK's columns */
1498 adatum = heap_getattr(tuple, Anum_pg_constraint_conkey,
1499 RelationGetDescr(pg_constraint), &isNull);
1500 if (isNull)
1501 elog(ERROR, "null conkey for constraint %u",
1502 ((Form_pg_constraint) GETSTRUCT(tuple))->oid);
1503 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1504 numkeys = ARR_DIMS(arr)[0];
1505 if (ARR_NDIM(arr) != 1 ||
1506 numkeys < 0 ||
1507 ARR_HASNULL(arr) ||
1508 ARR_ELEMTYPE(arr) != INT2OID)
1509 elog(ERROR, "conkey is not a 1-D smallint array");
1510 attnums = (int16 *) ARR_DATA_PTR(arr);
1511
1512 /* Construct the result value */
1513 for (i = 0; i < numkeys; i++)
1514 {
1515 pkattnos = bms_add_member(pkattnos,
1516 attnums[i] - FirstLowInvalidHeapAttributeNumber);
1517 }
1518 *constraintOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
1519
1520 /* No need to search further */
1521 break;
1522 }
1523
1524 systable_endscan(scan);
1525
1526 table_close(pg_constraint, AccessShareLock);
1527
1528 return pkattnos;
1529 }
1530
1531 /*
1532 * Extract data from the pg_constraint tuple of a foreign-key constraint.
1533 *
1534 * All arguments save the first are output arguments. All output arguments
1535 * other than numfks, conkey and confkey can be passed as NULL if caller
1536 * doesn't need them.
1537 */
1538 void
1539 DeconstructFkConstraintRow(HeapTuple tuple, int *numfks,
1540 AttrNumber *conkey, AttrNumber *confkey,
1541 Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs,
1542 int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
1543 {
1544 Datum adatum;
1545 bool isNull;
1546 ArrayType *arr;
1547 int numkeys;
1548
1549 /*
1550 * We expect the arrays to be 1-D arrays of the right types; verify that.
1551 * We don't need to use deconstruct_array() since the array data is just
1552 * going to look like a C array of values.
1553 */
1554 adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
1555 Anum_pg_constraint_conkey);
1556 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1557 if (ARR_NDIM(arr) != 1 ||
1558 ARR_HASNULL(arr) ||
1559 ARR_ELEMTYPE(arr) != INT2OID)
1560 elog(ERROR, "conkey is not a 1-D smallint array");
1561 numkeys = ARR_DIMS(arr)[0];
1562 if (numkeys <= 0 || numkeys > INDEX_MAX_KEYS)
1563 elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
1564 memcpy(conkey, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
1565 if ((Pointer) arr != DatumGetPointer(adatum))
1566 pfree(arr); /* free de-toasted copy, if any */
1567
1568 adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
1569 Anum_pg_constraint_confkey);
1570 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1571 if (ARR_NDIM(arr) != 1 ||
1572 ARR_DIMS(arr)[0] != numkeys ||
1573 ARR_HASNULL(arr) ||
1574 ARR_ELEMTYPE(arr) != INT2OID)
1575 elog(ERROR, "confkey is not a 1-D smallint array");
1576 memcpy(confkey, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
1577 if ((Pointer) arr != DatumGetPointer(adatum))
1578 pfree(arr); /* free de-toasted copy, if any */
1579
1580 if (pf_eq_oprs)
1581 {
1582 adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
1583 Anum_pg_constraint_conpfeqop);
1584 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1585 /* see TryReuseForeignKey if you change the test below */
1586 if (ARR_NDIM(arr) != 1 ||
1587 ARR_DIMS(arr)[0] != numkeys ||
1588 ARR_HASNULL(arr) ||
1589 ARR_ELEMTYPE(arr) != OIDOID)
1590 elog(ERROR, "conpfeqop is not a 1-D Oid array");
1591 memcpy(pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
1592 if ((Pointer) arr != DatumGetPointer(adatum))
1593 pfree(arr); /* free de-toasted copy, if any */
1594 }
1595
1596 if (pp_eq_oprs)
1597 {
1598 adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
1599 Anum_pg_constraint_conppeqop);
1600 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1601 if (ARR_NDIM(arr) != 1 ||
1602 ARR_DIMS(arr)[0] != numkeys ||
1603 ARR_HASNULL(arr) ||
1604 ARR_ELEMTYPE(arr) != OIDOID)
1605 elog(ERROR, "conppeqop is not a 1-D Oid array");
1606 memcpy(pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
1607 if ((Pointer) arr != DatumGetPointer(adatum))
1608 pfree(arr); /* free de-toasted copy, if any */
1609 }
1610
1611 if (ff_eq_oprs)
1612 {
1613 adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
1614 Anum_pg_constraint_conffeqop);
1615 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1616 if (ARR_NDIM(arr) != 1 ||
1617 ARR_DIMS(arr)[0] != numkeys ||
1618 ARR_HASNULL(arr) ||
1619 ARR_ELEMTYPE(arr) != OIDOID)
1620 elog(ERROR, "conffeqop is not a 1-D Oid array");
1621 memcpy(ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
1622 if ((Pointer) arr != DatumGetPointer(adatum))
1623 pfree(arr); /* free de-toasted copy, if any */
1624 }
1625
1626 if (fk_del_set_cols)
1627 {
1628 adatum = SysCacheGetAttr(CONSTROID, tuple,
1629 Anum_pg_constraint_confdelsetcols, &isNull);
1630 if (isNull)
1631 {
1632 *num_fk_del_set_cols = 0;
1633 }
1634 else
1635 {
1636 int num_delete_cols;
1637
1638 arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
1639 if (ARR_NDIM(arr) != 1 ||
1640 ARR_HASNULL(arr) ||
1641 ARR_ELEMTYPE(arr) != INT2OID)
1642 elog(ERROR, "confdelsetcols is not a 1-D smallint array");
1643 num_delete_cols = ARR_DIMS(arr)[0];
1644 memcpy(fk_del_set_cols, ARR_DATA_PTR(arr), num_delete_cols * sizeof(int16));
1645 if ((Pointer) arr != DatumGetPointer(adatum))
1646 pfree(arr); /* free de-toasted copy, if any */
1647
1648 *num_fk_del_set_cols = num_delete_cols;
1649 }
1650 }
1651
1652 *numfks = numkeys;
1653 }
1654
1655 /*
1656 * FindFKPeriodOpers -
1657 *
1658 * Looks up the operator oids used for the PERIOD part of a temporal foreign key.
1659 * The opclass should be the opclass of that PERIOD element.
1660 * Everything else is an output: containedbyoperoid is the ContainedBy operator for
1661 * types matching the PERIOD element.
1662 * aggedcontainedbyoperoid is also a ContainedBy operator,
1663 * but one whose rhs is a multirange.
1664 * That way foreign keys can compare fkattr <@ range_agg(pkattr).
1665 * intersectoperoid is used by NO ACTION constraints to trim the range being considered
1666 * to just what was updated/deleted.
1667 */
1668 void
1669 FindFKPeriodOpers(Oid opclass,
1670 Oid *containedbyoperoid,
1671 Oid *aggedcontainedbyoperoid,
1672 Oid *intersectoperoid)
1673 {
1674 Oid opfamily = InvalidOid;
1675 Oid opcintype = InvalidOid;
1676 StrategyNumber strat;
1677
1678 /* Make sure we have a range or multirange. */
1679 if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
1680 {
1681 if (opcintype != ANYRANGEOID && opcintype != ANYMULTIRANGEOID)
1682 ereport(ERROR,
1683 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1684 errmsg("invalid type for PERIOD part of foreign key"),
1685 errdetail("Only range and multirange are supported."));
1686
1687 }
1688 else
1689 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1690
1691 /*
1692 * Look up the ContainedBy operator whose lhs and rhs are the opclass's
1693 * type. We use this to optimize RI checks: if the new value includes all
1694 * of the old value, then we can treat the attribute as if it didn't
1695 * change, and skip the RI check.
1696 */
1697 GetOperatorFromCompareType(opclass,
1698 InvalidOid,
1699 COMPARE_CONTAINED_BY,
1700 containedbyoperoid,
1701 &strat);
1702
1703 /*
1704 * Now look up the ContainedBy operator. Its left arg must be the type of
1705 * the column (or rather of the opclass). Its right arg must match the
1706 * return type of the support proc.
1707 */
1708 GetOperatorFromCompareType(opclass,
1709 ANYMULTIRANGEOID,
1710 COMPARE_CONTAINED_BY,
1711 aggedcontainedbyoperoid,
1712 &strat);
1713
1714 switch (opcintype)
1715 {
1716 case ANYRANGEOID:
1717 *intersectoperoid = OID_RANGE_INTERSECT_RANGE_OP;
1718 break;
1719 case ANYMULTIRANGEOID:
1720 *intersectoperoid = OID_MULTIRANGE_INTERSECT_MULTIRANGE_OP;
1721 break;
1722 default:
1723 elog(ERROR, "unexpected opcintype: %u", opcintype);
1724 }
1725 }
1726
1727 /*
1728 * Determine whether a relation can be proven functionally dependent on
1729 * a set of grouping columns. If so, return true and add the pg_constraint
1730 * OIDs of the constraints needed for the proof to the *constraintDeps list.
1731 *
1732 * grouping_columns is a list of grouping expressions, in which columns of
1733 * the rel of interest are Vars with the indicated varno/varlevelsup.
1734 *
1735 * Currently we only check to see if the rel has a primary key that is a
1736 * subset of the grouping_columns. We could also use plain unique constraints
1737 * if all their columns are known not null, but there's a problem: we need
1738 * to be able to represent the not-null-ness as part of the constraints added
1739 * to *constraintDeps. FIXME whenever not-null constraints get represented
1740 * in pg_constraint.
1741 */
1742 bool
1743 check_functional_grouping(Oid relid,
1744 Index varno, Index varlevelsup,
1745 List *grouping_columns,
1746 List **constraintDeps)
1747 {
1748 Bitmapset *pkattnos;
1749 Bitmapset *groupbyattnos;
1750 Oid constraintOid;
1751 ListCell *gl;
1752
1753 /* If the rel has no PK, then we can't prove functional dependency */
1754 pkattnos = get_primary_key_attnos(relid, false, &constraintOid);
1755 if (pkattnos == NULL)
1756 return false;
1757
1758 /* Identify all the rel's columns that appear in grouping_columns */
1759 groupbyattnos = NULL;
1760 foreach(gl, grouping_columns)
1761 {
1762 Var *gvar = (Var *) lfirst(gl);
1763
1764 if (IsA(gvar, Var) &&
1765 gvar->varno == varno &&
1766 gvar->varlevelsup == varlevelsup)
1767 groupbyattnos = bms_add_member(groupbyattnos,
1768 gvar->varattno - FirstLowInvalidHeapAttributeNumber);
1769 }
1770
1771 if (bms_is_subset(pkattnos, groupbyattnos))
1772 {
1773 /* The PK is a subset of grouping_columns, so we win */
1774 *constraintDeps = lappend_oid(*constraintDeps, constraintOid);
1775 return true;
1776 }
1777
1778 return false;
1779 }