Repository: jdkandersson/OpenAlchemy

Issue:
Check whether foreign key defined for many/one to one
As a user I want to define the foreign key constraint manually so that I have more control over the creation and it is returned with the API response.

When creating the foreign key constraint for many/one to one relationship, check whether the property is a part of the schema/already has been defined. If so, check it is defined to allow for a foreign key constraint, otherwise raise error.

Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81ae4163..6aa3eba1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
 # Release Notes
 
+## Version _next_
+
+- Add check for whether foreign key for relationship is already constructed before automatically constructing it.
+
 ## Version 0.9.1 - 2019-11-11
 
 - Fix bug where some static files where not included in the distribution.
diff --git a/docs/source/technical_details/relationships.rst b/docs/source/technical_details/relationships.rst
index 82b7192b..1143664e 100644
--- a/docs/source/technical_details/relationships.rst
+++ b/docs/source/technical_details/relationships.rst
@@ -114,8 +114,38 @@ relationships referencing the same object. If *x-foreign-key-column* is both in
 the *allOf* list and the referenced object, the value from the *allOf* list
 will be used.
 
+It is also possible to define a property with the name that would otherwise be
+automatically generated by *OpenAlchemy* to have more control over how the
+foreign key property is defined. For example:
+
+.. literalinclude:: ./relationships/many_to_one/foreign_key_property_defined.yaml
+    :language: yaml
+    :linenos:
+
+Note the following:
+
+* When *OpenAlchemy* constructs the foreign key for you, the name of the
+  property is made up of the name of the property referencing the object
+  (*division* in the previous example) combined with the name of the property
+  in the foreign key constraint (*id* in the previous example). These two
+  values are combined as follows:
+  "<reference property name>_<foreign key column name>" (*division_id* in the
+  previous example).
+* If *OpenAlchemy* finds that property in the schema, it won't construct a
+  foreign key property automatically.
+* The defined property is type checked against the expected foreign key type
+  based on the relationship.
+* The defined property is checked for the *x-foreign-key* property against the
+  expected foreign key constraint based on the relationship.
+* The *x-foreign-key-column* extension property can be used to control which
+  property is used as the foreign key.
+* When the foreign key is defined, the *from_dict* and *to_dict* model
+  functions will use/return the foreign key values.
+
 .. seealso::
-    :ref:`foreign-key` describes how to define foreign key constraints.
+    * :ref:`foreign-key` describes how to define foreign key constraints.
+    * :ref:`from-dict` describes how to convert dictionaries to model instances.
+    * :ref:`to-dict` describes how to convert model instances to dictionaries.
 
 .. _one-to-one:
 
