diff --git a/services/catalog/src/simcore_service_catalog/db/repositories/_services_sql.py b/services/catalog/src/simcore_service_catalog/db/repositories/_services_sql.py index a09d2ef510b6..18dde513e9b8 100644 --- a/services/catalog/src/simcore_service_catalog/db/repositories/_services_sql.py +++ b/services/catalog/src/simcore_service_catalog/db/repositories/_services_sql.py @@ -211,3 +211,34 @@ def list_services_with_history_stmt( ) ).label("history"), ).group_by(subquery.c.key) + + +def list_services_stmt2(): + # Subquery to get the latest version for each key + subquery = sa.select( + services_meta_data.c.key, + services_meta_data.c.version, + services_meta_data.c.description, + func.row_number() + .over( + partition_by=services_meta_data.c.key, + order_by=sa.desc(_version(services_meta_data.c.version)), + ) + .label("row_num"), + ).alias("s") + + return ( + sa.select( + subquery.c.key, + subquery.c.description, + func.array_agg(services_meta_data.c.version).label("history"), + ) + .select_from( + subquery.join( + services_meta_data, subquery.c.key == services_meta_data.c.key + ) + ) + .where(subquery.c.row_num == 1) + .group_by(subquery.c.key, subquery.c.description) + .order_by(subquery.c.key) + ) diff --git a/services/catalog/tests/unit/with_dbs/test_db_repositories.py b/services/catalog/tests/unit/with_dbs/test_db_repositories.py index ef3f29e235ab..c11970179db2 100644 --- a/services/catalog/tests/unit/with_dbs/test_db_repositories.py +++ b/services/catalog/tests/unit/with_dbs/test_db_repositories.py @@ -15,6 +15,7 @@ from simcore_service_catalog.db.repositories._services_sql import ( AccessRightsClauses, batch_get_services_stmt, + list_services_stmt2, list_services_with_history_stmt, total_count_stmt, ) @@ -383,3 +384,7 @@ def test_services_sql_statements(): ], ) print(as_postgres_sql_query_str(stmt)) + + print(f"{list_services_stmt2.__name__:*^100}") + stmt = list_services_stmt2() + print(as_postgres_sql_query_str(stmt))