assert()

检查条件。 如果条件为 false,将输出错误消息并使查询失败。

注意

在查询分析阶段中,将在应用常数折叠和谓词短路等优化之前对 assert 函数进行求值。

注意

在查询分析阶段中,提供给 assert 的参数的求值结果必须为常数。 换句话说,只能基于引用了常数的其他表达式来构造它,并且不能将其绑定到行上下文。

语法

assert(condition,message)

详细了解语法约定

参数

客户 类型​​ 必需 说明
条件 bool 要计算的条件表达式。 在查询分析阶段,条件的计算结果必须为常量。
message string 断言计算结果为 false 时使用的消息。

返回

如果条件为 true,则返回 true。 如果条件计算结果为 false,则引发语义错误。

示例

下面的查询定义了用于检查输入字符串长度的函数 checkLength(),并使用 assert 验证输入长度参数(检查它是否大于零)。

let checkLength = (len:long, s:string)
{
    assert(len > 0, "Length must be greater than zero") and
    strlen(s) > len
};
datatable(input:string)
[
    '123',
    '4567'
]
| where checkLength(len=long(-1), input)

运行此查询将产生错误:assert() has failed with message: 'Length must be greater than zero'

使用有效的 len 输入运行的示例:

let checkLength = (len:long, s:string)
{
    assert(len > 0, "Length must be greater than zero") and strlen(s) > len
};
datatable(input:string)
[
    '123',
    '4567'
]
| where checkLength(len=3, input)

输出

input
4567

以下查询将始终失败,表明当 bfalse 时,即使 where b 运算符不返回数据,也会对 assert 函数进行求值:

let b=false;
print x="Hello"
| where b
| where assert(b, "Assertion failed")