Imports
Import runs with an external record map. A rerun inserts new keys, skips unchanged ones, updates changed ones and leaves user edits alone, and CSV files get a suggested mapping and a dry run.
imports is the counterpart of the data-lifecycle exporter. parseCsv reads RFC 4180 CSV (SPEC_PINS.rfc4180). defineImport names the source, a Standard Schema for one row, a row key and an insert function. suggestMapping pairs headers to fields. dryRun validates every row and returns errors without writing. runImport records the run, skips keys that already imported, inserts the rest in batches of 100 and finishes with import.completed or import.failed. Pass accessToken to read a token before every batch; an auth failure is retried once. A dropped batch returns resumeFrom, and passing that as resume continues the same run from that chunk.
better-supabase add importsimport { defineImport, runImport } from "better-supabase/blocks/imports";The row key makes a rerun skip a row that already imported.
Runs and the record map
A run reads one source system for one tenant. imports.runs.start creates it
as pending, and only one run per tenant and source is pending or running
at a time: a second start fails with IMPORT_RUN_ACTIVE. runs.get,
runs.list and runs.cancel read and end runs. A run has these options:
| Option | Meaning |
|---|---|
dryRun | Runs every write, rolls it back and reports only the counts. |
full | The run sends the whole source, so finish marks the records it did not send as missing. |
inputChecksum | Identifies the input, so a caller can tell a repeated file. |
correlationId | Links the run to the caller's own job. |
scopeAliases | [{ scope, of, entities }]: a scope reuses the records another scope imported. |
Every key a run writes is kept in import_records, unique per tenant,
source, scope, entity, external key and role. The server calls
imports.upsertBatch(run, entity, items) with items of { key, scope, data, refs }, and each item ends in exactly one outcome:
inserted: the key is new, so the target writes a row.unchanged: the hash ofdatamatches the last import, so nothing is written and no audit row exists.updated: the hash differs and nobody changed the row since the import.conflicted: the hash differs, but a user changed the row after the import. The row stays as the user has it.- An item that fails (
IMPORT_ITEM_INVALID, or the target's own hint) is listed in the run'serrorsand the batch goes on.
imports.finish(run) ends a running run. On a full run it sets
went_missing_at on records the run did not send and counts them as missing.
It never deletes a target row. It emits import.entity_completed for each
entity and then import.completed, or import.failed when the run has
errors. A dry run emits nothing. imports.resolve(run, entity, keys) maps
keys to the subjects they imported, and imports.markRunning(run) moves a
pending run on before its first batch.
counts is { <entity>: { inserted, updated, unchanged, conflicted, missing } }
and errors is [{ entity, key, code, message }].
Import targets
An entity is written by a target: { subjectType, write, updatedAt? }. A
block contributes one with the imports contribution kind, and an app lists
its own under blocks.imports.options.targets:
export default defineConfig({
blocks: {
imports: {
options: {
targets: {
customer: {
subjectType: "customer",
write: "public.import_customer",
updatedAt: "public.import_customer_updated_at",
},
},
},
},
},
});write is (run uuid, item jsonb, subject_id text) returns jsonb. It
receives the item with its tenant, and subject_id is null for an
insert. It returns { subjectId, role?, subjectType?, updatedAt? }, or an
array of them when one record writes several subjects (the first primary
role is the one resolve returns). updatedAt is
(subject_id text) returns timestamptz; without it a changed hash always
overwrites. ownedHash is (subject_id text) returns text over the columns
the importer writes. A newer updated_at is a conflict only when that hash
changed. When only the stamp moved, the library realigns it and applies the
row. naturalKey is (tenant, item jsonb) returns text. When no import record
exists and it returns a subject, the write updates that row. refs maps each
ref field to the entity it points at. The batch resolves those keys in one
query and passes resolved to the write. A missing key is the warning
IMPORT_REF_MISSING. A conflict, an error and a warning are stored on import_run_issues. A later run that
applies the key sets resolved_at. list_import_issues pages them by keyset: pass the next_cursor of the
previous page as after. row_offset still works while after is null. The
total is capped at 10,000 and is null on a keyset page. resolve_import_conflict takes keep (the database
value becomes the baseline) or overwrite (the next batch may write the
source). rebase_import_records(tenant, source, entities, keys) copies the
current stamp and hash onto the stored row. An entity without a target fails
the batch with IMPORT_TARGET_UNKNOWN.
A target whose functions follow a naming convention is written as a bare entity
name: targets: ["invoice"], or invoice: true next to full entries. The
target then writes through public.import_invoice, adds
public.import_invoice_updated_at as updatedAt when the app's schema files
create it, and takes subjectType from the record type invoice. Set
options.targetConvention ({ schema, write, updatedAt }, with {entity} in
the two templates) to change the convention. An entry that sets a key itself,
such as invoice: { replaces: true }, keeps its value over the convention.
replaces: true swaps a block's target for the app's write of the same
entity. The batch loop, the hash and the record map stay the library's, so a
later library change to that loop still runs. before and after name
(run uuid, item jsonb, subject_id text) returns jsonb functions: before
replaces the item, after replaces the write result. A null from either
keeps the value it received.
A target can add batch: "schema.function", (run uuid, items jsonb) returns jsonb, to write a whole batch in set-based statements. The items that need a
write (not unchanged, not conflicted) arrive as one array of what write
receives as item, plus subjectId (null for an item that needs an insert).
It returns an array with one answer per item in order: what write returns, or
{ "error": { code, message } } for an item it refused without writing. When
it raises, each item runs through write on its own, so one bad row costs only
its own error. A key that repeats inside a batch is written after the earlier
one is recorded, as with write. A batch target pays off when the triggers on
the table run once per statement too: the fixture's
public.import_customer_batch inserts and updates customers in two statements,
and customers sets search.statement: true (see
Search), so three batches of 1,000 customers
fire six search trigger calls instead of 3,000. The search index is refreshed
once per record when the run closes.
These blocks contribute targets:
| Block | Entity | Writes |
|---|---|---|
catalog | supplier_item | A supplier's price list row, by supplier and code |
catalog | product_identifier | An EAN or a supplier or manufacturer code on a variant |
catalog | discount_group | A customer or product discount group, with the customers of a customer group |
catalog | party_discount_group | One party in one customer discount group, or out of it when the group is empty |
catalog | discount_rule | A rule of the discount matrix, by group codes |
inventory | stock_count | An open stock count with its lines, by location |
invoices | invoice_allocation | A link from an existing receipt to an invoice, with no new ledger entry |
custom-fields | field_value | A custom field value of a record the record map knows, checked against its field type |
The catalog page lists
the data each one takes.
Pass target: { entity, item } to defineImport and hooks.upsertBatch to
runImport to write a file through the record map instead of insert.
appTableImport keeps its repository insert for now.
| Hint code | When |
|---|---|
IMPORT_RUN_ACTIVE | A run of the same tenant and source is pending or running. |
IMPORT_RUN_NOT_RUNNING | A batch or finish targets a run that is not running. |
IMPORT_TARGET_UNKNOWN | No target is registered for the entity. |
IMPORT_ITEM_INVALID | An item has no key or no data object, or the target rejects it. |
Listing the blocks that take rows
A block that contributes import targets declares their entity names in its
manifest as importTarget. importTargetsOf lists every entity with its block,
sorted by entity, for an import page that shows what a file can fill:
import { importTargetsOf } from "better-supabase/blocks/imports";
import { blocks } from "@/lib/supabase/blocks";
importTargetsOf(blocks);
// [{ entity: "asset", block: "assets" }, { entity: "invoice", block: "invoices" }, ...]It fails when two blocks declare the same entity. A test keeps each manifest equal to the SQL module it describes.
Reading a run as a job
imports.jobs.get(runId) is the import source of createJobs:
jobs.get("import:<run id>") returns the common JobResult, with progress
counted from the run's entity counts and the counts and errors as result
once the run completed. A canceled run reads as failed with
IMPORT_RUN_FAILED.
Paging a list
list is the capped convenience list. runs.page is the full contract for import runs (ADR 0749, 0939): it takes organizationId, which names the organization per call, and sort, filters whose values are lists (a row matches any of a filter's values), after and limit, and returns { items, hasMore, nextCursor }. Pass the nextCursor back as after. The sort is createdAt; the default order is newest first. The filters are source and status. The facets are source and status. runs.facets and runs.count take the same options. Each needs the manage permission on the organization. A cursor belongs to the sort it came from, so start again from the first page when sort or direction changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error.
const running = await imports.runs
.page({
organizationId,
filters: { source: ["erp"], status: ["running"] },
limit: 20,
})
.orThrow();
const facets = await imports.runs.facets({ organizationId }).orThrow();
const total = await imports.runs.count({ organizationId }).orThrow();Upsert into an app table
appTableImport builds an import that updates the rows a file already has
instead of skipping them. It takes the table's repository and key, one of
the table's unique sets (or its primary key), and throws when the key is
not one. previewImport validates the file like dryRun and counts the
rows it would create, change and leave unchanged, without writing:
import {
appTableImport,
previewImport,
runImport,
} from "better-supabase/blocks/imports";
const tasks = appTableImport({
table: "tasks",
columns: TaskRow,
repository: db.tasks,
key: ["projectId", "title"],
update: "fill",
});
const { preview, errors } = await previewImport(tasks, csv, mapping);
// preview: { created: 12, changed: 3, unchanged: 40 }update decides what happens to a row that exists. fill, the default,
writes only the fields that are empty in the database, so a rerun never
overwrites an edit. overwrite writes every field the file has. Pass the
definition to runImport without importedKeys, so a rerun updates rows
instead of skipping them. The upsert import recipe maps the
columns, shows the preview and runs the import.
Import mode
import_upsert_batch begins an import session for the batch it writes, so a
migration of historical rows does not fire the side effects of live traffic.
better_supabase.begin_import_session(run) does the same for a transaction
you control. It is callable by the service role only, needs a running run, and
sets the run id and the correlation id import:<run> for the rest of the
transaction. better_supabase.import_run() returns the run id inside a
session, and only to the service role: a user session that sets the setting
itself still gets null, so a user can never turn the mode on.
Two options decide what the mode does:
blocks: {
imports: {
options: {
events: { default: "skip", "customer.imported": "tag" },
audit: "summary",
},
},
}events maps an outbox event type (or default) to skip, tag or emit.
An event with no entry is skipped, so a run fires no webhook and no workflow
unless you list the event. tag emits the event with importRunId in its
payload, and emit leaves it as it is. audit is rows (the default) or
summary. In rows mode the audit log keeps one entry per changed row, tagged
with the actor kind integration and the correlation id import:<run>. In
summary mode a row writes no entry, and finish_import_run writes one
import.entity_completed entry per entity that inserted or updated rows, so a
second identical run adds none. The row audit triggers carry the check in their
when clause, so audit_row_change does not start for a row of a summary
import.
A quote or invoice whose number is already taken fails by default. Put
onTaken: "next_free" in the item's data and the import issues the next free
number instead and reports IMPORT_NUMBER_REASSIGNED as a warning; an unknown
value is IMPORT_ITEM_INVALID.
An imported quote that is already stored is kept as imported. Put
update: "apply" in the item's data to replace it: the import reopens a
sent or decided quote for the line replacement, then restores the status,
dates and answer in data, and applies the stored taxLines and totals
again, with the same warnings as a first import. A table of your own that
guards the quote status column with a trigger has to skip the change in
import mode, with better_supabase.importing().
The inventory block contributes the stock_allocation entity, written by
import_stock_allocation (the invoices block already owns import_allocation
for payment allocations). The data is variantId or sku, locationId or
location (a code), documentType, documentId, lineId, quantity, and the
allocated and fulfilled parts, with status of open, fulfilled or
released. An open allocation adds what it holds to the location's reserved
stock; a fulfilled or released one holds nothing. No stock movement or event is
written, so import the stock itself through its own target. A later run
replaces an open allocation and keeps a fulfilled or released one as
imported, with IMPORT_DOCUMENT_CHANGED.
A state machine accepts any declared status on insert in import mode. It
writes one history row from no status to the inserted status with the reason
imported, and no status.changed event.
Write your own SQL functions against the same condition with
ctx.importing() (better_supabase.import_run() is not null). The mode
guards these hooks:
| Hook | In import mode |
|---|---|
emit_event (every event, so webhooks and workflows) | skipped, tagged or emitted by imports.events |
Audit row changes and audit_event | tagged integration; one summary per entity with summary |
| State machine insert | one imported history row, no event |
ctx.notify (comment, inbox, task and other notifications) | not sent |
Accounting auto-posting of a document (bookSource) | not posted; post the entries with their own import |
| Orders: stock taken when an order is paid | not taken |
| Shipments: stock taken when a shipment ships | not taken |
Explicit calls stay as they are: adjust_stock, count_stock,
move_stock, production consumption and the ledger postings of an explicit
payment or credit call. Import those through their own targets with the
quantities and balances of the source system.
Importing historical documents
The invoices, quotes and orders blocks contribute import targets, so a
migration keeps each document as it was issued. The entities are invoice,
credit_note, quote and order; the database functions behind them are
import_invoice, import_credit_note, import_quote and import_order.
Each document keeps its number, its original dates and its final status. The
document is written in import mode: no events, no stock movement and no
accounting auto-post. An invoice payment keeps its real date through
payments. A stored tax total per code and the stored document totals are
taken as given and compared with the tax block's computation. A difference
becomes an item warning (IMPORT_TAX_MISMATCH, IMPORT_TOTALS_MISMATCH) in
the warnings of the batch outcome, and the item is still written.
The buyer is stored as given in the buyer column. With the
legal entities block on, the item's
legalEntity sets legal_entity_id. Importing the same document again
writes nothing. Set data.update to apply to write the header and, when the
line count is unchanged, the line title and tax. A different line count
replaces the lines inside the import session. A void or paid document keeps
its postings unless data.repost is true. data.settlement of row writes
paid, partially_paid or open on the invoice without a payment or a
ledger entry. That row mode is the fast path and does not link the invoice to
a receipt. Link mode is the invoice_allocation target: it writes
invoice_allocations with source import and moves the paid total, and it
posts no ledger entry. Use it when the receipt is already on the ledger. suppliedOn fills supplied_on, and fills the issue date when
issuedOn is empty. A blank title keeps the number template. A line with a
product is product. A payment term code and a tax rate that matches one
code are resolved when those blocks are installed. A negative total becomes a
credit note when resolved.original or originalId names the invoice, and
stays an invoice with IMPORT_CREDIT_WITHOUT_ORIGINAL when it does not. A
credit note in settlement row with no original records the same warning
and posts nothing. A document edited after the import is reported as a
conflict, and a document whose source changed yields
IMPORT_DOCUMENT_CHANGED while update stays keep.
Opening open items
The open_item entity writes an opening list of what customers owe and what
suppliers are owed. Each item takes number, side (customer or
supplier), issuedOn, dueOn, currency, the open balance in minor units
and the company or contact. The item keeps its original dates, so the
ageing is right on day one. It goes through import_invoice_document, so
sending the same list again writes nothing.
Over your own tables
Map tables.runs onto the app's import table. Optional columns can be null.
Run an import in one call
run({ organizationId, source, entities, batchSize?, maxBatchSize?, targetBatchMs?, onBatch? }) is for the service role. It starts a run, marks it running, writes each entity's items in batches of batchSize in the order given, then finishes the run. Item errors do not stop the run: they come back in errors. When the run cannot start or a batch call fails, the run is cancelled and the error is returned.
The batch size adapts. A batch that takes longer than targetBatchMs (default 30,000) halves the next one, and with maxBatchSize set a batch under half of it doubles the next one up to that size. A batch that hits the statement timeout (SQLSTATE 57014) is split in two and each half is sent again, down to one item. The result's suggestedBatchSize is the size to start the next run of the source with. Two batches of one run can write at the same time: import_upsert_batch reads the run without a row lock and only the counts update at its end locks the row.
Mapper versions and the record map
runs.start({ mapperVersion }) stores the version of the mapping code that produced a run's items (ImportRun.mapperVersion). After a mapper fix, reapply_import_records(tenant, source, mapper_version, entity?) clears the content hash of the source's records that a run of another version last wrote, and returns how many; the next run counts them as changed and rewrites them through their target (a row a user edited since stays as it is). export_import_hashes(tenant, source, entity?) lists the record map as { entity, scope, key, role, hash, subjectType, subjectId } objects in key order, so you can compare what a source sends with what was imported without reading the rows. Both are service-role functions.
Large imports in chunks
A source with millions of rows writes in chunks, so a worker pool shares the work and a retry never writes a chunk twice. Cut each entity's items into chunks, store them, queue one job per chunk and let workers process them:
for (const [chunk, items] of chunksOf(rows, 500).entries()) {
await imports.chunks
.store({ runId, entity: "customer", chunk, items })
.orThrow();
}
await db.$rpc("enqueue_import_chunks", {
run: runId,
entity: "customer",
chunks: count,
});
// In the worker process, with an `imports` queue whose schema is importChunkSchema:
await runImportWorker({ imports, queue, concurrency: 4, signal });chunks.process claims the chunk, writes it with upsertBatch and marks it done in one transaction, so a failure leaves it pending, a done chunk answers what it answered, and a chunk another worker holds is skipped (a claim older than five minutes is taken over). chunks.progress(runId) returns { pending, claimed, done, failed }. A worker that gives up on a chunk calls chunks.fail({ runId, entity, chunk, message }): the chunk is failed, process answers { status: "failed", message } instead of retrying it, and storing the chunk again makes it pending. A batch that finds conflicts lists the keys of the first 100 in conflictKeys, next to the conflicted count. importChunkHandler(imports) is the job handler for a worker you run yourself. The chunk rows go with the run and with a tenant purge.
The chunk lifecycle
A chunk holds its items only while it can still be written (ADR 1223):
| Step | What happens |
|---|---|
| Done | The chunk keeps its result and drops its items. |
| Failed on the job's last attempt | importChunkHandler calls chunks.fail({ ..., final: true }), which fails the chunk and the run with IMPORT_CHUNK_FAILED in its errors, then rethrows. |
| Failed earlier | enqueue_import_chunks makes a failed chunk that still has its items pending again and queues it under a new :retry: key. |
runs.finish | Refuses a run with a chunk that is not done (IMPORT_CHUNKS_OPEN, PT409). |
maintenance(), every hour | Clears the items of chunks whose run completed, was canceled, or failed longer than chunks.keepFailedItems ago (default 7 days). |
Set chunks.staleAfter (an interval such as "30 minutes", off by default) and
the same job also cancels a pending or running run whose heartbeat is older,
with the outcome stale. That covers a worker that died before it could mark
its chunk failed. runs.get reports the chunks as
chunks: { pending, claimed, done, failed, bytes }, where bytes is what the
stored items take. On the local stack the chunks of a done 50,000-item run took
839,540 bytes before and take none now.
imports: { options: { chunks: { keepFailedItems: "2 days", staleAfter: "30 minutes" } } },runs.conflicts({ runId, entity?, after?, limit? }) pages every conflict of a
run, oldest first, as { rows, nextCursor }, with up to 1,000 rows a page. Use
it when a run has more conflicts than the 100 keys of conflictKeys.
The stock_count target writes a count without location or locationId to
the organization's only active location, and refuses it when the organization
has more than one.
Replacing a copied runner
An app that copied the import runner to change how one entity is written can
go back to the library's loop with replaces: true on that entity's target. The
app keeps its write function, and the batch loop, the content hash, the
record map, chunks and conflicts stay the library's. Move the parts of the copy
that changed an item before the write into a before function, and the parts
that changed the answer into an after function:
imports: {
options: {
targets: {
invoice: {
replaces: true,
write: "public.import_invoice",
before: "public.import_invoice_before",
after: "public.import_invoice_after",
},
},
},
},Both take (run uuid, item jsonb, subject_id text) and return jsonb; a null
keeps the value they received. Then delete the copied runner, so a later
library fix to the loop reaches the entity.
Hooks
createImports takes hooks, keyed by method name, that run your code
before and after a call: refuse it with a DbError, rewrite its arguments
or observe the result (see extending blocks).
Paging runs
runs.page, runs.facets, runs.count and runs.get follow the block list contract. Sorts are createdAt, filters and facets are source and status. runs.list is deprecated.
Last updated on