Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 78 additions & 51 deletions content/docs/analyzers/PlatformCop/PC0030.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
+++
title = 'Use partial records on read operation'
title = 'Use partial records when looping over records'
linkTitle = 'PC0030'

[params]
Expand All @@ -10,72 +10,104 @@ linkTitle = 'PC0030'
ignoreObsolete = true
+++

When a local record variable performs a read operation (`Get`, `Find`, `FindFirst`, `FindLast`, or `FindSet`) without a preceding `SetLoadFields` call, the runtime generates a SQL `SELECT` that includes **every** normal field in the table. On tables with many fields this transfers significantly more data from SQL Server than the procedure actually needs, increasing I/O, network traffic, and memory consumption.
This rule reports a read on a local record variable that drives a `Next()` loop, when no `SetLoadFields`, `AddLoadFields` or `SetBaseLoadFields` call precedes it. A loop read is any read that positions the record (`FindSet`, `Find`, `FindFirst`, `FindLast`, `Get`, `GetBySystemId`) followed by a loop that calls `Next()` on the same variable, such as `repeat ... until Next() = 0` or `while Next() <> 0`. The read method does not matter: the rows the loop reads come through `Next`, and that is where partial records pay off.

The overhead compounds in loops. A `FindSet` / `Next` cycle over thousands of records fetches unused columns on every iteration — the cost scales linearly with both the field count and the result set size.
Without partial records, the runtime loads every normal field of the table for every row the loop reads, including fields added by table extensions. `SetLoadFields` narrows the SQL column list to the fields the loop needs. The gain scales with the number of rows times the number of columns.

Calling `SetLoadFields` before a read tells the runtime to load only the fields you actually need, narrowing the SQL column list to the minimum. This is known as using **partial records**.
> **Breaking change.** Earlier versions of PC0030 reported every read operation (`Get`, `FindFirst`, `FindLast`, `Find`, `FindSet`). Single-record reads are no longer reported: they show no measurable gain, and repeated reads that are not primary key lookups lose the server record cache.

### Example

{{< highlight al "hl_lines=7" >}}
{{< highlight al "hl_lines=8" >}}
codeunit 50100 MyCodeunit
{
procedure GetCustomerName(CustomerNo: Code[20]): Text
procedure GetRecipients(SalespersonCode: Code[20]) Recipients: List of [Text]
var
Customer: Record Customer;
begin
Customer.Get(CustomerNo); // Use partial records on read operation [PC0030]
exit(Customer.Name);
Customer.SetRange("Salesperson Code", SalespersonCode);
if Customer.FindSet() then // Use partial records when looping over records [PC0030]
repeat
if Customer."E-Mail" <> '' then
Recipients.Add(Customer."E-Mail");
until Customer.Next() = 0;
end;
}
{{< /highlight >}}

Add `SetLoadFields` before the read operation:
Add `SetLoadFields` before the loop read:

{{< highlight al "hl_lines=7" >}}
codeunit 50100 MyCodeunit
{
procedure GetCustomerName(CustomerNo: Code[20]): Text
procedure GetRecipients(SalespersonCode: Code[20]) Recipients: List of [Text]
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Customer.Name);
Customer.Get(CustomerNo);
exit(Customer.Name);
Customer.SetLoadFields("E-Mail");
Customer.SetRange("Salesperson Code", SalespersonCode);
if Customer.FindSet() then
repeat
if Customer."E-Mail" <> '' then
Recipients.Add(Customer."E-Mail");
until Customer.Next() = 0;
end;
}
{{< /highlight >}}

### Why single-record reads are not reported

The server (NST) keeps a data cache. A full-record read is stored in that cache, and a repeated identical read is served from memory without a SQL round trip. A partial read is served from the cache only when it is a lookup on the full primary key. Any other partial read goes back to SQL Server on every repetition.

Measured on Business Central 29.1, the effect of `SetLoadFields` depends on the shape of the read:

| Read shape | Effect of `SetLoadFields` |
|---|---|
| Loop over many rows (any read followed by `Next`; measured for `FindSet`, `Find('-')`, `Find('+')`, `FindFirst`, `FindLast` and `Get`) | Clearly faster: about 5-8x, more with table extensions, the same for every entry method |
| Single record by full primary key (`Get`, `GetBySystemId`, `FindFirst` with the full key filtered) | No measurable gain; the read stays cached |
| Single record with any other filter (`FindFirst` or `FindLast` without a filter, a non-key filter, a range) | No gain; repeated reads lose the cache, about 60-90x slower per repeated read |

