# Loading data

> Feed Pivot Studio arrays of records, CSV or JSON, control field detection with field definitions, and use the automatic date hierarchy.

Pivot Studio works on flat records: one object per order line, transaction or event. It never fetches data itself; you pass it records or text, and it detects the fields, their types and a date hierarchy.

## Data sources

`data` (as an option, or through `setData()`) accepts three kinds of input:

| Input | Example | Notes |
| --- | --- | --- |
| An array of objects | `[{ store: 'Leeds Trinity', revenue: 1840 }, …]` | Used as is; the records you pass are the ones drill-through returns |
| CSV text | `'store,revenue\nLeeds Trinity,1840\n…'` | Delimiter sniffed, quotes handled, first row as headers |
| JSON text | `'[{"store":"Leeds Trinity","revenue":1840}]'` | An array of objects, an array of arrays with a header row, or `{ "data": [...] }` |

```ts title="load-sales.ts"
const studio = createPivotStudio(container, { data: await fetch('/api/sales').then((r) => r.json()) });

const csvText = await fetch('/exports/store-sales-2026.csv').then((r) => r.text());
studio.setData(csvText);

studio.setData(await fetch('/api/sales.json').then((r) => r.text()), { format: 'json' });
```

With the default `dataFormat: 'auto'`, text that starts with `[` or `{` is read as JSON and anything else as CSV. Pass `format: 'csv'` or `format: 'json'` to `setData()`, or set `dataFormat` and `csvDelimiter` as options, to skip detection.

If the data cannot be parsed, for example malformed JSON, the widget keeps its previous data, logs the problem with `console.error`, announces it to screen readers and fires the `error` event:

```ts
studio.on('error', ({ message, error }) => toast.show(`${message}. Check the file and try again.`));
```

After every successful load, `dataLoaded` reports the number of records and the detected fields:

```ts
studio.on('dataLoaded', ({ rowCount, fields }) => {
  status.textContent = `${rowCount.toLocaleString()} order lines, ${fields.length} fields`;
});
```

### Changing records in place

If you change record objects you passed in, call `refresh()` so the widget re-reads them. It returns a promise that resolves when the table has been recomputed.

```ts
for (const sale of studio.getRecords()) if (sale.store === 'Leeds Briggate') sale.store = 'Leeds Trinity';
await studio.refresh();
```

## CSV

CSV text is parsed with these rules:

- The delimiter is detected from the first 20 lines among comma, semicolon, tab and pipe, preferring the one that appears the same number of times on each line. Set `csvDelimiter` to force one.
- Fields can be quoted with double quotes; quotes inside quoted fields are doubled (`""`). Line breaks inside quoted fields are kept.
- A leading byte order mark is removed and empty lines are skipped.
- The first row provides field names. Duplicate names get a numeric suffix and empty ones become "Column 1", "Column 2".
- Every value is converted to the detected type of its column; empty cells become `null`.

The parser is exported if you need it elsewhere:

```ts
import { csvToRecords, parseCsv, sniffDelimiter } from '@birchui/pivot-studio';

const delimiter = sniffDelimiter(text);
const rows: string[][] = parseCsv(text, { delimiter });
const { records, columns } = csvToRecords(text, { types: { postcode: 'string' } });
```

### Size limits

CSV and JSON text is refused when it is larger than the loader expects, so a file built to exhaust memory is stopped early.

| Limit | Default | Applies to |
| --- | --- | --- |
| `maxLength` | 67,108,864 (64 MiB of characters) | The length of the text |
| `maxRows` | 2,000,000 | Rows of CSV, or records in JSON text |
| `maxColumns` | 16,384 | Columns in any one CSV row |

```ts
import { InputLimitError } from '@birchui/pivot-studio';

try {
  studio.setData(text, { limits: { maxRows: 5_000_000 } });
} catch (error) {
  if (error instanceof InputLimitError) {
    console.warn(error.code, error.limit, error.actual);
  }
}
```

Pass only the limits you want to change. `Infinity` turns one off. The error's `code` is `'input-too-long'`, `'too-many-rows'` or `'too-many-columns'`. Set limits for every load with the `dataLimits` option, or per call with `limits` on `setData`, `csvToRecords`, `parseCsv` and `parseJsonData`. The defaults are exported as `DEFAULT_DATA_LIMITS`. An array of records that you pass directly is not checked.

## Field detection

Pivot Studio reads field names from the first 200 records and samples up to 2,000 records, evenly spread across the data, to choose each field's type:

