LCOV - differential code coverage report
Current view: top level - src/backend/catalog - pg_constraint.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 94.3 % 598 564 34 1 563 1
Current Date: 2025-09-06 07:49:51 +0900 Functions: 100.0 % 22 22 1 21
Baseline: lcov-20250906-005545-baseline Branches: 64.7 % 433 280 153 280
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 93.5 % 123 115 8 115
(360..) days: 94.5 % 474 448 26 448
Function coverage date bins:
(30,360] days: 100.0 % 6 6 6
(360..) days: 100.0 % 16 16 1 15
Branch coverage date bins:
(30,360] days: 68.7 % 83 57 26 57
(360..) days: 63.7 % 350 223 127 223

 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
 8457 tgl@sss.pgh.pa.us          51                 :CBC       26583 : 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 */
  157 peter@eisentraut.org      104   [ +  +  +  +  :          26583 :     Assert(isEnforced || constraintType == CONSTRAINT_CHECK ||
                                              -  + ]
                                105                 :                :            constraintType == CONSTRAINT_FOREIGN);
                                106                 :                :     /* NOT ENFORCED constraint must be NOT VALID */
  238                           107   [ +  +  -  + ]:          26583 :     Assert(isEnforced || !isValidated);
                                108                 :                : 
 2420 andres@anarazel.de        109                 :          26583 :     conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
                                110                 :                : 
 8457 tgl@sss.pgh.pa.us         111         [ -  + ]:          26583 :     Assert(constraintName);
                                112                 :          26583 :     namestrcpy(&cname, constraintName);
                                113                 :                : 
                                114                 :                :     /*
                                115                 :                :      * Convert C arrays into Postgres arrays.
                                116                 :                :      */
                                117         [ +  + ]:          26583 :     if (constraintNKeys > 0)
                                118                 :                :     {
                                119                 :                :         Datum      *conkey;
                                120                 :                : 
                                121                 :          26084 :         conkey = (Datum *) palloc(constraintNKeys * sizeof(Datum));
                                122         [ +  + ]:          57215 :         for (i = 0; i < constraintNKeys; i++)
                                123                 :          31131 :             conkey[i] = Int16GetDatum(constraintKey[i]);
 1163 peter@eisentraut.org      124                 :          26084 :         conkeyArray = construct_array_builtin(conkey, constraintNKeys, INT2OID);
                                125                 :                :     }
                                126                 :                :     else
 8457 tgl@sss.pgh.pa.us         127                 :            499 :         conkeyArray = NULL;
                                128                 :                : 
                                129         [ +  + ]:          26583 :     if (foreignNKeys > 0)
                                130                 :                :     {
                                131                 :                :         Datum      *fkdatums;
  155                           132                 :           2008 :         int         nkeys = Max(foreignNKeys, numFkDeleteSetCols);
                                133                 :                : 
                                134                 :           2008 :         fkdatums = (Datum *) palloc(nkeys * sizeof(Datum));
 8457                           135         [ +  + ]:           4613 :         for (i = 0; i < foreignNKeys; i++)
 6779                           136                 :           2605 :             fkdatums[i] = Int16GetDatum(foreignKey[i]);
 1163 peter@eisentraut.org      137                 :           2008 :         confkeyArray = construct_array_builtin(fkdatums, foreignNKeys, INT2OID);
 6779 tgl@sss.pgh.pa.us         138         [ +  + ]:           4613 :         for (i = 0; i < foreignNKeys; i++)
                                139                 :           2605 :             fkdatums[i] = ObjectIdGetDatum(pfEqOp[i]);
 1163 peter@eisentraut.org      140                 :           2008 :         conpfeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
 6779 tgl@sss.pgh.pa.us         141         [ +  + ]:           4613 :         for (i = 0; i < foreignNKeys; i++)
                                142                 :           2605 :             fkdatums[i] = ObjectIdGetDatum(ppEqOp[i]);
 1163 peter@eisentraut.org      143                 :           2008 :         conppeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
 6779 tgl@sss.pgh.pa.us         144         [ +  + ]:           4613 :         for (i = 0; i < foreignNKeys; i++)
                                145                 :           2605 :             fkdatums[i] = ObjectIdGetDatum(ffEqOp[i]);
 1163 peter@eisentraut.org      146                 :           2008 :         conffeqopArray = construct_array_builtin(fkdatums, foreignNKeys, OIDOID);
                                147                 :                : 
 1368                           148         [ +  + ]:           2008 :         if (numFkDeleteSetCols > 0)
                                149                 :                :         {
                                150         [ +  + ]:             60 :             for (i = 0; i < numFkDeleteSetCols; i++)
                                151                 :             30 :                 fkdatums[i] = Int16GetDatum(fkDeleteSetCols[i]);
 1163                           152                 :             30 :             confdelsetcolsArray = construct_array_builtin(fkdatums, numFkDeleteSetCols, INT2OID);
                                153                 :                :         }
                                154                 :                :         else
 1368                           155                 :           1978 :             confdelsetcolsArray = NULL;
                                156                 :                :     }
                                157                 :                :     else
                                158                 :                :     {
 8457 tgl@sss.pgh.pa.us         159                 :          24575 :         confkeyArray = NULL;
 6779                           160                 :          24575 :         conpfeqopArray = NULL;
                                161                 :          24575 :         conppeqopArray = NULL;
                                162                 :          24575 :         conffeqopArray = NULL;
 1368 peter@eisentraut.org      163                 :          24575 :         confdelsetcolsArray = NULL;
                                164                 :                :     }
                                165                 :                : 
 5752 tgl@sss.pgh.pa.us         166         [ +  + ]:          26583 :     if (exclOp != NULL)
                                167                 :                :     {
                                168                 :                :         Datum      *opdatums;
                                169                 :                : 
                                170                 :            398 :         opdatums = (Datum *) palloc(constraintNKeys * sizeof(Datum));
                                171         [ +  + ]:           1159 :         for (i = 0; i < constraintNKeys; i++)
                                172                 :            761 :             opdatums[i] = ObjectIdGetDatum(exclOp[i]);
 1163 peter@eisentraut.org      173                 :            398 :         conexclopArray = construct_array_builtin(opdatums, constraintNKeys, OIDOID);
                                174                 :                :     }
                                175                 :                :     else
 5752 tgl@sss.pgh.pa.us         176                 :          26185 :         conexclopArray = NULL;
                                177                 :                : 
                                178                 :                :     /* initialize nulls and values */
 8457                           179         [ +  + ]:         770907 :     for (i = 0; i < Natts_pg_constraint; i++)
                                180                 :                :     {
 6152                           181                 :         744324 :         nulls[i] = false;
   29 tgl@sss.pgh.pa.us         182                 :GNC      744324 :         values[i] = (Datum) 0;
                                183                 :                :     }
                                184                 :                : 
 2482 andres@anarazel.de        185                 :CBC       26583 :     conOid = GetNewOidWithIndex(conDesc, ConstraintOidIndexId,
                                186                 :                :                                 Anum_pg_constraint_oid);
                                187                 :          26583 :     values[Anum_pg_constraint_oid - 1] = ObjectIdGetDatum(conOid);
 8457 tgl@sss.pgh.pa.us         188                 :          26583 :     values[Anum_pg_constraint_conname - 1] = NameGetDatum(&cname);
                                189                 :          26583 :     values[Anum_pg_constraint_connamespace - 1] = ObjectIdGetDatum(constraintNamespace);
                                190                 :          26583 :     values[Anum_pg_constraint_contype - 1] = CharGetDatum(constraintType);
                                191                 :          26583 :     values[Anum_pg_constraint_condeferrable - 1] = BoolGetDatum(isDeferrable);
                                192                 :          26583 :     values[Anum_pg_constraint_condeferred - 1] = BoolGetDatum(isDeferred);
  238 peter@eisentraut.org      193                 :          26583 :     values[Anum_pg_constraint_conenforced - 1] = BoolGetDatum(isEnforced);
 5324 simon@2ndQuadrant.co      194                 :          26583 :     values[Anum_pg_constraint_convalidated - 1] = BoolGetDatum(isValidated);
 8457 tgl@sss.pgh.pa.us         195                 :          26583 :     values[Anum_pg_constraint_conrelid - 1] = ObjectIdGetDatum(relId);
                                196                 :          26583 :     values[Anum_pg_constraint_contypid - 1] = ObjectIdGetDatum(domainId);
 5884                           197                 :          26583 :     values[Anum_pg_constraint_conindid - 1] = ObjectIdGetDatum(indexRelId);
 2724 alvherre@alvh.no-ip.      198                 :          26583 :     values[Anum_pg_constraint_conparentid - 1] = ObjectIdGetDatum(parentConstrId);
 8457 tgl@sss.pgh.pa.us         199                 :          26583 :     values[Anum_pg_constraint_confrelid - 1] = ObjectIdGetDatum(foreignRelId);
                                200                 :          26583 :     values[Anum_pg_constraint_confupdtype - 1] = CharGetDatum(foreignUpdateType);
                                201                 :          26583 :     values[Anum_pg_constraint_confdeltype - 1] = CharGetDatum(foreignDeleteType);
                                202                 :          26583 :     values[Anum_pg_constraint_confmatchtype - 1] = CharGetDatum(foreignMatchType);
 6329                           203                 :          26583 :     values[Anum_pg_constraint_conislocal - 1] = BoolGetDatum(conIsLocal);
  893 peter@eisentraut.org      204                 :          26583 :     values[Anum_pg_constraint_coninhcount - 1] = Int16GetDatum(conInhCount);
 4887 alvherre@alvh.no-ip.      205                 :          26583 :     values[Anum_pg_constraint_connoinherit - 1] = BoolGetDatum(conNoInherit);
  354 peter@eisentraut.org      206                 :          26583 :     values[Anum_pg_constraint_conperiod - 1] = BoolGetDatum(conPeriod);
                                207                 :                : 
 8457 tgl@sss.pgh.pa.us         208         [ +  + ]:          26583 :     if (conkeyArray)
                                209                 :          26084 :         values[Anum_pg_constraint_conkey - 1] = PointerGetDatum(conkeyArray);
                                210                 :                :     else
 6152                           211                 :            499 :         nulls[Anum_pg_constraint_conkey - 1] = true;
                                212                 :                : 
 8457                           213         [ +  + ]:          26583 :     if (confkeyArray)
                                214                 :           2008 :         values[Anum_pg_constraint_confkey - 1] = PointerGetDatum(confkeyArray);
                                215                 :                :     else
 6152                           216                 :          24575 :         nulls[Anum_pg_constraint_confkey - 1] = true;
                                217                 :                : 
 6779                           218         [ +  + ]:          26583 :     if (conpfeqopArray)
                                219                 :           2008 :         values[Anum_pg_constraint_conpfeqop - 1] = PointerGetDatum(conpfeqopArray);
                                220                 :                :     else
 6152                           221                 :          24575 :         nulls[Anum_pg_constraint_conpfeqop - 1] = true;
                                222                 :                : 
 6779                           223         [ +  + ]:          26583 :     if (conppeqopArray)
                                224                 :           2008 :         values[Anum_pg_constraint_conppeqop - 1] = PointerGetDatum(conppeqopArray);
                                225                 :                :     else
 6152                           226                 :          24575 :         nulls[Anum_pg_constraint_conppeqop - 1] = true;
                                227                 :                : 
 6779                           228         [ +  + ]:          26583 :     if (conffeqopArray)
                                229                 :           2008 :         values[Anum_pg_constraint_conffeqop - 1] = PointerGetDatum(conffeqopArray);
                                230                 :                :     else
 6152                           231                 :          24575 :         nulls[Anum_pg_constraint_conffeqop - 1] = true;
                                232                 :                : 
 1368 peter@eisentraut.org      233         [ +  + ]:          26583 :     if (confdelsetcolsArray)
                                234                 :             30 :         values[Anum_pg_constraint_confdelsetcols - 1] = PointerGetDatum(confdelsetcolsArray);
                                235                 :                :     else
                                236                 :          26553 :         nulls[Anum_pg_constraint_confdelsetcols - 1] = true;
                                237                 :                : 
 5752 tgl@sss.pgh.pa.us         238         [ +  + ]:          26583 :     if (conexclopArray)
                                239                 :            398 :         values[Anum_pg_constraint_conexclop - 1] = PointerGetDatum(conexclopArray);
                                240                 :                :     else
                                241                 :          26185 :         nulls[Anum_pg_constraint_conexclop - 1] = true;
                                242                 :                : 
 8457                           243         [ +  + ]:          26583 :     if (conBin)
 6374                           244                 :           1707 :         values[Anum_pg_constraint_conbin - 1] = CStringGetTextDatum(conBin);
                                245                 :                :     else
 6152                           246                 :          24876 :         nulls[Anum_pg_constraint_conbin - 1] = true;
                                247                 :                : 
                                248                 :          26583 :     tup = heap_form_tuple(RelationGetDescr(conDesc), values, nulls);
                                249                 :                : 
 2482 andres@anarazel.de        250                 :          26583 :     CatalogTupleInsert(conDesc, tup);
                                251                 :                : 
 1893 michael@paquier.xyz       252                 :          26583 :     ObjectAddressSet(conobject, ConstraintRelationId, conOid);
                                253                 :                : 
 2420 andres@anarazel.de        254                 :          26583 :     table_close(conDesc, RowExclusiveLock);
                                255                 :                : 
                                256                 :                :     /* Handle set of auto dependencies */
 1827 michael@paquier.xyz       257                 :          26583 :     addrs_auto = new_object_addresses();
                                258                 :                : 
 8457 tgl@sss.pgh.pa.us         259         [ +  + ]:          26583 :     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                 :                : 
 2709 teodor@sigaev.ru          267         [ +  + ]:          26170 :         if (constraintNTotalKeys > 0)
                                268                 :                :         {
                                269         [ +  + ]:          57369 :             for (i = 0; i < constraintNTotalKeys; i++)
                                270                 :                :             {
 1893 michael@paquier.xyz       271                 :          31285 :                 ObjectAddressSubSet(relobject, RelationRelationId, relId,
                                272                 :                :                                     constraintKey[i]);
 1827                           273                 :          31285 :                 add_exact_object_address(&relobject, addrs_auto);
                                274                 :                :             }
                                275                 :                :         }
                                276                 :                :         else
                                277                 :                :         {
 1893                           278                 :             86 :             ObjectAddressSet(relobject, RelationRelationId, relId);
 1827                           279                 :             86 :             add_exact_object_address(&relobject, addrs_auto);
                                280                 :                :         }
                                281                 :                :     }
                                282                 :                : 
 8331 bruce@momjian.us          283         [ +  + ]:          26583 :     if (OidIsValid(domainId))
                                284                 :                :     {
                                285                 :                :         /*
                                286                 :                :          * Register auto dependency from constraint to owning domain
                                287                 :                :          */
                                288                 :                :         ObjectAddress domobject;
                                289                 :                : 
 1893 michael@paquier.xyz       290                 :            413 :         ObjectAddressSet(domobject, TypeRelationId, domainId);
 1827                           291                 :            413 :         add_exact_object_address(&domobject, addrs_auto);
                                292                 :                :     }
                                293                 :                : 
                                294                 :          26583 :     record_object_address_dependencies(&conobject, addrs_auto,
                                295                 :                :                                        DEPENDENCY_AUTO);
                                296                 :          26583 :     free_object_addresses(addrs_auto);
                                297                 :                : 
                                298                 :                :     /* Handle set of normal dependencies */
                                299                 :          26583 :     addrs_normal = new_object_addresses();
                                300                 :                : 
 8457 tgl@sss.pgh.pa.us         301         [ +  + ]:          26583 :     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         [ +  - ]:           2008 :         if (foreignNKeys > 0)
                                310                 :                :         {
                                311         [ +  + ]:           4613 :             for (i = 0; i < foreignNKeys; i++)
                                312                 :                :             {
 1893 michael@paquier.xyz       313                 :           2605 :                 ObjectAddressSubSet(relobject, RelationRelationId,
                                314                 :                :                                     foreignRelId, foreignKey[i]);
 1827                           315                 :           2605 :                 add_exact_object_address(&relobject, addrs_normal);
                                316                 :                :             }
                                317                 :                :         }
                                318                 :                :         else
                                319                 :                :         {
 1893 michael@paquier.xyz       320                 :UBC           0 :             ObjectAddressSet(relobject, RelationRelationId, foreignRelId);
 1827                           321                 :              0 :             add_exact_object_address(&relobject, addrs_normal);
                                322                 :                :         }
                                323                 :                :     }
                                324                 :                : 
 5884 tgl@sss.pgh.pa.us         325   [ +  +  +  + ]:CBC       26583 :     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                 :                : 
 1893 michael@paquier.xyz       335                 :           2008 :         ObjectAddressSet(relobject, RelationRelationId, indexRelId);
 1827                           336                 :           2008 :         add_exact_object_address(&relobject, addrs_normal);
                                337                 :                :     }
                                338                 :                : 
 6779 tgl@sss.pgh.pa.us         339         [ +  + ]:          26583 :     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                 :           2008 :         oprobject.classId = OperatorRelationId;
                                350                 :           2008 :         oprobject.objectSubId = 0;
                                351                 :                : 
                                352         [ +  + ]:           4613 :         for (i = 0; i < foreignNKeys; i++)
                                353                 :                :         {
                                354                 :           2605 :             oprobject.objectId = pfEqOp[i];
 1827 michael@paquier.xyz       355                 :           2605 :             add_exact_object_address(&oprobject, addrs_normal);
 6779 tgl@sss.pgh.pa.us         356         [ +  + ]:           2605 :             if (ppEqOp[i] != pfEqOp[i])
                                357                 :                :             {
                                358                 :             28 :                 oprobject.objectId = ppEqOp[i];
 1827 michael@paquier.xyz       359                 :             28 :                 add_exact_object_address(&oprobject, addrs_normal);
                                360                 :                :             }
 6779 tgl@sss.pgh.pa.us         361         [ +  + ]:           2605 :             if (ffEqOp[i] != pfEqOp[i])
                                362                 :                :             {
                                363                 :             28 :                 oprobject.objectId = ffEqOp[i];
 1827 michael@paquier.xyz       364                 :             28 :                 add_exact_object_address(&oprobject, addrs_normal);
                                365                 :                :             }
                                366                 :                :         }
                                367                 :                :     }
                                368                 :                : 
                                369                 :          26583 :     record_object_address_dependencies(&conobject, addrs_normal,
                                370                 :                :                                        DEPENDENCY_NORMAL);
                                371                 :          26583 :     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                 :                : 
 8453 tgl@sss.pgh.pa.us         381         [ +  + ]:          26583 :     if (conExpr != NULL)
                                382                 :                :     {
                                383                 :                :         /*
                                384                 :                :          * Register dependencies from constraint to objects mentioned in CHECK
                                385                 :                :          * expression.
                                386                 :                :          */
 8137                           387                 :           1707 :         recordDependencyOnSingleRelExpr(&conobject, conExpr, relId,
                                388                 :                :                                         DEPENDENCY_NORMAL,
                                389                 :                :                                         DEPENDENCY_NORMAL, false);
                                390                 :                :     }
                                391                 :                : 
                                392                 :                :     /* Post creation hook for new constraint */
 4556 rhaas@postgresql.org      393         [ -  + ]:          26583 :     InvokeObjectPostCreateHookArg(ConstraintRelationId, conOid, 0,
                                394                 :                :                                   is_internal);
                                395                 :                : 
 8457 tgl@sss.pgh.pa.us         396                 :          26583 :     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
 7758                           412                 :           8374 : ConstraintNameIsUsed(ConstraintCategory conCat, Oid objId,
                                413                 :                :                      const char *conname)
                                414                 :                : {
                                415                 :                :     bool        found;
                                416                 :                :     Relation    conDesc;
                                417                 :                :     SysScanDesc conscan;
                                418                 :                :     ScanKeyData skey[3];
                                419                 :                : 
 2420 andres@anarazel.de        420                 :           8374 :     conDesc = table_open(ConstraintRelationId, AccessShareLock);
                                421                 :                : 
 2559 tgl@sss.pgh.pa.us         422         [ +  + ]:           8374 :     ScanKeyInit(&skey[0],
                                423                 :                :                 Anum_pg_constraint_conrelid,
                                424                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                425                 :                :                 ObjectIdGetDatum((conCat == CONSTRAINT_RELATION)
                                426                 :                :                                  ? objId : InvalidOid));
                                427         [ +  + ]:           8374 :     ScanKeyInit(&skey[1],
                                428                 :                :                 Anum_pg_constraint_contypid,
                                429                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                430                 :                :                 ObjectIdGetDatum((conCat == CONSTRAINT_DOMAIN)
                                431                 :                :                                  ? objId : InvalidOid));
                                432                 :           8374 :     ScanKeyInit(&skey[2],
                                433                 :                :                 Anum_pg_constraint_conname,
                                434                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                                435                 :                :                 CStringGetDatum(conname));
                                436                 :                : 
                                437                 :           8374 :     conscan = systable_beginscan(conDesc, ConstraintRelidTypidNameIndexId,
                                438                 :                :                                  true, NULL, 3, skey);
                                439                 :                : 
                                440                 :                :     /* There can be at most one matching row */
                                441                 :           8374 :     found = (HeapTupleIsValid(systable_getnext(conscan)));
                                442                 :                : 
                                443                 :           8374 :     systable_endscan(conscan);
 2420 andres@anarazel.de        444                 :           8374 :     table_close(conDesc, AccessShareLock);
                                445                 :                : 
 2559 tgl@sss.pgh.pa.us         446                 :           8374 :     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                 :           4358 : ConstraintNameExists(const char *conname, Oid namespaceid)
                                458                 :                : {
                                459                 :                :     bool        found;
                                460                 :                :     Relation    conDesc;
                                461                 :                :     SysScanDesc conscan;
                                462                 :                :     ScanKeyData skey[2];
                                463                 :                : 
 2420 andres@anarazel.de        464                 :           4358 :     conDesc = table_open(ConstraintRelationId, AccessShareLock);
                                465                 :                : 
 7969 tgl@sss.pgh.pa.us         466                 :           4358 :     ScanKeyInit(&skey[0],
                                467                 :                :                 Anum_pg_constraint_conname,
                                468                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                                469                 :                :                 CStringGetDatum(conname));
                                470                 :                : 
                                471                 :           4358 :     ScanKeyInit(&skey[1],
                                472                 :                :                 Anum_pg_constraint_connamespace,
                                473                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                474                 :                :                 ObjectIdGetDatum(namespaceid));
                                475                 :                : 
 7450                           476                 :           4358 :     conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
                                477                 :                :                                  NULL, 2, skey);
                                478                 :                : 
 2559                           479                 :           4358 :     found = (HeapTupleIsValid(systable_getnext(conscan)));
                                480                 :                : 
 8457                           481                 :           4358 :     systable_endscan(conscan);
 2420 andres@anarazel.de        482                 :           4358 :     table_close(conDesc, AccessShareLock);
                                483                 :                : 
 8457 tgl@sss.pgh.pa.us         484                 :           4358 :     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 *
 7758                           513                 :          12561 : ChooseConstraintName(const char *name1, const char *name2,
                                514                 :                :                      const char *label, Oid namespaceid,
                                515                 :                :                      List *others)
                                516                 :                : {
                                517                 :          12561 :     int         pass = 0;
                                518                 :          12561 :     char       *conname = NULL;
                                519                 :                :     char        modlabel[NAMEDATALEN];
                                520                 :                :     Relation    conDesc;
                                521                 :                :     SysScanDesc conscan;
                                522                 :                :     ScanKeyData skey[2];
                                523                 :                :     bool        found;
                                524                 :                :     ListCell   *l;
                                525                 :                : 
 2420 andres@anarazel.de        526                 :          12561 :     conDesc = table_open(ConstraintRelationId, AccessShareLock);
                                527                 :                : 
                                528                 :                :     /* try the unmodified label first, unless it's empty */
  136 tgl@sss.pgh.pa.us         529         [ +  + ]:          12561 :     if (label[0] != '\0')
                                530                 :          11979 :         strlcpy(modlabel, label, sizeof(modlabel));
                                531                 :                :     else
                                532                 :            582 :         snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
                                533                 :                : 
                                534                 :                :     for (;;)
                                535                 :                :     {
 7758                           536                 :          14158 :         conname = makeObjectName(name1, name2, modlabel);
                                537                 :                : 
 8457                           538                 :          14158 :         found = false;
                                539                 :                : 
 7758                           540   [ +  +  +  +  :          16180 :         foreach(l, others)
                                              +  + ]
                                541                 :                :         {
                                542         [ +  + ]:           2031 :             if (strcmp((char *) lfirst(l), conname) == 0)
                                543                 :                :             {
 8457                           544                 :              9 :                 found = true;
                                545                 :              9 :                 break;
                                546                 :                :             }
                                547                 :                :         }
                                548                 :                : 
 7758                           549         [ +  + ]:          14158 :         if (!found)
                                550                 :                :         {
                                551                 :          14149 :             ScanKeyInit(&skey[0],
                                552                 :                :                         Anum_pg_constraint_conname,
                                553                 :                :                         BTEqualStrategyNumber, F_NAMEEQ,
                                554                 :                :                         CStringGetDatum(conname));
                                555                 :                : 
                                556                 :          14149 :             ScanKeyInit(&skey[1],
                                557                 :                :                         Anum_pg_constraint_connamespace,
                                558                 :                :                         BTEqualStrategyNumber, F_OIDEQ,
                                559                 :                :                         ObjectIdGetDatum(namespaceid));
                                560                 :                : 
 7450                           561                 :          14149 :             conscan = systable_beginscan(conDesc, ConstraintNameNspIndexId, true,
                                562                 :                :                                          NULL, 2, skey);
                                563                 :                : 
 7758                           564                 :          14149 :             found = (HeapTupleIsValid(systable_getnext(conscan)));
                                565                 :                : 
                                566                 :          14149 :             systable_endscan(conscan);
                                567                 :                :         }
                                568                 :                : 
                                569         [ +  + ]:          14158 :         if (!found)
                                570                 :          12561 :             break;
                                571                 :                : 
                                572                 :                :         /* found a conflict, so try a new name component */
                                573                 :           1597 :         pfree(conname);
                                574                 :           1597 :         snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
                                575                 :                :     }
                                576                 :                : 
 2420 andres@anarazel.de        577                 :          12561 :     table_close(conDesc, AccessShareLock);
                                578                 :                : 
 7758 tgl@sss.pgh.pa.us         579                 :          12561 :     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
  302 alvherre@alvh.no-ip.      592                 :           6110 : findNotNullConstraintAttnum(Oid relid, AttrNumber attnum)
                                593                 :                : {
                                594                 :                :     Relation    pg_constraint;
                                595                 :                :     HeapTuple   conTup,
                                596                 :           6110 :                 retval = NULL;
                                597                 :                :     SysScanDesc scan;
                                598                 :                :     ScanKeyData key;
                                599                 :                : 
                                600                 :           6110 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                                601                 :           6110 :     ScanKeyInit(&key,
                                602                 :                :                 Anum_pg_constraint_conrelid,
                                603                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                604                 :                :                 ObjectIdGetDatum(relid));
                                605                 :           6110 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
                                606                 :                :                               true, NULL, 1, &key);
                                607                 :                : 
                                608         [ +  + ]:           9836 :     while (HeapTupleIsValid(conTup = systable_getnext(scan)))
                                609                 :                :     {
                                610                 :           4409 :         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         [ +  + ]:           4409 :         if (con->contype != CONSTRAINT_NOTNULL)
                                618                 :           1674 :             continue;
                                619                 :                : 
                                620                 :           2735 :         conkey = extractNotNullColumn(conTup);
                                621         [ +  + ]:           2735 :         if (conkey != attnum)
                                622                 :           2052 :             continue;
                                623                 :                : 
                                624                 :                :         /* Found it */
                                625                 :            683 :         retval = heap_copytuple(conTup);
                                626                 :            683 :         break;
                                627                 :                :     }
                                628                 :                : 
                                629                 :           6110 :     systable_endscan(scan);
                                630                 :           6110 :     table_close(pg_constraint, AccessShareLock);
                                631                 :                : 
                                632                 :           6110 :     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                 :            660 : findNotNullConstraint(Oid relid, const char *colname)
                                643                 :                : {
                                644                 :                :     AttrNumber  attnum;
                                645                 :                : 
                                646                 :            660 :     attnum = get_attnum(relid, colname);
                                647         [ +  + ]:            660 :     if (attnum <= InvalidAttrNumber)
                                648                 :             18 :         return NULL;
                                649                 :                : 
                                650                 :            642 :     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
  535 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)
  535 peter@eisentraut.org      682                 :UBC           0 :             continue;
  535 peter@eisentraut.org      683         [ -  + ]:CBC           6 :         if (!con->convalidated)
  535 peter@eisentraut.org      684                 :UBC           0 :             continue;
                                685                 :                : 
                                686                 :                :         /* Found it */
  535 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
  302 alvherre@alvh.no-ip.      702                 :           6222 : extractNotNullColumn(HeapTuple constrTup)
                                703                 :                : {
                                704                 :                :     Datum       adatum;
                                705                 :                :     ArrayType  *arr;
                                706                 :                : 
                                707                 :                :     /* only tuples for not-null constraints should be given */
                                708         [ -  + ]:           6222 :     Assert(((Form_pg_constraint) GETSTRUCT(constrTup))->contype == CONSTRAINT_NOTNULL);
                                709                 :                : 
                                710                 :           6222 :     adatum = SysCacheGetAttrNotNull(CONSTROID, constrTup,
                                711                 :                :                                     Anum_pg_constraint_conkey);
                                712                 :           6222 :     arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                                713         [ +  - ]:           6222 :     if (ARR_NDIM(arr) != 1 ||
                                714         [ +  - ]:           6222 :         ARR_HASNULL(arr) ||
                                715         [ +  - ]:           6222 :         ARR_ELEMTYPE(arr) != INT2OID ||
                                716         [ -  + ]:           6222 :         ARR_DIMS(arr)[0] != 1)
  302 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                 :                : 
  298 alvherre@alvh.no-ip.      721         [ -  + ]:CBC        6222 :     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
  302                           741                 :           4990 : AdjustNotNullInheritance(Oid relid, AttrNumber attnum,
                                742                 :                :                          bool is_local, bool is_no_inherit, bool is_notvalid)
                                743                 :                : {
                                744                 :                :     HeapTuple   tup;
                                745                 :                : 
                                746                 :           4990 :     tup = findNotNullConstraintAttnum(relid, attnum);
                                747         [ +  + ]:           4990 :     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                 :                :          */
  152                           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                 :                : 
  302                           780         [ +  + ]:             47 :         if (!is_local)
                                781                 :                :         {
                                782         [ -  + ]:             35 :             if (pg_add_s16_overflow(conform->coninhcount, 1,
                                783                 :                :                                     &conform->coninhcount))
  302 alvherre@alvh.no-ip.      784         [ #  # ]:UBC           0 :                 ereport(ERROR,
                                785                 :                :                         errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                786                 :                :                         errmsg("too many inheritance parents"));
  302 alvherre@alvh.no-ip.      787                 :CBC          35 :             changed = true;
                                788                 :                :         }
                                789         [ -  + ]:             12 :         else if (!conform->conislocal)
                                790                 :                :         {
  302 alvherre@alvh.no-ip.      791                 :UBC           0 :             conform->conislocal = true;
                                792                 :              0 :             changed = true;
                                793                 :                :         }
                                794                 :                : 
  302 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                 :           4922 :     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                 :           5384 : RelationGetNotNullConstraints(Oid relid, bool cooked, bool include_noinh)
                                818                 :                : {
                                819                 :           5384 :     List       *notnulls = NIL;
                                820                 :                :     Relation    constrRel;
                                821                 :                :     HeapTuple   htup;
                                822                 :                :     SysScanDesc conscan;
                                823                 :                :     ScanKeyData skey;
                                824                 :                : 
                                825                 :           5384 :     constrRel = table_open(ConstraintRelationId, AccessShareLock);
                                826                 :           5384 :     ScanKeyInit(&skey,
                                827                 :                :                 Anum_pg_constraint_conrelid,
                                828                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                                829                 :                :                 ObjectIdGetDatum(relid));
                                830                 :           5384 :     conscan = systable_beginscan(constrRel, ConstraintRelidTypidNameIndexId, true,
                                831                 :                :                                  NULL, 1, &skey);
                                832                 :                : 
                                833         [ +  + ]:           8457 :     while (HeapTupleIsValid(htup = systable_getnext(conscan)))
                                834                 :                :     {
                                835                 :           3073 :         Form_pg_constraint conForm = (Form_pg_constraint) GETSTRUCT(htup);
                                836                 :                :         AttrNumber  colnum;
                                837                 :                : 
                                838         [ +  + ]:           3073 :         if (conForm->contype != CONSTRAINT_NOTNULL)
                                839                 :           1650 :             continue;
                                840   [ +  +  +  + ]:           1423 :         if (conForm->connoinherit && !include_noinh)
                                841                 :             30 :             continue;
                                842                 :                : 
                                843                 :           1393 :         colnum = extractNotNullColumn(htup);
                                844                 :                : 
                                845         [ +  + ]:           1393 :         if (cooked)
                                846                 :                :         {
                                847                 :                :             CookedConstraint *cooked;
                                848                 :                : 
                                849                 :           1191 :             cooked = (CookedConstraint *) palloc(sizeof(CookedConstraint));
                                850                 :                : 
                                851                 :           1191 :             cooked->contype = CONSTR_NOTNULL;
                                852                 :           1191 :             cooked->conoid = conForm->oid;
                                853                 :           1191 :             cooked->name = pstrdup(NameStr(conForm->conname));
                                854                 :           1191 :             cooked->attnum = colnum;
                                855                 :           1191 :             cooked->expr = NULL;
  238 peter@eisentraut.org      856                 :           1191 :             cooked->is_enforced = true;
  152 alvherre@alvh.no-ip.      857                 :           1191 :             cooked->skip_validation = !conForm->convalidated;
  302                           858                 :           1191 :             cooked->is_local = true;
                                859                 :           1191 :             cooked->inhcount = 0;
                                860                 :           1191 :             cooked->is_no_inherit = conForm->connoinherit;
                                861                 :                : 
                                862                 :           1191 :             notnulls = lappend(notnulls, cooked);
                                863                 :                :         }
                                864                 :                :         else
                                865                 :                :         {
                                866                 :                :             Constraint *constr;
                                867                 :                : 
                                868                 :            202 :             constr = makeNode(Constraint);
                                869                 :            202 :             constr->contype = CONSTR_NOTNULL;
                                870                 :            202 :             constr->conname = pstrdup(NameStr(conForm->conname));
                                871                 :            202 :             constr->deferrable = false;
                                872                 :            202 :             constr->initdeferred = false;
                                873                 :            202 :             constr->location = -1;
                                874                 :            202 :             constr->keys = list_make1(makeString(get_attname(relid, colnum,
                                875                 :                :                                                              false)));
  238 peter@eisentraut.org      876                 :            202 :             constr->is_enforced = true;
  152 alvherre@alvh.no-ip.      877                 :            202 :             constr->skip_validation = !conForm->convalidated;
  302                           878                 :            202 :             constr->initially_valid = true;
                                879                 :            202 :             constr->is_no_inherit = conForm->connoinherit;
                                880                 :            202 :             notnulls = lappend(notnulls, constr);
                                881                 :                :         }
                                882                 :                :     }
                                883                 :                : 
                                884                 :           5384 :     systable_endscan(conscan);
                                885                 :           5384 :     table_close(constrRel, AccessShareLock);
                                886                 :                : 
                                887                 :           5384 :     return notnulls;
                                888                 :                : }
                                889                 :                : 
                                890                 :                : 
                                891                 :                : /*
                                892                 :                :  * Delete a single constraint record.
                                893                 :                :  */
                                894                 :                : void
 8457 tgl@sss.pgh.pa.us         895                 :          13627 : RemoveConstraintById(Oid conId)
                                896                 :                : {
                                897                 :                :     Relation    conDesc;
                                898                 :                :     HeapTuple   tup;
                                899                 :                :     Form_pg_constraint con;
                                900                 :                : 
 2420 andres@anarazel.de        901                 :          13627 :     conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
                                902                 :                : 
 5683 rhaas@postgresql.org      903                 :          13627 :     tup = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conId));
 6779 tgl@sss.pgh.pa.us         904         [ -  + ]:          13627 :     if (!HeapTupleIsValid(tup)) /* should not happen */
 6779 tgl@sss.pgh.pa.us         905         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for constraint %u", conId);
 8457 tgl@sss.pgh.pa.us         906                 :CBC       13627 :     con = (Form_pg_constraint) GETSTRUCT(tup);
                                907                 :                : 
                                908                 :                :     /*
                                909                 :                :      * Special processing depending on what the constraint is for.
                                910                 :                :      */
                                911         [ +  + ]:          13627 :     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                 :                :          */
 2420 andres@anarazel.de        919                 :          13448 :         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                 :                :          */
 8457 tgl@sss.pgh.pa.us         926         [ +  + ]:          13447 :         if (con->contype == CONSTRAINT_CHECK)
                                927                 :                :         {
                                928                 :                :             Relation    pgrel;
                                929                 :                :             HeapTuple   relTup;
                                930                 :                :             Form_pg_class classForm;
                                931                 :                : 
 2420 andres@anarazel.de        932                 :           1013 :             pgrel = table_open(RelationRelationId, RowExclusiveLock);
 5683 rhaas@postgresql.org      933                 :           1013 :             relTup = SearchSysCacheCopy1(RELOID,
                                934                 :                :                                          ObjectIdGetDatum(con->conrelid));
 8457 tgl@sss.pgh.pa.us         935         [ -  + ]:           1013 :             if (!HeapTupleIsValid(relTup))
 8083 tgl@sss.pgh.pa.us         936         [ #  # ]:UBC           0 :                 elog(ERROR, "cache lookup failed for relation %u",
                                937                 :                :                      con->conrelid);
 8457 tgl@sss.pgh.pa.us         938                 :CBC        1013 :             classForm = (Form_pg_class) GETSTRUCT(relTup);
                                939                 :                : 
 2999                           940         [ -  + ]:           1013 :             if (classForm->relchecks == 0)   /* should not happen */
 8083 tgl@sss.pgh.pa.us         941         [ #  # ]:UBC           0 :                 elog(ERROR, "relation \"%s\" has relchecks = 0",
                                942                 :                :                      RelationGetRelationName(rel));
 8457 tgl@sss.pgh.pa.us         943                 :CBC        1013 :             classForm->relchecks--;
                                944                 :                : 
 3140 alvherre@alvh.no-ip.      945                 :           1013 :             CatalogTupleUpdate(pgrel, &relTup->t_self, relTup);
                                946                 :                : 
 8457 tgl@sss.pgh.pa.us         947                 :           1013 :             heap_freetuple(relTup);
                                948                 :                : 
 2420 andres@anarazel.de        949                 :           1013 :             table_close(pgrel, RowExclusiveLock);
                                950                 :                :         }
                                951                 :                : 
                                952                 :                :         /* Keep lock on constraint's rel until end of xact */
                                953                 :          13447 :         table_close(rel, NoLock);
                                954                 :                :     }
 8331 bruce@momjian.us          955         [ -  + ]:            179 :     else if (OidIsValid(con->contypid))
                                956                 :                :     {
                                957                 :                :         /*
                                958                 :                :          * XXX for now, do nothing special when dropping a domain constraint
                                959                 :                :          *
                                960                 :                :          * Probably there should be some form of locking on the domain type,
                                961                 :                :          * but we have no such concept at the moment.
                                962                 :                :          */
                                963                 :                :     }
                                964                 :                :     else
 8083 tgl@sss.pgh.pa.us         965         [ #  # ]:UBC           0 :         elog(ERROR, "constraint %u is not of a known type", conId);
                                966                 :                : 
                                967                 :                :     /* Fry the constraint itself */
 3139 tgl@sss.pgh.pa.us         968                 :CBC       13626 :     CatalogTupleDelete(conDesc, &tup->t_self);
                                969                 :                : 
                                970                 :                :     /* Clean up */
 6779                           971                 :          13626 :     ReleaseSysCache(tup);
 2420 andres@anarazel.de        972                 :          13626 :     table_close(conDesc, RowExclusiveLock);
 8457 tgl@sss.pgh.pa.us         973                 :          13626 : }
                                974                 :                : 
                                975                 :                : /*
                                976                 :                :  * RenameConstraintById
                                977                 :                :  *      Rename a constraint.
                                978                 :                :  *
                                979                 :                :  * Note: this isn't intended to be a user-exposed function; it doesn't check
                                980                 :                :  * permissions etc.  Currently this is only invoked when renaming an index
                                981                 :                :  * that is associated with a constraint, but it's made a little more general
                                982                 :                :  * than that with the expectation of someday having ALTER TABLE RENAME
                                983                 :                :  * CONSTRAINT.
                                984                 :                :  */
                                985                 :                : void
 6442                           986                 :             48 : RenameConstraintById(Oid conId, const char *newname)
                                987                 :                : {
                                988                 :                :     Relation    conDesc;
                                989                 :                :     HeapTuple   tuple;
                                990                 :                :     Form_pg_constraint con;
                                991                 :                : 
 2420 andres@anarazel.de        992                 :             48 :     conDesc = table_open(ConstraintRelationId, RowExclusiveLock);
                                993                 :                : 
 5683 rhaas@postgresql.org      994                 :             48 :     tuple = SearchSysCacheCopy1(CONSTROID, ObjectIdGetDatum(conId));
 6442 tgl@sss.pgh.pa.us         995         [ -  + ]:             48 :     if (!HeapTupleIsValid(tuple))
 6442 tgl@sss.pgh.pa.us         996         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for constraint %u", conId);
 6442 tgl@sss.pgh.pa.us         997                 :CBC          48 :     con = (Form_pg_constraint) GETSTRUCT(tuple);
                                998                 :                : 
                                999                 :                :     /*
                               1000                 :                :      * For user-friendliness, check whether the name is already in use.
                               1001                 :                :      */
                               1002   [ +  +  -  + ]:             93 :     if (OidIsValid(con->conrelid) &&
                               1003                 :             45 :         ConstraintNameIsUsed(CONSTRAINT_RELATION,
                               1004                 :                :                              con->conrelid,
                               1005                 :                :                              newname))
 6442 tgl@sss.pgh.pa.us        1006         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1007                 :                :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
                               1008                 :                :                  errmsg("constraint \"%s\" for relation \"%s\" already exists",
                               1009                 :                :                         newname, get_rel_name(con->conrelid))));
 6442 tgl@sss.pgh.pa.us        1010   [ +  +  -  + ]:CBC          51 :     if (OidIsValid(con->contypid) &&
                               1011                 :              3 :         ConstraintNameIsUsed(CONSTRAINT_DOMAIN,
                               1012                 :                :                              con->contypid,
                               1013                 :                :                              newname))
 6442 tgl@sss.pgh.pa.us        1014         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1015                 :                :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
                               1016                 :                :                  errmsg("constraint \"%s\" for domain %s already exists",
                               1017                 :                :                         newname, format_type_be(con->contypid))));
                               1018                 :                : 
                               1019                 :                :     /* OK, do the rename --- tuple is a copy, so OK to scribble on it */
 6442 tgl@sss.pgh.pa.us        1020                 :CBC          48 :     namestrcpy(&(con->conname), newname);
                               1021                 :                : 
 3140 alvherre@alvh.no-ip.     1022                 :             48 :     CatalogTupleUpdate(conDesc, &tuple->t_self, tuple);
                               1023                 :                : 
 4556 rhaas@postgresql.org     1024         [ -  + ]:             48 :     InvokeObjectPostAlterHook(ConstraintRelationId, conId, 0);
                               1025                 :                : 
 6442 tgl@sss.pgh.pa.us        1026                 :             48 :     heap_freetuple(tuple);
 2420 andres@anarazel.de       1027                 :             48 :     table_close(conDesc, RowExclusiveLock);
 6442 tgl@sss.pgh.pa.us        1028                 :             48 : }
                               1029                 :                : 
                               1030                 :                : /*
                               1031                 :                :  * AlterConstraintNamespaces
                               1032                 :                :  *      Find any constraints belonging to the specified object,
                               1033                 :                :  *      and move them to the specified new namespace.
                               1034                 :                :  *
                               1035                 :                :  * isType indicates whether the owning object is a type or a relation.
                               1036                 :                :  */
                               1037                 :                : void
 7341                          1038                 :             53 : AlterConstraintNamespaces(Oid ownerId, Oid oldNspId,
                               1039                 :                :                           Oid newNspId, bool isType, ObjectAddresses *objsMoved)
                               1040                 :                : {
                               1041                 :                :     Relation    conRel;
                               1042                 :                :     ScanKeyData key[2];
                               1043                 :                :     SysScanDesc scan;
                               1044                 :                :     HeapTuple   tup;
                               1045                 :                : 
 2420 andres@anarazel.de       1046                 :             53 :     conRel = table_open(ConstraintRelationId, RowExclusiveLock);
                               1047                 :                : 
 2559 tgl@sss.pgh.pa.us        1048         [ +  + ]:             53 :     ScanKeyInit(&key[0],
                               1049                 :                :                 Anum_pg_constraint_conrelid,
                               1050                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1051                 :                :                 ObjectIdGetDatum(isType ? InvalidOid : ownerId));
                               1052         [ +  + ]:             53 :     ScanKeyInit(&key[1],
                               1053                 :                :                 Anum_pg_constraint_contypid,
                               1054                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1055                 :                :                 ObjectIdGetDatum(isType ? ownerId : InvalidOid));
                               1056                 :                : 
                               1057                 :             53 :     scan = systable_beginscan(conRel, ConstraintRelidTypidNameIndexId, true,
                               1058                 :                :                               NULL, 2, key);
                               1059                 :                : 
 7341                          1060         [ +  + ]:            129 :     while (HeapTupleIsValid((tup = systable_getnext(scan))))
                               1061                 :                :     {
                               1062                 :             76 :         Form_pg_constraint conform = (Form_pg_constraint) GETSTRUCT(tup);
                               1063                 :                :         ObjectAddress thisobj;
                               1064                 :                : 
 1893 michael@paquier.xyz      1065                 :             76 :         ObjectAddressSet(thisobj, ConstraintRelationId, conform->oid);
                               1066                 :                : 
 4693 alvherre@alvh.no-ip.     1067         [ -  + ]:             76 :         if (object_address_present(&thisobj, objsMoved))
 4693 alvherre@alvh.no-ip.     1068                 :UBC           0 :             continue;
                               1069                 :                : 
                               1070                 :                :         /* Don't update if the object is already part of the namespace */
 3579 rhaas@postgresql.org     1071   [ +  -  +  + ]:CBC          76 :         if (conform->connamespace == oldNspId && oldNspId != newNspId)
                               1072                 :                :         {
 7341 tgl@sss.pgh.pa.us        1073                 :             61 :             tup = heap_copytuple(tup);
                               1074                 :             61 :             conform = (Form_pg_constraint) GETSTRUCT(tup);
                               1075                 :                : 
                               1076                 :             61 :             conform->connamespace = newNspId;
                               1077                 :                : 
 3140 alvherre@alvh.no-ip.     1078                 :             61 :             CatalogTupleUpdate(conRel, &tup->t_self, tup);
                               1079                 :                : 
                               1080                 :                :             /*
                               1081                 :                :              * Note: currently, the constraint will not have its own
                               1082                 :                :              * dependency on the namespace, so we don't need to do
                               1083                 :                :              * changeDependencyFor().
                               1084                 :                :              */
                               1085                 :                :         }
                               1086                 :                : 
 4556 rhaas@postgresql.org     1087         [ -  + ]:             76 :         InvokeObjectPostAlterHook(ConstraintRelationId, thisobj.objectId, 0);
                               1088                 :                : 
 4693 alvherre@alvh.no-ip.     1089                 :             76 :         add_exact_object_address(&thisobj, objsMoved);
                               1090                 :                :     }
                               1091                 :                : 
 7341 tgl@sss.pgh.pa.us        1092                 :             53 :     systable_endscan(scan);
                               1093                 :                : 
 2420 andres@anarazel.de       1094                 :             53 :     table_close(conRel, RowExclusiveLock);
 7341 tgl@sss.pgh.pa.us        1095                 :             53 : }
                               1096                 :                : 
                               1097                 :                : /*
                               1098                 :                :  * ConstraintSetParentConstraint
                               1099                 :                :  *      Set a partition's constraint as child of its parent constraint,
                               1100                 :                :  *      or remove the linkage if parentConstrId is InvalidOid.
                               1101                 :                :  *
                               1102                 :                :  * This updates the constraint's pg_constraint row to show it as inherited, and
                               1103                 :                :  * adds PARTITION dependencies to prevent the constraint from being deleted
                               1104                 :                :  * on its own.  Alternatively, reverse that.
                               1105                 :                :  */
                               1106                 :                : void
 2399                          1107                 :            321 : ConstraintSetParentConstraint(Oid childConstrId,
                               1108                 :                :                               Oid parentConstrId,
                               1109                 :                :                               Oid childTableId)
                               1110                 :                : {
                               1111                 :                :     Relation    constrRel;
                               1112                 :                :     Form_pg_constraint constrForm;
                               1113                 :                :     HeapTuple   tuple,
                               1114                 :                :                 newtup;
                               1115                 :                :     ObjectAddress depender;
                               1116                 :                :     ObjectAddress referenced;
                               1117                 :                : 
 2420 andres@anarazel.de       1118                 :            321 :     constrRel = table_open(ConstraintRelationId, RowExclusiveLock);
 2756 alvherre@alvh.no-ip.     1119                 :            321 :     tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(childConstrId));
                               1120         [ -  + ]:            321 :     if (!HeapTupleIsValid(tuple))
 2756 alvherre@alvh.no-ip.     1121         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for constraint %u", childConstrId);
 2756 alvherre@alvh.no-ip.     1122                 :CBC         321 :     newtup = heap_copytuple(tuple);
                               1123                 :            321 :     constrForm = (Form_pg_constraint) GETSTRUCT(newtup);
 2521                          1124         [ +  + ]:            321 :     if (OidIsValid(parentConstrId))
                               1125                 :                :     {
                               1126                 :                :         /* don't allow setting parent for a constraint that already has one */
 2417                          1127         [ -  + ]:            197 :         Assert(constrForm->coninhcount == 0);
                               1128         [ -  + ]:            197 :         if (constrForm->conparentid != InvalidOid)
 2417 alvherre@alvh.no-ip.     1129         [ #  # ]:UBC           0 :             elog(ERROR, "constraint %u already has a parent constraint",
                               1130                 :                :                  childConstrId);
                               1131                 :                : 
 2521 alvherre@alvh.no-ip.     1132                 :CBC         197 :         constrForm->conislocal = false;
  331                          1133         [ -  + ]:            197 :         if (pg_add_s16_overflow(constrForm->coninhcount, 1,
                               1134                 :                :                                 &constrForm->coninhcount))
  893 peter@eisentraut.org     1135         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1136                 :                :                     errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                               1137                 :                :                     errmsg("too many inheritance parents"));
                               1138                 :                : 
 2521 alvherre@alvh.no-ip.     1139                 :CBC         197 :         constrForm->conparentid = parentConstrId;
                               1140                 :                : 
                               1141                 :            197 :         CatalogTupleUpdate(constrRel, &tuple->t_self, newtup);
                               1142                 :                : 
                               1143                 :            197 :         ObjectAddressSet(depender, ConstraintRelationId, childConstrId);
                               1144                 :                : 
 2399 tgl@sss.pgh.pa.us        1145                 :            197 :         ObjectAddressSet(referenced, ConstraintRelationId, parentConstrId);
                               1146                 :            197 :         recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_PRI);
                               1147                 :                : 
                               1148                 :            197 :         ObjectAddressSet(referenced, RelationRelationId, childTableId);
                               1149                 :            197 :         recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_SEC);
                               1150                 :                :     }
                               1151                 :                :     else
                               1152                 :                :     {
 2521 alvherre@alvh.no-ip.     1153                 :            124 :         constrForm->coninhcount--;
 2417                          1154                 :            124 :         constrForm->conislocal = true;
 2521                          1155                 :            124 :         constrForm->conparentid = InvalidOid;
                               1156                 :                : 
                               1157                 :                :         /* Make sure there's no further inheritance. */
 2417                          1158         [ -  + ]:            124 :         Assert(constrForm->coninhcount == 0);
                               1159                 :                : 
 2399 tgl@sss.pgh.pa.us        1160                 :            124 :         CatalogTupleUpdate(constrRel, &tuple->t_self, newtup);
                               1161                 :                : 
 2521 alvherre@alvh.no-ip.     1162                 :            124 :         deleteDependencyRecordsForClass(ConstraintRelationId, childConstrId,
                               1163                 :                :                                         ConstraintRelationId,
                               1164                 :                :                                         DEPENDENCY_PARTITION_PRI);
 2399 tgl@sss.pgh.pa.us        1165                 :            124 :         deleteDependencyRecordsForClass(ConstraintRelationId, childConstrId,
                               1166                 :                :                                         RelationRelationId,
                               1167                 :                :                                         DEPENDENCY_PARTITION_SEC);
                               1168                 :                :     }
                               1169                 :                : 
 2521 alvherre@alvh.no-ip.     1170                 :            321 :     ReleaseSysCache(tuple);
 2420 andres@anarazel.de       1171                 :            321 :     table_close(constrRel, RowExclusiveLock);
 2756 alvherre@alvh.no-ip.     1172                 :            321 : }
                               1173                 :                : 
                               1174                 :                : 
                               1175                 :                : /*
                               1176                 :                :  * get_relation_constraint_oid
                               1177                 :                :  *      Find a constraint on the specified relation with the specified name.
                               1178                 :                :  *      Returns constraint's OID.
                               1179                 :                :  */
                               1180                 :                : Oid
 4904 peter_e@gmx.net          1181                 :            270 : get_relation_constraint_oid(Oid relid, const char *conname, bool missing_ok)
                               1182                 :                : {
                               1183                 :                :     Relation    pg_constraint;
                               1184                 :                :     HeapTuple   tuple;
                               1185                 :                :     SysScanDesc scan;
                               1186                 :                :     ScanKeyData skey[3];
 5808 andrew@dunslane.net      1187                 :            270 :     Oid         conOid = InvalidOid;
                               1188                 :                : 
 2420 andres@anarazel.de       1189                 :            270 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                               1190                 :                : 
 5808 andrew@dunslane.net      1191                 :            270 :     ScanKeyInit(&skey[0],
                               1192                 :                :                 Anum_pg_constraint_conrelid,
                               1193                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1194                 :                :                 ObjectIdGetDatum(relid));
 2559 tgl@sss.pgh.pa.us        1195                 :            270 :     ScanKeyInit(&skey[1],
                               1196                 :                :                 Anum_pg_constraint_contypid,
                               1197                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1198                 :                :                 ObjectIdGetDatum(InvalidOid));
                               1199                 :            270 :     ScanKeyInit(&skey[2],
                               1200                 :                :                 Anum_pg_constraint_conname,
                               1201                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               1202                 :                :                 CStringGetDatum(conname));
                               1203                 :                : 
                               1204                 :            270 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
                               1205                 :                :                               NULL, 3, skey);
                               1206                 :                : 
                               1207                 :                :     /* There can be at most one matching row */
                               1208         [ +  + ]:            270 :     if (HeapTupleIsValid(tuple = systable_getnext(scan)))
 2482 andres@anarazel.de       1209                 :            264 :         conOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
                               1210                 :                : 
 5808 andrew@dunslane.net      1211                 :            270 :     systable_endscan(scan);
                               1212                 :                : 
                               1213                 :                :     /* If no such constraint exists, complain */
 5511 rhaas@postgresql.org     1214   [ +  +  +  - ]:            270 :     if (!OidIsValid(conOid) && !missing_ok)
 5808 andrew@dunslane.net      1215         [ +  - ]:              6 :         ereport(ERROR,
                               1216                 :                :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
                               1217                 :                :                  errmsg("constraint \"%s\" for table \"%s\" does not exist",
                               1218                 :                :                         conname, get_rel_name(relid))));
                               1219                 :                : 
 2420 andres@anarazel.de       1220                 :            264 :     table_close(pg_constraint, AccessShareLock);
                               1221                 :                : 
 5808 andrew@dunslane.net      1222                 :            264 :     return conOid;
                               1223                 :                : }
                               1224                 :                : 
                               1225                 :                : /*
                               1226                 :                :  * get_relation_constraint_attnos
                               1227                 :                :  *      Find a constraint on the specified relation with the specified name
                               1228                 :                :  *      and return the constrained columns.
                               1229                 :                :  *
                               1230                 :                :  * Returns a Bitmapset of the column attnos of the constrained columns, with
                               1231                 :                :  * attnos being offset by FirstLowInvalidHeapAttributeNumber so that system
                               1232                 :                :  * columns can be represented.
                               1233                 :                :  *
                               1234                 :                :  * *constraintOid is set to the OID of the constraint, or InvalidOid on
                               1235                 :                :  * failure.
                               1236                 :                :  */
                               1237                 :                : Bitmapset *
 2861 dean.a.rasheed@gmail     1238                 :             96 : get_relation_constraint_attnos(Oid relid, const char *conname,
                               1239                 :                :                                bool missing_ok, Oid *constraintOid)
                               1240                 :                : {
                               1241                 :             96 :     Bitmapset  *conattnos = NULL;
                               1242                 :                :     Relation    pg_constraint;
                               1243                 :                :     HeapTuple   tuple;
                               1244                 :                :     SysScanDesc scan;
                               1245                 :                :     ScanKeyData skey[3];
                               1246                 :                : 
                               1247                 :                :     /* Set *constraintOid, to avoid complaints about uninitialized vars */
                               1248                 :             96 :     *constraintOid = InvalidOid;
                               1249                 :                : 
 2420 andres@anarazel.de       1250                 :             96 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                               1251                 :                : 
 2861 dean.a.rasheed@gmail     1252                 :             96 :     ScanKeyInit(&skey[0],
                               1253                 :                :                 Anum_pg_constraint_conrelid,
                               1254                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1255                 :                :                 ObjectIdGetDatum(relid));
 2559 tgl@sss.pgh.pa.us        1256                 :             96 :     ScanKeyInit(&skey[1],
                               1257                 :                :                 Anum_pg_constraint_contypid,
                               1258                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1259                 :                :                 ObjectIdGetDatum(InvalidOid));
                               1260                 :             96 :     ScanKeyInit(&skey[2],
                               1261                 :                :                 Anum_pg_constraint_conname,
                               1262                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               1263                 :                :                 CStringGetDatum(conname));
                               1264                 :                : 
                               1265                 :             96 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
                               1266                 :                :                               NULL, 3, skey);
                               1267                 :                : 
                               1268                 :                :     /* There can be at most one matching row */
                               1269         [ +  - ]:             96 :     if (HeapTupleIsValid(tuple = systable_getnext(scan)))
                               1270                 :                :     {
                               1271                 :                :         Datum       adatum;
                               1272                 :                :         bool        isNull;
                               1273                 :                : 
 2482 andres@anarazel.de       1274                 :             96 :         *constraintOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
                               1275                 :                : 
                               1276                 :                :         /* Extract the conkey array, ie, attnums of constrained columns */
 2861 dean.a.rasheed@gmail     1277                 :             96 :         adatum = heap_getattr(tuple, Anum_pg_constraint_conkey,
                               1278                 :                :                               RelationGetDescr(pg_constraint), &isNull);
 2559 tgl@sss.pgh.pa.us        1279         [ +  - ]:             96 :         if (!isNull)
                               1280                 :                :         {
                               1281                 :                :             ArrayType  *arr;
                               1282                 :                :             int         numcols;
                               1283                 :                :             int16      *attnums;
                               1284                 :                :             int         i;
                               1285                 :                : 
                               1286                 :             96 :             arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1287                 :             96 :             numcols = ARR_DIMS(arr)[0];
                               1288   [ +  -  +  - ]:             96 :             if (ARR_NDIM(arr) != 1 ||
                               1289                 :             96 :                 numcols < 0 ||
                               1290         [ +  - ]:             96 :                 ARR_HASNULL(arr) ||
                               1291         [ -  + ]:             96 :                 ARR_ELEMTYPE(arr) != INT2OID)
 2559 tgl@sss.pgh.pa.us        1292         [ #  # ]:UBC           0 :                 elog(ERROR, "conkey is not a 1-D smallint array");
 2559 tgl@sss.pgh.pa.us        1293         [ -  + ]:CBC          96 :             attnums = (int16 *) ARR_DATA_PTR(arr);
                               1294                 :                : 
                               1295                 :                :             /* Construct the result value */
                               1296         [ +  + ]:            270 :             for (i = 0; i < numcols; i++)
                               1297                 :                :             {
                               1298                 :            174 :                 conattnos = bms_add_member(conattnos,
                               1299                 :            174 :                                            attnums[i] - FirstLowInvalidHeapAttributeNumber);
                               1300                 :                :             }
                               1301                 :                :         }
                               1302                 :                :     }
                               1303                 :                : 
 2861 dean.a.rasheed@gmail     1304                 :             96 :     systable_endscan(scan);
                               1305                 :                : 
                               1306                 :                :     /* If no such constraint exists, complain */
                               1307   [ -  +  -  - ]:             96 :     if (!OidIsValid(*constraintOid) && !missing_ok)
 2861 dean.a.rasheed@gmail     1308         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1309                 :                :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
                               1310                 :                :                  errmsg("constraint \"%s\" for table \"%s\" does not exist",
                               1311                 :                :                         conname, get_rel_name(relid))));
                               1312                 :                : 
 2420 andres@anarazel.de       1313                 :CBC          96 :     table_close(pg_constraint, AccessShareLock);
                               1314                 :                : 
 2861 dean.a.rasheed@gmail     1315                 :             96 :     return conattnos;
                               1316                 :                : }
                               1317                 :                : 
                               1318                 :                : /*
                               1319                 :                :  * Return the OID of the constraint enforced by the given index in the
                               1320                 :                :  * given relation; or InvalidOid if no such index is cataloged.
                               1321                 :                :  *
                               1322                 :                :  * Much like get_constraint_index, this function is concerned only with the
                               1323                 :                :  * one constraint that "owns" the given index.  Therefore, constraints of
                               1324                 :                :  * types other than unique, primary-key, and exclusion are ignored.
                               1325                 :                :  */
                               1326                 :                : Oid
 2756 alvherre@alvh.no-ip.     1327                 :            674 : get_relation_idx_constraint_oid(Oid relationId, Oid indexId)
                               1328                 :                : {
                               1329                 :                :     Relation    pg_constraint;
                               1330                 :                :     SysScanDesc scan;
                               1331                 :                :     ScanKeyData key;
                               1332                 :                :     HeapTuple   tuple;
                               1333                 :            674 :     Oid         constraintId = InvalidOid;
                               1334                 :                : 
 2420 andres@anarazel.de       1335                 :            674 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                               1336                 :                : 
 2756 alvherre@alvh.no-ip.     1337                 :            674 :     ScanKeyInit(&key,
                               1338                 :                :                 Anum_pg_constraint_conrelid,
                               1339                 :                :                 BTEqualStrategyNumber,
                               1340                 :                :                 F_OIDEQ,
                               1341                 :                :                 ObjectIdGetDatum(relationId));
 2559 tgl@sss.pgh.pa.us        1342                 :            674 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId,
                               1343                 :                :                               true, NULL, 1, &key);
 2756 alvherre@alvh.no-ip.     1344         [ +  + ]:           1309 :     while ((tuple = systable_getnext(scan)) != NULL)
                               1345                 :                :     {
                               1346                 :                :         Form_pg_constraint constrForm;
                               1347                 :                : 
                               1348                 :           1028 :         constrForm = (Form_pg_constraint) GETSTRUCT(tuple);
                               1349                 :                : 
                               1350                 :                :         /* See above */
 1065                          1351         [ +  + ]:           1028 :         if (constrForm->contype != CONSTRAINT_PRIMARY &&
                               1352         [ +  + ]:            663 :             constrForm->contype != CONSTRAINT_UNIQUE &&
                               1353         [ +  - ]:            627 :             constrForm->contype != CONSTRAINT_EXCLUSION)
                               1354                 :            627 :             continue;
                               1355                 :                : 
 2756                          1356         [ +  + ]:            401 :         if (constrForm->conindid == indexId)
                               1357                 :                :         {
 2482 andres@anarazel.de       1358                 :            393 :             constraintId = constrForm->oid;
 2756 alvherre@alvh.no-ip.     1359                 :            393 :             break;
                               1360                 :                :         }
                               1361                 :                :     }
                               1362                 :            674 :     systable_endscan(scan);
                               1363                 :                : 
 2420 andres@anarazel.de       1364                 :            674 :     table_close(pg_constraint, AccessShareLock);
 2756 alvherre@alvh.no-ip.     1365                 :            674 :     return constraintId;
                               1366                 :                : }
                               1367                 :                : 
                               1368                 :                : /*
                               1369                 :                :  * get_domain_constraint_oid
                               1370                 :                :  *      Find a constraint on the specified domain with the specified name.
                               1371                 :                :  *      Returns constraint's OID.
                               1372                 :                :  */
                               1373                 :                : Oid
 4904 peter_e@gmx.net          1374                 :             33 : get_domain_constraint_oid(Oid typid, const char *conname, bool missing_ok)
                               1375                 :                : {
                               1376                 :                :     Relation    pg_constraint;
                               1377                 :                :     HeapTuple   tuple;
                               1378                 :                :     SysScanDesc scan;
                               1379                 :                :     ScanKeyData skey[3];
                               1380                 :             33 :     Oid         conOid = InvalidOid;
                               1381                 :                : 
 2420 andres@anarazel.de       1382                 :             33 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                               1383                 :                : 
 4904 peter_e@gmx.net          1384                 :             33 :     ScanKeyInit(&skey[0],
                               1385                 :                :                 Anum_pg_constraint_conrelid,
                               1386                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1387                 :                :                 ObjectIdGetDatum(InvalidOid));
 2559 tgl@sss.pgh.pa.us        1388                 :             33 :     ScanKeyInit(&skey[1],
                               1389                 :                :                 Anum_pg_constraint_contypid,
                               1390                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1391                 :                :                 ObjectIdGetDatum(typid));
                               1392                 :             33 :     ScanKeyInit(&skey[2],
                               1393                 :                :                 Anum_pg_constraint_conname,
                               1394                 :                :                 BTEqualStrategyNumber, F_NAMEEQ,
                               1395                 :                :                 CStringGetDatum(conname));
                               1396                 :                : 
                               1397                 :             33 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
                               1398                 :                :                               NULL, 3, skey);
                               1399                 :                : 
                               1400                 :                :     /* There can be at most one matching row */
                               1401         [ +  + ]:             33 :     if (HeapTupleIsValid(tuple = systable_getnext(scan)))
 2482 andres@anarazel.de       1402                 :             30 :         conOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
                               1403                 :                : 
 4904 peter_e@gmx.net          1404                 :             33 :     systable_endscan(scan);
                               1405                 :                : 
                               1406                 :                :     /* If no such constraint exists, complain */
                               1407   [ +  +  +  - ]:             33 :     if (!OidIsValid(conOid) && !missing_ok)
                               1408         [ +  - ]:              3 :         ereport(ERROR,
                               1409                 :                :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
                               1410                 :                :                  errmsg("constraint \"%s\" for domain %s does not exist",
                               1411                 :                :                         conname, format_type_be(typid))));
                               1412                 :                : 
 2420 andres@anarazel.de       1413                 :             30 :     table_close(pg_constraint, AccessShareLock);
                               1414                 :                : 
 4904 peter_e@gmx.net          1415                 :             30 :     return conOid;
                               1416                 :                : }
                               1417                 :                : 
                               1418                 :                : /*
                               1419                 :                :  * get_primary_key_attnos
                               1420                 :                :  *      Identify the columns in a relation's primary key, if any.
                               1421                 :                :  *
                               1422                 :                :  * Returns a Bitmapset of the column attnos of the primary key's columns,
                               1423                 :                :  * with attnos being offset by FirstLowInvalidHeapAttributeNumber so that
                               1424                 :                :  * system columns can be represented.
                               1425                 :                :  *
                               1426                 :                :  * If there is no primary key, return NULL.  We also return NULL if the pkey
                               1427                 :                :  * constraint is deferrable and deferrableOk is false.
                               1428                 :                :  *
                               1429                 :                :  * *constraintOid is set to the OID of the pkey constraint, or InvalidOid
                               1430                 :                :  * on failure.
                               1431                 :                :  */
                               1432                 :                : Bitmapset *
 3495 tgl@sss.pgh.pa.us        1433                 :            103 : get_primary_key_attnos(Oid relid, bool deferrableOk, Oid *constraintOid)
                               1434                 :                : {
                               1435                 :            103 :     Bitmapset  *pkattnos = NULL;
                               1436                 :                :     Relation    pg_constraint;
                               1437                 :                :     HeapTuple   tuple;
                               1438                 :                :     SysScanDesc scan;
                               1439                 :                :     ScanKeyData skey[1];
                               1440                 :                : 
                               1441                 :                :     /* Set *constraintOid, to avoid complaints about uninitialized vars */
                               1442                 :            103 :     *constraintOid = InvalidOid;
                               1443                 :                : 
                               1444                 :                :     /* Scan pg_constraint for constraints of the target rel */
 2420 andres@anarazel.de       1445                 :            103 :     pg_constraint = table_open(ConstraintRelationId, AccessShareLock);
                               1446                 :                : 
 3495 tgl@sss.pgh.pa.us        1447                 :            103 :     ScanKeyInit(&skey[0],
                               1448                 :                :                 Anum_pg_constraint_conrelid,
                               1449                 :                :                 BTEqualStrategyNumber, F_OIDEQ,
                               1450                 :                :                 ObjectIdGetDatum(relid));
                               1451                 :                : 
 2559                          1452                 :            103 :     scan = systable_beginscan(pg_constraint, ConstraintRelidTypidNameIndexId, true,
                               1453                 :                :                               NULL, 1, skey);
                               1454                 :                : 
 3495                          1455         [ +  + ]:            254 :     while (HeapTupleIsValid(tuple = systable_getnext(scan)))
                               1456                 :                :     {
                               1457                 :            233 :         Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
                               1458                 :                :         Datum       adatum;
                               1459                 :                :         bool        isNull;
                               1460                 :                :         ArrayType  *arr;
                               1461                 :                :         int16      *attnums;
                               1462                 :                :         int         numkeys;
                               1463                 :                :         int         i;
                               1464                 :                : 
                               1465                 :                :         /* Skip constraints that are not PRIMARY KEYs */
                               1466         [ +  + ]:            233 :         if (con->contype != CONSTRAINT_PRIMARY)
                               1467                 :            151 :             continue;
                               1468                 :                : 
                               1469                 :                :         /*
                               1470                 :                :          * If the primary key is deferrable, but we've been instructed to
                               1471                 :                :          * ignore deferrable constraints, then we might as well give up
                               1472                 :                :          * searching, since there can only be a single primary key on a table.
                               1473                 :                :          */
                               1474   [ -  +  -  - ]:             82 :         if (con->condeferrable && !deferrableOk)
                               1475                 :             82 :             break;
                               1476                 :                : 
                               1477                 :                :         /* Extract the conkey array, ie, attnums of PK's columns */
                               1478                 :             82 :         adatum = heap_getattr(tuple, Anum_pg_constraint_conkey,
                               1479                 :                :                               RelationGetDescr(pg_constraint), &isNull);
                               1480         [ -  + ]:             82 :         if (isNull)
 3495 tgl@sss.pgh.pa.us        1481         [ #  # ]:UBC           0 :             elog(ERROR, "null conkey for constraint %u",
                               1482                 :                :                  ((Form_pg_constraint) GETSTRUCT(tuple))->oid);
 2999 tgl@sss.pgh.pa.us        1483                 :CBC          82 :         arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
 3495                          1484                 :             82 :         numkeys = ARR_DIMS(arr)[0];
                               1485   [ +  -  +  - ]:             82 :         if (ARR_NDIM(arr) != 1 ||
                               1486                 :             82 :             numkeys < 0 ||
                               1487         [ +  - ]:             82 :             ARR_HASNULL(arr) ||
                               1488         [ -  + ]:             82 :             ARR_ELEMTYPE(arr) != INT2OID)
 3495 tgl@sss.pgh.pa.us        1489         [ #  # ]:UBC           0 :             elog(ERROR, "conkey is not a 1-D smallint array");
 3495 tgl@sss.pgh.pa.us        1490         [ -  + ]:CBC          82 :         attnums = (int16 *) ARR_DATA_PTR(arr);
                               1491                 :                : 
                               1492                 :                :         /* Construct the result value */
                               1493         [ +  + ]:            173 :         for (i = 0; i < numkeys; i++)
                               1494                 :                :         {
                               1495                 :             91 :             pkattnos = bms_add_member(pkattnos,
 2999                          1496                 :             91 :                                       attnums[i] - FirstLowInvalidHeapAttributeNumber);
                               1497                 :                :         }
 2482 andres@anarazel.de       1498                 :             82 :         *constraintOid = ((Form_pg_constraint) GETSTRUCT(tuple))->oid;
                               1499                 :                : 
                               1500                 :                :         /* No need to search further */
 3495 tgl@sss.pgh.pa.us        1501                 :             82 :         break;
                               1502                 :                :     }
                               1503                 :                : 
                               1504                 :            103 :     systable_endscan(scan);
                               1505                 :                : 
 2420 andres@anarazel.de       1506                 :            103 :     table_close(pg_constraint, AccessShareLock);
                               1507                 :                : 
 3495 tgl@sss.pgh.pa.us        1508                 :            103 :     return pkattnos;
                               1509                 :                : }
                               1510                 :                : 
                               1511                 :                : /*
                               1512                 :                :  * Extract data from the pg_constraint tuple of a foreign-key constraint.
                               1513                 :                :  *
                               1514                 :                :  * All arguments save the first are output arguments.  All output arguments
                               1515                 :                :  * other than numfks, conkey and confkey can be passed as NULL if caller
                               1516                 :                :  * doesn't need them.
                               1517                 :                :  */
                               1518                 :                : void
 2423 alvherre@alvh.no-ip.     1519                 :           4414 : DeconstructFkConstraintRow(HeapTuple tuple, int *numfks,
                               1520                 :                :                            AttrNumber *conkey, AttrNumber *confkey,
                               1521                 :                :                            Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs,
                               1522                 :                :                            int *num_fk_del_set_cols, AttrNumber *fk_del_set_cols)
                               1523                 :                : {
                               1524                 :                :     Datum       adatum;
                               1525                 :                :     bool        isNull;
                               1526                 :                :     ArrayType  *arr;
                               1527                 :                :     int         numkeys;
                               1528                 :                : 
                               1529                 :                :     /*
                               1530                 :                :      * We expect the arrays to be 1-D arrays of the right types; verify that.
                               1531                 :                :      * We don't need to use deconstruct_array() since the array data is just
                               1532                 :                :      * going to look like a C array of values.
                               1533                 :                :      */
  896 dgustafsson@postgres     1534                 :           4414 :     adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
                               1535                 :                :                                     Anum_pg_constraint_conkey);
 2423 alvherre@alvh.no-ip.     1536                 :           4414 :     arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1537         [ +  - ]:           4414 :     if (ARR_NDIM(arr) != 1 ||
                               1538         [ +  - ]:           4414 :         ARR_HASNULL(arr) ||
                               1539         [ -  + ]:           4414 :         ARR_ELEMTYPE(arr) != INT2OID)
 2423 alvherre@alvh.no-ip.     1540         [ #  # ]:UBC           0 :         elog(ERROR, "conkey is not a 1-D smallint array");
 2423 alvherre@alvh.no-ip.     1541                 :CBC        4414 :     numkeys = ARR_DIMS(arr)[0];
                               1542   [ +  -  -  + ]:           4414 :     if (numkeys <= 0 || numkeys > INDEX_MAX_KEYS)
 2423 alvherre@alvh.no-ip.     1543         [ #  # ]:UBC           0 :         elog(ERROR, "foreign key constraint cannot have %d columns", numkeys);
 2423 alvherre@alvh.no-ip.     1544         [ -  + ]:CBC        4414 :     memcpy(conkey, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
                               1545         [ +  - ]:           4414 :     if ((Pointer) arr != DatumGetPointer(adatum))
                               1546                 :           4414 :         pfree(arr);             /* free de-toasted copy, if any */
                               1547                 :                : 
  896 dgustafsson@postgres     1548                 :           4414 :     adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
                               1549                 :                :                                     Anum_pg_constraint_confkey);
 2423 alvherre@alvh.no-ip.     1550                 :           4414 :     arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1551         [ +  - ]:           4414 :     if (ARR_NDIM(arr) != 1 ||
                               1552         [ +  - ]:           4414 :         ARR_DIMS(arr)[0] != numkeys ||
                               1553         [ +  - ]:           4414 :         ARR_HASNULL(arr) ||
                               1554         [ -  + ]:           4414 :         ARR_ELEMTYPE(arr) != INT2OID)
 2423 alvherre@alvh.no-ip.     1555         [ #  # ]:UBC           0 :         elog(ERROR, "confkey is not a 1-D smallint array");
 2423 alvherre@alvh.no-ip.     1556         [ -  + ]:CBC        4414 :     memcpy(confkey, ARR_DATA_PTR(arr), numkeys * sizeof(int16));
                               1557         [ +  - ]:           4414 :     if ((Pointer) arr != DatumGetPointer(adatum))
                               1558                 :           4414 :         pfree(arr);             /* free de-toasted copy, if any */
                               1559                 :                : 
                               1560         [ +  - ]:           4414 :     if (pf_eq_oprs)
                               1561                 :                :     {
  896 dgustafsson@postgres     1562                 :           4414 :         adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
                               1563                 :                :                                         Anum_pg_constraint_conpfeqop);
 2423 alvherre@alvh.no-ip.     1564                 :           4414 :         arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1565                 :                :         /* see TryReuseForeignKey if you change the test below */
                               1566         [ +  - ]:           4414 :         if (ARR_NDIM(arr) != 1 ||
                               1567         [ +  - ]:           4414 :             ARR_DIMS(arr)[0] != numkeys ||
                               1568         [ +  - ]:           4414 :             ARR_HASNULL(arr) ||
                               1569         [ -  + ]:           4414 :             ARR_ELEMTYPE(arr) != OIDOID)
 2423 alvherre@alvh.no-ip.     1570         [ #  # ]:UBC           0 :             elog(ERROR, "conpfeqop is not a 1-D Oid array");
 2423 alvherre@alvh.no-ip.     1571         [ -  + ]:CBC        4414 :         memcpy(pf_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
                               1572         [ +  - ]:           4414 :         if ((Pointer) arr != DatumGetPointer(adatum))
                               1573                 :           4414 :             pfree(arr);         /* free de-toasted copy, if any */
                               1574                 :                :     }
                               1575                 :                : 
                               1576         [ +  + ]:           4414 :     if (pp_eq_oprs)
                               1577                 :                :     {
  896 dgustafsson@postgres     1578                 :           2563 :         adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
                               1579                 :                :                                         Anum_pg_constraint_conppeqop);
 2423 alvherre@alvh.no-ip.     1580                 :           2563 :         arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1581         [ +  - ]:           2563 :         if (ARR_NDIM(arr) != 1 ||
                               1582         [ +  - ]:           2563 :             ARR_DIMS(arr)[0] != numkeys ||
                               1583         [ +  - ]:           2563 :             ARR_HASNULL(arr) ||
                               1584         [ -  + ]:           2563 :             ARR_ELEMTYPE(arr) != OIDOID)
 2423 alvherre@alvh.no-ip.     1585         [ #  # ]:UBC           0 :             elog(ERROR, "conppeqop is not a 1-D Oid array");
 2423 alvherre@alvh.no-ip.     1586         [ -  + ]:CBC        2563 :         memcpy(pp_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
                               1587         [ +  - ]:           2563 :         if ((Pointer) arr != DatumGetPointer(adatum))
                               1588                 :           2563 :             pfree(arr);         /* free de-toasted copy, if any */
                               1589                 :                :     }
                               1590                 :                : 
                               1591         [ +  + ]:           4414 :     if (ff_eq_oprs)
                               1592                 :                :     {
  896 dgustafsson@postgres     1593                 :           2563 :         adatum = SysCacheGetAttrNotNull(CONSTROID, tuple,
                               1594                 :                :                                         Anum_pg_constraint_conffeqop);
 2423 alvherre@alvh.no-ip.     1595                 :           2563 :         arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1596         [ +  - ]:           2563 :         if (ARR_NDIM(arr) != 1 ||
                               1597         [ +  - ]:           2563 :             ARR_DIMS(arr)[0] != numkeys ||
                               1598         [ +  - ]:           2563 :             ARR_HASNULL(arr) ||
                               1599         [ -  + ]:           2563 :             ARR_ELEMTYPE(arr) != OIDOID)
 2423 alvherre@alvh.no-ip.     1600         [ #  # ]:UBC           0 :             elog(ERROR, "conffeqop is not a 1-D Oid array");
 2423 alvherre@alvh.no-ip.     1601         [ -  + ]:CBC        2563 :         memcpy(ff_eq_oprs, ARR_DATA_PTR(arr), numkeys * sizeof(Oid));
                               1602         [ +  - ]:           2563 :         if ((Pointer) arr != DatumGetPointer(adatum))
                               1603                 :           2563 :             pfree(arr);         /* free de-toasted copy, if any */
                               1604                 :                :     }
                               1605                 :                : 
 1368 peter@eisentraut.org     1606         [ +  + ]:           4414 :     if (fk_del_set_cols)
                               1607                 :                :     {
                               1608                 :           2563 :         adatum = SysCacheGetAttr(CONSTROID, tuple,
                               1609                 :                :                                  Anum_pg_constraint_confdelsetcols, &isNull);
                               1610         [ +  + ]:           2563 :         if (isNull)
                               1611                 :                :         {
                               1612                 :           2524 :             *num_fk_del_set_cols = 0;
                               1613                 :                :         }
                               1614                 :                :         else
                               1615                 :                :         {
                               1616                 :                :             int         num_delete_cols;
                               1617                 :                : 
                               1618                 :             39 :             arr = DatumGetArrayTypeP(adatum);   /* ensure not toasted */
                               1619         [ +  - ]:             39 :             if (ARR_NDIM(arr) != 1 ||
                               1620         [ +  - ]:             39 :                 ARR_HASNULL(arr) ||
                               1621         [ -  + ]:             39 :                 ARR_ELEMTYPE(arr) != INT2OID)
 1368 peter@eisentraut.org     1622         [ #  # ]:UBC           0 :                 elog(ERROR, "confdelsetcols is not a 1-D smallint array");
 1368 peter@eisentraut.org     1623                 :CBC          39 :             num_delete_cols = ARR_DIMS(arr)[0];
                               1624         [ -  + ]:             39 :             memcpy(fk_del_set_cols, ARR_DATA_PTR(arr), num_delete_cols * sizeof(int16));
                               1625         [ +  - ]:             39 :             if ((Pointer) arr != DatumGetPointer(adatum))
 1213 tgl@sss.pgh.pa.us        1626                 :             39 :                 pfree(arr);     /* free de-toasted copy, if any */
                               1627                 :                : 
 1368 peter@eisentraut.org     1628                 :             39 :             *num_fk_del_set_cols = num_delete_cols;
                               1629                 :                :         }
                               1630                 :                :     }
                               1631                 :                : 
 2423 alvherre@alvh.no-ip.     1632                 :           4414 :     *numfks = numkeys;
                               1633                 :           4414 : }
                               1634                 :                : 
                               1635                 :                : /*
                               1636                 :                :  * FindFKPeriodOpers -
                               1637                 :                :  *
                               1638                 :                :  * Looks up the operator oids used for the PERIOD part of a temporal foreign key.
                               1639                 :                :  * The opclass should be the opclass of that PERIOD element.
                               1640                 :                :  * Everything else is an output: containedbyoperoid is the ContainedBy operator for
                               1641                 :                :  * types matching the PERIOD element.
                               1642                 :                :  * aggedcontainedbyoperoid is also a ContainedBy operator,
                               1643                 :                :  * but one whose rhs is a multirange.
                               1644                 :                :  * That way foreign keys can compare fkattr <@ range_agg(pkattr).
                               1645                 :                :  * intersectoperoid is used by NO ACTION constraints to trim the range being considered
                               1646                 :                :  * to just what was updated/deleted.
                               1647                 :                :  */
                               1648                 :                : void
  354 peter@eisentraut.org     1649                 :            152 : FindFKPeriodOpers(Oid opclass,
                               1650                 :                :                   Oid *containedbyoperoid,
                               1651                 :                :                   Oid *aggedcontainedbyoperoid,
                               1652                 :                :                   Oid *intersectoperoid)
                               1653                 :                : {
                               1654                 :            152 :     Oid         opfamily = InvalidOid;
                               1655                 :            152 :     Oid         opcintype = InvalidOid;
                               1656                 :                :     StrategyNumber strat;
                               1657                 :                : 
                               1658                 :                :     /* Make sure we have a range or multirange. */
                               1659         [ +  - ]:            152 :     if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype))
                               1660                 :                :     {
                               1661   [ +  +  -  + ]:            152 :         if (opcintype != ANYRANGEOID && opcintype != ANYMULTIRANGEOID)
  354 peter@eisentraut.org     1662         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1663                 :                :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1664                 :                :                     errmsg("invalid type for PERIOD part of foreign key"),
                               1665                 :                :                     errdetail("Only range and multirange are supported."));
                               1666                 :                : 
                               1667                 :                :     }
                               1668                 :                :     else
                               1669         [ #  # ]:              0 :         elog(ERROR, "cache lookup failed for opclass %u", opclass);
                               1670                 :                : 
                               1671                 :                :     /*
                               1672                 :                :      * Look up the ContainedBy operator whose lhs and rhs are the opclass's
                               1673                 :                :      * type. We use this to optimize RI checks: if the new value includes all
                               1674                 :                :      * of the old value, then we can treat the attribute as if it didn't
                               1675                 :                :      * change, and skip the RI check.
                               1676                 :                :      */
  234 peter@eisentraut.org     1677                 :CBC         152 :     GetOperatorFromCompareType(opclass,
                               1678                 :                :                                InvalidOid,
                               1679                 :                :                                COMPARE_CONTAINED_BY,
                               1680                 :                :                                containedbyoperoid,
                               1681                 :                :                                &strat);
                               1682                 :                : 
                               1683                 :                :     /*
                               1684                 :                :      * Now look up the ContainedBy operator. Its left arg must be the type of
                               1685                 :                :      * the column (or rather of the opclass). Its right arg must match the
                               1686                 :                :      * return type of the support proc.
                               1687                 :                :      */
                               1688                 :            152 :     GetOperatorFromCompareType(opclass,
                               1689                 :                :                                ANYMULTIRANGEOID,
                               1690                 :                :                                COMPARE_CONTAINED_BY,
                               1691                 :                :                                aggedcontainedbyoperoid,
                               1692                 :                :                                &strat);
                               1693                 :                : 
  228                          1694      [ +  +  - ]:            152 :     switch (opcintype)
                               1695                 :                :     {
                               1696                 :             81 :         case ANYRANGEOID:
                               1697                 :             81 :             *intersectoperoid = OID_RANGE_INTERSECT_RANGE_OP;
                               1698                 :             81 :             break;
                               1699                 :             71 :         case ANYMULTIRANGEOID:
                               1700                 :             71 :             *intersectoperoid = OID_MULTIRANGE_INTERSECT_MULTIRANGE_OP;
                               1701                 :             71 :             break;
  228 peter@eisentraut.org     1702                 :UBC           0 :         default:
                               1703         [ #  # ]:              0 :             elog(ERROR, "unexpected opcintype: %u", opcintype);
                               1704                 :                :     }
  354 peter@eisentraut.org     1705                 :CBC         152 : }
                               1706                 :                : 
                               1707                 :                : /*
                               1708                 :                :  * Determine whether a relation can be proven functionally dependent on
                               1709                 :                :  * a set of grouping columns.  If so, return true and add the pg_constraint
                               1710                 :                :  * OIDs of the constraints needed for the proof to the *constraintDeps list.
                               1711                 :                :  *
                               1712                 :                :  * grouping_columns is a list of grouping expressions, in which columns of
                               1713                 :                :  * the rel of interest are Vars with the indicated varno/varlevelsup.
                               1714                 :                :  *
                               1715                 :                :  * Currently we only check to see if the rel has a primary key that is a
                               1716                 :                :  * subset of the grouping_columns.  We could also use plain unique constraints
                               1717                 :                :  * if all their columns are known not null, but there's a problem: we need
                               1718                 :                :  * to be able to represent the not-null-ness as part of the constraints added
                               1719                 :                :  * to *constraintDeps.  FIXME whenever not-null constraints get represented
                               1720                 :                :  * in pg_constraint.
                               1721                 :                :  */
                               1722                 :                : bool
 5509 tgl@sss.pgh.pa.us        1723                 :            103 : check_functional_grouping(Oid relid,
                               1724                 :                :                           Index varno, Index varlevelsup,
                               1725                 :                :                           List *grouping_columns,
                               1726                 :                :                           List **constraintDeps)
                               1727                 :                : {
                               1728                 :                :     Bitmapset  *pkattnos;
                               1729                 :                :     Bitmapset  *groupbyattnos;
                               1730                 :                :     Oid         constraintOid;
                               1731                 :                :     ListCell   *gl;
                               1732                 :                : 
                               1733                 :                :     /* If the rel has no PK, then we can't prove functional dependency */
 3495                          1734                 :            103 :     pkattnos = get_primary_key_attnos(relid, false, &constraintOid);
                               1735         [ +  + ]:            103 :     if (pkattnos == NULL)
                               1736                 :             21 :         return false;
                               1737                 :                : 
                               1738                 :                :     /* Identify all the rel's columns that appear in grouping_columns */
                               1739                 :             82 :     groupbyattnos = NULL;
                               1740   [ +  -  +  +  :            185 :     foreach(gl, grouping_columns)
                                              +  + ]
                               1741                 :                :     {
                               1742                 :            103 :         Var        *gvar = (Var *) lfirst(gl);
                               1743                 :                : 
                               1744         [ +  - ]:            103 :         if (IsA(gvar, Var) &&
                               1745         [ +  + ]:            103 :             gvar->varno == varno &&
                               1746         [ +  - ]:             82 :             gvar->varlevelsup == varlevelsup)
                               1747                 :             82 :             groupbyattnos = bms_add_member(groupbyattnos,
 2999                          1748                 :             82 :                                            gvar->varattno - FirstLowInvalidHeapAttributeNumber);
                               1749                 :                :     }
                               1750                 :                : 
 3495                          1751         [ +  + ]:             82 :     if (bms_is_subset(pkattnos, groupbyattnos))
                               1752                 :                :     {
                               1753                 :                :         /* The PK is a subset of grouping_columns, so we win */
                               1754                 :             61 :         *constraintDeps = lappend_oid(*constraintDeps, constraintOid);
                               1755                 :             61 :         return true;
                               1756                 :                :     }
                               1757                 :                : 
                               1758                 :             21 :     return false;
                               1759                 :                : }
        

Generated by: LCOV version 2.4-beta