LCOV - differential code coverage report
Current view: top level - src/backend/catalog - pg_constraint.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: 7a15cff1f11193467898da1c1fabf06fd2caee04 vs 84a3778c79c2d28b4dc281d03ef2ab019b16483b Lines: 94.3 % 598 564 1 33 11 553 1 11
Current Date: 2025-12-15 18:36:29 -0500 Functions: 100.0 % 22 22 4 18
Baseline: lcov-20251216-010103-baseline Branches: 64.7 % 433 280 9 144 7 273
Baseline Date: 2025-12-15 13:30:48 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 2 2 2
(7,30] days: 100.0 % 6 6 6
(30,360] days: 89.7 % 29 26 1 2 3 23
(360..) days: 94.5 % 561 530 31 530
Function coverage date bins:
(360..) days: 100.0 % 22 22 4 18
Branch coverage date bins:
(7,30] days: 50.0 % 12 6 6 6
(30,360] days: 66.7 % 27 18 3 6 1 17
(360..) days: 65.0 % 394 256 138 256

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

Generated by: LCOV version 2.4-beta