CSV import

What it's for

Customers, products, price lists: the data people already have is in a spreadsheet, and the easiest way out of one is CSV. Splitting lines on commas works until a field holds a comma, a quote or a line break, which real files do. The module reads CSV properly with the csv crate (quotes, "" inside quotes, CRLF line ends, Excel's UTF-8 BOM) and gives back one JSON object per row, keyed by the header line.

The route

An API route a superuser posts a file to, which imports it into contacts (name text, required; email email):

// pb_pages/import/contacts.ts: superusers import contacts from a CSV file (the request body)
interface CsvImport {
  rows: Array<{ name: string; email: string }> // one object per row, keyed by the header line
  errors: Array<{ line: number; message: string }>
}

export async function post(ctx: any) {
  if (!ctx.auth?.isSuperuser()) throw ctx.httpError(403, "Superusers only")
  const csv = new Uint8Array(toBytes(ctx.req.event.request.body))
  const { rows, errors } = await $wasm.run.async<CsvImport>("csv", csv)
  const contacts = ctx.app.findCollectionByNameOrId("contacts")
  ctx.app.runInTransaction((txApp: any) => {
    for (const row of rows) {
      const contact = new Record(contacts)
      contact.load({ name: row.name, email: row.email })
      txApp.save(contact) // an invalid row throws: nothing is imported
    }
  })
  return ctx.res.json({ imported: rows.length, skipped: errors })
}
curl -H "Authorization: $TOKEN" --data-binary @contacts.csv http://127.0.0.1:8090/import/contacts

The file is the request body, sent as it is; ctx.req.event is PocketBase's request event, and its request.body is the raw body. In a transaction, the import is all or nothing: a row the collection refuses (a blank name, a bad email) stops it with that row's error, and nothing is saved. A row with the wrong number of fields doesn't stop it; it's skipped and listed with its line number:

{"imported": 2, "skipped": [{"line": 4, "message": "CSV error: record 3 (line: 4, byte: 64): found record with 1 fields, but the previous record has 2 fields"}]}

The module

src/main.rs:

let mut reader = csv::ReaderBuilder::new().delimiter(delimiter).from_reader(data);
for result in reader.records() {
    match result {
        Ok(record) => { /* one object: column name -> value */ }
        Err(e) => { /* {line, message} into errors */ }
    }
}

run reads comma-separated files, tsv tab-separated and semicolon semicolon-separated, which is what spreadsheets save in many European locales: $wasm.call.async("csv", "semicolon", csv). Every value comes back as a string, as it is in the file; convert numbers and dates in your page code, or let the collection's field types do it.

Build

cd ext/wasm/example/csv
cargo build --release --target wasm32-wasip1   # rustup target add wasm32-wasip1 first
cp target/wasm32-wasip1/release/csv.wasm pb_hooks/csv.pb.wasm

Cost

108 KB. The first call compiles it (about 30 ms); later calls load it from the cache in about 1.5 ms and read a small file in under 1 ms.

Limits

  • The file and the JSON that comes back are each at most 4 MB (MaxPayload). The JSON repeats the column names on every row, so it's bigger than the file: keep files to about 2 MB, or split them.
  • Spreadsheet formulas come through as their saved values, if the file has them; CSV has no types or formatting.