diff --git a/docs/source/technical_details/relationships/many_to_one/foreign_key_property_defined.yaml b/docs/source/technical_details/relationships/many_to_one/foreign_key_property_defined.yaml
new file mode 100644
index 00000000..5d6b48aa
--- /dev/null
+++ b/docs/source/technical_details/relationships/many_to_one/foreign_key_property_defined.yaml
@@ -0,0 +1,16 @@
+Division:
+  x-tablename: division
+  ...
+  properties:
+    ...
+    id:
+      type: integer
+Employee:
+  ...
+  properties:
+    ...
+    division:
+      "$ref": "#/components/schemas/Division"
+    division_id:
+      type: integer
+      x-foreign-key: division.id
diff --git a/open_alchemy/column_factory/__init__.py b/open_alchemy/column_factory/__init__.py
index 38adb730..9cc36f62 100644
--- a/open_alchemy/column_factory/__init__.py
+++ b/open_alchemy/column_factory/__init__.py
@@ -45,7 +45,11 @@ def column_factory(
     if type_ == "object":
         # Handle objects
         return object_ref.handle_object(
-            spec=spec, schemas=schemas, required=required, logical_name=logical_name
+            spec=spec,
+            schemas=schemas,
+            required=required,
+            logical_name=logical_name,
+            model_schema=model_schema,
         )
 
     if type_ == "array":
diff --git a/open_alchemy/column_factory/array_ref.py b/open_alchemy/column_factory/array_ref.py
index 51e38b61..650c1882 100644
--- a/open_alchemy/column_factory/array_ref.py
+++ b/open_alchemy/column_factory/array_ref.py
@@ -125,6 +125,19 @@ def _set_foreign_key(
     tablename = helpers.get_ext_prop(source=model_schema, name="x-tablename")
     fk_logical_name = f"{tablename}_{fk_column}"
 
+    # Gather referenced schema
+    ref_schema = schemas[ref_model_name]
+    # Any top level $ref must already be resolved
+    ref_schema = helpers.merge_all_of(schema=ref_schema, schemas=schemas)
+    fk_required = object_ref.check_foreign_key_required(
+        fk_spec=fk_spec,
+        fk_logical_name=fk_logical_name,
+        model_schema=ref_schema,
+        schemas=schemas,
+    )
+    if not fk_required:
+        return
+
     # Handle model already constructed
     ref_model = getattr(open_alchemy.models, ref_model_name, None)
     if ref_model is not None:
diff --git a/open_alchemy/column_factory/object_ref.py b/open_alchemy/column_factory/object_ref.py
index c5002b30..f43deff3 100644
--- a/open_alchemy/column_factory/object_ref.py
+++ b/open_alchemy/column_factory/object_ref.py
@@ -18,6 +18,7 @@ def handle_object(
     schemas: types.Schemas,
     required: typing.Optional[bool] = None,
     logical_name: str,
+    model_schema: types.Schema,
 ) -> typing.Tuple[
     typing.List[typing.Tuple[str, typing.Union[sqlalchemy.Column, typing.Type]]],
     types.Schema,
@@ -32,6 +33,7 @@ def handle_object(
         schemas: Used to resolve any $ref.
         required: Whether the object property is required.
         logical_name: The logical name in the specification for the schema.
+        model_schema: The schema of the model.
 
     Returns:
         The logical name, the SQLAlchemy column for the foreign key and the logical
@@ -39,19 +41,28 @@ def handle_object(
         record for the object reference.
 
     """
+    # Retrieve artifacts required for object
     obj_artifacts = gather_object_artifacts(
         spec=spec, logical_name=logical_name, schemas=schemas
     )
 
-    # Handle object
+    # Construct foreign key
     foreign_key_spec = handle_object_reference(
         spec=obj_artifacts.spec, schemas=schemas, fk_column=obj_artifacts.fk_column
     )
-    return_value = column.handle_column(
-        logical_name=f"{logical_name}_{obj_artifacts.fk_column}",
-        spec=foreign_key_spec,
-        required=required,
+    fk_logical_name = f"{logical_name}_{obj_artifacts.fk_column}"
+    fk_required = check_foreign_key_required(
+        fk_spec=foreign_key_spec,
+        fk_logical_name=fk_logical_name,
+        model_schema=model_schema,
+        schemas=schemas,
     )
+    if fk_required:
+        return_value = column.handle_column(
+            logical_name=fk_logical_name, spec=foreign_key_spec, required=required
+        )
+    else:
+        return_value = []
 
     # Creating relationship
     backref = None
@@ -252,3 +263,76 @@ def handle_object_reference(
         )
 
     return {"type": fk_type, "x-foreign-key": f"{tablename}.{fk_logical_name}"}
+
+
+def check_foreign_key_required(
+    *,
+    fk_spec: types.Schema,
+    fk_logical_name: str,
+    model_schema: types.Schema,
+    schemas: types.Schemas,
+) -> bool:
+    """
+    Check whether a foreign key has already been defined.
+
+    Assume model_schema has already resolved any $ref and allOf at the object level.
+    They may not have been resolved at the property level.
+
+    Check whether the proposed logical name is already defined on the model schema. If
+    it has been, check that the type is correct and that the foreign key reference has
+    been defined and points to the correct column.
+
+    Raise MalformedRelationshipError if a property has already been defined with the
+    same name as is proposed for the foreign key but it has the wrong type or does not
+    define the correct foreign key constraint.
+
+    Args:
+        fk_spec: The proposed foreign key specification.
+        fk_logical_name: The proposed name for the foreign key property.
+        model_schema: The schema for the model on which the foreign key is proposed to
+            be added.
+        schemas: Used to resolve any $ref at the property level.
+
+    Returns:
+        Whether defining the foreign key is necessary given the model schema.
+
+    """
+    properties = model_schema["properties"]
+    model_fk_spec = properties.get(fk_logical_name)
+    if model_fk_spec is None:
+        return True
+    model_fk_spec = helpers.prepare_schema(schema=model_fk_spec, schemas=schemas)
+
+    # Check type
+    model_fk_type = model_fk_spec.get("type")
+    if model_fk_type is None:
+        raise exceptions.MalformedRelationshipError(
+            f"{fk_logical_name} does not have a type. "
+        )
+    fk_type = fk_spec["type"]
+    if model_fk_type != fk_type:
+        raise exceptions.MalformedRelationshipError(
+            "The foreign key required for the relationship has a different type than "
+            "the property already defined under that name. "
+            f"The required type is {fk_type}. "
+            f"The {fk_logical_name} property has the {model_fk_type} type."
+        )
+
+    # Check foreign key constraint
+    model_foreign_key = helpers.get_ext_prop(source=model_fk_spec, name="x-foreign-key")
+    foreign_key = fk_spec["x-foreign-key"]
+    if model_foreign_key is None:
+        raise exceptions.MalformedRelationshipError(
+            f"The property already defined under {fk_logical_name} does not define a "
+            'foreign key constraint. Use the "x-foreign-key" extension property to '
+            f'define a foreign key constraint, for example: "{foreign_key}".'
+        )
+    if model_foreign_key != foreign_key:
+        raise exceptions.MalformedRelationshipError(
+            "The foreign key required for the relationship has a different foreign "
+            "key constraint than the property already defined under that name. "
+            f"The required constraint is {foreign_key}. "
+            f"The {fk_logical_name} property has the {model_foreign_key} constraint."
+        )
+
+    return False
diff --git a/open_alchemy/exceptions.py b/open_alchemy/exceptions.py
index 0df39a44..0f284ae0 100644
--- a/open_alchemy/exceptions.py
+++ b/open_alchemy/exceptions.py
@@ -30,7 +30,7 @@ class MalformedSchemaError(ValueError, BaseError):
 
 
 class MalformedRelationshipError(ValueError, BaseError):
-    """Raised when a many to one relationship was not defined as expected."""
+    """Raised when a relationship was not defined as expected."""
 
 
 class MalformedExtensionPropertyError(ValueError, BaseError):


Test patch:
diff --git a/tests/open_alchemy/column_factory/test_array_ref.py b/tests/open_alchemy/column_factory/test_array_ref.py
index 7877efa4..6bf03a1b 100644
--- a/tests/open_alchemy/column_factory/test_array_ref.py
+++ b/tests/open_alchemy/column_factory/test_array_ref.py
@@ -92,7 +92,13 @@ def test_handle_array_invalid(spec, schemas):
     [
         (
             {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}},
-            {"RefSchema": {"type": "object", "x-tablename": "ref_schema"}},
+            {
+                "RefSchema": {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {},
+                }
+            },
         ),
         (
             {"$ref": "#/components/schemas/Schema"},
@@ -101,7 +107,11 @@ def test_handle_array_invalid(spec, schemas):
                     "type": "array",
                     "items": {"$ref": "#/components/schemas/RefSchema"},
                 },
-                "RefSchema": {"type": "object", "x-tablename": "ref_schema"},
+                "RefSchema": {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {},
+                },
             },
         ),
         (
@@ -113,18 +123,40 @@ def test_handle_array_invalid(spec, schemas):
                     }
                 ]
             },
-            {"RefSchema": {"type": "object", "x-tablename": "ref_schema"}},
+            {
+                "RefSchema": {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {},
+                }
+            },
         ),
         (
             {
                 "type": "array",
                 "items": {"allOf": [{"$ref": "#/components/schemas/RefSchema"}]},
             },
-            {"RefSchema": {"type": "object", "x-tablename": "ref_schema"}},
+            {
+                "RefSchema": {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {},
+                }
+            },
         ),
         (
             {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}},
-            {"RefSchema": {"allOf": [{"type": "object", "x-tablename": "ref_schema"}]}},
+            {
+                "RefSchema": {
+                    "allOf": [
+                        {
+                            "type": "object",
+                            "x-tablename": "ref_schema",
+                            "properties": {},
+                        }
+                    ]
+                }
+            },
         ),
     ],
     ids=[
@@ -175,6 +207,7 @@ def test_handle_array_relationship_backref():
             "type": "object",
             "x-tablename": "ref_schema",
             "x-backref": "schema",
+            "properties": {},
         }
     }
     model_schema = {
@@ -204,7 +237,9 @@ def test_handle_array_schemas():
         "properties": {"id": {"type": "integer"}},
     }
     spec = {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}}
-    schemas = {"RefSchema": {"type": "object", "x-tablename": "ref_schema"}}
+    schemas = {
+        "RefSchema": {"type": "object", "x-tablename": "ref_schema", "properties": {}}
+    }
 
     array_ref.handle_array(
         spec=spec, model_schema=model_schema, schemas=schemas, logical_name="ref_schema"
@@ -213,7 +248,7 @@ def test_handle_array_schemas():
     assert schemas == {
         "RefSchema": {
             "allOf": [
-                {"type": "object", "x-tablename": "ref_schema"},
+                {"type": "object", "x-tablename": "ref_schema", "properties": {}},
                 {
                     "type": "object",
                     "properties": {
@@ -229,6 +264,94 @@ def test_handle_array_schemas():
     }
 
 
+@pytest.mark.column
+def test_handle_array_schemas_fk_def():
+    """
+    GIVEN schema with array referencing another schema which already has foreign key
+        and schemas
+    WHEN handle_array is called
+    THEN foreign key is not added to the referenced schema.
+    """
+    tablename = "schema"
+    model_schema = {
+        "type": "object",
+        "x-tablename": tablename,
+        "properties": {"id": {"type": "integer"}},
+    }
+    spec = {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}}
+    schemas = {
+        "RefSchema": {
+            "type": "object",
+            "x-tablename": "ref_schema",
+            "properties": {
+                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+            },
+        }
+    }
+
+    array_ref.handle_array(
+        spec=spec, model_schema=model_schema, schemas=schemas, logical_name="ref_schema"
+    )
+
+    assert schemas == {
+        "RefSchema": {
+            "type": "object",
+            "x-tablename": "ref_schema",
+            "properties": {
+                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+            },
+        }
+    }
+
+
+@pytest.mark.column
+def test_handle_array_schemas_fk_def_all_of():
+    """
+    GIVEN schema with array referencing another schema which has allOf which already
+        has foreign key and schemas
+    WHEN handle_array is called
+    THEN foreign key is not added to the referenced schema.
+    """
+    tablename = "schema"
+    model_schema = {
+        "type": "object",
+        "x-tablename": tablename,
+        "properties": {"id": {"type": "integer"}},
+    }
+    spec = {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}}
+    schemas = {
+        "RefSchema": {
+            "allOf": [
+                {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {
+                        "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+                    },
+                }
+            ]
+        }
+    }
+
+    array_ref.handle_array(
+        spec=spec, model_schema=model_schema, schemas=schemas, logical_name="ref_schema"
+    )
+
+    assert schemas == {
+        "RefSchema": {
+            "allOf": [
+                {
+                    "type": "object",
+                    "x-tablename": "ref_schema",
+                    "properties": {
+                        "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+                    },
+                }
+            ]
+        }
+    }
+
+
 @pytest.mark.column
 def test_handle_array_schemas_foreign_key_column():
     """
@@ -248,6 +371,7 @@ def test_handle_array_schemas_foreign_key_column():
             "type": "object",
             "x-tablename": "ref_schema",
             "x-foreign-key-column": "fk_column",
+            "properties": {},
         }
     }
 
@@ -262,6 +386,7 @@ def test_handle_array_schemas_foreign_key_column():
                     "type": "object",
                     "x-tablename": "ref_schema",
                     "x-foreign-key-column": "fk_column",
+                    "properties": {},
                 },
                 {
                     "type": "object",
@@ -318,7 +443,7 @@ def test_set_foreign_key_schemas():
         "x-tablename": tablename,
         "properties": {fk_column: {"type": "integer"}},
     }
-    schemas = {ref_model_name: {"type": "object"}}
+    schemas = {ref_model_name: {"type": "object", "properties": {}}}
 
     array_ref._set_foreign_key(  # pylint: disable=protected-access
         ref_model_name=ref_model_name,
@@ -330,7 +455,7 @@ def test_set_foreign_key_schemas():
     assert schemas == {
         ref_model_name: {
             "allOf": [
-                {"type": "object"},
+                {"type": "object", "properties": {}},
                 {
                     "type": "object",
                     "properties": {
@@ -363,7 +488,7 @@ def test_set_foreign_key_models(mocked_models: mock.MagicMock):
         "x-tablename": tablename,
         "properties": {fk_column: {"type": "integer"}},
     }
-    schemas = {ref_model_name: {"type": "object"}}
+    schemas = {ref_model_name: {"type": "object", "properties": {}}}
     mock_ref_model = mock.MagicMock()
     setattr(mocked_models, ref_model_name, mock_ref_model)
 
diff --git a/tests/open_alchemy/column_factory/test_integration.py b/tests/open_alchemy/column_factory/test_integration.py
index 579cb068..42811b60 100644
--- a/tests/open_alchemy/column_factory/test_integration.py
+++ b/tests/open_alchemy/column_factory/test_integration.py
@@ -75,20 +75,23 @@ def test_integration_object_ref():
     schemas = {
         "RefSchema": {
             "type": "object",
-            "x-tablename": "table 1",
+            "x-tablename": "ref_schema",
             "properties": {"id": {"type": "integer"}},
         }
     }
-    logical_name = "column_1"
+    logical_name = "ref_schema"
 
     (
         [(fk_logical_name, fk_column), (tbl_logical_name, relationship)],
         spec,
     ) = column_factory.column_factory(
-        spec=spec, schemas=schemas, logical_name=logical_name, model_schema={}
+        spec=spec,
+        schemas=schemas,
+        logical_name=logical_name,
+        model_schema={"properties": {}},
     )
 
-    assert fk_logical_name == "column_1_id"
+    assert fk_logical_name == "ref_schema_id"
     assert isinstance(fk_column.type, sqlalchemy.Integer)
     assert len(fk_column.foreign_keys) == 1
     assert tbl_logical_name == logical_name
@@ -98,6 +101,37 @@ def test_integration_object_ref():
     assert spec == {"type": "object", "x-de-$ref": "RefSchema"}
 
 
+@pytest.mark.column
+def test_integration_object_ref_fk_def():
+    """
+    GIVEN schema that references another object schema which already has the foreign
+        key defined and schemas
+    WHEN column_factory is called with the schema and schemas
+    THEN no foreign key column is returned.
+    """
+    model_schema = {
+        "properties": {
+            "ref_schema_id": {"type": "integer", "x-foreign-key": "ref_schema.id"}
+        }
+    }
+    spec = {"$ref": "#/components/schemas/RefSchema"}
+    schemas = {
+        "RefSchema": {
+            "type": "object",
+            "x-tablename": "ref_schema",
+            "properties": {"id": {"type": "integer"}},
+        }
+    }
+    logical_name = "ref_schema"
+
+    ([(tbl_logical_name, relationship)], _) = column_factory.column_factory(
+        spec=spec, schemas=schemas, logical_name=logical_name, model_schema=model_schema
+    )
+
+    assert tbl_logical_name == logical_name
+    assert relationship.argument == "RefSchema"
+
+
 @pytest.mark.column
 def test_integration_object_ref_backref():
     """
@@ -109,13 +143,16 @@ def test_integration_object_ref_backref():
     schemas = {
         "RefSchema": {
             "type": "object",
-            "x-tablename": "table 1",
+            "x-tablename": "ref_schema",
             "properties": {"id": {"type": "integer"}},
             "x-backref": "ref_schemas",
         }
     }
     ([_, (_, relationship)], spec) = column_factory.column_factory(
-        spec=spec, schemas=schemas, logical_name="column_1", model_schema={}
+        spec=spec,
+        schemas=schemas,
+        logical_name="ref_schema",
+        model_schema={"properties": {}},
     )
 
     assert relationship.backref == ("ref_schemas", {"uselist": None})
@@ -132,14 +169,17 @@ def test_integration_object_ref_uselist():
     schemas = {
         "RefSchema": {
             "type": "object",
-            "x-tablename": "table 1",
+            "x-tablename": "ref_schema",
             "properties": {"id": {"type": "integer"}},
             "x-backref": "ref_schemas",
             "x-uselist": False,
         }
     }
     ([_, (_, relationship)], spec) = column_factory.column_factory(
-        spec=spec, schemas=schemas, logical_name="column_1", model_schema={}
+        spec=spec,
+        schemas=schemas,
+        logical_name="ref_schema",
+        model_schema={"properties": {}},
     )
 
     assert relationship.backref == ("ref_schemas", {"uselist": False})
@@ -166,7 +206,7 @@ def test_integration_array_ref():
         "x-tablename": "schema",
         "properties": {"id": {"type": "integer"}},
     }
-    logical_name = "column_1"
+    logical_name = "ref_schema"
 
     ([(tbl_logical_name, relationship)], spec) = column_factory.column_factory(
         spec=spec, schemas=schemas, logical_name=logical_name, model_schema=model_schema
@@ -199,3 +239,45 @@ def test_integration_array_ref():
             ]
         }
     }
+
+
+@pytest.mark.column
+def test_integration_array_ref_fk_def():
+    """
+    GIVEN schema that references another object schema with a foreign key already
+        defined from an array and schemas
+    WHEN column_factory is called with the schema and schemas
+    THEN schemas is not modified and relationship is returned with the spec.
+    """
+    spec = {"type": "array", "items": {"$ref": "#/components/schemas/RefSchema"}}
+    schemas = {
+        "RefSchema": {
+            "type": "object",
+            "x-tablename": "table 1",
+            "properties": {
+                "id": {"type": "integer"},
+                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"},
+            },
+        }
+    }
+    model_schema = {
+        "type": "object",
+        "x-tablename": "schema",
+        "properties": {"id": {"type": "integer"}},
+    }
+    logical_name = "ref_schema"
+
+    column_factory.column_factory(
+        spec=spec, schemas=schemas, logical_name=logical_name, model_schema=model_schema
+    )
+
+    assert schemas == {
+        "RefSchema": {
+            "type": "object",
+            "x-tablename": "table 1",
+            "properties": {
+                "id": {"type": "integer"},
+                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"},
+            },
+        }
+    }
diff --git a/tests/open_alchemy/column_factory/test_object_ref.py b/tests/open_alchemy/column_factory/test_object_ref.py
index 72c15afa..128d7947 100644
--- a/tests/open_alchemy/column_factory/test_object_ref.py
+++ b/tests/open_alchemy/column_factory/test_object_ref.py
@@ -21,7 +21,11 @@ def test_handle_object_error(spec):
     """
     with pytest.raises(exceptions.MalformedRelationshipError):
         object_ref.handle_object(
-            spec=spec, schemas={"type": "object"}, required=True, logical_name="name 1"
+            spec=spec,
+            schemas={"type": "object"},
+            required=True,
+            logical_name="name 1",
+            model_schema={},
         )
 
 
@@ -134,6 +138,7 @@ def test_handle_object_reference_fk_return():
     ],
     ids=["$ref", "$ref to allOf", "allOf"],
 )
+@pytest.mark.column
 def test_gather_object_artifacts_spec(spec, schemas, expected_spec):
     """
     GIVEN specification, schemas and expected specification
@@ -158,6 +163,7 @@ def test_gather_object_artifacts_spec(spec, schemas, expected_spec):
     ],
     ids=["$ref", "allOf"],
 )
+@pytest.mark.column
 def test_gather_object_artifacts_ref_logical_name(spec, schemas):
     """
     GIVEN specification and schemas
@@ -247,6 +253,7 @@ def test_gather_object_artifacts_ref_logical_name(spec, schemas):
         "allOf backref $ref backref",
     ],
 )
+@pytest.mark.column
 def test_gather_object_artifacts_backref(spec, schemas, expected_backref):
     """
     GIVEN specification and schemas and expected backref
@@ -260,6 +267,7 @@ def test_gather_object_artifacts_backref(spec, schemas, expected_backref):
     assert obj_artifacts.backref == expected_backref
 
 
+@pytest.mark.column
 def test_gather_object_artifacts_uselist_no_backref():
     """
     GIVEN specification with uselist but not backref and schemas
@@ -357,6 +365,7 @@ def test_gather_object_artifacts_uselist_no_backref():
         "allOf uselist $ref uselist",
     ],
 )
+@pytest.mark.column
 def test_gather_object_artifacts_uselist(spec, schemas, expected_uselist):
     """
     GIVEN specification and schemas and expected uselist
@@ -435,6 +444,7 @@ def test_gather_object_artifacts_uselist(spec, schemas, expected_uselist):
         "allOf fk $ref fk",
     ],
 )
+@pytest.mark.column
 def test_gather_object_artifacts_fk_column(spec, schemas, expected_fk_column):
     """
     GIVEN specification and schemas and expected foreign key column
@@ -446,3 +456,117 @@ def test_gather_object_artifacts_fk_column(spec, schemas, expected_fk_column):
     )
 
     assert obj_artifacts.fk_column == expected_fk_column
