You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "jscheffl (via GitHub)" <gi...@apache.org> on 2025/03/23 11:27:55 UTC

[PR] Connections API is able to patch all fields correctly [airflow]

jscheffl opened a new pull request, #48109:
URL: https://github.com/apache/airflow/pull/48109

   During implementation of #48102 we saw that the patch API for connections is not working correctly.
   
   This PR fixes the problem - reason is that pydantic fields to not map 1:1 to API fields - as well as extends pytests to cover the difference


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2010854162


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,29 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):
+    """Update ORM object from Pydantic object."""
+    # Not all fields match and some need setters, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        orm_conn.conn_type = pydantic_conn.conn_type
+    if not update_mask or "description" in update_mask:
+        orm_conn.description = pydantic_conn.description
+    if not update_mask or "host" in update_mask:
+        orm_conn.host = pydantic_conn.host
+    if not update_mask or "schema" in update_mask:
+        orm_conn.schema = pydantic_conn.schema_
+    if not update_mask or "login" in update_mask:
+        orm_conn.login = pydantic_conn.login
+    if not update_mask or "password" in update_mask:
+        orm_conn.set_password(pydantic_conn.password)
+    if not update_mask or "port" in update_mask:
+        orm_conn.port = pydantic_conn.port
+    if not update_mask or "extra" in update_mask:
+        orm_conn.set_extra(pydantic_conn.extra)

Review Comment:
   If you and @ash "insist" on making it generic I could make a generic field setter. With the exception of conn ID and add some exceptions and manual tweaking for the setters, whereas the update mask  need to be considered as well. so I don't know if this is better readable or better maintainable. I just would like to make it usable before RC1.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2012149189


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,29 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):
+    """Update ORM object from Pydantic object."""
+    # Not all fields match and some need setters, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        orm_conn.conn_type = pydantic_conn.conn_type
+    if not update_mask or "description" in update_mask:
+        orm_conn.description = pydantic_conn.description
+    if not update_mask or "host" in update_mask:
+        orm_conn.host = pydantic_conn.host
+    if not update_mask or "schema" in update_mask:
+        orm_conn.schema = pydantic_conn.schema_
+    if not update_mask or "login" in update_mask:
+        orm_conn.login = pydantic_conn.login
+    if not update_mask or "password" in update_mask:
+        orm_conn.set_password(pydantic_conn.password)
+    if not update_mask or "port" in update_mask:
+        orm_conn.port = pydantic_conn.port
+    if not update_mask or "extra" in update_mask:
+        orm_conn.set_extra(pydantic_conn.extra)

Review Comment:
   I think the `setter` part is fine to do manually like this. Aliasing part should leverage pydantic aliases idealy.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2009166637


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,28 +187,35 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())
+
+    # Not all fields match, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        connection.conn_type = patch_body.conn_type
+    if not update_mask or "description" in update_mask:
+        connection.description = patch_body.description
+    if not update_mask or "host" in update_mask:
+        connection.host = patch_body.host
+    if not update_mask or "schema" in update_mask:
+        connection.schema = patch_body.schema_
+    if not update_mask or "login" in update_mask:
+        connection.login = patch_body.login
+    if not update_mask or "password" in update_mask:
+        connection._password = patch_body.password
+    if not update_mask or "port" in update_mask:
+        connection.port = patch_body.port
+    if not update_mask or "extra" in update_mask:
+        connection._extra = patch_body.extra

Review Comment:
   @ashb okay even worse. Took a look deeper into code. The model_dump()/property-transfer is only working if you _create_ a new DB connection object (as this maps the internals in `__init__()`). Otherwise for password and extra because of encryption you need to walk via the official setters to properly update the fields.
   
   Hope this is okay?
   
   Also adjusted the Bulk API service, this had the same problem. Also consolidated the Pydantic to ORM mapping to one helper function.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2009114189


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,28 +187,35 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())
+
+    # Not all fields match, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        connection.conn_type = patch_body.conn_type
+    if not update_mask or "description" in update_mask:
+        connection.description = patch_body.description
+    if not update_mask or "host" in update_mask:
+        connection.host = patch_body.host
+    if not update_mask or "schema" in update_mask:
+        connection.schema = patch_body.schema_
+    if not update_mask or "login" in update_mask:
+        connection.login = patch_body.login
+    if not update_mask or "password" in update_mask:
+        connection._password = patch_body.password
+    if not update_mask or "port" in update_mask:
+        connection.port = patch_body.port
+    if not update_mask or "extra" in update_mask:
+        connection._extra = patch_body.extra

