샘플 동기식 Lambda 함수

샘플 동기식 Lambda 함수 (Sample Synchronous Lambda Function)

이 문서는 첫 번째 외부 함수를 만들 때 그대로 사용할 수 있거나 커스텀 Lambda 함수의 출발점으로 사용할 수 있는 샘플 Lambda 함수 코드를 제공해 드려요. 이 함수는 동기식(synchronous) 이에요. Python으로 작성된 이 예제는 각 행을 추출·처리해 그 행에 대한 값을 반환하며, 반환된 배열은 Snowflake에서 SQL VARIANT로 취급돼요.

출처: Snowflake SQL Reference

본문

이 문서는 첫 번째 외부 함수를 만들 때 그대로 사용하거나 커스텀 Lambda Function의 출발점으로 사용할 수 있는 샘플 Lambda Function 코드를 포함해요.

이 함수는 동기식 이에요.

(비동기(asynchronous) 예제 도 별도로 제공돼요.)

이 예제는 Python으로 작성됐어요.

이 샘플 동기식 Lambda Function은 각 행을 추출·처리해 그 행에 대한 값을 반환해요. 각 출력 값은 단순히 입력 행의 각 값을 복사한 배열이에요. 반환된 배열은 Snowflake에 의해 SQL VARIANT로 취급돼요.

import json

def lambda_handler(event, context):

    # 200 is the HTTP status code for "ok".
    status_code = 200

    # The return value will contain an array of arrays (one inner array per input row).
    array_of_rows_to_return = [ ]

    try:
        # From the input parameter named "event", get the body, which contains
        # the input rows.
        event_body = event["body"]

        # Convert the input from a JSON string into a JSON object.
        payload = json.loads(event_body)
        # This is basically an array of arrays. The inner array contains the
        # row number, and a value for each parameter passed to the function.
        rows = payload["data"]

        # For each input row in the JSON object...
        for row in rows:
            # Read the input row number (the output row number will be the same).
            row_number = row[0]

            # Read the first input parameter's value. For example, this can be a
            # numeric value or a string, or it can be a compound value such as
            # a JSON structure.
            input_value_1 = row[1]

            # Read the second input parameter's value.
            input_value_2 = row[2]

            # Compose the output based on the input. This simple example
            # merely echoes the input by collecting the values into an array that
            # will be treated as a single VARIANT value.
            output_value = ["Echoing inputs:", input_value_1, input_value_2]

            # Put the returned row number and the returned value into an array.
            row_to_return = [row_number, output_value]

            # ... and add that array to the main array.
            array_of_rows_to_return.append(row_to_return)

        json_compatible_string_to_return = json.dumps({"data" : array_of_rows_to_return})

    except Exception as err:
        # 400 implies some type of error.
        status_code = 400
        # Tell caller what this function could not handle.
        json_compatible_string_to_return = event_body

    # Return the return value and HTTP status code.
    return {
        'statusCode': status_code,
        'body': json_compatible_string_to_return
    }

Note

이 샘플 코드는 Lambda 프록시 통합(proxy integration)을 사용하고 있다고 가정해요. Snowflake는 API Gateway 엔드포인트 생성 지침에서 Lambda 프록시 통합을 권장해요.

더 알아보기 (Learn more)