Do not add `SetLoadFields` to frequently repeated single-record reads that are not full primary key lookups. The same applies to a small loop that runs the same query very often. The analyzer cannot know how often a loop runs, so the rule stays at Info severity.

These measurements come from Business Central 29.1 (W1, Cronus data). Older versions that still store extension fields in companion tables may behave differently. Results from other builds are welcome on the issue. The full numbers are in the [investigation report](https://github.com/ALCops/Analyzers/issues/531#issuecomment-7080398726).

### Code fix

The **ALCops: Add SetLoadFields** code fix inserts a `SetLoadFields` call on the line before the statement that contains the read operation. It inspects the method body for field accesses on the variable and pre-populates the argument list with those fields, sorted alphabetically. When no field accesses are found, it falls back to the primary key fields.

When the read is part of a loop or `if` condition, the call goes before the loop or `if` statement.

When that statement is the only statement of an `if` or `else` branch, a `case` line, or a `while`, `for` or `foreach` body, there is no line before it inside the branch. The code fix then wraps the statement in a `begin..end` block with the `SetLoadFields` call first, so the call runs only on the path that reads the record. An `else if` becomes `else begin ... end`:

{{< highlight al >}}
if CustomerNo = '' then
exit('')
if SalespersonCode = '' then
exit
else
if Customer.Get(CustomerNo) then // Use partial records on read operation [PC0030]
exit(Customer.Name);
if Customer.FindSet() then // Use partial records when looping over records [PC0030]
repeat
if Customer."E-Mail" <> '' then
Recipients.Add(Customer."E-Mail");
until Customer.Next() = 0;
{{< /highlight >}}

becomes

{{< highlight al >}}
if CustomerNo = '' then
exit('')
if SalespersonCode = '' then
exit
else begin
Customer.SetLoadFields(Name);
if Customer.Get(CustomerNo) then
exit(Customer.Name);
Customer.SetLoadFields("E-Mail");
if Customer.FindSet() then
repeat
if Customer."E-Mail" <> '' then
Recipients.Add(Customer."E-Mail");
until Customer.Next() = 0;
end;
{{< /highlight >}}

When the read is part of a loop or `if` condition, the call goes before the loop or `if` statement. The code fix is not offered when the statement it would wrap contains a compiler directive such as `#if`.
The code fix is not offered when the statement it would wrap contains a compiler directive such as `#if`.

**Fix all** applies every fix in the document in one pass, including reads nested inside each other's branches. Each statement gets one `SetLoadFields` call per record variable, so two reads of the same variable in one statement share a single call, while the same variable read in two branches gets a call in each branch.
**Fix all** applies every fix in the document in one pass, including reads nested inside each other's branches. Each statement gets one `SetLoadFields` call per record variable. The same variable read in two branches gets a call in each branch.

FlowField, FlowFilter, and Blob fields are excluded because `SetLoadFields` does not support them.

Expand All @@ -85,59 +117,54 @@ For `RecordRef` variables the diagnostic is reported, but the code fix is not of

The diagnostic is not reported when:

- The variable is also used in a write operation (`Insert`, `Modify`, `Delete`, `Rename`, `TransferFields`, `Init`, `Copy`)
- The variable is passed as an argument to any function, event, or `PAGE.Run`/`PAGE.RunModal`
- The variable is used in a write operation (`Insert`, `Modify`, `Delete`, `Rename`, `TransferFields`, `Init`, `Copy`) anywhere after the read, including inside the loop
- The variable is passed as an argument to any function, event, or `PAGE.Run`/`PAGE.RunModal`, or returned with `exit`
- The variable is a temporary record
- The variable is a global or parameter variable — only local variables are analyzed
- The variable is a global or parameter variable; only local variables are analyzed
- The table is a setup or reference table (see below)
- The `Next` call is not inside a loop, for example `FindFirst` followed by a single `Next`
- The read is inside the body of the loop it would drive, for example a `Get` inside `repeat ... until Customer.Next() = 0`
- The read is not followed by a `Next` loop, including a `FindSet` that reads one row

### Setup and reference tables

Partial records interact with the server's record cache in a way that can make `SetLoadFields` slower, not faster. When a full record is read, the NST keeps it in its record cache, and a repeated identical read is served from memory without a SQL round trip. A partial-record read bypasses that cache: every repetition goes back to SQL Server. On a table with a handful of rows that is read constantly — a setup singleton, a posting group, a payment term — the cache is essentially always hot, so loading fewer columns saves nothing while losing the cache hit.

The rule therefore does not report any read operation on a local variable whose table is recognized as a setup or reference table. The recognition is structural, so it applies equally to Microsoft, partner and localized apps:
A loop over a setup or reference table reads only a few rows, and often runs many times. With `SetLoadFields` such a loop loses the server record cache and gains nothing from the narrower column list. The rule therefore does not report reads on a table it recognizes as a setup or reference table:

- The table's namespace ends with `.Setup` (for example `Microsoft.Finance.GeneralLedger.Setup`, home of `Gen. Product Posting Group` and `General Posting Setup`).
- The primary key is a single `Code` field named `Code` or `Name` — the shape of posting groups, payment terms, currencies, locations, units of measure, dimensions and journal templates.
- The primary key is a single `Code` field named `Primary Key`, or the table declares a parameterless `GetRecordOnce` procedure — the shape of setup singletons such as `General Ledger Setup`.
- The table's namespace ends with `.Setup` (for example `Microsoft.Finance.GeneralLedger.Setup`).
- The primary key is a single `Code` field named `Code` or `Name`, the shape of posting groups, payment terms and currencies.
- The primary key is a single `Code` field named `Primary Key`, or the table declares a parameterless `GetRecordOnce` procedure, the shape of setup singletons.

A table whose primary key is an `AutoIncrement` field is never treated as a reference table, even inside a `.Setup` namespace: an auto-incrementing key marks a growing table.

Master data (`Customer`, `Vendor`, `Item`), documents and ledgers are still reported. Whether a specific read on those tables benefits more from partial records or from the record cache depends on the data volume and how often the same record is re-read — information the analyzer does not have. Treat PC0030 there as the suggestion it is, and measure when in doubt.
A table whose primary key is an `AutoIncrement` field is never treated as a reference table, even inside a `.Setup` namespace.

### Local variables only

The rule analyzes only local record variables. For a local variable the analyzer can see the full lifetime — declaration, every field access, and every read operation — within a single procedure body. That is enough to determine whether `SetLoadFields` is missing and which fields should be in the list.
The rule analyzes only local record variables. For a local variable the analyzer can see the full lifetime within a single procedure body: declaration, every field access, and every read operation. That is enough to determine whether `SetLoadFields` is missing and which fields belong in the list.

Global and parameter variables are excluded because their usage spans multiple procedures, event subscribers, and page triggers. A static analyzer cannot reliably trace all code paths that access the variable, so it cannot guarantee that the inferred field list is complete. Reporting a diagnostic with an incomplete field list would cause JIT loads at runtime — the opposite of the intended improvement.
Global and parameter variables are excluded because their usage spans multiple procedures, event subscribers, and page triggers. The analyzer cannot reliably trace every code path that accesses them, so an inferred field list could be incomplete. An incomplete field list causes JIT loads at runtime, the opposite of the intended improvement.

### Data model for table extensions

The storage model for table extension fields has evolved across Business Central releases, changing the performance profile of `SetLoadFields`.

**Before Business Central 2023 wave 2**, each table extension created its own companion table in SQL Server. Reading from a table with *N* installed extensions required an *(N+1)*-way SQL join — one per extension. On heavily extended tables like `Customer` or `Item`, this could degrade read performance dramatically. `SetLoadFields` was critical here: by excluding extension fields from the load, entire joins could be eliminated.

**From Business Central 2023 wave 2** (October 2023), the platform stores all extension fields for a given base table in a [single companion table](https://learn.microsoft.com/en-us/dynamics365/release-plan/2023wave2/smb/dynamics365-business-central/data-loads-faster-server). Regardless of how many extensions are installed, at most **one** SQL join occurs.

**From Business Central 2024 wave 1** (April 2024), table extensions defined in the [same app as their target table](https://demiliani.com/2024/03/04/dynamics-365-business-central-support-for-multiple-extensions-to-same-target-in-the-same-app/) have their fields and keys merged directly into the base table — no companion table, no join at all.

**From Business Central 2026 wave 2** (October 2026), companion tables will be eliminated entirely, merging all extension fields into the base table.
The storage model for table extension fields has changed across Business Central releases:

Even without companion table joins, `SetLoadFields` remains valuable. Reducing the SQL column list cuts the volume of data transferred from SQL Server to the application server on every read. The gain grows with the number of fields on the table and the size of the result set — in looping scenarios over large tables, partial records can still cut read times significantly.
- **Before Business Central 2023 wave 2**, each table extension created its own companion table in SQL Server. Reading a table with *N* installed extensions required an *(N+1)*-way join.
- **From Business Central 2023 wave 2** (October 2023), all extension fields for a base table are stored in a [single companion table](https://learn.microsoft.com/en-us/dynamics365/release-plan/2023wave2/smb/dynamics365-business-central/data-loads-faster-server). At most one join occurs.
- **From Business Central 2024 wave 1** (April 2024), table extensions defined in the [same app as their target table](https://demiliani.com/2024/03/04/dynamics-365-business-central-support-for-multiple-extensions-to-same-target-in-the-same-app/) are merged directly into the base table.
- **From Business Central 2026 wave 2** (October 2026), companion tables are eliminated entirely and all extension fields are merged into the base table.

### Relationship to AA0242

This rule complements the CodeCop rule **AA0242** ("Field is not selected for loading and accessing it may cause a JIT load"). The two rules cover different scenarios:

| Rule | When it fires |
|---|---|
| **PC0030** | `SetLoadFields` is entirely absent before a read operation |
| **PC0030** | `SetLoadFields` is entirely absent before a read that drives a loop |
| **AA0242** | `SetLoadFields` is present but a field access is missing from the field list |

Together they provide full coverage: PC0030 encourages adopting partial records, and AA0242 ensures the field list stays complete.
PC0030 encourages adopting partial records in loops, and AA0242 ensures the field list stays complete.

### See also

- [Investigation report: `SetLoadFields` and the NST data cache](https://github.com/ALCops/Analyzers/issues/531#issuecomment-7080398726) on GitHub
- [Using Partial Records](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-partial-records) on Microsoft Learn
- [Record.SetLoadFields](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/record/record-setloadfields-method) on Microsoft Learn
- [RecordRef.SetLoadFields](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/methods-auto/recordref/recordref-setloadfields-method) on Microsoft Learn
Expand All @@ -147,4 +174,4 @@ Together they provide full coverage: PC0030 encourages adopting partial records,
- [Partial Records in detail (part 2)](https://bccaptain.com.au/2020/12/29/partial-records-in-detail-part-2/) by Tomas Kapitan
- [SetLoadFields with reference and value passing](https://demiliani.com/2021/06/03/dynamics-365-business-central-setloadfields-performances-with-reference-passing-or-value-passing-parameters/) by Stefano Demiliani
- [Using partial records in Business Central](https://ivansingleton.dev/using-partial-records-in-business-central-setloadfields/) by Ivan Singleton
- [Partial records — Performance improvements](https://vld-bc.com/blog/business-central-performance-partial-records) by Volodymyr Dvernytskyi
- [Partial records: Performance improvements](https://vld-bc.com/blog/business-central-performance-partial-records) by Volodymyr Dvernytskyi
2 changes: 1 addition & 1 deletion content/docs/analyzers/PlatformCop/PC0031.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Temporary record variables (no SQL backing, no JIT load) and record variables wh

### See also

- [PC0030: Use SetLoadFields before read operations](../pc0030/)
- [PC0030: Use partial records when looping over records](../pc0030/)
- [Using Partial Records](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-partial-records) on Microsoft Learn
- [Partial Records FAQ](https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-partial-records-faq) on Microsoft Learn
- [SetLoadFields Performances](https://demiliani.com/2021/06/03/dynamics-365-business-central-setloadfields-performances-with-reference-passing-or-value-passing-parameters/) by Stefano Demiliani
2 changes: 1 addition & 1 deletion content/docs/analyzers/PlatformCop/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ PlatformCop inspects AL code for constructs the platform rejects, ignores, or ex
| [PC0027](pc0027/) | Avoid triggering table logic on temporary records | Warning | ✓ | |
| [PC0028](pc0028/) | Table relation field length mismatch | Warning | ✓ | |
| [PC0029](pc0029/) | Use CreateSequentialGuid for key fields | Info | ✓ | ✓ |
| [PC0030](pc0030/) | Use partial records on read operation | Info | ✓ | ✓ |
| [PC0030](pc0030/) | Use partial records when looping over records | Info | ✓ | ✓ |
| [PC0031](pc0031/) | Partial records cause JIT load on full-field operations | Warning | ✓ | ✓ |
| [PC0032](pc0032/) | Report layout property exceeds maximum length | Error | ✓ | |
| [PC0033](pc0033/) | Duplicate OData EntityName on page controls | Warning | ✓ | |
Expand Down