跟著CodeQL官方的QL tutorials做練習(xí)鸥昏,在Crown the rightful heir這一章節(jié)中有五個(gè)問(wèn)題,來(lái)做一做。在看這篇文章之前需先跟著官方的QL tutorial做一遍蜂大。
下面的CodeQL代碼踩蔚,直接放到這里運(yùn)行即可
What is the most common hair color in the village? And in each region?
第一個(gè)問(wèn)題:村里發(fā)色最多的一種是哪種顏色
import tutorial
class HairColor extends string{
HairColor(){
exists(Person p | this = p.getHairColor())
}
int ct(){
result = count(Person p | p.getHairColor() = this | p)
}
}
from HairColor c
where not exists(HairColor c1 | c1.ct() > c.ct())
select c, c.ct()
執(zhí)行結(jié)果:
brown 46
第二個(gè)問(wèn)題:每個(gè)地區(qū)發(fā)色最多的一種是哪種顏色
import tutorial
class HairColor extends string{
HairColor(){
exists(Person p | this = p.getHairColor())
}
// int ct(){
// result = count(Person p | p.getHairColor() = this | p)
// }
int ctOfLocation(Location loc){
result = count(Person p | p.getLocation() = loc and p.getHairColor() = this | p)
}
}
class Location extends string{
Location() {
this in ["east", "west", "south", "north"]
}
}
from Location location, HairColor c
where c.ctOfLocation(location) = max(HairColor c1 | | c1.ctOfLocation(location) )
select location, c, c.ctOfLocation(location)
執(zhí)行結(jié)果:
west brown 7
east brown 11
north black 8
south brown 10
說(shuō)明下:各地區(qū)擁有brown發(fā)色的人的個(gè)數(shù)分別是:
- 西部:7
- 東部:11
- 北部:3
- 南部:10
- 無(wú)地區(qū):15 (也就是
Person.getLocation()
為空的人)
總數(shù)就是46聂薪,符合第一個(gè)問(wèn)題的查詢結(jié)果部逮。
Which villager has the most children? Who has the most descendants?
第一個(gè)問(wèn)題:哪位村民擁有最多小孩
import tutorial
Person childOf(Person p) {
p = parentOf(result)
}
int childrenNumber(Person p) {
result = count(Person c | c = childOf(p) | c)
}
from Person p
where childrenNumber(p) = max(Person q | | childrenNumber(q))
select p, childrenNumber(p)
第二個(gè)問(wèn)題:哪位村民擁有最多后代
import tutorial
Person descendantOf(Person p) {
p = parentOf+(result)
}
int descendantNumber(Person p) {
result = count(Person c | c = descendantOf(p) | c)
}
from Person p
where descendantNumber(p) = max(Person q | | descendantNumber(q))
select p, descendantNumber(p)
How many people live in each region of the village?
各地區(qū)分別有多少人居准纤 :
import tutorial
class Location extends string{
Location() {
this in ["east", "west", "south", "north"]
}
}
from Location location
select location, count(Person p | p.getLocation() = location | p)
(查詢結(jié)果不包含20位無(wú)地區(qū)的人員)
Do all villagers live in the same region of the village as their parents?
找出跟他家長(zhǎng)不住在同一地區(qū)的人:
import tutorial
from Person p, Person c
where p = parentOf(c) and p.getLocation() != c.getLocation()
select c
Find out whether there are any time travelers in the village! (Hint: Look for “impossible” family relations.)
這個(gè)問(wèn)題不太具體醋虏,我理解為:找出比他后代的年紀(jì)還小的人寻咒。
import tutorial
Person descendantOf(Person p) {
p = parentOf+(result)
}
from Person p
where exists(Person c | c = descendantOf(p) and p.getAge() < c.getAge())
select p, p.getAge()