Skip to Content
Database

Import

Validated, chunked, idempotent bulk insert with a report per row.

Usage

import { scoped } from "@dapplelight/signet-db"
import { bulkInsert } from "@dapplelight/signet-db/import"
import { contacts } from "./schema"
import { db } from "./db"
import { rows, userId } from "./session"

const report = await bulkInsert(scoped(db, { userId }), contacts, rows, { key: "email" })
// { inserted: 118, skipped: 4, errors: [{ row: 7, field: "email", message: "..." }] }

API

ExportWhat it does
bulkInsert(ops, table, rows, options)Validate, de-duplicate and insert rows. Never throws for a bad row.
BulkInsertOptionsThe options type.
BulkInsertReport{ inserted, skipped, errors }.
BulkInsertErrorEntry of errors: { row, field?, message }; row indexes into rows.
BulkInsertSchemaThe part of a Zod schema it uses (safeParse).

bulkInsert(ops, table, rows, options)

ops is a scoped(...) or audited(...) handle, so owner columns, encryption, audit and version history apply.

OptionTypeDefault
keystringrequiredJS key of a unique column. A row whose key exists, or repeats in this import, is skipped.
schemaBulkInsertSchematoZod(table, { mode: "insert" })Validates and shapes each row.
chunkSizenumber500 on Postgres; as many as fit in 100 bound parameters on SQLiteRows per insert statement.
  • A row that fails validation is reported and left out; the rest still go in.
  • A missing or empty key value is reported as an error.
  • When a chunk fails, its rows are retried one at a time to find the ones the database refuses.
  • An unknown key throws UNKNOWN_KEY.

Examples

Re-run the same file safely

import { bulkInsert } from "@dapplelight/signet-db/import"
import { contacts } from "./schema"
import { ops, rows } from "./session"

await bulkInsert(ops, contacts, rows, { key: "email" })
const again = await bulkInsert(ops, contacts, rows, { key: "email" })
// again.inserted === 0, again.skipped === rows.length

Custom row schema

import { z } from "zod"
import { bulkInsert } from "@dapplelight/signet-db/import"
import { contacts } from "./schema"
import { ops, rows } from "./session"

await bulkInsert(ops, contacts, rows, {
  key: "email",
  schema: z.object({ email: z.string().email().toLowerCase(), name: z.string().min(1) }),
})