Skip to content

Latest commit

 

History

History
391 lines (309 loc) · 21.9 KB

import-mappings.mdx

File metadata and controls

391 lines (309 loc) · 21.9 KB
title Import mappings — load external data files
navTitle Import Mappings
description Named, reusable source-column to field projections for CSV/JSON/xlsx import, and the mappingName request that applies one.

An import mapping is a named, reusable projection from the columns of a source file onto the fields of one object. mapping is a first-class metadata kind, so a mapping either ships inside a package or is saved at runtime — and either way POST /api/v1/data/:object/import applies it by name with mappingName.

Reach for one when the same file shape keeps arriving: a weekly export from another system, whose column headers and codes are not yours. For a single ad-hoc file the import wizard's inline column rename is enough — the two are different mechanisms with different semantics, compared in Inline mapping vs mappingName.


Declaring one in a package

{/* os:check */}

import { defineMapping } from '@objectstack/spec/data';

export const InquiryFeedMapping = defineMapping({
  name: 'showcase_inquiry_feed',            // machine id — lowercase snake_case
  label: 'Inquiry feed (marketing CSV)',
  sourceFormat: 'csv',
  targetObject: 'showcase_inquiry',
  fieldMapping: [
    { source: 'Full Name', target: 'name' },
    { source: 'E-mail', target: 'email' },
    { source: 'Company', target: 'company' },
    {
      source: 'Channel',
      target: 'source',
      transform: 'map',
      params: { valueMap: { Webform: 'website', 'Partner Referral': 'referral' } },
    },
  ],
  mode: 'upsert',
  upsertKey: ['email'],
});

Register it on the stack alongside the objects it targets:

export default defineStack({
  manifest: { /* … */ },
  objects: [Inquiry],
  mappings: [InquiryFeedMapping],
});

defineStack() validates the mapping while you build, not at first use:

  • targetObject must name an object the stack defines, otherwise the build fails with Mapping '<name>' targets object '<object>' which is not defined in objects.;
  • a javascript transform fails the build outright — see Transformations.
`defineMapping()` parses the config at import time, so a misspelled key (`fields:` instead of `fieldMapping:`, `column:` instead of `source:`) is rejected where you wrote it, with the canonical spelling named in the error. A bare `: Mapping` annotation gets none of that.

The two ways a mapping comes into being

Origin How Notes
Shipped in a package defineMapping() + defineStack({ mappings }) Versioned with the package; validated at build time. Packaged mappings are locked against tenant edits.
Saved at runtime PUT /api/v1/meta/mapping/<name> The mapping kind is runtime-creatable, which is what lets an import wizard save the column choices a user just made as a reusable artifact.

Both end up resolvable by the same name. When the import endpoint resolves mappingName it reads the runtime metadata rows first (org-scoped, then env-wide) and falls back to the packaged registry — so a runtime-saved mapping and a packaged one are addressed identically by the request.

A bare mappingName names no package, so the name resolves the way any read that names no package does (ADR-0150 D3): the environment's own mapping, else the one package that holds the name. When two packages hold the same mapping name, the import is refused with 409 RESOURCE_CONFLICT naming every package that holds it, and no row is written; it never picks one of them. GET /api/v1/meta/mapping/<name> answers the same 409.

To name the holder, put the mapping's qualified address in mappingName: "<namespace>/<name>", where the namespace is the holding package's manifest namespace, or "_env/<name>" for the mapping saved in the environment. It is the address GET /api/v1/meta/mapping/<namespace>/<name> reads, and the import door reads it the same way (ADR-0150 D5). The import applies exactly that holder's mapping. When that namespace, or the environment, holds no mapping of the name and a package does, the import is refused with the 409 RESOURCE_CONFLICT that read answers, naming every holder, and no row is written. A disabled package holds no name: when every package that holds the name is disabled, "_env/<name>" answers 404 MAPPING_NOT_FOUND, naming no package, as GET /api/v1/meta/mapping/_env/<name> answers 404. Enable a holder again and the address is refused with the 409 naming it, as before. A first segment that is neither _env nor an installed namespace is no address: the whole string is read as the name, which no mapping has, so the import answers 404 MAPPING_NOT_FOUND. Two limits come with the metadata read's address. Where two packages that share a namespace (base, system, sys) both hold the name, the address answers 409 naming both. A mapping named like one of that read's sub-resource segments (audit, diff, history, layers, publish, published, references, rollback, tree) has no qualified address, and is imported by its bare name.

