# Recipe — CSV import ## Import contacts from a CSV Upload a CSV as a signed-in user and import contacts in one request. A repeat import updates that user's contacts by email. ### 1. db/schema.ts Choose `unique: true` only for a permanent uniqueness rule. Deploy refuses to remove the constraint later. ```ts // db/schema.ts import { files, id, integer, owner, schema, table, text, timestamp } from 'somewhere/db'; export default schema({ imports: table( { id: id(), file_id: text({ unique: true }), status: text({ default: 'running' }), rows_stored: integer({ default: 0 }), error: text({ nullable: true }), created_at: timestamp({ default: 'now' }), }, { scope: owner(), client: { read: ['id', 'file_id', 'status', 'rows_stored', 'error', 'created_at'] } }, ), contacts: table( { id: id(), email: text(), name: text(), import_id: text() }, { scope: owner(), unique: [['user_id', 'email']], indexes: [['import_id']], client: { read: ['id', 'name', 'email'] } }, ), }, { files: { csv_uploads: files({ path: '/csv-uploads', scope: owner(), client: { read: true, upload: true }, limits: { maxSize: '2MB', types: ['text/csv'] }, }), }, }); ``` `owner()` scopes uploads and rows to the signed-in user. The fixed `upload.csv` name lets the endpoint find the upload by ID. The composite unique key gives each user one contact per email address. ### 2. The CSV reader ```ts // api/_lib/csv.ts — comma-separated text: quoted fields, "" escapes, commas and line breaks inside quotes, LF or CRLF export class CsvError extends Error {} /** maxRecords counts the header row. */ export function parseCsv(text: string, maxRecords: number): string[][] { const records: string[][] = []; let record: string[] = []; let field = ''; let state: 'start' | 'plain' | 'quoted' | 'closed' = 'start'; const endField = () => { record.push(field); field = ''; state = 'start'; }; const endRecord = () => { endField(); if (record.length > 1 || record[0] !== '') records.push(record); // skip blank lines if (records.length > maxRecords) throw new CsvError(`The file has more than ${maxRecords - 1} rows below the header.`); record = []; }; for (let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; i < text.length; i++) { const ch = text[i]; if (state === 'quoted') { if (ch !== '"') field += ch; else if (text[i + 1] === '"') { field += '"'; i++; } else state = 'closed'; } else if (ch === ',') endField(); else if (ch === '\n') endRecord(); else if (ch === '\r' && text[i + 1] === '\n') { endRecord(); i++; } else if (ch === '"' && state === 'start') state = 'quoted'; else if (ch === '"' || ch === '\r' || state === 'closed') throw new CsvError(`Row ${records.length + 1} is not valid CSV.`); else { field += ch; state = 'plain'; } } if (state === 'quoted') throw new CsvError('A quoted field is not closed.'); if (state !== 'start' || field !== '' || record.length > 0) endRecord(); return records; } export type ContactRow = { name: string; email: string }; /** Checks every row before any is written; a CsvError names the row to fix. */ export function contactsFromCsv(text: string, maxRows: number): ContactRow[] { const [header, ...rows] = parseCsv(text, maxRows + 1); if (header?.map((h) => h.trim().toLowerCase()).join(',') !== 'name,email') throw new CsvError('The first row must be: name,email'); return rows.map((row, index) => { const [name = '', email = ''] = row.map((value) => value.trim()); if (row.length !== 2 || !name || name.length > 200 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { throw new CsvError(`Row ${index + 2}: expected a name and an email address.`); } return { name, email: email.toLowerCase() }; }); } ``` ### 3. Import the file and report it ```ts // api/imports.ts — POST { file_id } imports one uploaded CSV; GET ?file_id= reports it import { type ContactRow, CsvError, contactsFromCsv } from './_lib/csv'; const MAX_ROWS = 2000; // this example's cap: one request reads, checks and writes the whole file const BATCH = 100; // sw.db.tx takes 1–100 writes export default sw.endpoint({ auth: 'required', handler: async ({ request, user }, sw) => { if (request.method === 'GET') { const fileId = new URL(request.url).searchParams.get('file_id'); if (!fileId) return Response.json({ error: 'Pass ?file_id=.' }, { status: 400 }); // Runs as this user: another user's import is not found. const { data: found } = await sw.db.from('imports', { where: { file_id: fileId }, limit: 1 }); const row = found[0]; if (!row) return Response.json({ error: 'No such import for this account.' }, { status: 404 }); return Response.json({ status: row.status, rows_stored: Number(row.rows_stored), error: row.error }); } if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } }); const input = (await request.json().catch(() => null)) as { file_id?: unknown } | null; const fileId = input?.file_id; if (typeof fileId !== 'string' || !/^[A-Za-z0-9-]{8,64}$/.test(fileId)) { return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 }); } // 20 per hour per user is this example's choice. const allowance = await sw.rateLimit.check(`csv-import:${user.id}`, 20, 3600); if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 }); let text: string; try { // Runs as this user: another user's upload is not found. const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`); text = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()); } catch (error) { if (error instanceof Error && 'status' in error && error.status === 404) { return Response.json({ error: 'No such upload for this account.' }, { status: 404 }); } if (error instanceof TypeError) return Response.json({ error: 'Save the file as CSV UTF-8 and upload it again.' }, { status: 422 }); throw error; } await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' }); const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null, httpStatus: number) => { await sw.db.update('imports', { where: { file_id: fileId }, set: { status, rows_stored: rowsStored, error } }); return Response.json({ status, rows_stored: rowsStored, error }, { status: httpStatus }); }; let contacts: ContactRow[]; try { contacts = contactsFromCsv(text, MAX_ROWS); } catch (error) { if (error instanceof CsvError) return finish('failed', 0, error.message, 422); throw error; } // Each batch is one atomic write as this user. An address already stored for this user is updated. for (let start = 0; start < contacts.length; start += BATCH) { await sw.db.tx(contacts.slice(start, start + BATCH).map((contact) => ({ op: 'insert' as const, table: 'contacts', values: { ...contact, import_id: fileId }, options: { onConflict: 'update' as const }, }))); } return finish('complete', contacts.length, null, 200); }, }); ``` The endpoint validates the whole file before writing contacts. Each batch is atomic. A retry with the same file ID safely updates any contacts the earlier batches stored. The last row for a repeated email supplies its name. ### 4. The page ```ts // src/services/csv-import.ts import { files } from 'somewhere:files'; export type ImportState = { status: string; rows_stored: number | null; error: string | null }; /** Upload a CSV and import it. Returns the import's result. */ export async function importCsv(file: File): Promise { if (!file.name.toLowerCase().endsWith('.csv')) throw new Error('Choose a .csv file.'); const { data: uploaded, error } = await files.csv_uploads.upload(file, { name: 'upload.csv', contentType: 'text/csv' }); if (error) throw new Error(error.message); const response = await fetch('/api/imports', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ file_id: uploaded.id }), }); const result = (await response.json().catch(() => null)) as (ImportState & { error?: string | null }) | null; if (response.status === 422 && result) return { ...result, file_id: uploaded.id }; if (!response.ok || typeof result?.status !== 'string') throw new Error(result?.error ?? `Could not import the file (${response.status}).`); return { ...result, file_id: uploaded.id }; } /** Read one import's recorded result. */ export async function readCsvImport(fileId: string): Promise { const response = await fetch(`/api/imports?file_id=${encodeURIComponent(fileId)}`); if (response.status === 404) return null; const result = (await response.json().catch(() => null)) as ImportState | null; if (!response.ok || typeof result?.status !== 'string') throw new Error(`Could not read the import (${response.status}).`); return result; } ``` Call `importCsv` from a file input. Show `rows_stored` on completion or `error` on failure. Upload a corrected file to retry a validation failure. After a timeout, use `readCsvImport` to check the result and retry a still running import with the same file ID. ### 5. Check it ```bash somewhere typecheck && somewhere deploy somewhere db rows contacts ``` Upload three valid contacts. Expect three rows. Re-upload with one name changed and check that the count stays at three. A missing email should fail before any contacts are written. A second user should see only their own contacts. For a background import, run `somewhere docs example csv-import-background`. ## Larger files Start with the schema, parser, import status endpoint, and browser service from `somewhere docs example csv-import`. Add these files to run it in a background job. The job reads the upload first using the starting user's file access. That access lasts 10 minutes from `sw.jobs.verifyInvocation`. The job uses `sw.db.server` for writes and sets the owner from the verified job payload. ```ts // api/import-jobs.ts — POST { file_id } queues the import of one uploaded CSV export default sw.endpoint({ auth: 'required', body: { file_id: 'string' }, rateLimit: '20/hour', handler: async ({ user, body }, sw) => { const fileId = body.file_id; if (!/^[A-Za-z0-9-]{8,64}$/.test(fileId)) { return Response.json({ error: 'Send the file_id from the upload result.' }, { status: 400 }); } try { // Runs as this user, reading only the first line: another user's upload is not found. await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`, { lines: [1, 1] }); } catch (error) { if (error instanceof Error && 'status' in error && error.status === 404) { return Response.json({ error: 'No such upload for this account.' }, { status: 404 }); } throw error; } await sw.db.insert('imports', { file_id: fileId }, { onConflict: 'ignore' }); // One job per user and file: a repeated POST returns the same job. const job = await sw.jobs.create({ handler: '/api/jobs/import-csv', idempotency_key: `csv-import:${user.id}:${fileId}`, payload: { file_id: fileId, user_id: user.id }, timeout_seconds: 120, }); return Response.json({ job_id: job.job_id, file_id: fileId }, { status: 202 }); }, }); ``` ```ts // api/jobs/import-csv.ts — runs only when the platform delivers the job import { type ContactRow, CsvError, contactsFromCsv } from '../_lib/csv'; const MAX_ROWS = 20_000; const BATCH = 100; // sw.db.server.tx takes 1–100 writes const IN_FLIGHT = 4; export default async function importCsvJob(request: Request, sw: SomewhereRuntimeContext): Promise { if (!(await sw.jobs.verifyInvocation(request))) return Response.json({ error: 'forbidden' }, { status: 403 }); const payload = (await request.json().catch(() => null)) as { file_id?: unknown; user_id?: unknown } | null; const fileId = payload?.file_id; const userId = payload?.user_id; if (typeof fileId !== 'string' || !fileId || typeof userId !== 'string' || !userId) { return Response.json({ error: 'Invalid payload.' }, { status: 400 }); } const finish = async (status: 'complete' | 'failed', rowsStored: number, error: string | null) => { await sw.db.server.update('imports', { where: { file_id: fileId, user_id: userId }, set: { status, rows_stored: rowsStored, error } }); return Response.json({ status, rows_stored: rowsStored, error }); }; let contacts: ContactRow[]; try { // First, while the starting user's file authority is fresh. const file = await sw.fs.read(`/csv-uploads/${fileId}/upload.csv`); contacts = contactsFromCsv(new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer()), MAX_ROWS); } catch (error) { if (error instanceof CsvError) return finish('failed', 0, error.message); if (error instanceof TypeError) return finish('failed', 0, 'Save the file as CSV UTF-8 and upload it again.'); throw error; } // Keep the last occurrence of each normalized email so batches can run independently. const uniqueContacts = [...new Map(contacts.map(contact => [contact.email, contact])).values()]; for (let start = 0; start < uniqueContacts.length; start += BATCH * IN_FLIGHT) { const writes: Promise[] = []; for (let batch = 0; batch < IN_FLIGHT; batch++) { const offset = start + batch * BATCH; const chunk = uniqueContacts.slice(offset, offset + BATCH); if (chunk.length === 0) break; writes.push(sw.db.server.tx(chunk.map(contact => ({ op: 'insert' as const, table: 'contacts', values: { ...contact, import_id: fileId, user_id: userId }, options: { onConflict: 'update' as const }, })))); } await Promise.all(writes); } return finish('complete', contacts.length, null); } ``` Raise the collection's `limits.maxSize` within your plan's per-file ceiling. Change the browser service to POST the upload's `file_id` to `/api/import-jobs`, then poll `readCsvImport(file_id)` until it finishes. A validation failure records `failed` and writes no contacts. A thrown error can retry within the job deadline. Each retry upserts the same contacts. If the import is still running after the deadline, upload again to start a new job. Time your largest file before raising the row cap. To load a dataset once as the developer, not from the app, use the `db_import_csv` tool with a CSV already in your project files. If a batch fails, the error gives the number of rows already imported and the CSV line to resume from. Keep the header and import only the remaining rows. If the error says a write could not be confirmed, check the table before trying again.