Delphi-RAG-Lint
Delphi tooling · database code

A Query Per Loop Iteration Is Now Reported by Default

Since drag-lint 1.55.0-alpha the query-in-loop rule is on by default, so a Delphi loop that runs one database query per iteration is reported without any setting. Such a loop is the classic reason a screen is fast on ten rows and slow on ten thousand. The rule finds it with a fixed algorithm, not a model.

Availability

In 1.54 the rule existed but was off. drag-lint 1.55.0-alpha, released 2026-11-27, turns it on: the release has 463 rules, 375 of them on by default. Every output below is real output of 1.55.0-alpha on the small unit in section 01 (paths shortened; the note drag-lint prints about project rules is left out).

The pattern is easy to write and hard to see in review: a helper that runs a query looks harmless, until a loop calls it once per row. Each call is a round trip to the database, and the release notes name BDE as the slowest case. Rules like this one come out of our work on Micronite, the quality and production-control software we ship to manufacturers.

01 — The fixture

A loop that calls a helper that runs a query

The unit OrderTotals.pas sums the prices of the items in an order through a FireDAC TFDQuery. The loop in SumOrder never mentions a query: the query hides inside PriceOf.

function TOrderTotals.PriceOf(pItemId: Integer): Currency;
begin
  FQuery.SQL.Text := 'select PRICE from ITEMS where ID = :ID';
  FQuery.ParamByName('ID').AsInteger := pItemId;
  FQuery.Open;
  try
    Result := FQuery.FieldByName('PRICE').AsCurrency;
  finally
    FQuery.Close;
  end;
end;

function TOrderTotals.SumOrder(const pItems: array of Integer): Currency;
var
  I: Integer;
begin
  Result := 0;
  for I := Low(pItems) to High(pItems) do
    Result := Result + PriceOf(pItems[I]);
end;
02 — Steps

Index, lint, read the finding

Step 1. Index the folder into a database of its own. Nothing else is touched.

drag-lint index . --db fix.sqlite

Done. Files: 1, Symbols: 10, Refs: 51, 0.63s, parse-errors=0

Step 2. Lint the unit. No --rule, no setting, no config file: the finding appears because the rule is on by default.

drag-lint lint OrderTotals.pas --db fix.sqlite

OrderTotals.pas:44:24  [hint] query-in-loop: PriceOf runs a query per iteration of this loop (ITEMS) -- read or write the rows as one set
1 finding(s)

Line 44, column 24 is the call PriceOf(pItems[I]) inside the for loop. The message names the routine that runs the query and the table it reads. The rule is a hint, which is its default severity, and it carries the weakness label CWE-1050 (excessive platform resource consumption within a loop). drag-lint rules --rule query-in-loop lists it under firedac.

Step 3. Ask for the same finding as data, so a script or a build step can count them.

drag-lint lint OrderTotals.pas --db fix.sqlite --rule query-in-loop --json

[
  {
    "rule": "query-in-loop",
    "severity": "hint",
    "file_path": "...\\OrderTotals.pas",
    "start_line": 44,
    "start_col": 24,
    "end_line": 44,
    "end_col": 31,
    "message": "PriceOf runs a query per iteration of this loop (ITEMS) -- read or write the rows as one set",
    "compliance": {
      "cwe": [
        "CWE-1050"
      ],
      "cert": [
      ],
      "misra": [
      ],
      "weak": [
        "CWE-1050"
      ]
    }
  }
]
03 — The fix

Read the rows as one set, then loop over memory

The message says what to do: read the rows as one set. LoadPrices runs the query once and fills a dictionary; the loop in SumOrder only looks prices up. The while loop in LoadPrices walks the rows of one open result set and starts no query, so it is not reported.

procedure TOrderTotals.LoadPrices(const pPrices: TDictionary<Integer, Currency>);
begin
  FQuery.SQL.Text := 'select ID, PRICE from ITEMS';
  FQuery.Open;
  try
    while not FQuery.Eof do
    begin
      pPrices.Add(FQuery.FieldByName('ID').AsInteger,
        FQuery.FieldByName('PRICE').AsCurrency);
      FQuery.Next;
    end;
  finally
    FQuery.Close;
  end;
end;

function TOrderTotals.SumOrder(const pItems: array of Integer): Currency;
var
  I: Integer;
  Prices: TDictionary<Integer, Currency>;
begin
  Result := 0;
  Prices := TDictionary<Integer, Currency>.Create;
  try
    LoadPrices(Prices);
    for I := Low(pItems) to High(pItems) do
      Result := Result + Prices[pItems[I]];
  finally
    Prices.Free;
  end;
end;

Step 4. Reindex the folder, because the lint reads the index, then lint again.

drag-lint index . --db fix.sqlite

Done. Files: 1, Symbols: 11, Refs: 73, 0.62s, parse-errors=0

drag-lint lint OrderTotals.pas --db fix.sqlite --rule query-in-loop

0 finding(s)

The finding is gone because the loop no longer reaches a query, not because anything was hidden. Nothing in the unit carries a suppression marker.

04 — What it leaves alone

Loops that look like the pattern but are not

The rule reports an Open, ExecSQL, Execute, ExecProc or Active := True in the body of a for, for in, while or repeat loop, and, through the index, a call in the loop to a routine that runs a query, directly or one call further down. It stays silent when:

  • the loop has at most ten literal steps, such as for I := 0 to 3;
  • the loop walks a chain, where the next step depends on what this one read: a while or repeat whose condition names neither Eof, Bof nor < Count;
  • each step asks another table, database or connection, for example a table name built from an expression;
  • it is a retry or polling loop, or the branch leaves the loop with Break, Exit or raise, so the query runs once;
  • an if asks a cache or the dataset first (TryGetValue, ContainsKey, not D.Active);
  • the statement is array DML (Params.ArraySize), or the dataset is in memory.
05 — Why it is repeatable

A deterministic Delphi algorithm, not AI and not manual work

The answer comes from the index drag-lint builds by parsing your source: the loop is a node in the syntax tree, and the call inside it is resolved to PriceOf, whose body the index records as reading ITEMS. The rule follows that chain through the call. No model is asked, nothing is guessed, and nobody reads the code by hand: the same source and the same index give the same finding on every run.

06 — Limits

When the rule is wrong for you

  • Some loops should query per item, such as a batch job where memory is the constraint. Turn the rule off with "disabled": ["query-in-loop"] in the lint configuration, or approve a single line with a dl:ok marker that says why.
  • A query more than two calls away from the loop is not reported.
  • Before the release the rule was measured on four project indexes (2026-11-23). On the two database applications every finding left was right. On drag-lint's own graph code more than one finding in ten was not real, which is why 1.54 shipped the rule off.
  • The rule has no automatic fix. Turning a per-row query into one set needs a human decision about the query and where the rows live.
  • The run above used a single unit. The index is what lets the rule see through a call, so index the whole project for a real check.

Numbers and output measured 2026-11-27 with drag-lint 1.55.0-alpha on a one-unit fixture. The silent cases in section 04 and the measurement in section 06 come from the rule's documentation, not from this run.