The mapping kind carries no per-organization overlay: there is no tenant-customized variant of a packaged mapping. A tenant that needs different columns saves its own mapping under its own name.


The shape

Key Type What it does
name string (snake_case) The id mappingName resolves. Missing artifact → 404 MAPPING_NOT_FOUND.
label string Display text in a saved-mapping picker. Falls back to name.
sourceFormat 'csv' | 'json' | 'xml' | 'sql' Declared payload format, checked against what the request actually sent. Defaults to csv. See the format gate.
targetObject string The object this mapping is for. Must equal the object in the URL.
fieldMapping ImportFieldMapping[] The projection itself — one entry per target field.
mode 'insert' | 'update' | 'upsert' Supplies the request's writeMode when the request omits it. Defaults to insert.
upsertKey string[] Supplies the request's matchFields when the request omits them.

Each fieldMapping entry:

Key Type What it does
source string | string[] Source column header(s). An array is only meaningful for join.
target string | string[] Target field name(s), or field.part for a declared part of an address field (mailing_address.street; the parts are street, city, state, postalCode, country, countryCode, formatted). The parts one row maps are assembled into the field's one value: a blank part cell is left out, a row whose parts are all blank leaves the field unset, and on an update the assembled value replaces the stored one. A mapping writes a field whole or by its parts, never both. An array is only meaningful for split.
transform TransformType Defaults to 'none'.
params object Configuration for the transform — value, valueMap, separator.

The full generated property tables live in the Mapping schema reference.


Transformations: what the server actually does

TransformType declares seven values. Five are executed row by row by the import path, one is a deliberate pass-through, and one is refused:

transform Behaviour params it reads
none Copy the source cell to the target field. The default. —
constant Write a fixed value into the target field, ignoring the source column. value
map Translate the source system's codes into yours. A value with no entry in the table passes through unchanged. valueMap
split Split one column into several fields ("John Doe" into first_name / last_name). Each part is trimmed. separator (default ' ')
join Compose one field from several columns. Empty and missing cells are dropped before joining. separator (default ' ')
lookup Pass-through. The cell is copied unchanged, and the import's own reference resolution turns the display text into a record id afterwards — see After the mapping. —
javascript Refused. There is no server-side sandbox, and silently skipping a declared transform would corrupt data. defineStack() fails the build; a runtime-saved mapping is rejected by the import request with 400 UNSUPPORTED_TRANSFORM. —

For logic beyond these, transform the data before you post it, or model it as a flow on the target object.


Applying it: POST /api/v1/data/:object/import

The request that makes the mapping worth having is the one that names it:

POST /api/v1/data/showcase_inquiry/import

{
  "format": "csv",
  "csv": "Full Name,E-mail,Company,Channel\nAda Lovelace,ada@example.com,Analytical Engines,Webform\nAlan Turing,alan@example.com,NPL,Partner Referral\n",
  "mappingName": "showcase_inquiry_feed"
}

No mapping, no writeMode, no matchFields: the artifact supplies all three. The response is the standard import report — aggregate counters plus one entry per row:

{
  "object": "showcase_inquiry",
  "dryRun": false,
  "writeMode": "upsert",
  "total": 2,
  "ok": 2,
  "errors": 0,
  "created": 1,
  "updated": 1,
  "skipped": 0,
  "results": [
    { "row": 1, "ok": true, "action": "created", "id": "inq_01HQ4A7B9D3F5G8J2K4L" },
    { "row": 2, "ok": true, "action": "updated", "id": "inq_01HQ3V5K8N2M4P6R7T9W" }
  ]
}

mappingName works the same way on the three payload shapes the endpoint accepts — format: "csv" with csv text, format: "json" with rows[], and format: "xlsx" with xlsxBase64 — and on the asynchronous POST /api/v1/data/:object/import/jobs route, which parses the identical body.

Add "dryRun": true to get the same report with nothing persisted; the verdict comes from the engine's own write-path validation.

What the artifact contributes to the request

Request key When omitted When present
writeMode Falls back to the artifact's mode (when that is update or upsert). The request wins.
matchFields Falls back to the artifact's upsertKey. The request wins.

Everything else on the request — dryRun, runAutomations, treatAsHistorical, trimWhitespace, nullValues, createMissingOptions, skipBlankMatchKey — belongs to the request alone. The mapping declares no error policy and no batch size; error handling is per-row and reported per-row, and the write path sizes its own batches.


