I have a sample stored procedure in Snowflake where it does the below steps one after the other
- Insert Metadata with start details
- Get the total count of table which is passed as argument
- Update Metadata with success/failure
Issue here is When the given table name doesn't exist on database, The stored procedure exits with error however its not updating the Metadata with error details and the Metadata entry shows status as "In-Progress" while the stored procedure failed at point #2.
I'm looking for a clean exit when the table doesn't exist in database then stored procedure should update metadata with error details and exit cleanly.
Can someone have a look on below code and suggest if I'm missing something here please. I'm new to snowflake and procedure's as well. Thanks.
CREATE OR REPLACE PROCEDURE abc.PROC_GET_COUNT(table_name varchar)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS $$
// SQL Queries
var get_execution_id_sql = "select t.nextval from table(getnextval(EXECUTION_SEQUENCE)) t";
var get_count_sql = `select count(*) from abc.`+ TABLE_NAME +;
var result_set1 = snowflake.createStatement({sqlText: get_execution_id_sql}).execute();
result_set1.next();
var seq_num= result_set1.getColumnValue(1);
var insert_meta_sql1= `INSERT into abc.ERROR_LOG (EXECUTION_ID, STATUS, START_TS) values ( '` +seq_num+ `', 'In_Progress', CURRENT_TIMESTAMP)`;
try {
message = 'In insert Metadata with start details';
snowflake.execute({sqlText: insert_meta_sql1});
message = 'In Process of get count';
get_count_out = snowflake.execute ({sqlText: get_count_sql});
get_count_out.next();
rec_count = get_count_out.getColumnValue(1);
upd_meta_sql = `UPDATE abc.ERROR_LOG SET END_TS = current_timestamp, STATUS = 'SUCCESS', MESSAGE = '` + TABLE_NAME + ` - Total count: ` + rec_count + `' where EXECUTION_ID = '` + seq_num + `';
message = 'In update Metadata with end details';
snowflake.execute ({sqlText: upd_meta_sql});
} catch (err) {
upd_meta_sql = `UPDATE abc.ERROR_LOG SET
END_TS = current_timestamp,
STATUS = 'FAILED',
MESSAGE = '` + message + `. Error Details -- \n Code: `+ err.code +`\n State: `+ err.state +`\n Message: `+ err.message +`\n Stack Trace: `+ err.stackTraceTxt +`'
where EXECUTION_ID = '` + seq_num + `';
snowflake.execute ({sqlText: upd_meta_sql});
return "Failed: " + message + ' -- ' +err;
}
return 'SUCCESS';
$$;