# Data import into Dataverse

CSV, Excel and dataflow; load order with Lookup; checking; and how to avoid the divergence between
the script and the environment. Source of the facts: the data plan and the CSV package of a reference project, and the way the
real environment ended up being created.

## Contents

1. [The rule that decides everything](#1-the-rule-that-decides-everything)
2. [Choosing the path](#2-choosing-the-path)
3. [Mandatory order](#3-mandatory-order)
4. [File format](#4-file-format)
5. [Lookup and Choice on import](#5-lookup-and-choice-on-import)
6. [Prepare the legacy data before generating the CSV](#6-prepare-the-legacy-data-before-generating-the-csv)
7. [Checking the load](#7-checking-the-load)
8. [How to avoid the script × environment divergence](#8-how-to-avoid-the-script--environment-divergence)

---

## 1. The rule that decides everything

**The maker's "Import data" wizard creates TEXT columns, and Dataverse does not convert text into
Choice or Lookup afterwards.** Importing first and adjusting later means rebuilding the tables.
`[verified: reference project]` -- it was also the origin of the real environment's divergence: tables created
by Excel import have text columns where the plan foresaw Choice and Lookup.

To avoid it: **create Choices, tables, columns, Lookups and alternate keys first**; import data
**into** that structure, mapping each column of the file to the existing column. Importing into a
new table generated by the wizard only makes sense when all the columns **should** be text.

Exception: the **mockup load** of `/pp-en:architecture` (`skills/power-platform/references/mockup-load.md`) is made for this.
- It creates the structure **with fictitious data**, lets the type inference get it wrong there and goes through
  the check (`montar-carga-mockup.py --conferir`) before any real data.
- Recreating a column that only has mockup rows is free.
- Or, with no inference: the builder (`skills/power-platform/references/dataverse-builder.md`) creates
  the tables, the columns with the spec's type, the Lookups and the mockup rows through the Web API.
- Real data keeps going in through this reference, into a table that already exists.

## 2. Choosing the path

| Path | When | Attention |
|---|---|---|
| **Import from CSV/Excel** (maker, *Import data*) | One-off or rare load, clean file, structure already created | Maps to existing columns; resolves Choice by label and Lookup by the primary name column or alternate key |
| **Dataflow** (Power Query) | Recurring load, transformation (cleaning, join, types), external source | Maps and transforms; allows a key to update existing rows `[unverified]` -- read the dataflows Learn page before counting on upsert |
| **Flow** (`Add a new row`, `$batch`) | Programmatic load, small/medium volume, business rule on entry | Respects the flow's rules; large volume calls for batching (`power-automate`) |
| **Connector/data tool** | Large migration, between systems | Outside the scope of this skill |

Sources: [Import data](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/import-data) and
[Dataflows](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/create-and-use-dataflows).
This document describes the practice of the reference projects (CSV); dataflow details are
`[unverified]` in this repository.

## 3. Mandatory order

```
1. Create the Choices (global, if shared)
2. Create the tables and the columns (Lookup included) — by hand, through the mockup load or through the builder, checked with --conferir
3. Create the alternate keys  →  wait for EntityKeyIndexStatus = Active
4. Extract the as-built and check it against the plan      (references/as-built-names.md)
5. Import, in dependency order: catalogs → profiles/users → links → transactional → trail
```

The order in step 5 is that of the **Lookup dependencies**: a row can only point to something that
already exists. With a circular dependency, import without the Lookup and fill it afterwards.

Step 3 is not a detail: a `Pending` key **does not resolve Lookup on import and the error is silent**
(the row goes in without the link, with no message) `[verified: reference project]`.

## 4. File format

`[verified: reference project]` except where marked:

| Item | Rule |
|---|---|
| Encoding | UTF-8 **with BOM** (the maker wizard reads accents without breaking) |
| Separator | `,` -- the import does not reliably accept `;`. The **output** CSV for a pt-BR Excel uses `;`: they are files for different purposes |
| Date | ISO: `YYYY-MM-DD` (date) and `YYYY-MM-DDTHH:MM:SSZ` (date and time). The spreadsheet import has swapped day and month before: check one date after importing (`field-lessons.md` §8) |
| Yes/No | The environment's label (`Yes`/`No` in en-US; `Sim`/`Não` in pt-BR) |
| Choice | The option's **label** (not the integer value) |
| Lookup | Value of the target's primary name column, or of the alternate key chosen in the mapping step |
| System columns | None (`createdon`, `ownerid`, `statecode`, etc.) |
| Text with a leading zero | Treat as text at the source; Excel strips zeros. Standardize beforehand (e.g. a code with leading zeros) |
| First row | Header with the **display names** of the target columns, as in the as-built |

Generate the header **from the as-built**, not from the dictionary (§8).

## 5. Lookup and Choice on import

- **Choice**: the wizard resolves by **label**. A label with an accent or space different from the
  environment's option does not match; check against the as-built options.
- **Lookup**: resolves by the target's **primary name** column. If the primary name is **not unique**
  (a business rule allows duplicates), the resolution is silently wrong or fails at the first duplicate.
  Use an **alternate key** and choose it in the mapping step.
- When the target only has a **numeric** business key from the legacy system, include in the child
  table's file an **auxiliary column** with that key (e.g. `<target>_legacy_id`) and use it as the match.
  `[verified: reference project]` -- that is how child records and the trail pointed to the parent.
- **Text instead of Lookup** (as-built with text): nothing resolves; the value goes in as it came. Validate
  beforehand against the source table (§6).

## 6. Prepare the legacy data before generating the CSV

Run the consistency check **before** generating the files, not on the eve of go-live. Example
queries (adapt the source; here in illustrative SQL, destination: the source's SQL client):

```sql
-- rows that violate a business rule and will be blocked on load
SELECT COUNT(*) FROM <tabela>
 WHERE (<tipo> = 'A' AND <campo_b> <> 'X') OR (<tipo> <> 'A' AND <campo_b> = 'X');

-- nonexistent unit values (the defect that the lack of a Lookup lets in)
SELECT <unidade> FROM <tabela_usuarios>
 WHERE <unidade> NOT IN (SELECT <codigo> FROM <tabela_unidades>);

-- dates outside ISO format
SELECT <id>, <data> FROM <tabela> WHERE <data> NOT LIKE '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]';
```

Typical transformations (`[verified: reference project]`):

| Field | Transformation | Reason |
|---|---|---|
| Date as text | Convert to ISO and **validate the format beforehand** | The column never had a format constraint; there may be a `01/05/2026` |
| Numeric identifier with zeros | Pad with a leading zero | Excel strips them |
| Reference code | Upper case | Normalization business rule |
| Fields derived at the source (region, etc.) | Discard | They derive from the unit; do not duplicate |
| Password hash | Discard | Identity belongs to Entra |

Measure what Dataverse will require (modeling §9): a required field that the legacy data does not fill brings the
whole load down.

## 7. Checking the load

- **Count**: compare the number of rows in the file with the table's. Use
  `CountIf(<Table>, true)` (exact up to 50,000), **not** `CountRows(<Table>)` with no filter, which is
  approximate (cache) -- `references/dataverse-delegation.md` §3. Above 50,000, count by flow or through the
  Web API: `$count=true` saturates at **5,000** (default); `RetrieveTotalRecordCount` returns a
  snapshot of the last 24 h, not the exact current number.
- **Links**: child rows without the Lookup filled = alternate key not active or wrong match.
  Count: `Filter(<Child>, IsBlank(<lookup>))` (the result should be 0 or the expected number).
- **Choices**: no Choice column was left blank because a label did not match.
- **Sample**: check edge rows (accent, leading zero, boundary date).
- Keep the command and the result with the date (P5).

## 8. How to avoid the script × environment divergence

The root cause of the rework in the reference projects was writing against what *should* exist.

1. **One owner of creation** (`references/modeling.md` §1). If the environment was created by hand, the
   creation script **is discarded or rebuilt from the as-built**, not reused.
2. **Extract the as-built after creating** and before generating any CSV, screen or flow.
3. **Generate the CSV and the mapping from the as-built**, never from the dictionary. The file header is the
   display name the as-built says.
4. **Re-extract after any change** and compare (diff) with the versioned as-built.
5. **Record divergence as a decision** (keep, realign, update the dictionary;
   `references/as-built-names.md` §6).
6. **Re-importing does not repair a wrong type**: if a column was born text and should be Choice, the way is to
   recreate the column and reload, not "import again on top".
7. **A CSV generator is an example, not a standard.** The one from a reference project generated the files from the source database and
   the dictionary; it serves as a model of *how to validate before generating*, but the contract is the as-built.