+
+
+@pytest.mark.parametrize(
+    "model_schema",
+    [
+        {
+            "properties": {
+                "ref_table_fk_column": {"x-foreign-key": "ref_table.fk_column"}
+            }
+        },
+        {
+            "properties": {
+                "ref_table_fk_column": {
+                    "type": "not_fk_type",
+                    "x-foreign-key": "ref_table.fk_column",
+                }
+            }
+        },
+        {"properties": {"ref_table_fk_column": {"type": "fk_type"}}},
+        {
+            "properties": {
+                "ref_table_fk_column": {
+                    "type": "fk_type",
+                    "x-foreign-key": "wrong_table.wrong_column",
+                }
+            }
+        },
+    ],
+    ids=["no type", "wrong type", "no x-foreign-key", "wrong x-foreign-key"],
+)
+@pytest.mark.column
+def test_check_foreign_key_required_invalid_schema(model_schema):
+    """
+    GIVEN model schema that is not valid
+    WHEN check_foreign_key_required is called
+    THEN MalformedRelationshipError is raised.
+    """
+    fk_spec = {"type": "fk_type", "x-foreign-key": "ref_table.fk_column"}
+    fk_logical_name = "ref_table_fk_column"
+
+    with pytest.raises(exceptions.MalformedRelationshipError):
+        object_ref.check_foreign_key_required(
+            fk_spec=fk_spec,
+            fk_logical_name=fk_logical_name,
+            model_schema=model_schema,
+            schemas={},
+        )
+
+
+@pytest.mark.parametrize(
+    "model_schema, schemas, expected_required",
+    [
+        ({"properties": {}}, {}, True),
+        (
+            {
+                "properties": {
+                    "ref_table_fk_column": {
+                        "type": "fk_type",
+                        "x-foreign-key": "ref_table.fk_column",
+                    }
+                }
+            },
+            {},
+            False,
+        ),
+        (
+            {
+                "properties": {
+                    "ref_table_fk_column": {"$ref": "#/components/schemas/FkSchema"}
+                }
+            },
+            {"FkSchema": {"type": "fk_type", "x-foreign-key": "ref_table.fk_column"}},
+            False,
+        ),
+        (
+            {
+                "properties": {
+                    "ref_table_fk_column": {
+                        "allOf": [
+                            {"type": "fk_type", "x-foreign-key": "ref_table.fk_column"}
+                        ]
+                    }
+                }
+            },
+            {},
+            False,
+        ),
+    ],
+    ids=[
+        "not in model schema",
+        "in model schema",
+        "in model schema $ref",
+        "in model schema allOf",
+    ],
+)
+@pytest.mark.column
+def test_check_foreign_key_required(model_schema, schemas, expected_required):
+    """
+    GIVEN foreign key spec, foreign key logical name, model schema, schemas and
+        expected required
+    WHEN check_foreign_key_required is called
+    THEN the expected required is returned.
+    """
+    fk_spec = {"type": "fk_type", "x-foreign-key": "ref_table.fk_column"}
+    fk_logical_name = "ref_table_fk_column"
+
+    required = object_ref.check_foreign_key_required(
+        fk_spec=fk_spec,
+        fk_logical_name=fk_logical_name,
+        model_schema=model_schema,
+        schemas=schemas,
+    )
+
+    assert required == expected_required
diff --git a/tests/open_alchemy/test_integration/test_to_from_dict.py b/tests/open_alchemy/test_integration/test_to_from_dict.py
index 979b629d..6e593db7 100644
--- a/tests/open_alchemy/test_integration/test_to_from_dict.py
+++ b/tests/open_alchemy/test_integration/test_to_from_dict.py
@@ -142,3 +142,59 @@ def test_to_from_dict_one_to_many_relationship(engine, sessionmaker):
     session.flush()
     queried_instance = session.query(model).first()
     assert queried_instance.to_dict() == model_dict
