* relationHasPrimaryKey * See whether an existing relation has a primary key. * * Caller must have suitable lock on the relation. * * Note: we intentionally do not check indisvalid here; that's because this * is used to enforce the rule that there can be only one indisprimary index, * and we want that to be true even if said index is invalid. */
| 165 | * and we want that to be true even if said index is invalid. |
| 166 | */ |
| 167 | bool |
| 168 | relationHasPrimaryKey(Relation rel) |
| 169 | { |
| 170 | bool result = false; |
| 171 | List *indexoidlist; |
| 172 | ListCell *indexoidscan; |
| 173 | |
| 174 | /* |
| 175 | * Get the list of index OIDs for the table from the relcache, and look up |
| 176 | * each one in the pg_index syscache until we find one marked primary key |
| 177 | * (hopefully there isn't more than one such). |
| 178 | */ |
| 179 | indexoidlist = RelationGetIndexList(rel); |
| 180 | |
| 181 | foreach(indexoidscan, indexoidlist) |
| 182 | { |
| 183 | Oid indexoid = lfirst_oid(indexoidscan); |
| 184 | HeapTuple indexTuple; |
| 185 | |
| 186 | indexTuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexoid)); |
| 187 | if (!HeapTupleIsValid(indexTuple)) /* should not happen */ |
| 188 | elog(ERROR, "cache lookup failed for index %u", indexoid); |
| 189 | result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary; |
| 190 | ReleaseSysCache(indexTuple); |
| 191 | if (result) |
| 192 | break; |
| 193 | } |
| 194 | |
| 195 | list_free(indexoidlist); |
| 196 | |
| 197 | return result; |
| 198 | } |
| 199 | |
| 200 | /* |
| 201 | * relationHasUniqueIndex - |
no test coverage detected