Repository: jdkandersson/OpenAlchemy

Issue:
Support date time
As a user I want to define a date time format so that I can store and retrieve dates from the database.

Support dates as indicated by the appropriate format directive of a string.

Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e0c7e91..b15f51a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
 ## Version _next_
 
 - Refactor column handler to first check the schema, then gather the required artifacts for column construction and then construct the column.
+- Add support for DateTime.
 
 ## Version 0.10.0 - 2019-11-23
 _Beta release_
diff --git a/README.md b/README.md
index fd56aa24..2a1a6242 100644
--- a/README.md
+++ b/README.md
@@ -100,6 +100,7 @@ An example API has been defined using connexion and Flask here:
 - `number` (float only),
 - `boolean`,
 - `string`,
+- `date-time`,
 - `$ref` references for columns and models,
 - primary keys,
 - auto incrementing,
diff --git a/docs/source/technical_details/type_mapping.rst b/docs/source/technical_details/type_mapping.rst
index 54fd813e..5fe03584 100644
--- a/docs/source/technical_details/type_mapping.rst
+++ b/docs/source/technical_details/type_mapping.rst
@@ -17,14 +17,25 @@ following mappings:
 +--------------+----------------+-----------------+
 |              | float          | Float           |
 +--------------+----------------+-----------------+
-| string       |                | String          |
+| string       | *undefined*    | String          |
++--------------+----------------+-----------------+
+|              | date-time      | DateTime        |
 +--------------+----------------+-----------------+
 | boolean      |                | Boolean         |
 +--------------+----------------+-----------------+
 
-string
+String
 ------
 
 *OpenAPI* optionally allows the *maxLength* property for *strings*. This is
 translated to the *length* argument for the *SQLAlchemy* *String*, which is set
 to *None* if *maxLength* is *undefined*.
+
+DateTime
+--------
+
+*OpenAPI* supports the inbuilt *date-time* format for a string. This is mapped
+to the *DateTime* SQLAlchemy type. Currently, time zones are not supported.
+Database best practice is to store everything in UTC. Applications, such as web
+front ends, should convert to UTC as early as possible and localize a date and
+time as late as possible.
diff --git a/open_alchemy/column_factory/column.py b/open_alchemy/column_factory/column.py
index 04bfb9e8..5e8cf512 100644
--- a/open_alchemy/column_factory/column.py
+++ b/open_alchemy/column_factory/column.py
@@ -272,13 +272,15 @@ def _handle_string(*, artifacts: types.ColumnArtifacts) -> sqlalchemy.String:
         raise exceptions.MalformedSchemaError(
             "The string type does not support autoincrement."
         )
-    if artifacts.format is not None:
-        raise exceptions.FeatureNotImplementedError(
-            f"{artifacts.format} format for string is not supported."
-        )
-    if artifacts.max_length is None:
-        return sqlalchemy.String
-    return sqlalchemy.String(length=artifacts.max_length)
+    if artifacts.format is None:
+        if artifacts.max_length is None:
+            return sqlalchemy.String
+        return sqlalchemy.String(length=artifacts.max_length)
+    if artifacts.format == "date-time":
+        return sqlalchemy.DateTime
+    raise exceptions.FeatureNotImplementedError(
+        f"{artifacts.format} format for string is not supported."
+    )
 
 
 def _handle_boolean(*, artifacts: types.ColumnArtifacts) -> sqlalchemy.Boolean:
diff --git a/open_alchemy/utility_base.py b/open_alchemy/utility_base.py
index 7c51c55c..9b7a9436 100644
--- a/open_alchemy/utility_base.py
+++ b/open_alchemy/utility_base.py
@@ -1,5 +1,6 @@
 """Base class providing utilities for SQLAlchemy models."""
 
+import datetime
 import functools
 import json
 import typing
@@ -150,6 +151,7 @@ class UtilityBase:
 
             # Check type
             type_ = spec.get("type")
+            format_ = spec.get("format")
             if type_ is None:
                 raise exceptions.TypeMissingError(
                     f"The schema for the {name} property does not have a type."
@@ -180,6 +182,9 @@ class UtilityBase:
                 continue
 
             # Handle other types
+            if format_ == "date-time":
+                model_dict[name] = datetime.datetime.fromisoformat(value)
+                continue
             model_dict[name] = value
 
         return cls(**model_dict)
@@ -257,6 +262,7 @@ class UtilityBase:
         if not read_only:
             read_only = spec.get("readOnly", read_only)
         type_ = spec.get("type")
+        format_ = spec.get("format")
 
         if type_ is None:
             schema_descriptor = "array item" if array_context else "property"
@@ -298,6 +304,8 @@ class UtilityBase:
             )
 
         # Handle other types
+        if format_ == "date-time":
+            return value.isoformat()
         return value
 
     def to_dict(self) -> typing.Dict[str, typing.Any]:


