首页 > 解决方案 > 检查 JavaScript 过程是否已经在运行

问题描述

我有一个要求,我想检查我要运行的程序是否已经处于运行状态;我打算使用以下查询进行检查

 "SELECT EXECUTION_STATUS FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY WHERE EXECUTION_STATUS ='RUNNING'" ; 

或者我应该使用“

SELECT EXECUTION_STATUS FROM DATABASE.INFORMATION_SCHEMA.QUERY_HISTORY WHERE EXECUTION_STATUS ='RUNNING'"

如果列值为 RUNNING,则其实例已在运行。让我知道这种方法是否正确。

标签: snowflake-cloud-data-platform

解决方案


是的,您可以使用EXECUTION_STATUSQUERY_HISTORY来确定存储过程调用是否仍在运行。

但是,在这种情况下,ACCOUNT_USAGE.QUERY_HISTORY无法使用该视图,因为该视图有一些延迟。换言之,它无法捕捉实时的执行状态。因此,INFORMATION_SCHEMA.QUERY_HISTORY表函数是首选。

以下是如何INFORMATION_SCHEMA.QUERY_HISTORY在此用例中使用表函数的示例。请注意,这INFORMATION_SCHEMA.QUERY_HISTORY是一个表函数,而不是视图,因此您必须使用TABLE()包装器来使用它,如下所示:

工作表 1:

-- Sample stored procedure just waiting for 60 seconds

create or replace procedure sp1 ()
returns varchar
language javascript
as 'snowflake.createStatement({sqlText: "select system$wait(60);"}).execute();'
;

call sp1();

工作表 2:

select start_time, query_id, query_text, execution_status
from table(information_schema.query_history())
where execution_status = 'RUNNING'
;
/*
START_TIME  QUERY_ID    QUERY_TEXT  EXECUTION_STATUS
2021-10-26 08:25:56.969 +0200   019fdc41-0000-2c1d-0000-3f8100091e56    select start_time, query_id, query_text, execution_status  from table(information_schema.query_history())  where execution_status = 'RUNNING'  ;    RUNNING
2021-10-26 08:25:53.869 +0200   019fdc41-0000-2c5c-0000-3f81000935aa    select system$wait(60); RUNNING
2021-10-26 08:25:53.515 +0200   019fdc41-0000-2c5c-0000-3f81000935a6    call sp1(); RUNNING
*/

请注意,上述QUERY_HISTORY表函数的结果EXECUTION_STATUS = 'RUNNING'包含QUERY_HISTORY查询本身。因此,如果仅收集EXECUTION_STATUS列作为示例,则很难区分正在运行的查询是否为存储过程调用。

因此,如果人类使用状态检查查询进行视觉检查,则该查询应包括其他列,如QUERY_ID,START_TIMEQUERY_TEXT区分存储过程调用。

否则,如果任何自动化使用状态检查查询,查询应该有另一个过滤器(WHERE子句)来区分存储过程调用,如下所示:

select query_id
from table(information_schema.query_history())
where execution_status = 'RUNNING'
and query_text ilike 'call%'
;
/*
QUERY_ID
019fdc48-0000-2c1d-0000-3f8100091e6e
*/

您可以更改新过滤器中的模式以区分不同的存储过程调用,也可以使用查询标记:

工作表 1:

alter session set query_tag = 'ws1';
call sp1();

工作表 2:

alter session set query_tag = 'ws2';
call sp1();

工作表 3:

select query_tag, query_id
from table(information_schema.query_history())
where execution_status = 'RUNNING'
and query_text ilike 'call%'
;
/*
QUERY_TAG   QUERY_ID
ws2 019fdc4b-0000-2c5c-0000-3f8100093642
ws1 019fdc4b-0000-2c1d-0000-3f8100091ec6
*/

select query_tag, query_id
from table(information_schema.query_history())
where execution_status = 'RUNNING'
and query_text ilike 'call%'
and query_tag = 'ws2'
;
/*
QUERY_TAG   QUERY_ID
ws2 019fdc4b-0000-2c5c-0000-3f8100093642
*/

推荐阅读