Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot map ForeignKey due to dual Primary Keys

I'm trying to create tables on-the-fly from existing data...however, the table I need has dual Primary Keys. I can't find how to satisfy the restrictions.

I.e. I start with the following two tables...

self.DDB_PAT_BASE = Table('DDB_PAT_BASE', METADATA, 
    Column('PATID', INTEGER(), primary_key=True),
    Column('PATDB', INTEGER(), primary_key=True),
    Column('FAMILYID', INTEGER()),
)

self.DDB_ERX_MEDICATION_BASE = Table('DDB_ERX_MEDICATION_BASE', METADATA, 
    Column('ErxID', INTEGER(), primary_key=True),
    Column('ErxGuid', VARCHAR(length=36)),
    Column('LastDownload', DATETIME()),
    Column('LastUpload', DATETIME()),
    Column('Source', INTEGER()),
    )

When I try the following, it works...

t = Table('testtable', METADATA,
    Column('ErxID', INTEGER(), ForeignKey('DDB_ERX_MEDICATION_BASE.ErxID')),
    )     
t.create()

However, both the following give me the error...

t = Table('testtable', METADATA,
    Column('PATID', INTEGER(), ForeignKey('DDB_PAT_BASE.PATID')),
)
t.create()

t = Table('testtable', METADATA,
    Column('PATID', INTEGER(), ForeignKey('DDB_PAT_BASE.PATID')),
    Column('PATDB', INTEGER(), ForeignKey('DDB_PAT_BASE.PATDB')),
)
t.create()


sqlalchemy.exc.OperationalError: (pymssql.OperationalError) (1776, "There are no primary or candidate keys in the referenced table 'DDB_PAT_BASE' that match the referencing column list in the foreign key 'FK__testtabl__PATID__3FD3A585'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") [SQL: '\nCREATE TABLE [testtable] (\n\t[PATID] INTEGER NULL, \n\tFOREIGN KEY([PATID]) REFERENCES [DDB_PAT_BASE] ([PATID])\n)\n\n']
like image 712
RightmireM Avatar asked Mar 02 '16 15:03

RightmireM


1 Answers

The table you are pointing to has a composite primary key, not multiple primary keys. Hence. you need to create a composite foreign key, not two foreign keys pointing to each half of the composite primary key:

t = Table('testtable', METADATA,
    Column('PATID', INTEGER()),
    Column('PATDB', INTEGER()),
    ForeignKeyConstraint(['PATID', 'PATDB'], ['DDB_PAT_BASE.PATID', 'DDB_PAT_BASE.PATDB']),
)
t.create()
like image 171
univerio Avatar answered Sep 27 '22 22:09

univerio