@@ -39,6 +39,16 @@ databaseContextExprForUniqueKey rvName attrNames = AddInclusionDependency (rvNam
3939
4040-- | Create a foreign key constraint from the first relation variable and attributes to the second.
4141databaseContextExprForForeignKey :: IncDepName -> (RelVarName, [AttributeName]) -> (RelVarName, [AttributeName]) -> DatabaseContextExpr
42−databaseContextExprForForeignKey fkName (rvA, attrsA) (rvB, attrsB) = AddInclusionDependency fkName $ InclusionDependency (Project (attrsL attrsA) (RelationVariable rvA ())) (Project (attrsL attrsB) (RelationVariable rvB ()))
42+databaseContextExprForForeignKey fkName (rvA, attrsA) (rvB, attrsB) =
43+ AddInclusionDependency fkName (InclusionDependency
44+ (renameIfNecessary attrsB attrsA (Project (attrsL attrsA)
45+ (RelationVariable rvA ())))
46+ (Project (attrsL attrsB)
47+ (RelationVariable rvB ())))
4348 where
44− attrsL = AttributeNames . S.fromList
49+ attrsL = AttributeNames . S.fromList
50+ renameIfNecessary attrsExpected attrsExisting expr = foldr folder expr (zip attrsExpected attrsExisting)
51+ folder (attrExpected, attrExisting) expr = if attrExpected == attrExisting then
52+ expr
53+ else
54+ Rename attrExisting attrExpected expr