Loading

QL语言参考-2查询

查询(Queries)

官方文档

https://codeql.github.com/docs/ql-language-reference/queries/

查询是 QL 程序的输出,它们计算成组的结果。

有两种查询方式:

  • 使用select字句进行查询。如果存在select模块,在该模块中定义。
  • 使用query谓词进行查询。该模块的谓词命名空间中的任何查询谓词。也就是说,它们可以在模块本身中定义,或者从不同的模块中导入。

Select 字句

在编写查询模块时,可以包含以下格式的 select 子句(通常位于文件的末尾) :

from /* ... variable declarations ... */
where /* ... logical formula ... */
select /* ... expressions ... */

fromwhere 部分是可选的。

除了“表达式”中描述的表达式之外,还可以包括:

  • as 关键字,后跟名称。这为结果列提供了一个“标签”,并允许您在后续的选择表达式中使用它们。
  • order by关键字,后面跟着结果列的名称,还可以选择关键字 asc 或 desc。这决定了显示结果的顺序。

例如:

from int x, int y
where x = 3 and y in [0 .. 2]
select x, y, x * y as product, "product: " + product 

select 语句输出的结果

x y product
3 0 0 product: 0
3 1 3 product: 3
3 2 6 product: 6

还可以在 select 子句的末尾添加order by y desc 实现排序。现在根据 y 列中的值按降序排列结果:

from int x, int y
where x = 3 and y in [0 .. 2]
select x, y, x * y as product, "product: " + product order by y desc
x y product
3 2 6 product: 6
3 1 3 product: 3
3 0 0 product: 0

Query 谓词

查询谓词是带有查询注释非成员谓词。它返回谓词计算得到的所有元组。

query int getProduct(int x, int y) {
  x = 3 and
  y in [0 .. 2] and
  result = x * y 
}
序号 x y result
1 3 1 3
2 3 0 0
3 3 2 6

编写Query查询谓词而不是Select选择子句的一个好处是,您也可以在代码的其他部分调用谓词。例如,你可以在类的主体中调用 getProduct:

class MultipleOfThree extends int {
  MultipleOfThree() { this = getProduct(_, _) }
}

相比之下,select 子句就像一个匿名谓词,因此您不能在以后调用它。

在调试代码时向谓词添加查询注释也很有帮助。这样,就可以显式地看到谓词计算得到的元组集。

posted @ 2022-04-25 15:55  我是面包  阅读(100)  评论(0编辑  收藏  举报