Inline mapping vs mappingName

The endpoint accepts two mapping mechanisms and they are mutually exclusive — sending both is 400 CONFLICTING_MAPPING.

inline mapping mappingName
Shape A flat { "<source column>": "<field>" } rename (or a sourceField/targetField array) A registered mapping artifact
Transforms Per entry of the array form: transform (trim, uppercase, lowercase; none and lookup copy the cell), defaultValue for a blank cell, required, applyOn. The flat record is a rename only The fieldMapping pipeline
Unmapped columns Pass through to the write path under their own header Dropped. The artifact is a strict projection: only mapped targets survive
Lives In the one request In a package or in metadata, reusable

That projection difference is the one to keep in mind: a file from an external system routinely carries columns that must not reach the write path, and the artifact path guarantees they do not.

Columns written only when a row is created: applyOn

An entry of the array form may declare applyOn: 'create' (the default is 'always'). Its column is written when the import creates the row and left out when an upsert updates an existing one; an update import never writes it. That makes one upsert safe to re-run: master-data columns refresh, while a column the app has moved on since the first run (a status, a flag) keeps its current value.

{
  "writeMode": "upsert", "matchFields": ["credit_code"],
  "mapping": [
    { "sourceField": "Code", "targetField": "credit_code" },
    { "sourceField": "Name", "targetField": "name" },
    { "sourceField": "Status", "targetField": "status", "applyOn": "create" }
  ]
}

A create-only column is still read for matching: the match key a row was found by stays in that row's update, with the value it was found by.

Rows identified in different ways: ordered key sets

matchFields takes one key set (["email"]) or an ordered list of key sets, for a sheet whose rows are identified in different ways:

{ "writeMode": "upsert", "matchFields": [["credit_code"], ["country", "registration_no"]] }

Each row is matched by the first set whose fields are all non-blank on that row, and only by that set: a domestic row with a credit code is matched on it (and created when nothing matches), an overseas row with a blank credit code is matched on country and registration number. A row blank on every set fails with BLANK_MATCH_KEY instead of being created or skipped, so skipBlankMatchKey cannot be combined with key sets. A set that matches more than one record fails the row with AMBIGUOUS_MATCH, as one key set does.


Rejections before any row is read

These are whole-request failures — nothing is written, and there is no per-row report:

Status code Cause
404 MAPPING_NOT_FOUND No mapping artifact is registered under that name, or every package that holds it is disabled.
409 RESOURCE_CONFLICT Two or more packages hold a mapping under that name, and the environment holds none; or a qualified mappingName (<namespace>/<name>, _env/<name>) names a holder that holds no mapping of that name while another, enabled, package does. The error names every holder.
400 MAPPING_TARGET_MISMATCH The artifact's targetObject is not the object in the URL.
400 MAPPING_FORMAT_UNSUPPORTED The artifact declares sourceFormat: 'xml' or 'sql'; the endpoint accepts csv, json and xlsx payloads only.
400 MAPPING_FORMAT_MISMATCH The declared sourceFormat contradicts the payload actually sent. A csv mapping does apply to an xlsx payload — those rows are tabular in the same way — but a json mapping does not.
400 UNSUPPORTED_TRANSFORM Some artifact entry declares javascript, or a transform name the pipeline does not implement; or an inline entry declares date_format (it carries no format to apply) or a name outside none, lookup, trim, uppercase, lowercase.
400 MISSING_REQUIRED_FIELD An inline entry is marked required: true and some row leaves its column blank after its defaultValue. The error names the column and the rows; it applies to the dry run and the commit alike.
400 CONFLICTING_MAPPING Both mappingName and an inline mapping were supplied.
400 INVALID_REQUEST No recognizable payload; writeMode resolved to update/upsert with no matchFields from either the request or the artifact; malformed key sets in matchFields (an empty set or name, or names mixed with sets); writeMode update/upsert with a match key (the request's matchFields or the artifact's upsertKey) naming a field that holds a list or a structured value — a multiple: true lookup, user, select, radio, file or image field, a multiselect, checkboxes or tags field, or a json, address, location or other JSON-stored field — refused before any row, naming each such field (match on single-value fields instead); skipBlankMatchKey: true with key sets; or an inline entry's applyOn outside create / always.
413 PAYLOAD_TOO_LARGE More than 5,000 rows on the synchronous route.