| Type | When every non-empty sampled value is |
| --- | --- |
| `number` | A number, or numeric text such as `1840`, `-12.5`, `1.2e3` or `12,500` |
| `boolean` | `true` or `false`, as booleans or text |
| `date` | A `Date`, or an ISO date such as `2026-03-14`, `2026/03/14` or `2026-03-14T09:30:00Z` |
| `string` | Anything else, including a mix of types |

Text with leading zeros, such as postcodes (`02139`) or product codes (`007`), stays text. Dates in other notations, such as `14/03/2026`, are text; convert them to ISO dates or `Date` objects before loading.

The type decides how a field can be summarized: numbers can be summed, averaged and so on, while text and dates are counted. See [Calculations](https://docs.birchui.com/pivot-studio/calculations.md#aggregations).

### Captions

Field names are turned into captions for the field list and headers: `orderDate` becomes "Order date", `store_region` becomes "Store region", and `unitPrice` becomes "Unit price". Override any caption with a field definition.

## Field definitions

Pass `fields` to override detection for some fields; every field you do not mention is still detected:

```ts title="field-definitions.ts"
createPivotStudio(container, {
  data: sales,
  fields: [
    { name: 'revenue', caption: 'Net revenue', format: { style: 'currency', currency: 'GBP', decimals: 0 } },
    { name: 'storeCode', type: 'string', caption: 'Store code' },
    { name: 'orderDate', dateParts: ['year', 'month'] },
    { name: 'shippedAt', dateParts: false },
    { name: 'internalId', hidden: true },
  ],
});
```

**`FieldDefinition`** (interface from `@birchui/pivot-studio`, full reference: https://docs.birchui.com/api/pivot-studio.md)

```ts
interface FieldDefinition
```

| Property | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `caption?` | `string` |  |
| `type?` | `FieldType` |  |
| `format?` | `PivotNumberFormat` |  |
| `dateParts?` | `boolean \| DatePart[]` |  |
| `hidden?` | `boolean` |  |

| Property | Meaning |
| --- | --- |
| `name` | The record key |
| `caption` | Label in the field list, headers and exports |
| `type` | `'string'`, `'number'`, `'date'` or `'boolean'`, instead of the detected type |
| `format` | The default number format for values of this field. See [Number formats](https://docs.birchui.com/pivot-studio/totals-and-formatting.md#number-formats). |
| `dateParts` | Which date levels to derive: `true` (all, the default), `false` (none) or a list |
| `hidden` | Keep the field out of the field list |

`setData(data, { fields })` replaces the definitions together with the data. `getFields()` returns every field after detection, including the derived date parts, and `getMembers(field)` the distinct members of one field.

## The date hierarchy

Every date field gets four derived fields, named after the source field: `orderDate.year`, `orderDate.quarter`, `orderDate.month` and `orderDate.day`. In the field list they appear as "Order date › Year", "Order date › Quarter" and so on, so users can put years in columns and months in rows without preparing the data.

| Derived field | Members | Labels |
| --- | --- | --- |
| `field.year` | `2025`, `2026`, … | `2025`, `2026` |
| `field.quarter` | `"1"` to `"4"` | `Q1` to `Q4` |
| `field.month` | `"1"` to `"12"` | Short month names in the widget's `locale` (Jan, Feb, … or janv., févr., …) |
| `field.day` | `"1"` to `"31"` | The day of the month |

Members sort in calendar order, not alphabetically. Use the member keys in reports and filters, for example `filters: { 'orderDate.quarter': { include: ['1', '2'] } }`.

Dates are read in UTC: a plain date such as `2026-03-31` always falls in March and Q1, whatever the user's time zone. Timestamps with an offset, such as `2026-03-31T23:30:00-02:00`, are converted to UTC first, so that example counts as April 1.

## Blank values

`null`, `undefined`, empty strings and invalid numbers or dates are blank. In rows and columns they are grouped into one member labelled "(Blanks)", whose member key is an empty string. Blank values are left out of sums, averages, minimums, maximums and medians, and are not counted.

## Preparing data

- **One record per fact.** Pivot Studio aggregates for you, so load order lines or transactions rather than pre-aggregated tables, otherwise averages and distinct counts are wrong.
- **Flatten nested objects.** Fields are top-level keys only: turn `{ store: { name, region } }` into `storeName` and `storeRegion`.
- **Send numbers as numbers.** Numeric text works, but numbers skip parsing and are faster to load.
- **Keep keys stable.** Saved reports refer to field names, so renaming a column breaks reports that use it. See [Reports](https://docs.birchui.com/pivot-studio/saving-reports.md).
