Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
2.8 kB
2
Indexable
Never
from sqlalchemy import update, select

@mutation
def update_field_details(
    self, info: Info, input: List[UpdateFieldDetailsInput]
) -> UpdateFieldDetailsMutationPayload:
    try:
        current_user = info.context.current_user.login
        updated_field_details_ids = []

        for field_detail in input:
            # Initialize the base update statement
            stmt = update(FieldDetails).where(FieldDetails.id == field_detail.id)
            
            # Determine which fields to update based on the field type
            if field_detail.type in ["Text Box", "Text Area"]:
                # Update only the field_options for Text Box or Text Area
                stmt = stmt.values(
                    options=field_detail.options,
                    updated_by=current_user,
                    updated_date=datetime.now(),
                )
            elif field_detail.type in ["Select", "Multi-select"]:
                # Update field_format and validation_id for Select or Multi-select
                # Fetch the validation ID from the mdm_validation table
                validation_stmt = select([mdm_validation.c.id]).where(
                    mdm_validation.c.validation_type == field_detail.validation_type
                )
                validation_result = info.context.session.execute(validation_stmt).first()
                
                if validation_result:
                    validation_id = validation_result[0]
                else:
                    raise ValueError(f"Validation type '{field_detail.validation_type}' not found.")
                
                stmt = stmt.values(
                    field_format=field_detail.field_format,
                    validation_id=validation_id,
                    updated_by=current_user,
                    updated_date=datetime.now(),
                )
            
            # Execute the update statement
            info.context.session.execute(stmt)
            updated_field_details_ids.append(field_detail.id)

        # Commit the changes
        info.context.session.commit()

        # Fetch and return the updated field details
        updated_field_details = (
            info.context.session.query(FieldDetails)
            .filter(FieldDetails.id.in_(updated_field_details_ids))
            .all()
        )

        return UpdateFieldDetailsMutationPayload(
            updated_field_details=updated_field_details,
            success=True,
            message="Field details updated successfully",
        )
    except Exception as e:
        info.context.session.rollback()
        return UpdateFieldDetailsMutationPayload(
            updated_field_details=[],
            success=False,
            message=f"Update failed: {str(e)}",
        )
Leave a Comment