|
| 1 | +"""Data transformation utilities for SQLSpec. |
| 2 | +
|
| 3 | +Provides functions for transforming data structures, particularly for |
| 4 | +field name conversion when mapping database results to schema objects. |
| 5 | +Used primarily for msgspec field name conversion with rename configurations. |
| 6 | +""" |
| 7 | + |
| 8 | +from typing import Any, Callable, Union |
| 9 | + |
| 10 | +__all__ = ("transform_dict_keys",) |
| 11 | + |
| 12 | + |
| 13 | +def _safe_convert_key(key: Any, converter: Callable[[str], str]) -> Any: |
| 14 | + """Safely convert a key using the converter function. |
| 15 | +
|
| 16 | + Args: |
| 17 | + key: Key to convert (may not be a string). |
| 18 | + converter: Function to convert string keys. |
| 19 | +
|
| 20 | + Returns: |
| 21 | + Converted key if conversion succeeds, original key otherwise. |
| 22 | + """ |
| 23 | + if not isinstance(key, str): |
| 24 | + return key |
| 25 | + |
| 26 | + try: |
| 27 | + return converter(key) |
| 28 | + except (TypeError, ValueError, AttributeError): |
| 29 | + # If conversion fails, return the original key |
| 30 | + return key |
| 31 | + |
| 32 | + |
| 33 | +def transform_dict_keys(data: Union[dict, list, Any], converter: Callable[[str], str]) -> Union[dict, list, Any]: |
| 34 | + """Transform dictionary keys using the provided converter function. |
| 35 | +
|
| 36 | + Recursively transforms all dictionary keys in a data structure using |
| 37 | + the provided converter function. Handles nested dictionaries, lists |
| 38 | + of dictionaries, and preserves non-dict values unchanged. |
| 39 | +
|
| 40 | + Args: |
| 41 | + data: The data structure to transform. Can be a dict, list, or any other type. |
| 42 | + converter: Function to convert string keys (e.g., camelize, kebabize). |
| 43 | +
|
| 44 | + Returns: |
| 45 | + The transformed data structure with converted keys. Non-dict values |
| 46 | + are returned unchanged. |
| 47 | +
|
| 48 | + Examples: |
| 49 | + Transform snake_case keys to camelCase: |
| 50 | +
|
| 51 | + >>> from sqlspec.utils.text import camelize |
| 52 | + >>> data = {"user_id": 123, "created_at": "2024-01-01"} |
| 53 | + >>> transform_dict_keys(data, camelize) |
| 54 | + {"userId": 123, "createdAt": "2024-01-01"} |
| 55 | +
|
| 56 | + Transform nested structures: |
| 57 | +
|
| 58 | + >>> nested = { |
| 59 | + ... "user_data": {"first_name": "John", "last_name": "Doe"}, |
| 60 | + ... "order_items": [ |
| 61 | + ... {"item_id": 1, "item_name": "Product A"}, |
| 62 | + ... {"item_id": 2, "item_name": "Product B"}, |
| 63 | + ... ], |
| 64 | + ... } |
| 65 | + >>> transform_dict_keys(nested, camelize) |
| 66 | + { |
| 67 | + "userData": { |
| 68 | + "firstName": "John", |
| 69 | + "lastName": "Doe" |
| 70 | + }, |
| 71 | + "orderItems": [ |
| 72 | + {"itemId": 1, "itemName": "Product A"}, |
| 73 | + {"itemId": 2, "itemName": "Product B"} |
| 74 | + ] |
| 75 | + } |
| 76 | + """ |
| 77 | + if isinstance(data, dict): |
| 78 | + return _transform_dict(data, converter) |
| 79 | + if isinstance(data, list): |
| 80 | + return _transform_list(data, converter) |
| 81 | + return data |
| 82 | + |
| 83 | + |
| 84 | +def _transform_dict(data: dict, converter: Callable[[str], str]) -> dict: |
| 85 | + """Transform a dictionary's keys recursively. |
| 86 | +
|
| 87 | + Args: |
| 88 | + data: Dictionary to transform. |
| 89 | + converter: Function to convert string keys. |
| 90 | +
|
| 91 | + Returns: |
| 92 | + Dictionary with transformed keys and recursively transformed values. |
| 93 | + """ |
| 94 | + transformed = {} |
| 95 | + |
| 96 | + for key, value in data.items(): |
| 97 | + # Convert the key using the provided converter function |
| 98 | + # Use safe conversion that handles edge cases without try-except |
| 99 | + converted_key = _safe_convert_key(key, converter) |
| 100 | + |
| 101 | + # Recursively transform the value |
| 102 | + transformed_value = transform_dict_keys(value, converter) |
| 103 | + |
| 104 | + transformed[converted_key] = transformed_value |
| 105 | + |
| 106 | + return transformed |
| 107 | + |
| 108 | + |
| 109 | +def _transform_list(data: list, converter: Callable[[str], str]) -> list: |
| 110 | + """Transform a list's elements recursively. |
| 111 | +
|
| 112 | + Args: |
| 113 | + data: List to transform. |
| 114 | + converter: Function to convert string keys in nested structures. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + List with recursively transformed elements. |
| 118 | + """ |
| 119 | + # Use list comprehension for better performance and avoid try-except in loop |
| 120 | + return [transform_dict_keys(item, converter) for item in data] |
0 commit comments