stored-proceduressnowflake-cloud-data-platformexecute

Snowflake stored procedure - session object error


I'm able to create stored procedure in my snowflake account but when I'm trying to call my procedure I'm getting error: 'Session' object has no attribute 'execute'. Stored procedure is created and I can see my procedure in my private schema.


CALL TEST_PROCEDURE('PAR1','PAR2','PAR3');

My code exaple:

CREATE OR REPLACE PROCEDURE TEST_PROCEDURE(

    PAR1 STRING,

    PAR2 STRING,

    PAR3 STRING)

   

    RETURNS STRING

    LANGUAGE PYTHON

    RUNTIME_VERSION = '3.8'

    PACKAGES = ('snowflake-snowpark-python')

    HANDLER = 'filter_by_role'

    EXECUTE AS CALLER

AS

$$

 

def filter_by_role(context,PAR1,PAR2,PAR3):   

    

    try:

       

        # Convert comma-separated strings to sets

        par1_set = set(PAR1.split(',')) if PAR1 is not None else None

        par2_set = set(PAR2.split(',')) if PAR2 is not None else None

 

        # Query to retrieve eligible rows

        main_query = """

        SELECT COL1, COL2 FROM TABLE_MAIN;

        """

       

    

        # Main query results in a set

        

        eligible_rows = {(row[0], row[1]) for row in context.execute(main_query)}

 

        

        for col1, col2 in eligible_rows:

            # Check if col1 and col2 are in eligible_rows

            if (par1_set is None or col1 in par1_set) and (par2_set is None or col2 in par2_set):

                query = f"INSERT OVERWRITE INTO {col1}.{col2} SELECT * FROM {col1}.{col2} AT (TIMESTAMP => '{PAR3}'::timestamp)"

           

                # Execute query

               

                context.execute(query)

            else:

                # Log exclusion criteria

                print(f"Skipped due to exclusion in main query, {col1}, {col2}")

 

        return "Executed successfully!"

 

    except Exception as e:

        return "Error: " + str(e)

$$;

I tried to use different execute approuch such as session.execute() etc.I would appreciate any advice.


Solution

  • In snowpark python you need use session.sql method to execute any sql https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/latest/api/snowflake.snowpark.Session.sql

    Use context.sql(main_query).collect()