Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ad15560

Browse files
Jan WieckJan Wieck
Jan Wieck
authored and
Jan Wieck
committed
Enabling automatic primary key detection for self-referencing
FOREIGN KEY constraint during CREATE TABLE. Tnx to Stephan. Jan
1 parent 582ec17 commit ad15560

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/backend/parser/analyze.c

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* Portions Copyright (c) 1996-2000, PostgreSQL, Inc
77
* Portions Copyright (c) 1994, Regents of the University of California
88
*
9-
* $Id: analyze.c,v 1.135 2000/02/04 18:49:32 wieck Exp $
9+
* $Id: analyze.c,v 1.136 2000/02/05 00:20:38 wieck Exp $
1010
*
1111
*-------------------------------------------------------------------------
1212
*/
@@ -967,11 +967,36 @@ transformCreateStmt(ParseState *pstate, CreateStmt *stmt)
967967

968968
/*
969969
* If the attribute list for the referenced table was
970-
* omitted, lookup for the definition of the primary key
970+
* omitted, lookup for the definition of the primary key.
971+
* If the referenced table is this table, use the definition
972+
* we found above, rather than looking to the system
973+
* tables.
971974
*
972975
*/
973976
if (fkconstraint->fk_attrs != NIL && fkconstraint->pk_attrs == NIL)
974-
transformFkeyGetPrimaryKey(fkconstraint);
977+
if (strcmp(fkconstraint->pktable_name, stmt->relname) != 0)
978+
transformFkeyGetPrimaryKey(fkconstraint);
979+
else if (pkey != NULL)
980+
{
981+
List *pkey_attr = pkey->indexParams;
982+
List *attr;
983+
IndexElem *ielem;
984+
Ident *pkattr;
985+
986+
foreach (attr, pkey_attr)
987+
{
988+
ielem = lfirst(attr);
989+
pkattr = (Ident *)makeNode(Ident);
990+
pkattr->name = pstrdup(ielem->name);
991+
pkattr->indirection = NIL;
992+
pkattr->isRel = false;
993+
fkconstraint->pk_attrs = lappend(fkconstraint->pk_attrs, pkattr);
994+
}
995+
}
996+
else {
997+
elog(ERROR, "PRIMARY KEY for referenced table \"%s\" not found",
998+
fkconstraint->pktable_name);
999+
}
9751000

9761001
/*
9771002
* Build a CREATE CONSTRAINT TRIGGER statement for the CHECK

0 commit comments

Comments
 (0)