Review Comment:
   That was before. And not working.
   But we need a mapping in both directions unfortunately, `schema` is aliased to `schema_` and on the other hand `_password` and `_extra` need to be aliased with underscore in the front :-(



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl merged PR #48109:
URL: https://github.com/apache/airflow/pull/48109


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2014984735


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -569,7 +608,7 @@ def test_patch_should_respond_404(self, test_client, body):
 
     @pytest.mark.enable_redact
     @pytest.mark.parametrize(
-        "body, expected_response",
+        "body, expected_response, update_mask",

Review Comment:
   Oh, we should. Especially because of the Alias and logic you requested to make "better" the current pytest found a regression. Actually needed to scratch my head 3-times until I found the bug.
   
   The more I look on the revised code comparing to the previous list the more I hate it. Over generlized. And error prone because of aliases. So we SHOULD keep this pytest with update mask.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2021640510


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -404,6 +514,27 @@ def test_should_respond_403(self, unauthorized_test_client):
                 },
                 {"update_mask": ["login", "port"]},
             ),
+            (
+                {
+                    "connection_id": TEST_CONN_ID,
+                    "conn_type": TEST_CONN_TYPE,
+                    "extra": '{"key": "var"}',
+                    "login": None,
+                    "port": None,
+                },

Review Comment:
   Good point, added another "negative" kind of test case where `None` is passed explicitly



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "ashb (via GitHub)" <gi...@apache.org>.
ashb commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2009106429


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,28 +187,35 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())
+
+    # Not all fields match, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        connection.conn_type = patch_body.conn_type
+    if not update_mask or "description" in update_mask:
+        connection.description = patch_body.description
+    if not update_mask or "host" in update_mask:
+        connection.host = patch_body.host
+    if not update_mask or "schema" in update_mask:
+        connection.schema = patch_body.schema_
+    if not update_mask or "login" in update_mask:
+        connection.login = patch_body.login
+    if not update_mask or "password" in update_mask:
+        connection._password = patch_body.password
+    if not update_mask or "port" in update_mask:
+        connection.port = patch_body.port
+    if not update_mask or "extra" in update_mask:
+        connection._extra = patch_body.extra

Review Comment:
   I wonder if instead of hard-coding this list here, we should make use of Pydantic's [aliases](https://docs.pydantic.dev/latest/concepts/alias/) so that the mapping can be maintained in the datamodel and handled for us by pydantic?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2013802759


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -569,7 +608,7 @@ def test_patch_should_respond_404(self, test_client, body):
 
     @pytest.mark.enable_redact
     @pytest.mark.parametrize(
-        "body, expected_response",
+        "body, expected_response, update_mask",

Review Comment:
   I don't think we need the update_mask update.
   
   All fields that are wet will be updated.



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,26 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):

Review Comment:
   return type annotation



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,29 +190,20 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())

Review Comment:
   This needs to be moved inside the `update_orm_from_pydantic` I guess. 
   
   It needs to be done only when there is no update mask. (This check is weird, I think it's some old remnant of refactoring and we should probably update that in all `PATCH` endpoint, but for an other PR)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2021023511


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -404,6 +514,27 @@ def test_should_respond_403(self, unauthorized_test_client):
                 },
                 {"update_mask": ["login", "port"]},
             ),
