1

Inspired by creating a temporary table from a query using sqlalchemy orm I had similar requirement but only needs PrimaryKey Constraint and want to add ForeinKeyConstraint based on new temp tables created.

I have added only foreign constraint by checking if the constraint is of type PrimaryKeyConstraint then add in constraints

constraints = [c.copy() for c in table.constraints if isinstance(c,PrimaryKeyConstraint)]

This is fine but I want to create a foreign key constraint on two newly created tables. I have tried

constraints.append(ForeignKeyConstraint(['id'],['schema2.temp_table1.id']))

and as suggested added back to the table

 temp_table = Table(name, metadata, *(cols + constraints), schema=schema)

But it is taking a long time to create and insert the data. Any suggestions would be helpful.

mad_
  • 8,121
  • 2
  • 25
  • 40
  • Hard to tell without more information. My guess would be that inserting takes time because of the constraint checks. Can you try this: run your code without the `ForeignKeyConstraint`. If this is substantially faster, your problem is there. To solve it, you could do two things: 1) add the foreign key constraint only after you have inserted the initial data or 2) disable the triggers when initially inserting. – stephan Jun 14 '18 at 20:23

0 Answers0