Per-row outcomes

Once the mapping is applied, every row gets its own verdict in results[]. A row that fails does not stop the import.

action ok code Meaning
created true — Inserted.
updated true — Matched an existing record and updated it.
skipped true NO_MATCH writeMode: 'update' and the match fields matched nothing. Nothing is created.
skipped true BLANK_MATCH_KEY One key set in matchFields, and a field of it is blank on the row. Upsert creates such a row by default; update skips it, and skipBlankMatchKey: true skips it in either mode.
failed false BLANK_MATCH_KEY Ordered key sets in matchFields, and every set has a blank field on the row. Nothing is written for that row.
failed false AMBIGUOUS_MATCH The match fields matched more than one record. Nothing is written for that row.
failed false DUPLICATE_MATCH_KEY update or upsert, and another row of the same import has the same match key, compared after cell coercion (ISO 14001 and ISO14001 coerce to one option value). Every row of that key fails, error names them all, and none of them is written, on a dry run too: keep one row per key and import again.
failed false VALIDATION_ERROR Only for a caller that hands rows to the import runner without this endpoint (a mapping's connector pull): the match key names a field that holds a list or a structured value, the case this endpoint refuses with 400 INVALID_REQUEST above. Every row fails with that refusal, field names the first such field, and nothing is read or written.
failed false a field error code A cell could not be coerced, or the engine rejected the record. field names the column and error carries the message.

So "a row that does not match" is not one behaviour but three, chosen by writeMode and by how many records matched: created (upsert), skipped (update), or failed (more than one match).


After the mapping: cell coercion

The mapping decides which value lands in which field. Converting that value into what storage accepts is a separate step that runs afterwards, from the target object's own field metadata:

  • booleans — spreadsheet spellings are accepted on both sides, including non-English and check-mark cells;
  • numbers, dates and times — parsed to storage form; an offset-free datetime cell is read in the importing user's business timezone, which is the same clock the export writes;
  • select / multiselect — the human-visible option label resolves to the stored option value (the translated label too, when the app is localized);
  • lookup / master_detail / user — the display text resolves to a record id. This is what a lookup transform is relying on when it copies its cell through.

A lookup cell is resolved within the row's own master

The display text is matched against the target's id, its title field and its other identifying fields, as the caller who runs the import: a record that caller cannot read never matches. A name that matches no record fails the row with reference_not_found; a name that matches more than one fails it with reference_ambiguous, and nothing is linked.

A detail record's name is often unique only inside its master: two contracts can each carry an "Advance 30%" billing milestone. When the same row also names the master, the cell is resolved within that master's records:

  • the lookup's target has a master_detail field, and exactly one other single-value reference column of the row points at that master object and is filled in; or
  • the lookup field declares dependsOn, and the row fills in the sibling field it names. The string form compares the target field of the same name; { field, param } compares the target field param. This is the filter the record form's picker applies.

The master_detail rule has no counterpart in the picker, which narrows by dependsOn and lookupFilters, never by an inferred master: for a lookup without dependsOn, the import is stricter than the form.

Inside that scope a tie is reference_ambiguous and a name that only another master carries is reference_not_found; it never resolves to another master's record. A row that leaves the master blank is resolved across the whole target as before. When two columns of the row point at the master object (a bill-to and a ship-to account), neither is taken as the master; declare dependsOn on the lookup to say which one is. A master cell that fails its own lookup scopes nothing, and the row already fails on that cell.

The scope is part of the importing caller's own filter. A caller who cannot read the target's master field, or the target field a dependsOn entry names as param, has the scoped lookup refused, and the cell fails with reference_not_found, even for a detail that caller can read and whose name is unique. Without the master (or the dependsOn sibling) in the row, the same cell resolves.

A pasted id is scoped too, so a row that means another master's detail cannot be linked in one import. Correct the master cell; or, when the cross-master link is intended, leave the master column out of the import and set it in a second update. For the field-permission case, grant the caller read access to that field, or leave the master column out in the same way.

A field the object does not know is left untouched. A cell that cannot be coerced fails its own row with the offending column named.


Size limits

Route Ceiling
POST /api/v1/data/:object/import 5,000 rows — the report comes back in the response
POST /api/v1/data/:object/import/jobs 50,000 rows — returns a jobId; poll progress and results, and the job can be cancelled or undone

Related