+
+
+@pytest.mark.integration
+def test_to_from_dict_one_to_many_relationship_fk_def(engine, sessionmaker):
+    """
+    GIVEN specification that has a schema with a one to many relationship with defined
+        foreign key
+    WHEN model is defined based on schema and constructed using from_dict
+    THEN when to_dict is called on the child the parent foreign key is returned.
+    """
+    # Creating model factory
+    base = declarative.declarative_base()
+    model_factory = open_alchemy.init_model_factory(
+        base=base,
+        spec={
+            "components": {
+                "schemas": {
+                    "RefTable": {
+                        "properties": {
+                            "id": {"type": "integer", "x-primary-key": True},
+                            "table_id": {
+                                "type": "integer",
+                                "x-foreign-key": "table.id",
+                            },
+                        },
+                        "x-tablename": "ref_table",
+                        "type": "object",
+                    },
+                    "Table": {
+                        "properties": {
+                            "id": {"type": "integer", "x-primary-key": True},
+                            "ref_tables": {
+                                "type": "array",
+                                "items": {"$ref": "#/components/schemas/RefTable"},
+                            },
+                        },
+                        "x-tablename": "table",
+                        "type": "object",
+                    },
+                }
+            }
+        },
+    )
+    ref_model = model_factory(name="RefTable")
+    model = model_factory(name="Table")
+    # Creating models
+    base.metadata.create_all(engine)
+
+    # Constructing and turning back to dictionary
+    model_dict = {"id": 11, "ref_tables": [{"id": 12}]}
+    instance = model.from_dict(**model_dict)
+    session = sessionmaker()
+    session.add(instance)
+    session.flush()
+    queried_ref_instance = session.query(ref_model).first()
+    assert queried_ref_instance.to_dict() == {"id": 12, "table_id": 11}