setEmbedField :: HaskellName -> EmbedEntityMap -> FieldDef -> FieldDef
setEmbedField entName allEntities field = field
  { fieldReference = case fieldReference field of
      NoReference ->
        case mEmbedded allEntities (fieldType field) of
            Left _ -> case stripId $ fieldType field of
                Nothing -> NoReference
                Just name -> case M.lookup (HaskellName name) allEntities of
                    Nothing -> NoReference
                    Just x -> ForeignRef (HaskellName name)
                                    -- This will get corrected in mkEntityDefSqlTypeExp
                                    (FTTypeCon Nothing $ pack $ nameBase ''Int)
            Right em -> if embeddedHaskell em /= entName
              then EmbedRef em
              else if maybeNullable field
                     then SelfReference
                     else error $ unpack $ unHaskellName entName `mappend` ": a self reference must be a Maybe"
      existing@_   -> existing
  }
setEmbedField :: HaskellName -> EmbedEntityMap -> FieldDef -> FieldDef
setEmbedField entName allEntities field = field
  { fieldReference = case fieldReference field of
      NoReference ->
        case mEmbedded allEntities (fieldType field) of
            Left _ -> case stripId $ fieldType field of
                Nothing -> NoReference
                Just name -> case M.lookup (HaskellName name) allEntities of
                    Nothing -> NoReference
                    Just x -> ForeignRef (HaskellName name)
                                    -- This will get corrected in mkEntityDefSqlTypeExp
                                    (FTTypeCon Nothing $ pack $ nameBase ''Int)
            Right em -> if embeddedHaskell em /= entName
              then EmbedRef em
              else if maybeNullable field
                     then SelfReference
                     else error $ unpack $ unHaskellName entName `mappend` ": a self reference must be a Maybe"
      existing@_   -> existing
  }
setEmbedField entName allEntities field = field
  { fieldReference = case fieldReference field of
      NoReference ->
        case mEmbedded allEntities (fieldType field) of
            Left _ -> case stripId $ fieldType field of
                Nothing -> NoReference
                Just name -> case M.lookup (HaskellName name) allEntities of
                    Nothing -> NoReference
                    Just x -> ForeignRef (HaskellName name)
                                    -- This will get corrected in mkEntityDefSqlTypeExp
                                    (FTTypeCon Nothing $ pack $ nameBase ''Int)
            Right em -> if embeddedHaskell em /= entName
              then EmbedRef em
              else if maybeNullable field
                     then SelfReference
                     else error $ unpack $ unHaskellName entName `mappend` ": a self reference must be a Maybe"
      existing@_   -> existing
  }