sandman2 icon indicating copy to clipboard operation
sandman2 copied to clipboard

Composite primary keys

Open filmackay opened this issue 8 years ago • 1 comments

As far as I can tell there is no support for these (multiple columns in the primary key). @jeffknupp can you outline your view on this - are they supported, to what extent, do you think they should be etc.?

filmackay avatar Jan 23 '16 16:01 filmackay

I'm not sure this is a spot on answer but I've gotten compound keys to work. If you have two tables, TABLE and FOREIGN, both of which are auto-mapped. One can subclass the latter table as follows :

class FOREIGN(AutomapModel):

__tablename__ = "ForeignTable"
__endpoint__  = "android"

fk_A   = Column("A", Integer)
fk_B = Column("B", Integer)

__table_args__ = (ForeignKeyConstraint((fk_A, fk_B), ("TABLE.A","TABLE.B")), {})
# __table_args__ = (ForeignKeyConstraint((fk_A, fk_A), (TABLE.A, TABLE.B)), {}) # If TABLE is itself defined as an AutoModel subclass before this table and in the same file.

I got this working after reworking the Sandman 2 code base a little, I've submitted a PR accordingly but I'm awaiting acceptance/rejection thereof. If you want to pull my variant let me know and I'll post the URL. Then one might ask if you have to map the other fields in FOREIGN and the answer is not SQLAlchemy handles this for you. If you define your own TABLE use the second variant of __table__args__

Within my own notes I have the following links 1 is mostly thoeretical, 6 discusses foreign keys, 2, 3, 4 and 7 are more convenient for resolving the problem and 5 provides a nice script for identifying compound keys.

Carelvd avatar Nov 05 '19 21:11 Carelvd