Test patch:
diff --git a/tests/open_alchemy/column_factory/test_column.py b/tests/open_alchemy/column_factory/test_column.py
index 48bcafb6..bfc7f9c8 100644
--- a/tests/open_alchemy/column_factory/test_column.py
+++ b/tests/open_alchemy/column_factory/test_column.py
@@ -516,7 +516,9 @@ def test_handle_string_invalid_format():
 
 
 @pytest.mark.parametrize(
-    "format_, expected_type", [(None, sqlalchemy.String)], ids=["None"]
+    "format_, expected_type",
+    [(None, sqlalchemy.String), ("date-time", sqlalchemy.DateTime)],
+    ids=["None", "date-time"],
 )
 @pytest.mark.column
 def test_handle_string(format_, expected_type):
diff --git a/tests/open_alchemy/test_integration/test_database.py b/tests/open_alchemy/test_integration/test_database.py
index 96310ccb..1ee20c59 100644
--- a/tests/open_alchemy/test_integration/test_database.py
+++ b/tests/open_alchemy/test_integration/test_database.py
@@ -1,5 +1,6 @@
 """Integration tests against database."""
 
+import datetime
 import typing
 
 import pytest
@@ -16,6 +17,11 @@ import open_alchemy
         ("integer", "int64", 1),
         ("number", None, 1.0),
         ("string", None, "some string"),
+        (
+            "string",
+            "date-time",
+            datetime.datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1),
+        ),
         ("boolean", None, True),
     ],
 )
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 3a359864..850c225f 100644
--- a/tests/open_alchemy/test_integration/test_to_from_dict.py
+++ b/tests/open_alchemy/test_integration/test_to_from_dict.py
@@ -6,10 +6,21 @@ from sqlalchemy.ext import declarative
 import open_alchemy
 
 
+@pytest.mark.parametrize(
+    "column_schema, value",
+    [
+        ({"type": "integer", "x-primary-key": True}, 1),
+        (
+            {"type": "string", "format": "date-time", "x-primary-key": True},
+            "2000-01-01T01:01:01",
+        ),
+    ],
+    ids=["integer", "date-time"],
+)
 @pytest.mark.integration
-def test_to_from_dict(engine, sessionmaker):
+def test_basic_types(engine, sessionmaker, column_schema, value):
     """
-    GIVEN specification that has schema with a single property
+    GIVEN specification that has schema with a basic type property
     WHEN model is defined based on schema and constructed using from_dict
     THEN when to_dict is called the construction dictionary is returned.
     """
@@ -21,9 +32,7 @@ def test_to_from_dict(engine, sessionmaker):
             "components": {
                 "schemas": {
                     "Table": {
-                        "properties": {
-                            "column": {"type": "integer", "x-primary-key": True}
-                        },
+                        "properties": {"column": column_schema},
                         "x-tablename": "table",
                         "type": "object",
                     }
@@ -36,7 +45,7 @@ def test_to_from_dict(engine, sessionmaker):
     base.metadata.create_all(engine)
 
     # Constructing and turning back to dictionary
-    model_dict = {"column": 1}
+    model_dict = {"column": value}
     instance = model.from_dict(**model_dict)
     session = sessionmaker()
     session.add(instance)
diff --git a/tests/open_alchemy/test_utility_base.py b/tests/open_alchemy/test_utility_base.py
index cf131430..5aef48ea 100644
--- a/tests/open_alchemy/test_utility_base.py
+++ b/tests/open_alchemy/test_utility_base.py
@@ -1,5 +1,6 @@
 """Tests for UtilityBase."""
 
+import datetime
 from unittest import mock
 
 import pytest
@@ -396,6 +397,32 @@ def test_from_dict(schema, dictionary):
         assert getattr(instance, key) == value
 
 
+@pytest.mark.utility_base
+def test_from_dict_date_time():
+    """
+    GIVEN schema with string type and date-time format
+    WHEN model is defined and constructed with from_dict
+    THEN the instance has a datetime.
+    """
+    model = type(
+        "model",
+        (utility_base.UtilityBase,),
+        {
+            "_schema": {
+                "properties": {"key": {"type": "string", "format": "date-time"}}
+            },
+            "__init__": __init__,
+        },
+    )
+    dictionary = {"key": "2000-01-01T01:01:01"}
+
+    instance = model.from_dict(**dictionary)
+
+    assert instance.key == datetime.datetime(  # pylint: disable=no-member
+        year=2000, month=1, day=1, hour=1, minute=1, second=1
+    )
+
+
 @pytest.mark.utility_base
 def test_from_dict_object_de_ref_missing():
     """
@@ -804,6 +831,23 @@ class TestToDictProperty:
 
         assert returned_value == value
 
+    @staticmethod
+    @pytest.mark.utility_base
+    def test_date_time():
+        """
+        GIVEN spec that is a date time and value
+        WHEN _to_dict_property is called with the spec and value
+        THEN value is returned as a string.
+        """
+        spec = {"type": "string", "format": "date-time"}
+        value = datetime.datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1)
+
+        returned_value = utility_base.UtilityBase._to_dict_property(
+            value, spec=spec, name="name 1"
+        )
+
+        assert returned_value == "2000-01-01T01:01:01"
+
     @staticmethod
     @pytest.mark.utility_base
     def test_object_none():