Learn to write and run a simple CodeQL query using Visual Studio Code with the CodeQL extension.
The query we're going to run performs a basic search of the code for if expressions that are redundant, in the sense that they have an empty then branch. For example, code such as:
if error
# Handle the errorIn the quick query tab, delete the content and paste in the following query.
import codeql.ruby.AST from IfExpr ifexpr where not exists(ifexpr.getThen()) select ifexpr, "This 'if' expression is redundant."
If any matching code is found, click a link in the ifexpr column to open the file and highlight the matching if statement.
After the initial import statement, this simple query comprises three parts that serve similar purposes to the FROM, WHERE, and SELECT parts of an SQL query.
| Query part | Purpose | Details |
|---|---|---|
import codeql.ruby.AST |
Imports the standard CodeQL AST libraries for Ruby. | Every query begins with one or more import statements. |
from IfExpr ifexpr |
Defines the variables for the query.
Declarations are of the form:
<type> <variable name> |
We use: an IfExpr variable for if expressions. |
where not exists(ifexpr.getThen()) |
Defines a condition on the variables. |
|
select ifexpr, "This 'if' expression is redundant." |
Defines what to report for each match.
|
Reports the resulting if expression with a string that explains the problem. |
Query writing is an inherently iterative process. You write a simple query and then, when you run it, you discover examples that you had not previously considered, or opportunities for improvement.
Browsing the results of our basic query shows that it could be improved. Among the results you are likely to find examples of if statements with an else branch, where an empty then branch does serve a purpose. For example:
if option == "-verbose"
# nothing to do - handled earlier
else
error "unrecognized option"In this case, identifying the if statement with the empty then branch as redundant is a false positive. One solution to this is to modify the query to select if statements where both the then and else branches are missing.
To exclude if statements that have an else branch:
Add the following to the where clause:
and not exists(ifstmt.getElse())
The
whereclause is now:where not exists(ifexpr.getThen()) and not exists(ifexpr.getElse())
Re-run the query.
There are now fewer results because
ifexpressions with anelsebranch are no longer included.