+            (
+                {
+                    "connection_id": TEST_CONN_ID,
+                    "conn_type": TEST_CONN_TYPE,
+                    "extra": '{"key": "var"}',
+                    "login": None,
+                    "port": None,
+                },

Review Comment:
   Nit: Such test case would be awesome for `test_patch_should_respond_200` where no mask is provided. Just to be sure that it behaves as we expect. (setting to None `login` and `port`)



##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -390,7 +401,13 @@ def test_should_respond_403(self, unauthorized_test_client):
         "body, updated_connection, update_mask",
         [
             (
-                {"connection_id": TEST_CONN_ID, "conn_type": TEST_CONN_TYPE, "extra": '{"key": "var"}'},
+                {
+                    "connection_id": TEST_CONN_ID,
+                    "conn_type": TEST_CONN_TYPE,
+                    "extra": '{"key": "var"}',
+                    "login": TEST_CONN_LOGIN,
+                    "port": TEST_CONN_PORT,
+                },

Review Comment:
   Nice thanks for adding that test. Indeed a test case was missing



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2014992302


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,26 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):

Review Comment:
   Okay, return type is `None` - usually we do not define it. But okay, adjusted.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2013004431


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,29 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):
+    """Update ORM object from Pydantic object."""
+    # Not all fields match and some need setters, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        orm_conn.conn_type = pydantic_conn.conn_type
+    if not update_mask or "description" in update_mask:
+        orm_conn.description = pydantic_conn.description
+    if not update_mask or "host" in update_mask:
+        orm_conn.host = pydantic_conn.host
+    if not update_mask or "schema" in update_mask:
+        orm_conn.schema = pydantic_conn.schema_
+    if not update_mask or "login" in update_mask:
+        orm_conn.login = pydantic_conn.login
+    if not update_mask or "password" in update_mask:
+        orm_conn.set_password(pydantic_conn.password)
+    if not update_mask or "port" in update_mask:
+        orm_conn.port = pydantic_conn.port
+    if not update_mask or "extra" in update_mask:
+        orm_conn.set_extra(pydantic_conn.extra)

Review Comment:
   Okay, re-adjusted the consolidated Pydantic->ORM copy function. Okay now like this?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2017601835


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -390,7 +401,13 @@ def test_should_respond_403(self, unauthorized_test_client):
         "body, updated_connection, update_mask",
         [
             (
-                {"connection_id": TEST_CONN_ID, "conn_type": TEST_CONN_TYPE, "extra": '{"key": "var"}'},
+                {
+                    "connection_id": TEST_CONN_ID,
+                    "conn_type": TEST_CONN_TYPE,
+                    "extra": '{"key": "var"}',
+                    "login": TEST_CONN_LOGIN,
+                    "port": TEST_CONN_PORT,
+                },

Review Comment:
   Okay, I assume not it is considered- as discussed in 1:1 slack - that body fields are only set as provided when no update mask provided.
   
   Extended pytest on this to catch a regression as well, was not fully covered in tests before.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2014991889


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,29 +190,20 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())

Review Comment:
   I can not move this into `update_orm_from_pydantic` - I also wanted to - because in the batch handling there is directly a ValidationError raised which is catched to loop over other records, In the normal patch a RequestValidationError is raised which then directly raises a HTTP error response..



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2016706449


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -108,12 +129,17 @@ def handle_bulk_update(
 
             for connection in action.entities:
                 if connection.connection_id in update_connection_ids:
-                    old_connection = self.session.scalar(
+                    old_connection: Connection = self.session.scalar(
                         select(Connection).filter(Connection.conn_id == connection.connection_id).limit(1)
                     )
+                    if old_connection is None:
+                        raise ValidationError(
+                            f"The Connection with connection_id: `{connection.connection_id}` was not found"
+                        )
                     ConnectionBody(**connection.model_dump())
-                    for key, val in connection.model_dump(by_alias=True).items():
-                        setattr(old_connection, key, val)
+
+                    # Not all fields match and some need setters, therefore copy manually

Review Comment:
   I think we can remove this comment, it's part of the `update_orm_from_pydantic` fn now.



##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py:
##########
@@ -390,7 +401,13 @@ def test_should_respond_403(self, unauthorized_test_client):
         "body, updated_connection, update_mask",
         [
             (
-                {"connection_id": TEST_CONN_ID, "conn_type": TEST_CONN_TYPE, "extra": '{"key": "var"}'},
+                {
+                    "connection_id": TEST_CONN_ID,
+                    "conn_type": TEST_CONN_TYPE,
+                    "extra": '{"key": "var"}',
+                    "login": TEST_CONN_LOGIN,
+                    "port": TEST_CONN_PORT,
+                },

Review Comment:
   It seems that with this change we cannot explicitely set to `None`. (insert a None value on purpose)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2009166637


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/connections.py:
##########
@@ -187,28 +187,35 @@ def patch_connection(
             "The connection_id in the request body does not match the URL parameter",
         )
 
-    non_update_fields = {"connection_id", "conn_id"}
-    connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
+    connection: Connection = session.scalar(select(Connection).filter_by(conn_id=connection_id).limit(1))
 
     if connection is None:
         raise HTTPException(
             status.HTTP_404_NOT_FOUND, f"The Connection with connection_id: `{connection_id}` was not found"
         )
 
-    fields_to_update = patch_body.model_fields_set
-
-    if update_mask:
-        fields_to_update = fields_to_update.intersection(update_mask)
-    else:
-        try:
-            ConnectionBody(**patch_body.model_dump())
-        except ValidationError as e:
-            raise RequestValidationError(errors=e.errors())
-
-    data = patch_body.model_dump(include=fields_to_update - non_update_fields, by_alias=True)
-
-    for key, val in data.items():
-        setattr(connection, key, val)
+    try:
+        ConnectionBody(**patch_body.model_dump())
+    except ValidationError as e:
+        raise RequestValidationError(errors=e.errors())
+
+    # Not all fields match, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        connection.conn_type = patch_body.conn_type
+    if not update_mask or "description" in update_mask:
+        connection.description = patch_body.description
+    if not update_mask or "host" in update_mask:
+        connection.host = patch_body.host
+    if not update_mask or "schema" in update_mask:
+        connection.schema = patch_body.schema_
+    if not update_mask or "login" in update_mask:
+        connection.login = patch_body.login
+    if not update_mask or "password" in update_mask:
+        connection._password = patch_body.password
+    if not update_mask or "port" in update_mask:
+        connection.port = patch_body.port
+    if not update_mask or "extra" in update_mask:
+        connection._extra = patch_body.extra

Review Comment:
   @ashb okay even worse. Took a look deeper into code. The model_dump() is only working if you _create_ a new DB connection object. Otherwise for password and extra because of encryption you need to walk via the official setters to properly update the fields.
   
   Hope this is okay? I assume re-modelling the Connection model class is also a bit over-whelming?
   
   Also adjusted the Bulk API service, this had the same problem. Due to other logic hard to consolidate :-(



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Connections API is able to patch all fields correctly [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #48109:
URL: https://github.com/apache/airflow/pull/48109#discussion_r2010001285


##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,29 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):
+    """Update ORM object from Pydantic object."""
+    # Not all fields match and some need setters, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        orm_conn.conn_type = pydantic_conn.conn_type
+    if not update_mask or "description" in update_mask:
+        orm_conn.description = pydantic_conn.description
+    if not update_mask or "host" in update_mask:
+        orm_conn.host = pydantic_conn.host
+    if not update_mask or "schema" in update_mask:
+        orm_conn.schema = pydantic_conn.schema_
+    if not update_mask or "login" in update_mask:
+        orm_conn.login = pydantic_conn.login
+    if not update_mask or "password" in update_mask:
+        orm_conn.set_password(pydantic_conn.password)
+    if not update_mask or "port" in update_mask:
+        orm_conn.port = pydantic_conn.port
+    if not update_mask or "extra" in update_mask:
+        orm_conn.set_extra(pydantic_conn.extra)

Review Comment:
   I would have to take a deeper look but I agree with Ash.
   
   We normally don't use that because the powerful aliasing system of pydantic should be enough. 
   
   We had plenty of cases like this on other datamodel and we could always find a way. (maybe not this time but I'm convinced we can). Validation alias vs serializer alias, alias generator etc...



##########
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py:
##########
@@ -34,6 +34,29 @@
 from airflow.models.connection import Connection
 
 
+def update_orm_from_pydantic(
+    orm_conn: Connection, pydantic_conn: ConnectionBody, update_mask: list[str] | None = None
+):
+    """Update ORM object from Pydantic object."""
+    # Not all fields match and some need setters, therefore copy manually
+    if not update_mask or "conn_type" in update_mask:
+        orm_conn.conn_type = pydantic_conn.conn_type
+    if not update_mask or "description" in update_mask:
+        orm_conn.description = pydantic_conn.description
+    if not update_mask or "host" in update_mask:
+        orm_conn.host = pydantic_conn.host
+    if not update_mask or "schema" in update_mask:
+        orm_conn.schema = pydantic_conn.schema_
+    if not update_mask or "login" in update_mask:
+        orm_conn.login = pydantic_conn.login
+    if not update_mask or "password" in update_mask:
+        orm_conn.set_password(pydantic_conn.password)
+    if not update_mask or "port" in update_mask:
+        orm_conn.port = pydantic_conn.port
+    if not update_mask or "extra" in update_mask:
+        orm_conn.set_extra(pydantic_conn.extra)

Review Comment:
   This is for going from request to PydanticModel.
   
   For going from PydanticModel <=> ORMInstance indeed setters are a problem and we need to do that manually. (or via a service function)
   
   (from_datamodel_to_orm basically)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org