<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>Updog Blog</title>
<link>https://updog.tech/blog/</link>
<description>Notes from the people building Updog.</description>
<language>en-us</language>
<atom:link href="https://updog.tech/blog/rss.xml" rel="self" type="application/rss+xml"/>
<item><title>How 1,000 Companies Handle CSV Import</title><link>https://updog.tech/blog/how-1000-companies-handle-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/how-1000-companies-handle-csv-import/</guid><pubDate>Sun, 08 Nov 2026 00:00:00 GMT</pubDate><description>Research into 1,000 companies reveals five recurring CSV import problems and practical ways to improve the user experience.</description><content:encoded><![CDATA[<p>Research into how 1,000 companies handle CSV import revealed a recurring problem. Customers are still asked to prepare, correct, and split data outside the product before they can use it.</p>
<p>The research was conducted at Updog, a CSV and Excel importer for web apps.</p>
<p>Over six months, we collected around 50 public signals about data import each week from companies in different countries. These came from product documentation, company blogs, LinkedIn posts, and other public discussions. During that time, we connected with more than 1,000 people on LinkedIn whose companies had published material about their import workflows and problems. The findings below bring together the recurring problems described in those sources.</p>
<h2 id="research-findings">Research findings</h2>
<ul>
<li>Around 30% described correcting the source file and uploading it again.</li>
<li>Around 29% described fixed templates, prescribed headers, or a specific column structure.</li>
<li>Around 14% documented row or file-size limits on imports.</li>
<li>Around 11% documented update restrictions, duplicate risks on re-import, or replacement rules that can remove existing data.</li>
<li>Around 5% described spreadsheet imports performed by support, onboarding, or implementation teams.</li>
</ul>
<p>These requirements can overlap. A customer may need to reshape a spreadsheet, split it, and correct rejected rows before the same import is complete.</p>
<h2 id="fixing-errors-means-going-back-to-excel">Fixing errors means going back to Excel</h2>
<p>The file uploads, validation finds a problem, and the user gets an error report. Now they need to open their spreadsheet, locate the affected cells, correct them, save, and upload again. If the next attempt reveals another problem, they repeat the trip.</p>
<p>In some documented workflows, errors arrive by email in an attached file. The user reads that report but makes corrections in the original file. Two files are needed to fix data the application has already inspected.</p>
<p>The application knows which row failed and why. Showing the error beside an editable cell lets the user make the correction where the problem was found. Filters can narrow the view to invalid rows, while bulk edits handle repeated mistakes.</p>
<p>Updog uses an embedded spreadsheet for this. Users can filter invalid rows, edit cells, and replace repeated values while validation checks the result. Corrections happen before submission, without another upload.</p>
<p>The same trip back to Excel can begin before validation, when a file has to be reshaped to fit a template.</p>
<h2 id="templates-make-users-reshape-data-the-product-could-match">Templates make users reshape data the product could match</h2>
<p>The customer already has an export from their old system, but the application asks them to copy it into another spreadsheet. Documented requirements include preserving column names and order, keeping unused columns, and matching category names exactly, including case.</p>
<p>A template is useful as an example. Making it the only acceptable shape adds preparation whenever another system exports the same information differently. <code>Work Email</code> and <code>email</code> can describe the same field. Likewise, <code>Eng</code> may mean the department the application calls <code>Engineering</code>.</p>
<p>Column matching brings the first decision into the import flow. Value matching handles the second, letting users resolve a department name once for the column instead of correcting every occurrence. The application supplies its fields and allowed values, while users confirm the remaining matches beside their data.</p>
<h2 id="row-limits-make-users-split-and-track-their-files">Row limits make users split and track their files</h2>
<p>A file can match every required field and still exceed an import limit. The research found documented limits of 500 records per upload, with instructions to split larger files. At that limit, 10,000 records mean 20 uploads, each with its own validation and result.</p>
<p>If one batch fails and another succeeds, the user also has to remember which files to retry. They divide the data, name the pieces, track progress, and check that nothing was missed or uploaded twice.</p>
<p>A low limit may keep validation times, rendering costs, or server requests manageable. A commercial import component can also impose a plan limit. Asking users to split their files makes them work around those implementation and pricing constraints.</p>
<p>Updog is built to work with around one million rows in the browser. Its grid draws visible cells on a canvas instead of rendering the whole dataset as an HTML table, and filtering uses a worker. Practical capacity still depends on column count and available memory.</p>
<p>For customers bringing 10,000 or 50,000 rows, the value of that capacity is headroom. The file stays one dataset, and the interface helps locate the rows that need attention. Large-file support needs both capacity and tools to work on the data.</p>
<p>Once the whole file can be imported, the application needs to decide what to do with its rows. A first import may create records. Bringing the same file back to update them needs different behavior.</p>
<h2 id="bringing-a-file-back-can-create-duplicates-or-overwrite-data">Bringing a file back can create duplicates or overwrite data</h2>
<p>A user exports contacts, changes a few phone numbers, and imports the file again. They expect the existing contacts to receive those changes. Whether that happens depends on record identity and the meaning of the other cells.</p>
<p>The research found workflows where an absent ID column means creating records rather than updating them. In those same workflows, an empty cell in a mapped column can overwrite the existing value. A blank intended to leave a field unchanged can therefore clear it instead.</p>
<p>The review step should show which rows create records and which change existing ones. Empty cells need a clear meaning. Matching incoming rows against existing data using a stable key helps distinguish creates from updates, while change tracking lets the integration identify new, edited, and deleted rows.</p>
<p>The backend still controls permissions, duplicate prevention, and safe retries. A file that passed validation has not necessarily reached the database. After a partial save, the application needs to identify what succeeded and what still needs attention, so the user can continue without reconstructing the application's state in a local spreadsheet.</p>
<h2 id="support-becomes-part-of-the-import-flow">Support becomes part of the import flow</h2>
<p>Some documented onboarding flows ask customers to fill out a spreadsheet and send it by email or live chat for the team to import. Completion depends on support availability, so customers may wait longer during busy periods.</p>
<p>Assistance can be valuable during a complicated migration. Routine file preparation creates a different kind of work. Someone checks the format, requests corrections, resolves mismatched values, and runs the import while the customer waits to use the data.</p>
<p>Giving customers tools to map, validate, and correct their own files can remove those routine handoffs. The same tools can help support prepare difficult files, leaving human help available for decisions that need it.</p>
<h2 id="give-import-the-same-care-as-the-rest-of-the-product">Give import the same care as the rest of the product</h2>
<p>In 2026, AI can make an importer faster to build. These workflows show how much work the resulting product can still leave to the user. Data keeps moving between products, and importing it remains part of the experience customers depend on.</p>
<p>For teams whose main product is elsewhere, a capable ready-made importer is worth evaluating early. Test it with a real customer file, correct errors, and check what happens on a repeat upload. Choose one that handles that work well, then focus engineering time on the product your customers came to use.</p>
<p class="blog__disclosure">AI tools assisted with drafting and editing this article.</p>]]></content:encoded></item>
<item><title>How to Match CSV Columns and Values With Jev</title><link>https://updog.tech/blog/ai-matching-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/ai-matching-csv-import/</guid><pubDate>Sat, 19 Sep 2026 00:00:00 GMT</pubDate><description>AI column matching and value matching with Jev, a decision model, in two Updog Importer hooks. We measure accuracy, thresholds, cost and latency on one file.</description><content:encoded><![CDATA[<p>A CSV importer takes a file from one of your users and turns it into rows your app can store. The file comes from another system and uses that system's names. Before any row is imported, the importer translates those names into yours. It does this in two steps.</p>
<p>Column matching connects each column of the file to a field of your schema. A supplier writes <code>Art. No</code>, and your catalog calls the same thing <code>sku</code>.</p>
<p>Value matching works inside one column. When a field accepts a fixed list of options, every spelling in the file has to map to one of them. A supplier writes <code>pkt</code>, <code>bx</code> and <code>box</code>, and your catalog calls all three <code>pack</code>.</p>
<p>Updog Importer is a CSV and Excel importer you embed in your app. By default its built-in matcher performs both steps with fuzzy string matching. Two optional hooks, <code>onColumnMatch</code> and <code>onValueMatch</code>, let your own logic answer first. In this article that logic asks Jev, a decision model from TypeSafe AI, and we measure the result on one supplier price list.</p>
<p>On that file, the built-in matcher resolved one header of five and four unit spellings of fifteen. With Jev behind the hooks, five headers of five and fourteen spellings of fifteen were matched before the person importing the file clicked anything.</p>
<p>For the demonstration we chose a price list that a hardware shop receives from a supplier.</p>
<p><code>ironbridge-pricelist.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Art. No</td><td class="sheet__cell">Item Desc</td><td class="sheet__cell">Mfr</td><td class="sheet__cell">UoM</td><td class="sheet__cell">List Price</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">IB-00001</td><td class="sheet__cell">Hex bolt zinc plated M6x30</td><td class="sheet__cell">Hartley</td><td class="sheet__cell">pkt</td><td class="sheet__cell">168.01</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">IB-00002</td><td class="sheet__cell">Countersunk wood screw 5x60</td><td class="sheet__cell">Ostrel</td><td class="sheet__cell">bx</td><td class="sheet__cell">58.19</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">IB-00003</td><td class="sheet__cell">Nylon wall plug 8mm</td><td class="sheet__cell">Brennock</td><td class="sheet__cell">box</td><td class="sheet__cell">38.1</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">1 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">IB-00005</td><td class="sheet__cell">Round wire nails 50mm</td><td class="sheet__cell">Ostrel</td><td class="sheet__cell">KG</td><td class="sheet__cell">234.72</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">IB-00006</td><td class="sheet__cell">Claw hammer fibreglass shaft 16oz</td><td class="sheet__cell">Tamsin &#x26; Wye</td><td class="sheet__cell">ea</td><td class="sheet__cell">35.16</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">2 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">IB-00009</td><td class="sheet__cell">Wood chisel bevel edge 25mm</td><td class="sheet__cell">Tamsin &#x26; Wye</td><td class="sheet__cell">pc</td><td class="sheet__cell">221.15</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">3 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">14</th><td class="sheet__cell">IB-00013</td><td class="sheet__cell">Jigsaw variable speed 750W</td><td class="sheet__cell">Brennock</td><td class="sheet__cell">each</td><td class="sheet__cell">86.04</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">15</th><td class="sheet__cell">IB-00014</td><td class="sheet__cell">SDS rotary hammer 800W</td><td class="sheet__cell">Hartley</td><td class="sheet__cell">Stk</td><td class="sheet__cell">77.92</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">16</th><td class="sheet__cell">IB-00015</td><td class="sheet__cell">Twin and earth cable 1.5mm2</td><td class="sheet__cell">Brennock</td><td class="sheet__cell">mtr</td><td class="sheet__cell">11.24</td></tr></tbody></table>
<p>The shop's catalog uses different names. It has five fields, and the <code>unit</code> field accepts five options. Every field and every option has a one-line description, which the hooks later pass to Jev.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const UNIT_CRITERIA: Record&#x3C;string, string> = {
  pcs: "Sold as single pieces",
  kg: "Sold by weight in kilograms",
  l: "Sold by volume in litres",
  m: "Sold by length in metres",
  pack: "Sold as a box, bag or packet of several pieces",
};

export const FIELD_CRITERIA: Record&#x3C;string, string> = {
  sku: "The supplier's article or part number",
  name: "The product description",
  brand: "The manufacturer or brand",
  unit: "The unit of measure the product is sold in",
  price: "The list price",
};

export const UNITS = Object.keys(UNIT_CRITERIA);

export const columns: DataEditorColumn[] = [
  {
    id: "sku",
    title: "SKU",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  { id: "name", title: "Product name", validators: [{ type: "required" }] },
  { id: "brand", title: "Brand" },
  { id: "unit", title: "Unit", editor: { type: "select", options: UNITS } },
  {
    id: "price",
    title: "Price",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
  },
];</code></pre>
<p><code>UoM</code> has to map to <code>unit</code>. Inside that column, <code>ea</code>, <code>EA</code>, <code>pc</code>, <code>each</code> and <code>Stk</code> all mean <code>pcs</code>. The full file writes the five units in fifteen spellings.</p>
<h2 id="what-both-steps-have-in-common">What both steps have in common</h2>
<p>Column matching and value matching both ask a closed question. The input is open, because a supplier can write any header and any spelling. The answer is one item from a list your schema already holds, or none of them. <code>UoM</code> is one of five fields. <code>Stk</code> is one of five units.</p>
<h2 id="the-matching-hooks-in-updog">The matching hooks in Updog</h2>
<p>The built-in matcher compares strings, so it connects <code>List Price</code> to <code>price</code> and <code>KG</code> to <code>kg</code>. <code>UoM</code> and <code>unit</code> share a meaning and almost no letters, so string comparison does not connect them.</p>
<p><code>onColumnMatch</code> and <code>onValueMatch</code> pass such cases to your code. <code>onColumnMatch</code> receives the headers of the file and the fields of your schema. <code>onValueMatch</code> receives the distinct values of every field that has a fixed list of options, together with those options. Your function returns the matches it is sure about, and the built-in matcher handles every header or value you leave out. If the function throws or runs past 30 seconds, the built-in matcher performs the whole step and the import continues.</p>
<p>The logic inside the hook can be a lookup table, a set of rules, or a model.</p>
<p><a href="https://updog.tech/blog/bring-your-own-ai/">Bring Your Own AI to CSV and Excel Import</a> explains why the model is yours and how the hooks keep Updog out of the data path.</p>
<h2 id="what-jev-is">What Jev is</h2>
<p>On September 15, 2026, TypeSafe AI released Jev, the first of what the company calls System One models. The <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">announcement</a> describes the class as models "built to make fast, structured decisions that software can use directly". Jev "gives up string generation".</p>
<p>A request contains a <code>state</code>, which is the context, and a set of questions. The <a href="https://docs.typesafe.ai/">documentation</a> lists three question types. This article uses the Choice, which picks one option from a list you define, with up to 255 options. Every Choice answer returns the selected option, a probability for each option, and a <code>confidence</code> between 0 and 1.</p>
<h2 id="why-jev-fits-matching">Why Jev fits matching</h2>
<p>A Choice question is the closed question both steps ask. It returns one option from a list, and the hook expects one field of your schema back.</p>
<p>The option keys are the field ids of your schema, so the hook uses the returned <code>choice</code> as the field id without converting it. The <code>confidence</code> number gives the hook a rule for what to leave out. A match the hook leaves out goes to the built-in matcher, and then to the person at the matching step.</p>
<p>A language model with structured output can answer the same questions. There the closed list has to be written as a JSON schema, and the reply holds a choice without a confidence number unless the API exposes token probabilities. With Jev the closed list is the request format, and every answer includes <code>confidence</code>.</p>
<h2 id="setting-it-up">Setting it up</h2>
<p>The hooks run in the browser, and the TypeSafe key cannot go there, because any user can read a key that ships to the browser. The browser calls <code>POST /api/jev</code> on your backend, and the backend adds the key and forwards the request.</p>
<p>To keep the example small, the backend here is a proxy inside the Vite dev server. The same code can live on your own backend.</p>
<pre><code class="language-ts">import type { Plugin } from "vite";

const JEV_URL = "https://api.typesafe.ai/v1/systemone";

export const jevProxy = (apiKey: string | undefined): Plugin => {
  return {
    name: "jev-proxy",
    configureServer(server) {
      server.middlewares.use("/api/jev", async (request, response) => {
        try {
          const chunks: Buffer[] = [];
          for await (const chunk of request) {
            chunks.push(chunk);
          }
          const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
          const upstream = await fetch(JEV_URL, {
            method: "POST",
            headers: {
              Authorization: `Bearer ${apiKey}`,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ ...body, model: "jev-latest" }),
          });
          response.statusCode = upstream.status;
          response.end(await upstream.text());
        } catch {
          response.statusCode = 502;
          response.end();
        }
      });
    },
  };
};</code></pre>
<p>The headers of the file and the distinct values of the <code>unit</code> column go from the browser to TypeSafe. No other cell leaves the browser. If your users' data may not go to a third party, keep the built-in matcher or point the hook at a model you host.</p>
<p>On the frontend, both hooks call one client.</p>
<pre><code class="language-ts">type Ask = {
  state: string;
  items: string[];
  instructions: (item: string) => string;
  criteria: Record&#x3C;string, string>;
  threshold: number;
  signal?: AbortSignal;
};

type Answer = {
  choice: string;
  confidence: number;
};

export const askJev = async ({
  state,
  items,
  instructions,
  criteria,
  threshold,
  signal,
}: Ask): Promise&#x3C;Record&#x3C;string, string>> => {
  const questions = Object.fromEntries(
    items.map((item) => {
      return [
        item,
        { type: "choice", instructions: instructions(item), criteria },
      ];
    }),
  );

  try {
    const response = await fetch("/api/jev", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ state, questions }),
      signal,
    });
    if (!response.ok) {
      return {};
    }
    const { answers }: { answers: Record&#x3C;string, Answer> } =
      await response.json();

    const picked: Record&#x3C;string, string> = {};
    for (const [item, { choice, confidence }] of Object.entries(answers)) {
      if (confidence >= threshold &#x26;&#x26; choice !== "none") {
        picked[item] = choice;
      }
    }
    return picked;
  } catch {
    return {};
  }
};</code></pre>
<p><code>askJev</code> builds one Choice question per item, sends them in one request, and keeps the answers that pass the threshold and are not <code>none</code>. When the request fails it returns an empty object, so the built-in matcher performs the whole step and the person importing the file sees no error. The TypeSafe documentation asks clients to retry a 429 or a 529 with exponential backoff, and this example leaves that out.</p>
<h2 id="matching-columns">Matching columns</h2>
<p>The hook asks one Choice question per header, all in one request. The options are the five fields with a short description each, plus <code>none</code> for a column the catalog does not store. The TypeSafe documentation recommends such an option whenever an input may fit nothing on the list.</p>
<pre><code class="language-ts">import { FIELD_CRITERIA } from "../catalog";
import { askJev } from "./client";

export const matchColumns = (
  headers: string[],
): Promise&#x3C;Record&#x3C;string, string>> => {
  return askJev({
    state:
      "A hardware shop imports a supplier price list into its product catalog.",
    items: headers,
    instructions: (header) => {
      return `Which catalog field does the supplier column "${header}" hold?`;
    },
    criteria: {
      ...FIELD_CRITERIA,
      none: "The column holds something the catalog does not store",
    },
    threshold: 0.9,
  });
};</code></pre>
<p>The header goes inside the question, and the state holds one sentence of context. No question then has to point to an item of a list by its index, and the documentation says Jev does not count reliably.</p>
<p>The request for <code>UoM</code> alone shows what Jev receives and what it returns.</p>
<pre><code class="language-json">{
  "model": "jev-latest",
  "state": "A hardware shop imports a supplier price list into its product catalog.",
  "questions": {
    "UoM": {
      "type": "choice",
      "instructions": "Which catalog field does the supplier column \"UoM\" hold?",
      "criteria": {
        "sku": "The supplier's article or part number",
        "name": "The product description",
        "brand": "The manufacturer or brand",
        "unit": "The unit of measure the product is sold in",
        "price": "The list price",
        "none": "The column holds something the catalog does not store"
      }
    }
  }
}</code></pre>
<pre><code class="language-json">{
  "model": "jev-1.13.0",
  "answers": {
    "UoM": {
      "type": "choice",
      "choice": "unit",
      "confidence": 1,
      "probabilities": { "sku": 0, "name": 0, "brand": 0, "unit": 1, "price": 0, "none": 0 }
    }
  },
  "usage": { "input_tokens": 404, "output_tokens": 61 }
}</code></pre>
<p>Jev put the whole probability on <code>unit</code>, and the hook returns that <code>choice</code> as the match.</p>
<p>All five answers were correct, each with a confidence of 0.99 or higher. The file has no extra column, so this run never tested the <code>none</code> option on headers.</p>
<h2 id="matching-values">Matching values</h2>
<p><code>onValueMatch</code> passes the distinct spellings of the <code>unit</code> column. The hook asks one question per spelling, again in one request.</p>
<pre><code class="language-ts">import type { ValueMatchInput, ValueMatchOutput } from "@updog/data-editor";
import { UNIT_CRITERIA } from "../catalog";
import { askJev } from "./client";

export const matchValues = async (
  valuesToMatch: Record&#x3C;string, ValueMatchInput>,
): Promise&#x3C;ValueMatchOutput> => {
  const unit = await askJev({
    state:
      "A hardware shop imports a supplier price list. Each supplier spelling has to land on one of the shop's allowed values.",
    items: valuesToMatch.unit.importedValues,
    instructions: (value) => {
      return `Which allowed "unit" value does the supplier spelling "${value}" mean?`;
    },
    criteria: {
      ...UNIT_CRITERIA,
      none: "The spelling means none of the allowed values",
    },
    threshold: 0.8,
  });
  return { unit };
};</code></pre>
<p>Jev picked the right unit for all fifteen spellings.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Unit</th>
<th>Spelling and confidence</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>pack</code></td>
<td><code>pkt</code> 0.97, <code>bx</code> 0.83, <code>box</code> 0.94</td>
</tr>
<tr>
<td><code>kg</code></td>
<td><code>KG</code> 0.96, <code>kilo</code> 0.88</td>
</tr>
<tr>
<td><code>pcs</code></td>
<td><code>ea</code> 0.98, <code>EA</code> 0.98, <code>pc</code> 0.95, <code>each</code> 0.89, <code>Stk</code> 0.54</td>
</tr>
<tr>
<td><code>m</code></td>
<td><code>mtr</code> 0.98, <code>lin. m</code> 0.97</td>
</tr>
<tr>
<td><code>l</code></td>
<td><code>Ltr</code> 0.98, <code>L</code> 0.53, <code>litre</code> 0.96</td>
</tr>
</tbody>
</table></div>
<p>Thirteen answers passed the threshold of 0.8. The hook left out <code>L</code> and <code>Stk</code>, the German abbreviation for pieces. The built-in matcher then connected <code>L</code> to <code>l</code>, and <code>Stk</code> was left for the person to pick by hand. That makes fourteen of fifteen.</p>
<p>The <code>none</code> option covers values the list does not hold. We sent eight such values through the same hook, with <code>none</code> on the list and without it.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Value</th>
<th>Without <code>none</code></th>
<th>With <code>none</code></th>
</tr>
</thead>
<tbody>
<tr>
<td><code>pallet</code></td>
<td><code>pack</code> 0.82</td>
<td><code>none</code> 0.47</td>
</tr>
<tr>
<td><code>n/a</code></td>
<td><code>pcs</code> 0.78</td>
<td><code>none</code> 0.98</td>
</tr>
<tr>
<td><code>-</code></td>
<td><code>pcs</code> 0.39</td>
<td><code>none</code> 0.73</td>
</tr>
<tr>
<td><code>roll</code></td>
<td><code>m</code> 0.81</td>
<td><code>m</code> 0.47</td>
</tr>
<tr>
<td><code>pair</code></td>
<td><code>pack</code> 0.86</td>
<td><code>pack</code> 0.69</td>
</tr>
<tr>
<td><code>TBC</code></td>
<td><code>pcs</code> 0.45</td>
<td><code>none</code> 0.85</td>
</tr>
<tr>
<td><code>12</code></td>
<td><code>pcs</code> 0.47</td>
<td><code>none</code> 0.65</td>
</tr>
<tr>
<td><code>hour</code></td>
<td><code>pcs</code> 0.55</td>
<td><code>none</code> 0.93</td>
</tr>
</tbody>
</table></div>
<p>Without <code>none</code>, Jev has to choose a unit, and three of the eight answers pass 0.8. With <code>none</code>, six values go to <code>none</code>, which the hook drops. <code>roll</code> and <code>pair</code> still get a unit, at 0.47 and 0.69, and the threshold leaves them out. None of the eight is matched.</p>
<p>Pass both hooks to the importer as props.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Product>
  apiKey="YOUR_API_KEY"
  open={open}
  onClose={() => setOpen(false)}
  columns={columns}
  primaryKey="sku"
  onColumnMatch={matchColumns}
  onValueMatch={matchValues}
  onComplete={(result) => {
    console.log(result);
    setOpen(false);
  }}
/></code></pre>
<p><a href="https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/">How to Map CSV Values to Enums During Import</a> covers what the value matching step does with the spellings no matcher resolves.</p>
<h2 id="choosing-the-threshold">Choosing the threshold</h2>
<p>The threshold decides which answers the hook returns. A wrong match appears at the matching step as a finished match, and the person has to notice it among the correct ones. A missing match appears as an empty slot, and the person fills it.</p>
<p>Treat 0.9 and 0.8 as the numbers of this example. The TypeSafe documentation says that "the correct threshold values depend on your domain and the performance of the model for your use case", and asks you to test with your own data. We measured three things that move <code>confidence</code>.</p>
<p>The <code>none</code> option lowers the confidence of correct answers. Without it, <code>bx</code> had 0.97, <code>Stk</code> 0.61 and <code>L</code> 0.63. With it, they had 0.83, 0.54 and 0.53. At a threshold of 0.9 the hook accepted thirteen spellings without <code>none</code> and ten with it, which is why the value hook uses 0.8 together with <code>none</code>.</p>
<p>The order of the options moves the number. We sent the unit questions without <code>none</code> again, with the five options in reverse order. <code>Stk</code> went from 0.61 to 0.92, and <code>L</code> went from 0.63 to 0.31. This is one reversal of one list, so the size of the effect on other lists is unknown.</p>
<p>Repeating a request moves it too. We sent identical requests again on the same day, and confidence changed by up to 0.08. <code>Stk</code> had 0.54 in one run and 0.46 in the next. An answer within 0.08 of the threshold is accepted in one import and left out in the next.</p>
<p>No choice changed in any of these runs. Pick the threshold after the option list and its order are final, and pick it on files from your own users.</p>
<h2 id="what-it-costs">What it costs</h2>
<p>The two matching requests for this file took 929 and 2,330 input tokens, 3,259 in total. Calculated from the <code>usage</code> field of the responses at the published $0.042 per million input tokens, that is about $0.00014 for the import.</p>
<p>Every question contains the full option list, so the token count grows with the number of questions times the number of options. A question took 155 to 186 tokens here. The documentation gives one request a budget of about 32,000 tokens, shared by the state and the questions.</p>
<p>TypeSafe states an end-to-end response time of 70 to 500 ms and adds that its evaluations run from the West Coast of the United States, where the service is based. Our requests took between 1.2 and 1.6 seconds each from the United Arab Emirates against <code>jev-1.13.0</code>. We did not separate network time from model time. The person waits for one request per matching step.</p>
<h2 id="what-we-think-of-jev-for-matching">What we think of Jev for matching</h2>
<p>Jev is strongest where a task comes down to picking by meaning from a short fixed list, and both matching steps are such a task. In every run we made, with <code>none</code> and without it, in both option orders and on repeated requests, Jev picked the right field for all five headers and the right unit for all fifteen spellings. The whole import cost a fraction of a cent.</p>
<p>Read <code>confidence</code> as a relative number. It moved by up to 0.32 with the order of the options, by up to 0.14 when we added <code>none</code>, and by up to 0.08 between identical requests. A threshold holds for one option list in one order, so set it on files from your own users. On our file, every match the hook returned was correct.</p>]]></content:encoded></item>
<item><title>The Best UseCSV Alternatives in 2026</title><link>https://updog.tech/blog/best-usecsv-alternatives/</link><guid isPermaLink="true">https://updog.tech/blog/best-usecsv-alternatives/</guid><pubDate>Thu, 17 Sep 2026 00:00:00 GMT</pubDate><description>We picked five UseCSV alternatives and compared which limit each removes, the row cap per upload, the styling tier, or the iframe, and what it costs.</description><content:encoded><![CDATA[<p>UseCSV is an import modal you add to your app. You set the columns in its dashboard or pass them from code, the person uploads a CSV or Excel file in a window that opens from UseCSV's domain, matches the columns, and fixes invalid cells in an inline editor. The rows then reach your app as JSON, through a webhook or a frontend callback.</p>
<p>UseCSV prices plans by imports and by rows per upload. Hobby is free with 50 imports a month, Starter costs $49 for 250, Plus $99 for 1,000, and Pro $199 for 2,500. Hobby and Starter stop a file at 10,000 rows, Plus at 100,000, and Pro at 500,000, and a million rows or more needs a custom Enterprise plan. The pricing page removes the UseCSV branding from Plus and lists custom styling on Pro alone. The editor exists inside an import, and the importer loads in an iframe.</p>
<p>Flatfile, OneSchema, and Dromo are the established alternatives, so this list leaves them out.</p>
<h2 id="what-usecsv-does-well">What UseCSV does well</h2>
<p>UseCSV lets you choose where the rows go for each importer. In callback mode the rows reach your frontend, and UseCSV stores only the file name, row count, upload date, and status. In webhook mode the rows go to UseCSV's servers, which keep them for up to 24 hours while they are delivered to your backend.</p>
<p>The columns can live in the dashboard, where someone outside engineering edits them, in code through the <code>dynamicColumns</code> option, or in both at once. Validation hooks receive the matched rows in batches of 1,000 and return errors, messages, or corrected values, which UseCSV calls data healing. Every plan includes free imports in development mode.</p>
<p>Client libraries cover React, Vue, Angular, and plain JavaScript. The importer ships in 12 languages, including Arabic, and the person can switch between them.</p>
<p>The security page states GDPR compliance and offers a DPA with standard contractual clauses on request, while the pricing page lists the DPA under Enterprise. UseCSV runs on Vercel and PlanetScale, and the same page states that Layercode, the company behind it, has not undergone a SOC 2 Type 2 audit.</p>
<h2 id="the-five-alternatives">The five alternatives</h2>
<h3 id="impler">Impler</h3>
<p>Impler keeps UseCSV's dashboard and publishes the code under MIT. Someone outside engineering configures the columns, and your code can override them at runtime. The widget covers upload, header selection, mapping, validation, and an inline editor built on Handsontable, and custom validation can check values against your database.</p>
<p>You can run the open-source version on your own servers for free, and the rows stay there. Impler's cloud processes files on its servers and keeps them seven days by default.</p>
<p>SDKs cover React and Angular, with a plain JavaScript embed and a Bubble plugin. A team using UseCSV's Vue library finds no Vue SDK. No locale ships, every interface string is overridable, and the Powered by Impler footer comes off on Scale.</p>
<p>Cloud plans meter the records imported across a month, and no per-file cap is published. Starter is free at 2,500 records a month on the pricing page and 5,000 on the homepage. Growth costs $35 a month for 50,000 records and Scale $75 for 150,000 when billed yearly, with $0.70 and $0.50 per extra 10,000. The homepage states support for files up to five million rows.</p>
<p><a href="https://updog.tech/alternative-to-impler/">Updog against Impler, side by side</a></p>
<h3 id="importok">ImportOK</h3>
<p>ImportOK replaces the per-import meter and the row cap per plan with a yearly price. You define the schema in code, and there is no dashboard for someone outside engineering. The person uploads a CSV or Excel file, ImportOK matches the columns, runs your validators and transformers, and opens the rows in a spreadsheet editor with an error filter and find and replace.</p>
<p>Its pricing page states that file contents are processed in the browser and go directly to your server, and no mode that routes rows through ImportOK was found.</p>
<p>It ships as a web component with React and Vue packages, rendered in your page with no iframe, and your CSS overrides its classes. Branding comes off on every paid plan, and paid plans list AI column mapping and AI transformations. Seven interface languages are built in, you can add your own, and no right-to-left support was found.</p>
<p>The homepage states support for files up to two million rows. Pro costs $149 a year and Growth $299 a year, both with unlimited imports, and Scale is priced by contact. A year of Pro costs less than one month of UseCSV's Pro plan. The free tester on npm stops at 20 records per import.</p>
<p><a href="https://updog.tech/alternative-to-importok/">Updog against ImportOK, side by side</a></p>
<h3 id="expresscsv">ExpressCSV</h3>
<p>ExpressCSV keeps the shape UseCSV takes in callback mode. The importer opens in an iframe from ExpressCSV's domain, parses and validates the file in the browser, and hands the records to your frontend. The review step is an AG Grid table with inline edits, undo and redo, valid and invalid tabs, per-column filters, sorting, and export as CSV or Excel. A failing check can return a one-click fix.</p>
<p>The homepage states that the raw data never touches ExpressCSV's servers. Its DPA names ExpressCSV as a processor for customer import data, and its AI features send sample values to a model provider.</p>
<p>The schema lives in TypeScript, and no dashboard was found. Your backend needs a route that exchanges a secret key for a short-lived token before the importer opens. A React package and a framework-agnostic TypeScript SDK ship, with quickstarts for Vue, Angular, and Svelte. Theme tokens and custom CSS style it with no badge found, the interface is English with every string overridable, and paid plans turn a typed instruction into JavaScript that runs on the grid.</p>
<p>Pricing counts imports, and no row cap is published. Startup costs $35 a month for 500 imports, Growth $80 for 1,000, and Scale $270 for 20,000, with $0.50, $0.25, and $0.15 per extra import. The free plan covers development, where the importer returns the first 100 rows of a file.</p>
<p><a href="https://updog.tech/alternative-to-expresscsv/">Updog against ExpressCSV, side by side</a></p>
<h3 id="csvbox">CSVbox</h3>
<p>CSVbox follows UseCSV's model most closely, with templates in a dashboard, a modal in an iframe, and plans priced by imports and rows per file. The person uploads a CSV or Excel file, CSVbox maps the columns and validates the rows, and the review table sorts, filters, and undoes up to 50 steps.</p>
<p>By default the file uploads to CSVbox's servers, which delete it after a month, and Private Mode keeps the rows in the browser once you switch it on. CSVbox lists SOC 2 Type II, a DPA, and a US or EU region.</p>
<p>SDKs cover React, Angular, Vue, and plain JavaScript. Custom theme, fonts, and logo start on Pro. The install docs list 28 interface languages, and no right-to-left layout was found. CSVbox ships AI column matching, AI document import from PDFs and images, and AI bulk transforms from Pro.</p>
<p>Startup costs $19 a month for 1,000 imports of up to 10,000 rows, Pro $49 for 5,000 imports of 50,000 rows, Growth $99 for 100,000 rows, and Plus $199 for 2,000,000 rows. Billed yearly, the same plans cost $16, $39, $82, and $165. The free Sandbox stops at five rows per import.</p>
<p><a href="https://updog.tech/alternative-to-csvbox/">Updog against CSVbox, side by side</a></p>
<h3 id="updog">Updog</h3>
<p>Updog keeps the rows in the browser and caps no file by plan. The person drops a CSV, TSV, Excel, JSON, or XML file, and Updog parses it on their machine, matches the columns, maps the values, and validates the rows. PDFs, scans, and other formats enter the same flow through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you provide</a>. The rows then open in a spreadsheet editor with clipboard, a fill handle, find and replace, formulas, filters, sorting, and undo and redo. The same editor opens on existing data without an import, and submit returns the edited rows to your code.</p>
<p>Updog has no webhook or server mode, so row data never reaches Updog, and there is no DPA, retention window, or region. As of September 2026, Updog holds no SOC 2 report and no ISO 27001 certificate.</p>
<p>It ships as a React component and a Web Component for Vue, Angular, Svelte, and plain JavaScript, rendered in your page with no iframe. The columns live in code, and there is no dashboard for someone outside engineering. Your CSS styles it on every plan, no plan carries a badge, every string is overridable, and right-to-left is built in. Updog has no built-in AI. A hook hands the data to your application, which sends it to the model it already uses and returns the answer to the importer.</p>
<p>About one million rows at 20 columns is a practical browser limit, depending on the machine's memory. Updog is free in development and free in production up to 100,000 rows a month. Team costs $100 a month, or $1,000 a year with two months free, for any number of domains, with no row or import limit.</p>
<p><a href="https://updog.tech/alternative-to-usecsv/">Updog against UseCSV, side by side</a></p>
<h2 id="the-decision-table">The decision table</h2>
<figure class="blog-figure blog-figure--wide"><div class="blog-table blog-table--alternatives"><table><colgroup><col><col><col><col><col><col><col></colgroup><thead><tr><th scope="col"></th><th scope="col">UseCSV</th><th scope="col">Impler</th><th scope="col">ImportOK</th><th scope="col">ExpressCSV</th><th scope="col">CSVbox</th><th scope="col">Updog</th></tr></thead><tbody><tr><th scope="row">Processing</th><td>Browser or server, per importer</td><td>Server or self-hosted</td><td>Browser</td><td>Browser</td><td>Server, browser opt-in</td><td>Browser</td></tr><tr><th scope="row">Embeds as</th><td>iframe</td><td>iframe</td><td>Web component, React, Vue</td><td>iframe</td><td>iframe</td><td>React, web component</td></tr><tr><th scope="row">Columns</th><td>Dashboard or code</td><td>Dashboard</td><td>Code</td><td>Code</td><td>Dashboard</td><td>Code</td></tr><tr><th scope="row">Editing</th><td>Inline fixes, error filter</td><td>Inline edits</td><td>Spreadsheet, filters</td><td>Grid, undo, filters</td><td>Table, filters, undo</td><td>Spreadsheet, formulas, undo</td></tr><tr><th scope="row">AI</th><td>None found</td><td>None</td><td>Built in, paid</td><td>Built in, paid</td><td>Built in</td><td>Your own model</td></tr><tr><th scope="row">Styling and badge</th><td>Badge off from Plus, styling on Pro</td><td>Colors, fonts, badge below Scale</td><td>Your CSS, no badge on paid</td><td>Your CSS, no badge</td><td>Theme from Pro</td><td>Your CSS, no badge</td></tr><tr><th scope="row">Languages</th><td>12</td><td>Any</td><td>Seven</td><td>Any</td><td>28</td><td>Any, right-to-left</td></tr><tr><th scope="row">Accessibility</th><td>No statement</td><td>Keyboard, grid roles</td><td>Keyboard</td><td>Keyboard, grid roles</td><td>No statement</td><td>Keyboard, screen reader</td></tr><tr><th scope="row">Rows per file</th><td>10K to 500K</td><td>5M</td><td>2M</td><td>Not published</td><td>10K to 2M</td><td>About 1M</td></tr><tr><th scope="row">Open source</th><td>No</td><td>Yes</td><td>No</td><td>No</td><td>No</td><td>No</td></tr><tr><th scope="row">Price</th><td>$0 to $199 a month</td><td>Free, or $0 to $75 a month</td><td>$149 or $299 a year</td><td>$35 to $270 a month</td><td>$19 to $199 a month</td><td>Free, or $100 a month</td></tr></tbody></table></div><figcaption class="blog-figure__note">Prices and limits were checked against each vendor's public pages in September 2026.</figcaption></figure>
<p>Embedded importers keep appearing, and basic CSV import is becoming a commodity. Updog tracks the market and publishes a comparison for every product we find on <a href="https://updog.tech/alternatives/">the alternatives page</a>. Which one fits your product is your decision.</p>]]></content:encoded></item>
<item><title>The Best CSVbox Alternatives in 2026</title><link>https://updog.tech/blog/best-csvbox-alternatives/</link><guid isPermaLink="true">https://updog.tech/blog/best-csvbox-alternatives/</guid><pubDate>Fri, 11 Sep 2026 00:00:00 GMT</pubDate><description>We picked five CSVbox alternatives at or under its price and compared which limit each removes, the row cap, the upload, or the dashboard, and what it costs.</description><content:encoded><![CDATA[<p>CSVbox is a hosted import widget. You configure a template in its dashboard, the person uploads a file through a modal in your app, and CSVbox maps the columns, validates the rows, and delivers the data to your webhook, API, or database.</p>
<p>CSVbox prices plans by imports and rows. Startup costs $19 a month and caps an import at 10,000 rows, Pro $49 at 50,000, Growth $99 at 100,000, and Plus $199 at 2,000,000, with 1,000 to 10,000 imports a month. Billed yearly, the same plans cost $16, $39, $82, and $165. A file that outgrows its cap moves the plan. By default the file uploads to CSVbox's servers and stays there for a month, and Private Mode, which keeps the rows in the browser, is a setting you switch on per sheet. The template lives in the dashboard, the importer opens in an iframe, and custom colors, fonts, and a logo start on Pro.</p>
<p>Flatfile, OneSchema, and Dromo are the established alternatives, so this list leaves them out.</p>
<h2 id="what-csvbox-does-well">What CSVbox does well</h2>
<p>CSVbox takes large files on its servers. The Plus plan accepts two million rows per import, uploads stream up to 500 MB, and its benchmark page shows a two-million-row file finishing end to end in about 150 seconds.</p>
<p>CSVbox ships its own AI. Column matching is AI-assisted. AI document import reads tables out of PDFs, images, and Word files, with a monthly page allowance from 5 on Sandbox to 3,000 on Plus. AI bulk transforms let the person rewrite a column from a plain-language prompt on Pro and above.</p>
<p>CSVbox lists SOC 2 Type II, GDPR, a DPA on request, and a choice of a US or EU region per template.</p>
<p>The review table gained column sorting, filtering, context menus, and undo and redo up to 50 steps in August 2026, and it opens inside an import. Import Links accept files with no code at all, and 20-plus destinations from Supabase to Zapier are documented.</p>
<p>The install docs list 28 interface languages, including Hebrew, Egyptian Arabic, and Urdu, and the change log entry for Arabic reads "ltr". No right-to-left layout was found.</p>
<h2 id="the-five-alternatives">The five alternatives</h2>
<h3 id="impler">Impler</h3>
<p>Impler keeps CSVbox's shape, columns in a dashboard and processing on a server, as open source under MIT. You can override the dashboard columns from code at runtime. The widget covers upload, header selection, mapping, validation, and an inline editor built on Handsontable, and Auto Import pulls files from a source on a schedule.</p>
<p>Self-hosted, the rows stay on your infrastructure and the software costs nothing. On Impler's cloud, they are processed on Impler's servers, its GDPR page names India on Azure as the storage location, and its homepage lists IN, US, EU, CA, and AU regions.</p>
<p>SDKs cover React, Angular, and plain JavaScript, with a Bubble plugin, and no Vue package was found. The widget opens in an iframe. No locale ships, and every interface string is overridable. The widget carries a Powered by Impler footer until the Scale plan.</p>
<p>The homepage states support for files up to five million rows, and cloud plans meter rows a month. Starter is free at 2,500 rows a month on the pricing page and 5,000 on the homepage. Growth is $35 a month for 50,000 rows and Scale $75 for 150,000 when billed yearly, with $0.70 and $0.50 per extra 10,000 records.</p>
<p><a href="https://updog.tech/alternative-to-impler/">Updog against Impler, side by side</a></p>
<h3 id="importok">ImportOK</h3>
<p>ImportOK removes the row cap and the default upload at a yearly price. You define the schema in code. The person uploads a CSV or Excel file, ImportOK matches the columns, runs your validators and transformers, and opens the rows in a spreadsheet editor with an error filter and find and replace. Submit posts the records to your own API.</p>
<p>Its pricing page states that file contents are processed in the browser and never reach ImportOK's servers, and that in most cases no DPA is required.</p>
<p>It ships as a Web Component with React and Vue packages, rendered in your page, with examples for Next.js, Angular, and plain JavaScript. Seven interface languages are built in, you can add your own, and no right-to-left support was found. Paid plans list AI column mapping and AI transformations under fair use, and no branding.</p>
<p>The homepage states support for files up to two million rows, the figure CSVbox reaches on its Plus plan. The free tester on npm stops at 20 records per import. Pro costs $149 a year and Growth $299 a year, both with unlimited imports, and Scale is priced by contact.</p>
<p><a href="https://updog.tech/alternative-to-importok/">Updog against ImportOK, side by side</a></p>
<h3 id="hellocsv">HelloCSV</h3>
<p>HelloCSV is free under MIT and has no server side. You define sheets and columns in code. The person uploads a CSV or TSV file and maps the headers to your columns from the suggestions HelloCSV proposes. They fix the rows in an editable preview with search, row add and remove, and a CSV download. Your code receives the rows on completion, and progress can be saved in the browser's IndexedDB so the person can return to a half-finished import.</p>
<p>HelloCSV itself sends nothing to a server. There is no vendor behind it, so there is no DPA, no certification, and no region to choose.</p>
<p>It ships React, Preact, and bundled builds, plus a CDN script. English, French, and Brazilian Portuguese are built in, and you can pass your own translations. Colors are CSS variables, and no build carries a badge. The preview table carries button roles and no grid roles.</p>
<p>Excel needs a loader you write, a function that turns the file into CSV text and may run on your server. Validators cover required, unique, regex, list membership, integer, email, phone number, and postal code, plus your own, and sheets can reference each other. No undo and no find and replace were found. The default file limit is 20 MB and you set it, and no row limit is published, so the browser's memory is the ceiling.</p>
<p><a href="https://updog.tech/alternative-to-hellocsv/">Updog against HelloCSV, side by side</a></p>
<h3 id="filefeed">FileFeed</h3>
<p>FileFeed's importer is a free React component under MIT. You define sheets and typed fields in code, with required and unique flags. The person drops a CSV, XLSX, or XLS file, and FileFeed detects the encoding, matches the headers to your fields, and validates each cell. The person corrects a match by drag and drop, edits invalid cells inline, and can type rows in by hand. Your code receives the rows on completion.</p>
<p>Parsing and validation run in the browser, and the 0.1.11 package contains no network call. The product page describes AI-assisted column matching, the package README describes matching by string similarity, and no AI code was found in the package.</p>
<p>The component needs Mantine 7 as a peer dependency and renders with Mantine's look, inline or in a modal, with a light and a dark theme. The interface is English, and no translations were found. No badge was found. The product page says it works with any frontend framework, and the docs list Vue and Angular as coming soon.</p>
<p>The package rejects Excel files over 50 MB, no row limit is published, and the product page describes a virtualized grid at a hundred thousand rows. The importer is free, and FileFeed's paid plans, from $299 a month, cover its separate Automated FileFeeds product.</p>
<p><a href="https://updog.tech/alternative-to-filefeed/">Updog against FileFeed, side by side</a></p>
<h3 id="updog">Updog</h3>
<p>Updog keeps the columns in code and the rows in the browser, with no dashboard. The person drops a CSV, TSV, Excel, JSON, or XML file, and Updog parses it on their machine, matches the columns, maps the values, and validates the rows. PDFs, scans, and other formats enter the same flow through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you provide</a>. The rows then open in a spreadsheet editor with clipboard, a fill handle, find and replace, formulas, filters, sorting, and undo and redo. The same editor opens on existing data without an import, and submit returns the edited rows to your code.</p>
<p>Updog has no server mode. Row data never reaches Updog, so there is no DPA, retention window, or region. As of September 2026, Updog holds no SOC 2 report and no ISO 27001 certificate.</p>
<p>It ships as a React component and a Web Component for Vue, Angular, Svelte, and plain JavaScript, with no iframe. Your CSS styles it, every string is overridable, right-to-left is built in, and no plan carries a badge. Updog has no built-in AI. A hook hands the data to your application, which sends it to the model it already uses and returns the answer to the importer.</p>
<p>About one million rows at 20 columns is a practical browser limit, depending on the machine's memory. Updog is free in development and free in production up to 100,000 rows a month. Team costs $100 a month, or $1,000 a year with two months free, for any number of domains, with no row limit.</p>
<p><a href="https://updog.tech/alternative-to-csvbox/">Updog against CSVbox, side by side</a></p>
<h2 id="the-decision-table">The decision table</h2>
<figure class="blog-figure blog-figure--wide"><div class="blog-table blog-table--alternatives"><table><colgroup><col><col><col><col><col><col><col></colgroup><thead><tr><th scope="col"></th><th scope="col">CSVbox</th><th scope="col">Impler</th><th scope="col">ImportOK</th><th scope="col">HelloCSV</th><th scope="col">FileFeed</th><th scope="col">Updog</th></tr></thead><tbody><tr><th scope="row">Processing</th><td>Server, browser opt-in</td><td>Server or self-hosted</td><td>Browser</td><td>Browser</td><td>Browser</td><td>Browser</td></tr><tr><th scope="row">Embeds as</th><td>iframe</td><td>iframe</td><td>Web component, React, Vue</td><td>React, Preact, script tag</td><td>React</td><td>React, web component</td></tr><tr><th scope="row">Columns</th><td>Dashboard</td><td>Dashboard</td><td>Code</td><td>Code</td><td>Code</td><td>Code</td></tr><tr><th scope="row">Editing</th><td>Table, filters, undo</td><td>Inline edits</td><td>Spreadsheet, filters</td><td>Preview, search</td><td>Inline fixes</td><td>Spreadsheet, formulas, undo</td></tr><tr><th scope="row">AI</th><td>Built in</td><td>None</td><td>Built in, paid</td><td>None</td><td>None found</td><td>Your own model</td></tr><tr><th scope="row">Excel</th><td>Yes</td><td>Yes</td><td>Yes</td><td>Your own loader</td><td>Yes, 50 MB</td><td>Yes</td></tr><tr><th scope="row">Styling and badge</th><td>Theme from Pro, no badge</td><td>Colors, fonts, badge below Scale</td><td>Your CSS, no badge on paid</td><td>CSS variables, no badge</td><td>Themes, no badge</td><td>Your CSS, no badge</td></tr><tr><th scope="row">Languages</th><td>28</td><td>Any</td><td>Seven</td><td>Three, or your own</td><td>English</td><td>Any, right-to-left</td></tr><tr><th scope="row">Accessibility</th><td>No statement</td><td>Keyboard, grid roles</td><td>Keyboard</td><td>Button roles</td><td>No grid roles</td><td>Keyboard, screen reader</td></tr><tr><th scope="row">Rows per file</th><td>10K to 2M</td><td>5M</td><td>2M</td><td>Not published</td><td>Not published</td><td>About 1M</td></tr><tr><th scope="row">Open source</th><td>No</td><td>Yes</td><td>No</td><td>Yes</td><td>Yes</td><td>No</td></tr><tr><th scope="row">Price</th><td>$19 to $199 a month</td><td>Free, or $0 to $75 a month</td><td>$149 or $299 a year</td><td>Free</td><td>Free</td><td>Free, or $100 a month</td></tr></tbody></table></div><figcaption class="blog-figure__note">Prices and limits were checked against each vendor's public pages in September 2026.</figcaption></figure>
<p>Embedded importers keep appearing, and basic CSV import is becoming a commodity. Updog tracks the market and publishes a comparison for every product we find on <a href="https://updog.tech/alternatives/">the alternatives page</a>. Which one fits your product is your decision.</p>]]></content:encoded></item>
<item><title>The Best Flatfile Alternatives in 2026</title><link>https://updog.tech/blog/best-flatfile-alternatives/</link><guid isPermaLink="true">https://updog.tech/blog/best-flatfile-alternatives/</guid><pubDate>Wed, 09 Sep 2026 00:00:00 GMT</pubDate><description>We picked five Flatfile alternatives beyond the usual shortlist and compared where each processes the file, what it charges, and where it stops.</description><content:encoded><![CDATA[<p>Flatfile is a hosted data import platform. You define the schema in code, and the person uploads the file to Flatfile, where the platform maps, validates, and transforms the data. A whole team can work on the same import.</p>
<p>Flatfile publishes no price. It prices plans by the team's project volume, and every plan ends in a Talk to sales button. The company renamed itself Obvious in late 2025, and its knowledge base states that the Flatfile product stays in long-term support with the same pricing. Every file uploads to Flatfile's servers, so a team that prohibits third-party processors cannot use it. The whole platform, collaborative editing, multi-step approvals, comments, and audit trails, arrives inside an iframe when your app needs one import screen.</p>
<p>OneSchema and Dromo are the established alternatives, so this list leaves them out.</p>
<h2 id="what-flatfile-does-well">What Flatfile does well</h2>
<p>Flatfile takes large files. Its knowledge base recommends up to one million rows per sheet and points to a streaming JSONL endpoint past that.</p>
<p>Flatfile supports team workflows. A project includes collaborative editing, approvals, comments, version history, and audit trails, and the pricing page says seats are not counted. That matters when several people review the same import.</p>
<p>Its AI runs inside Flatfile's infrastructure, and its security page states that customer-uploaded data does not go to third-party AI vendors.</p>
<p>Flatfile holds the enterprise paperwork. It lists SOC 2 Type II, ISO 27001, GDPR and CCPA compliance, HIPAA readiness, a DPA, region-specific hosting, and self-managed deployment on the enterprise tier.</p>
<p>Flatfile's internationalization guide lists 26 locale codes across 17 languages.</p>
<h2 id="the-five-alternatives">The five alternatives</h2>
<h3 id="impler">Impler</h3>
<p>You define columns in a dashboard and can override them in code at runtime. The widget covers upload, header selection, mapping, editing, and validation, while Auto Import can pull files from a source on a schedule.</p>
<p>Impler processes files on a server. With self-hosting, the rows stay on your infrastructure. With Impler's cloud, they are processed on Impler's servers.</p>
<p>The code is MIT-licensed. SDKs cover React, Angular, and plain JavaScript, and there is a Bubble plugin. The importer runs in an iframe. Interface text is configurable. The widget's footer shows Powered by Impler by default, and the Scale plan removes it.</p>
<p>The homepage states support for files up to five million rows. Self-hosting is free apart from infrastructure. Cloud plans are priced by rows, starting with a free tier, then $35 a month for 50,000 rows and $75 for 150,000 when billed yearly. The free tier includes 2,500 rows by the pricing page and 5,000 by the homepage.</p>
<p><a href="https://updog.tech/alternative-to-impler/">Updog against Impler, side by side</a></p>
<h3 id="importok">ImportOK</h3>
<p>You define the schema in code. The person uploads a CSV or Excel file, and ImportOK maps columns, validates and transforms the rows, and opens them in a spreadsheet editor with an error filter and find and replace. Submit sends the finished records to your endpoint.</p>
<p>Its pricing page states that file contents are processed in the browser and never reach ImportOK's servers.</p>
<p>ImportOK ships as a Web Component, with React and Vue packages and examples for Next.js, Angular, and plain JavaScript. Seven interface languages are built in, and you can add your own. Paid plans include AI column mapping and transformations with no branding.</p>
<p>The homepage states support for files up to two million rows. The free npm tester stops at 20 records per import. Pro costs $149 a year and Growth $299 a year with unlimited imports. Scale pricing is available by contact.</p>
<p><a href="https://updog.tech/alternative-to-importok/">Updog against ImportOK, side by side</a></p>
<h3 id="importcsv">ImportCSV</h3>
<p>You pass columns or a Zod schema in code. In local mode, ImportCSV parses the person's file in the browser, matches the headers, validates and types the rows, and returns the result to your code. Headless primitives let you build the screens with your own component library.</p>
<p>Nothing leaves the browser in local mode. AI column mapping and plain-English fixes require the backend, which sends column names and sample values to OpenAI. The backend is AGPL-3.0 and can run on your own server with your own OpenAI key or on ImportCSV's hosting.</p>
<p>The frontend is an MIT-licensed React component with a Preact build. The README states there is no Vue or Angular version. The interface is English. The free hosted tier includes ImportCSV branding, while Pro removes it.</p>
<p>The README states support for up to 100,000 rows in the browser, and its large-file guide recommends server-side chunking above 50,000. Local mode is free. Hosted plans start at $0 for 100 imports a month, then $49 for 2,000 imports and $149 for unlimited imports, with higher row limits on each tier.</p>
<p><a href="https://updog.tech/alternative-to-importcsv/">Updog against ImportCSV, side by side</a></p>
<h3 id="expresscsv">ExpressCSV</h3>
<p>You define the schema in TypeScript. ExpressCSV parses and validates the person's file in the browser and opens it in an AG Grid editor with inline edits, undo and redo, filters, sorting, and valid and invalid tabs. Validation can return one-click fixes, and paid plans add prompt-based transformations that generate JavaScript and apply it to the grid.</p>
<p>The homepage states that user data never touches ExpressCSV's servers. Its DPA names ExpressCSV as a processor for customer import data, and the company offers a signed DPA. AI features send sample values to a model provider.</p>
<p>The importer runs in a full-screen iframe from ExpressCSV's domain. Your backend exchanges a secret key for a short-lived token. Theme variables, custom CSS, fonts, and interface text are configurable.</p>
<p>The free plan covers development, where the importer returns the first 100 rows of a file. Paid plans start at $35 a month for 500 imports, then $80 for 1,000 and $270 for 20,000, with per-import overage pricing.</p>
<p><a href="https://updog.tech/alternative-to-expresscsv/">Updog against ExpressCSV, side by side</a></p>
<h3 id="updog">Updog</h3>
<p>You define the schema in code. The person drops a CSV, TSV, Excel, JSON, or XML file, and Updog parses it in the browser, matches columns to your fields, maps values, validates the rows, and opens them in a spreadsheet editor. PDFs, scans, and other formats enter the same flow through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you provide</a>. Submit returns the edited rows to your code.</p>
<p>The editor works as a spreadsheet, with typed cell editors, clipboard, a fill handle, find and replace, formulas, filters, sorting, and undo and redo.</p>
<p>Row data never reaches Updog, so Updog is not a data processor and there is no DPA to sign. As of September 2026, Updog has no SOC 2 report or ISO 27001 certificate.</p>
<p>It ships as a React component and a Web Component for Vue, Angular, Svelte, and plain JavaScript, and renders in your page with no iframe. Styling, interface text, and right-to-left layout are configurable, and no plan carries a badge. Updog has no built-in AI. A hook hands the data to your application, which sends it to the model it already uses and returns the answer to the importer.</p>
<p>About one million rows at 20 columns is a practical browser limit, depending on the machine's memory. Updog is free in development and free in production up to 100,000 rows a month. Team costs $100 a month, or $1,000 a year with two months free, for any number of domains, with no row limit.</p>
<p><a href="https://updog.tech/alternative-to-flatfile/">Updog against Flatfile, side by side</a></p>
<h2 id="the-decision-table">The decision table</h2>
<figure class="blog-figure blog-figure--wide"><div class="blog-table blog-table--alternatives"><table><colgroup><col><col><col><col><col><col><col></colgroup><thead><tr><th scope="col"></th><th scope="col">Flatfile</th><th scope="col">Impler</th><th scope="col">ImportOK</th><th scope="col">ImportCSV</th><th scope="col">ExpressCSV</th><th scope="col">Updog</th></tr></thead><tbody><tr><th scope="row">Processing</th><td>Server</td><td>Server or self-hosted</td><td>Browser</td><td>Browser, server for AI</td><td>Browser</td><td>Browser</td></tr><tr><th scope="row">Embeds as</th><td>iframe</td><td>iframe</td><td>Web component, React, Vue</td><td>React</td><td>iframe</td><td>React, web component</td></tr><tr><th scope="row">Columns</th><td>Code</td><td>Dashboard</td><td>Code</td><td>Code</td><td>Code</td><td>Code</td></tr><tr><th scope="row">Editing</th><td>Grid, filters, snapshots</td><td>Inline edits</td><td>Spreadsheet, filters</td><td>Cell-by-cell review</td><td>Grid, undo, filters</td><td>Spreadsheet, formulas, undo</td></tr><tr><th scope="row">AI</th><td>Built in</td><td>None</td><td>Built in, paid</td><td>Server, OpenAI</td><td>Built in, paid</td><td>Your own model</td></tr><tr><th scope="row">Styling and badge</th><td>Theme, badge plan unstated</td><td>Colors, fonts, badge below Scale</td><td>Your CSS, no badge on paid</td><td>Theme, badge on free</td><td>Your CSS, no badge</td><td>Your CSS, no badge</td></tr><tr><th scope="row">Languages</th><td>17</td><td>Any</td><td>Seven</td><td>English</td><td>Any</td><td>Any, right-to-left</td></tr><tr><th scope="row">Accessibility</th><td>No statement</td><td>Keyboard, grid roles</td><td>Keyboard</td><td>No keyboard</td><td>Keyboard, grid roles</td><td>Keyboard, screen reader</td></tr><tr><th scope="row">Rows per file</th><td>About 1M</td><td>5M</td><td>2M</td><td>100K</td><td>Not published</td><td>About 1M</td></tr><tr><th scope="row">Open source</th><td>No</td><td>Yes</td><td>No</td><td>Yes</td><td>No</td><td>No</td></tr><tr><th scope="row">Price</th><td>Not published</td><td>Free, or $0 to $75 a month</td><td>$149 or $299 a year</td><td>Free, or $0 to $149 a month</td><td>$35 to $270 a month</td><td>Free, or $100 a month</td></tr></tbody></table></div><figcaption class="blog-figure__note">Prices and limits were checked against each vendor's public pages in September 2026.</figcaption></figure>
<p>Embedded importers keep appearing, and basic CSV import is becoming a commodity. Updog tracks the market and publishes a comparison for every product we find on <a href="https://updog.tech/alternatives/">the alternatives page</a>. Which one fits your product is your decision.</p>]]></content:encoded></item>
<item><title>How to Handle Large CSV Files in JavaScript Without Freezing the Browser</title><link>https://updog.tech/blog/handle-large-csv-files-in-javascript/</link><guid isPermaLink="true">https://updog.tech/blog/handle-large-csv-files-in-javascript/</guid><pubDate>Fri, 04 Sep 2026 00:00:00 GMT</pubDate><description>A large CSV file freezes the browser in more than one place, and a Web Worker clears one. We measured how a million rows go inside Updog Importer.</description><content:encoded><![CDATA[<p>I generated a CSV with one million rows, eleven columns, and a file size of 108 MB, enabled Chrome's long-task observer, and ran the file through Updog Importer from the file picker to the grid.</p>
<p>Parsing took 2.7 seconds. The full import took 12 seconds. The browser continued painting during both, although the main thread still hit one 389 ms task when the parsed rows arrived from the worker. Every measurement in this article comes from that run in Chrome 151 on 4 September 2026.</p>
<p>Handling a large CSV in JavaScript stalls a page at several boundaries, and fixing one leaves the others in place. Parsing occupies a thread for seconds. The parsed data takes several times the file size in memory. Moving a million rows into application state blocks the main thread again. Rendering every row turns the problem into layout and paint. Filtering scans the full dataset on every keystroke.</p>
<p>Each boundary has its own mechanism, and a Web Worker covers the first of them.</p>
<h2 id="parsing-runs-in-a-worker-and-comes-back-whole">Parsing runs in a worker and comes back whole</h2>
<p>Updog Importer sends the <code>File</code> to a Web Worker. The main thread posts the file with <code>postMessage</code>, and the browser clones the <code>File</code> as a reference to the same bytes, so nothing is copied into a second JavaScript buffer first.</p>
<p>Inside the Web Worker, the whole file is read into memory, decoded into one string, and parsed by PapaParse in one call.</p>
<pre><code class="language-ts">export const parseCsvFile = async ({ file }: ParseInput): Promise&#x3C;ParseResult> => {
  const { text, delimiter } = await decodeFileText(file);

  const results = Papa.parse&#x3C;string[]>(text, {
    header: false,
    skipEmptyLines: false,
    delimiter,
  });

  const rows = results.data;

  for (const row of rows) {
    for (let i = 0; i &#x3C; row.length; i++) row[i] = cleanCell(row[i]);
  }

  return { kind: "rows", rows, delimiter, errors };
};</code></pre>
<p>Decoding happens before parsing. The decoder sees the complete byte sequence, so a multibyte character cannot be split between parsing chunks, and delimiter detection runs on decoded text. Each cell then passes through one normalizer, which removes zero-width characters, replaces non-breaking spaces, and trims the value.</p>
<p>The worker returns the parsed rows in one message.</p>
<p>On the million-row file, reading the bytes took 65 ms and UTF-8 decoding took 46 ms when measured separately in a worker. The full worker round trip, from posting the file to receiving the parsed rows on the main thread, took 2,704 ms.</p>
<p>The main thread remained available while the worker parsed. The expensive moment came when the result arrived. Structured cloning had to materialize one million row arrays on the receiving side, producing a 389 ms main-thread task.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Stage</th>
<th>Measured</th>
</tr>
</thead>
<tbody>
<tr>
<td>File posted to rows on the main thread</td>
<td>2,704 ms</td>
</tr>
<tr>
<td>Reading the bytes in the worker</td>
<td>65 ms</td>
</tr>
<tr>
<td>Decoding UTF-8 in the worker</td>
<td>46 ms</td>
</tr>
<tr>
<td>Longest main-thread task during parsing</td>
<td>389 ms</td>
</tr>
<tr>
<td>Main-thread heap after parsing</td>
<td>351 MB</td>
</tr>
</tbody>
</table></div>
<p>The Web Worker removed parsing from the main thread. It did not reduce the size of the parsed result or change the fact that all one million rows arrived there together.</p>
<p>At that boundary the cost is memory, and the usual answer to memory is streaming.</p>
<h2 id="streaming-fits-a-one-pass-job">Streaming fits a one-pass job</h2>
<p>The standard advice for a large CSV is to stream it. Read the file in chunks, process each chunk as it arrives, and discard it when the work is done.</p>
<p>That works for one-pass jobs. Summing a column, checking a header, or sending rows to a server in batches can finish with one chunk before the next arrives. Memory stays close to the size of the active chunk.</p>
<p>An editable dataset has a different requirement. A person may sort it, filter it, correct a cell in the middle, and undo that correction. An in-memory editor needs the rows to remain available after parsing.</p>
<p>Put a streaming parser in front of that editor and the code eventually does this.</p>
<pre><code class="language-ts">const rows = [];

parser.on("chunk", (chunk) => {
  rows.push(...chunk);
});

parser.on("end", () => {
  renderGrid(rows);
});</code></pre>
<p>Parsing is incremental, and storage accumulates. Every chunk stays in <code>rows</code>, so the final dataset occupies the same memory the grid would have needed after a whole-file parse.</p>
<p>Updog Importer therefore parses the CSV in one pass inside the worker. Column matching, validation, sorting, filtering, editing, and undo all operate on a complete in-memory dataset, so the more important problem is reducing what that dataset costs once it exists.</p>
<h2 id="the-shape-of-a-row-decides-the-memory">The shape of a row decides the memory</h2>
<p>A million rows with eleven columns is eleven million cells, and the row objects around those cells have a cost of their own.</p>
<p>V8 normally gives objects with the same property layout a shared hidden class and stores their values in fixed slots. Add properties one at a time past a threshold, and an object can move into dictionary mode, where it carries a property table of its own. <a href="https://v8.dev/blog/fast-properties">V8's write-up on fast properties</a> describes the two representations. Measured on Chrome 151, objects built one key at a time switched at the twentieth key.</p>
<p>The difference is large. We measured one million rows with twenty properties.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>How the row was built</th>
<th>Memory</th>
<th>Column read</th>
<th>Column write</th>
</tr>
</thead>
<tbody>
<tr>
<td>20 keys, added one at a time</td>
<td>412 MB</td>
<td>40 ms</td>
<td>88 ms</td>
</tr>
<tr>
<td>20 keys, shape created up front</td>
<td>92 MB</td>
<td>4 ms</td>
<td>10 ms</td>
</tr>
</tbody>
</table></div>
<p>A CSV importer naturally tends towards the first shape. It reads a header, creates an empty row, and assigns one cell after another.</p>
<p>Updog Importer creates the complete shape first. <code>createRowShape</code> builds one template containing every column key, then each imported row starts as a clone of that template.</p>
<pre><code class="language-ts">const templateOf = (keys, booleanKeys) => {
  const body = keys
    .map((key) =>
      JSON.stringify(key) + ":" + (booleanKeys.has(key) ? "false" : '""')
    )
    .join(",");

  return JSON.parse("{" + body + "}");
};

const template = templateOf(keys, booleanKeys);

const make = () => {
  return { ...template };
};</code></pre>
<p>Every row therefore starts with the same set of properties before any imported value is written. Updating an existing key does not change that shape.</p>
<p>That also gives the editor a consistent row contract. A column absent from the file still exists on every row as an empty value. Without that, later comparison code has to distinguish between a missing property and an empty cell, which can make untouched rows look changed.</p>
<p>The store keeps those rows in a plain array indexed by sequential id. Deleting a row leaves <code>undefined</code> in its slot, so the array keeps one element kind in V8 and no row after it moves.</p>
<p>The importer also releases the raw representation while it builds the final one. Rows arrive from the worker as arrays of strings, while the editor stores row objects. Holding both complete representations for the whole import would keep two copies of the dataset on the heap at the same time.</p>
<p>Instead, the import converts 5,000 rows at a time. Once one chunk has entered the store, its raw rows are cleared before the next chunk begins.</p>
<pre><code class="language-ts">await onChunk(rows, { chunkIndex, chunkCount, isLastChunk });

for (let i = processed; i &#x3C; end; i++) {
  rawRows[dataIdx[i]] = undefined;
}
processed = end;

if (processed &#x3C; dataIdx.length) await yieldToBrowser();</code></pre>
<p>The heap measurements show the result.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Main-thread heap</th>
<th>Measured</th>
</tr>
</thead>
<tbody>
<tr>
<td>After parsing</td>
<td>351 MB</td>
</tr>
<tr>
<td>Peak during import</td>
<td>833 MB</td>
</tr>
<tr>
<td>After garbage collection</td>
<td>580 MB</td>
</tr>
</tbody>
</table></div>
<p>The peak stays below the raw grid plus the complete editor store because part of the raw representation is released while the store is still being built.</p>
<p>At this size, memory depends on how the values are represented and on how long two representations stay alive together, as much as on how many values there are.</p>
<h2 id="the-main-thread-yields-between-chunks">The main thread yields between chunks</h2>
<p>Landing a million rows is main-thread work by design. The store, validator, and grid all work over the same row objects, so those objects have to be created where the application reads them.</p>
<p>The importer keeps that work responsive by yielding between chunks.</p>
<pre><code class="language-ts">export const yieldToBrowser = (): Promise&#x3C;void> => {
  if (typeof MessageChannel === "undefined") {
    return new Promise((resolve) => setTimeout(resolve, 0));
  }
  return new Promise((resolve) => {
    const { port1, port2 } = new MessageChannel();
    port1.onmessage = () => {
      port1.close();
      resolve();
    };
    port2.postMessage(null);
  });
};</code></pre>
<p>A microtask is not enough. Promise continuations run before the event loop reaches its next rendering opportunity, so repeatedly awaiting resolved promises can keep the main thread occupied without giving the browser a chance to paint.</p>
<p>A timer can create that break, but chained timers eventually hit <a href="https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps">the HTML timer clamp</a>. After more than five nested timers, a timeout below 4 ms is raised to at least 4 ms.</p>
<p><code>MessageChannel</code> schedules another task without that timer clamp. When one import chunk finishes, control returns to the event loop before the next one starts. That gives the browser an opportunity to paint and to process input, where a single continuous task would keep both waiting until the import ended.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Import of one million rows</th>
<th>Measured</th>
</tr>
</thead>
<tbody>
<tr>
<td>Click on Import to grid on screen</td>
<td>12,261 ms</td>
</tr>
<tr>
<td>Tasks longer than 50 ms</td>
<td>71</td>
</tr>
<tr>
<td>Longest task</td>
<td>122 ms</td>
</tr>
<tr>
<td>Main-thread heap at peak</td>
<td>833 MB</td>
</tr>
<tr>
<td>Main-thread heap after garbage collection</td>
<td>580 MB</td>
</tr>
</tbody>
</table></div>
<p>The import still takes twelve seconds, and some chunks still produce long tasks. The difference is that those tasks are separated, with the event loop running between them. In this run, 71 tasks crossed the 50 ms long-task threshold and the longest lasted 122 ms.</p>
<p>Validation uses the same pattern. Revalidating a column after a bulk change runs through the same chunked processor, with a yield between chunks.</p>
<p>Large bulk operations do the same. An operation touching at least 50,000 cells shows progress and processes rows in batches of 25,000. Splitting a column across a million rows therefore advances through bounded pieces, and the main thread is free between them.</p>
<p>Yielding does not make the work cheaper. It changes when the browser gets control back.</p>
<h2 id="rendering-scales-with-the-viewport">Rendering scales with the viewport</h2>
<p>Every row in the store is now an object. A table built from DOM elements would also need an element for every visible cell, and each element brings layout and paint work with it.</p>
<p>DOM virtualization limits that cost by keeping only the visible rows mounted. A canvas grid goes further and removes the cell elements altogether. In both designs, the work required to draw a frame depends mostly on the viewport, and the total row count stops dominating the cost of a frame.</p>
<p>Updog Importer draws the grid on a canvas. When something changes, it redraws the visible viewport. When nothing changes, it does not draw another frame.</p>
<p>The rendering engine, the caches that keep full viewport redraws cheap, and the scroll mapping that lets the grid move beyond the browser's maximum element height are covered in <a href="https://updog.tech/blog/canvas-grid-performance/">the canvas grid post</a>.</p>
<p>That solves the rendering boundary. It does not help with the work that happens before the first frame appears. Parsing, memory, and store construction still need their own limits, which is why rendering is only one part of the large-file path.</p>
<h2 id="filtering-still-walks-every-row">Filtering still walks every row</h2>
<p>Viewport-sized rendering does not help with operations that inspect the dataset itself. A search term or error filter still has to test every row. On a million-row dataset, each change to the filter can mean another million-row scan.</p>
<p>Run that work on the main thread and the grid can render quickly while typing still freezes the page.</p>
<p>Updog Importer keeps a second representation of the dataset in a worker. Each row becomes a flat string for searchable cell text, with bitmasks for error and edit state. Filtering and sorting run against that worker-side data, and only the matching row ids return to the main thread.</p>
<p>An edit does not resend the dataset. Changing one cell sends a small message with the updated text for that row, so the worker keeps its copy in sync.</p>
<p>On one million rows with fifteen columns, a filter round trip took between 30 and 250 milliseconds in the session measured for <a href="https://updog.tech/blog/filter-panel-performance/">the filter panel post</a>, which also covers the ordering of the checks, the worker representation, and the protection against stale results.</p>
<p>Rendering scales with the viewport. Filtering and sorting still scale with the dataset, so they need a separate execution path.</p>
<h2 id="the-browser-sets-the-ceiling">The browser sets the ceiling</h2>
<p>Everything above still runs inside one browser tab, and browser memory sets the ceiling for any client-side importer.</p>
<p>In this run, one million rows with eleven columns settled at 580 MB on the main thread. The filtering worker held its own mirror of the dataset on top of that. One million rows is the scale this design makes room for by controlling representation, temporary copies, rendering, and dataset-wide work.</p>
<p>The worker boundary also isolates parsing from the rest of the page. If parsing cannot complete because the worker runs out of resources, the importer can terminate that path and report the failure without turning the parsing loop into main-thread work.</p>
<p>Beyond the memory available to a browser tab, the architecture has to change. The same applies to scheduled imports that run with nobody at the keyboard. Those jobs belong on a server. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">The client-side and server-side post</a> covers that boundary.</p>
<p>The million-row run shows why no single optimization was enough. A worker kept parsing off the main thread. A shared row shape kept the store compact. Chunked writes returned control to the browser during import. Canvas limited rendering to the viewport. A second worker handled filters and sorts over the full dataset.</p>
<p>Each mechanism removed a different way for the page to stall. Together they took a 108 MB CSV from the file picker to an editable grid of one million rows without turning the twelve-second import into one twelve-second main-thread task.</p>]]></content:encoded></item>
<item><title>Add CSV and Excel Import to a Replit App</title><link>https://updog.tech/blog/add-csv-and-excel-import-to-a-replit-app/</link><guid isPermaLink="true">https://updog.tech/blog/add-csv-and-excel-import-to-a-replit-app/</guid><pubDate>Thu, 03 Sep 2026 00:00:00 GMT</pubDate><description>A school writes its roll its own way. See how Updog Importer brings that file into an app built on Replit.</description><content:encoded><![CDATA[<p>Replit turns a prompt into a working app and publishes it from the same project. The Project Editor runs the app behind a development URL, and Publishing puts the result on a <code>replit.app</code> address.</p>
<p>An import in that project ends at a function you wrote. The browser hands it the corrected rows, and the body of that function is the only place the roll is stored.</p>
<p>Once that app has users, their records already sit somewhere else. A school office keeps its roll in a spreadsheet exported from whichever system it ran before, and those rows belong on your students page.</p>
<p>Updog Importer adds that path. The example runs on a students page backed by an empty roll.</p>
<p>The Replit Agent can build that import screen, or it can install one.</p>
<h2 id="replit-already-builds-an-app-out-of-a-spreadsheet">Replit already builds an app out of a spreadsheet</h2>
<p>Open <code>replit.com/import</code>, pick Spreadsheet, and hand over an <code>.xlsx</code> file, a <code>.csv</code> file or a public Google Sheets URL. Agent reads the structure and builds an app with a database seeded from that data, along with a screen for viewing, searching and managing the records.</p>
<p>That serves the person building the app.</p>
<p>A customer import runs the other way round. The school office opens the finished students page with a file you have never seen, reads it, corrects it, and sends you what they accept.</p>
<p>Importing a spreadsheet on <code>replit.com/import</code> happens while you build the product. The import screen below ships inside it.</p>
<h2 id="the-project-already-has-a-students-page">The project already has a students page</h2>
<p>One prompt to Agent produced the starting app.</p>
<pre><code class="language-text">Build a small school roll app with one page, on Vite, React and TypeScript.

A student carries these seven fields.

  student_ref      text, the key
  first_name       text
  last_name        text
  date_of_birth    a date written YYYY-MM-DD
  year_group       text
  house            text
  guardian_email   text

Put the roll behind one module, src/lib/roll.ts, holding an array in memory and
exporting two functions.

  loadStudents()          returns every student
  saveStudents(students)  stores each one under its student_ref, replacing a
                          student already held

Render /students as a page that reads the roll through loadStudents and shows
those seven fields in a table, with the roll count above it and an empty state
while the roll holds nothing. Redirect / to /students.

Have the dev server listen on 0.0.0.0 and on the port Replit gives it.

Keep the styling plain, and give the app one primary color, #2c5f5d. No
authentication, no database, no seed data, no extra pages.</code></pre>
<p>Agent scaffolded a Vite, React and TypeScript page, wrote the roll module behind those two functions, and bound the dev server to <code>0.0.0.0</code> and the port Replit gives it. The page rendered an empty roll.</p>
<p><code>saveStudents</code> holds the roll in memory here, so a reload empties it. Filling that body with a Replit database, or with anything else the project can reach, changes the module and leaves the page and the import screen as they are.</p>
<p>Those seven field names carry through the whole example. The importer's column ids use the same <code>snake_case</code> names as the roll module, so a row the editor returns already has the shape <code>saveStudents</code> expects.</p>
<p>Everything below builds on that project and on one file the project has never seen.</p>
<h2 id="the-file-brings-its-own-schema">The file brings its own schema</h2>
<p>The office's file follows a schema your app does not control. Its headers spell the old system's names. Its dates may run in another order, and its values may sit outside the options your fields allow.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>The screen has to</th>
<th>Because an export</th>
</tr>
</thead>
<tbody>
<tr>
<td>detect encoding and delimiter</td>
<td>arrives as UTF-8, Windows-1252, comma or semicolon</td>
</tr>
<tr>
<td>find the header row</td>
<td>carries a report title and an export date above it</td>
</tr>
<tr>
<td>read every sheet of a workbook</td>
<td>is <code>.xlsx</code> with one tab per year group</td>
</tr>
<tr>
<td>settle the date order per column</td>
<td>writes <code>04/11/2015</code> and means the fourth of November</td>
</tr>
<tr>
<td>keep leading zeros</td>
<td>holds <code>00417</code>, and a plain reader makes it <code>417</code></td>
</tr>
<tr>
<td>match headers onto your fields</td>
<td>says <code>DOB</code> where your app says <code>date_of_birth</code></td>
</tr>
<tr>
<td>match values onto your options</td>
<td>says <code>Yr 9</code> where your app says <code>Year 9</code></td>
</tr>
<tr>
<td>check and let the person fix</td>
<td>holds a row <code>saveStudents</code> will reject</td>
</tr>
<tr>
<td>stay usable at scale</td>
<td>is a hundred thousand rows on a laptop</td>
</tr>
<tr>
<td>report new and changed rows</td>
<td>is the second upload of a roll that landed once already</td>
</tr>
</tbody>
</table></div>
<p>Every line in that table turns into a rule somebody has to write. The prompt below opens on the field list, then walks the import stage by stage.</p>
<pre><code class="language-text">Build a CSV and Excel import screen for the students page. A button on that
page opens it as a modal wizard, the school office walks that wizard with the
export their old system produced, and it leaves them in a spreadsheet where
they correct what came in.

Where the fields come from
- Read the field list from my code, so the same screen serves the students page
  today and a staff page later.
- Support text, dates and a fixed list of options, and let one field carry
  several rules at once.
- Check required, a value from a list, and uniqueness inside the file.
- Show the office our label for a field, and hand my code back the field name.
- Take student_ref as the key, so a second upload of the same roll finds those
  students again.
- Drop columns the file carries beyond that list.

Opening the file
- Take a file by drop or by dialog, and show a card for it.
- Detect the encoding, strip a byte order mark, and read a Windows-1252 export
  without turning accented surnames into question marks.
- Detect the delimiter. Commas, semicolons, tabs and pipes all arrive.
- Drop a first line shaped sep=; that Excel writes for some locales.
- Read .xlsx, .xls and .ods, open a workbook as one card per sheet, and let the
  office choose which sheets go on.
- Find the real header row when a report title and an export date sit above it,
  and handle a file with duplicate headers or no header at all.
- Keep a row carrying one field too few, and say which fields it filled.

Reading what the cells hold
- Settle the date order per column, so 04/11/2015 does not become April.
- Keep 00417 as text, including a reference Excel already turned into 417.
- Tell an empty cell apart from a cell holding the word null.

Matching the columns
- Map the file's headers onto my field list, one field per column.
- Match the obvious ones on arrival, and show the office which of my fields
  reached nothing so they can point each one at a column by hand.
- Show a few values under every header, so the office tells two similar columns
  apart.
- Remember the pairs the office confirmed, so the next roll of that shape
  arrives matched.

Matching the values
- Collect the distinct values of year group and house as the file spells them.
- Match each one to an option we allow, and let the office place the rest.

Correcting before the handover
- Hand the finished file to a spreadsheet the office works in, with my labels
  on top and every row in it.
- Mark what the office changed. A new row and an edited cell read differently
  at a glance.
- Run every rule the field list carries, and say which cell failed and why.
- Let the office fix a cell in place, with the editor that fits the field. A
  date opens a calendar, a list opens its options.
- Sort and filter, so the office reaches the failing rows among the hundreds
  that pass.
- Copy and paste blocks between it and Excel or Google Sheets, and undo an edit.
- Stay smooth at a hundred thousand rows, with the reading off the main thread
  so the tab keeps responding.

Handing the rows over
- Tell me which rows are new and which changed.
- Keep every row and every mapping on screen when my write fails.</code></pre>
<p>Prompt that screen into existence when the columns never move, when you made the file yourself, and when the roll arrives once a term. The rules above stop being optional once the files come from people you have never met.</p>
<p>Build the importer yourself and every rule above turns into code on your side, which then has to survive whatever the office exports next term.</p>
<p><a href="https://updog.tech/blog/build-vs-buy-csv-importer/">Build or buy a CSV importer</a> puts a number on what owning that code costs over a few years.</p>
<p>The other path hands every one of those rules to a package.</p>
<h2 id="the-second-prompt-installs-the-importer">The second prompt installs the importer</h2>
<p>Replit installs an npm package from <code>npm install</code> in the Shell, from <code>upm add</code>, by detecting a missing dependency when you press Run, or by asking Agent for the package by name. The prompt below asks Agent, and it names the package once.</p>
<pre><code class="language-text">Add a spreadsheet import screen to the students page with the npm package
@updog/data-editor. Read https://updog.tech/updog.md and
https://docs.updog.tech first, and use only props documented there.

1. Install @updog/data-editor and import "@updog/data-editor/styles.css".
2. Add an "Import students" button above the table, holding one open state.
   The editor opens as a modal, which is its default: pass open={open} and an
   onClose that closes it. Do not pass mode="inline". Wrap it in nothing and
   give it no height of its own, because the modal sizes itself.
3. Render &#x3C;DataEditor /> with apiKey="updog-replit-demo", which is all the key
   a replit.dev or a replit.app URL needs, variant="uploader",
   primaryKey="student_ref" and these seven columns, written as id, title, then
   type and rules:
   student_ref "Student ref" text, required, unique
   first_name "First name" text, required
   last_name "Last name" text, required
   date_of_birth "Date of birth" date, required
   year_group "Year group" select: Year 7, Year 8, Year 9, Year 10, Year 11,
     required, closed list
   house "House" select: Ashdown, Bramley, Cransley, Denholm, closed list
   guardian_email "Guardian email" text, email
   The ids are the roll module's own field names on purpose, so no field is
   renamed between the editor and saveStudents.
4. In a stylesheet loaded after "@updog/data-editor/styles.css", set
   --updog-brand on :root to this app's primary color, written as a plain color
   value.
5. onComplete receives result.sources, and every entry in a source's rows is a
   wrapper shaped { row, isNew, isChanged, isDeleted, isValid }. Read the flags
   off the wrapper and the cell values off entry.row. Skip an entry whose
   isValid is false.
6. entry.row is keyed by those same ids, so pass the rows to saveStudents as
   they are. Write no mapper.
7. Throw from onComplete when saveStudents throws. The editor clears its rows as
   soon as onComplete resolves, so a swallowed error loses the import. When it
   succeeds, close the modal and reload the students list.
8. Do not build an uploader of your own, do not parse the file yourself, and do
   not invent props.</code></pre>
<p>Agent read <code>updog.md</code>, then the documentation site, then the type definitions inside the installed package, and wrote the screen.</p>
<p>A package is still code you did not write. Test what it does to a real export before the office ever sees it.</p>
<h2 id="the-importer-mirrors-the-roll-module">The importer mirrors the roll module</h2>
<p>The seven fields of a student become seven importer columns. Each column points at one field through its <code>id</code>, and <code>title</code> gives the office the name shown in the grid.</p>
<pre><code class="language-tsx">import {
  DataEditor,
  type DataEditorColumn,
  type DataEditorResult,
} from "@updog/data-editor";
import "@updog/data-editor/styles.css";

type Student = {
  student_ref: string;
  first_name: string;
  last_name: string;
  date_of_birth: string;
  year_group: string;
  house: string;
  guardian_email: string;
};

const columns: DataEditorColumn[] = [
  {
    id: "student_ref",
    title: "Student ref",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "first_name",
    title: "First name",
    validators: [{ type: "required" }],
  },
  {
    id: "last_name",
    title: "Last name",
    validators: [{ type: "required" }],
  },
  {
    id: "date_of_birth",
    title: "Date of birth",
    editor: { type: "date" },
    validators: [{ type: "required" }],
  },
  {
    id: "year_group",
    title: "Year group",
    editor: {
      type: "select",
      options: ["Year 7", "Year 8", "Year 9", "Year 10", "Year 11"],
      enableCustomValue: false,
    },
    validators: [{ type: "required" }],
  },
  {
    id: "house",
    title: "House",
    editor: {
      type: "select",
      options: ["Ashdown", "Bramley", "Cransley", "Denholm"],
      enableCustomValue: false,
    },
  },
  {
    id: "guardian_email",
    title: "Guardian email",
    validators: [{ type: "email" }],
  },
];</code></pre>
<p>The validators run in the browser, before any row leaves it. <code>{ type: "unique" }</code> flags every row that shares a reference with another row in the grid, which is the duplicate the office can still fix. <code>{ type: "required" }</code> sits on five columns, and a row leaving one of them empty comes back <code>isValid: false</code>.</p>
<p>The two option lists stay closed. <code>enableCustomValue: false</code> stops the editor creating an option for a value nobody recognizes, so a year group the file made up reaches the office on the value step with nothing beside it, and a value left unplaced there never reaches the grid.</p>
<h2 id="the-page-mounts-the-importer">The page mounts the importer</h2>
<p>The editor draws on canvas and needs the browser DOM. Nothing in the project above renders on the server, so the component mounts with no directive of its own.</p>
<pre><code class="language-tsx">export function StudentImporter({ onImported }: Props) {
  const [open, setOpen] = useState(false);

  return (
    &#x3C;>
      &#x3C;button type="button" onClick={() => setOpen(true)}>
        Import students
      &#x3C;/button>

      &#x3C;DataEditor&#x3C;Student>
        apiKey="updog-replit-demo"
        variant="uploader"
        open={open}
        onClose={() => {
          setOpen(false);
        }}
        columns={columns}
        primaryKey="student_ref"
        onComplete={handleComplete}
      />
    &#x3C;/>
  );
}</code></pre>
<p><code>variant="uploader"</code> opens the file wizard first, and the prop defaults to <code>"editor"</code>, which would open an empty grid instead. <code>primaryKey</code> names the column that identifies a student inside the editor, and the editor requires it.</p>
<p>The editor takes the app's primary color from a single variable.</p>
<pre><code class="language-css">/* loaded after @updog/data-editor/styles.css */
:root {
  --updog-brand: #2c5f5d;
}</code></pre>
<p><a href="https://updog.tech/blog/style-updog-to-match-your-product/">Match the importer to your product</a> reaches the fonts, the grid lines, the shadows and a dark theme.</p>
<h2 id="the-file-uses-the-schools-own-words">The file uses the school's own words</h2>
<p>The export carries 384 students out of the office's old system.</p>
<p><code>thornsett-academy.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Student no.</td><td class="sheet__cell">Forename</td><td class="sheet__cell">Surname</td><td class="sheet__cell">DOB</td><td class="sheet__cell">Year</td><td class="sheet__cell">School house</td><td class="sheet__cell">Contact email</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">TA-0001</td><td class="sheet__cell">Bilal</td><td class="sheet__cell">Fenwick</td><td class="sheet__cell">2013-06-28</td><td class="sheet__cell">Yr 9</td><td class="sheet__cell">Bramley House</td><td class="sheet__cell">lorna.fenwick@holtmail.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">TA-0002</td><td class="sheet__cell">Maeve</td><td class="sheet__cell">Lanyon</td><td class="sheet__cell">2014-10-20</td><td class="sheet__cell">Yr 7</td><td class="sheet__cell">Cransley House</td><td class="sheet__cell">harriet.lanyon@holtmail.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">TA-0003</td><td class="sheet__cell">Noor</td><td class="sheet__cell">Brightwell</td><td class="sheet__cell">2011-03-24</td><td class="sheet__cell">Yr 11</td><td class="sheet__cell">Denholm House</td><td class="sheet__cell">ivor.brightwell@holtmail.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">TA-0004</td><td class="sheet__cell">Elif</td><td class="sheet__cell">Brightwell</td><td class="sheet__cell">2011-04-17</td><td class="sheet__cell">Yr 11</td><td class="sheet__cell">Ashdown House</td><td class="sheet__cell">rowena.brightwell@holtmail.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">90 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">96</th><td class="sheet__cell">TA-0095</td><td class="sheet__cell">Willa</td><td class="sheet__cell">Gallacher</td><td class="sheet__cell">2010-09-15</td><td class="sheet__cell">Yr 11</td><td class="sheet__cell">Ashdown House</td><td class="sheet__cell">cyrus.gallacher@holtmail.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">100 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">197</th><td class="sheet__cell">TA-0196</td><td class="sheet__cell">Willa</td><td class="sheet__cell">Gallacher</td><td class="sheet__cell">2014-08-17</td><td class="sheet__cell">Yr 8</td><td class="sheet__cell">Denholm House</td><td class="sheet__cell">emmett.gallacher@holtmail.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">114 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">312</th><td class="sheet__cell">TA-0311</td><td class="sheet__cell">Hamza</td><td class="sheet__cell">Ijaz</td><td class="sheet__cell">2015-03-22</td><td class="sheet__cell">Yr 7</td><td class="sheet__cell">Bramley House</td><td class="sheet__cell">rowena.ijaz@holtmail.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">72 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">385</th><td class="sheet__cell">TA-0384</td><td class="sheet__cell">Rosalind</td><td class="sheet__cell">Zabala</td><td class="sheet__cell">2014-12-15</td><td class="sheet__cell">Yr 7</td><td class="sheet__cell">Denholm House</td><td class="sheet__cell">emmett.zabala@holtmail.example</td></tr></tbody></table>
<p>Every one of the seven headers is written differently from the column it belongs to, and the matcher resolves all seven.</p>
<pre><code class="language-text">Student no.    →  Student ref      70  half the words shared
Forename       →  First name       90  synonym
Surname        →  Last name        90  synonym
DOB            →  Date of birth    90  synonym
Year           →  Year group       80  one string inside the other
School house   →  House            80  one string inside the other
Contact email  →  Guardian email   70  half the words shared</code></pre>
<p><code>Forename</code>, <code>Surname</code> and <code>DOB</code> reach their columns through the importer's built-in synonym table, and a synonym match scores 90. <code>Year</code> and <code>School house</code> score 80, where the shorter of the two normalized names runs to four characters or more and sits inside the longer. <code>Student no.</code> and <code>Contact email</code> score 70, where the two names share half their words.</p>
<p>The wizard reports <code>7/7 matched</code>. <code>Year group</code> and <code>House</code> carry closed lists, and the value step settles those as <code>5/5</code> and <code>4/4</code>, with nothing left to place by hand.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">Building a column mapping screen</a> picks up the case this file avoids, a header that scores under the threshold everywhere.</p>
<p>The grid then holds all 384 rows, every cell filled and no rule broken. Sorting, filtering, cell edits, undo and a paste out of Excel all work there before anybody submits. The confirmation dialog counts what is about to leave, and on this file it read <code>384 new rows will be created</code>.</p>
<h2 id="submit-returns-the-rows-and-their-state">Submit returns the rows and their state</h2>
<p>Submit returns the corrected rows grouped by source. Every row arrives inside a wrapper carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>, and the four move independently. Your handler decides what those states mean for the roll.</p>
<pre><code class="language-tsx">const handleComplete = async (result: DataEditorResult&#x3C;Student>) => {
  const students = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid)
    .map((entry) => entry.row);

  await saveStudents(students);

  setOpen(false);
  await onImported();
};</code></pre>
<p>No mapper sits between the row and the call. The keys of <code>entry.row</code> are the roll module's own field names, so <code>students</code> reaches <code>saveStudents</code> as it is.</p>
<p>The values arrive canonical. <code>date_of_birth</code> leaves as ISO <code>2013-06-28</code> independent of how the date appeared in the grid. <code>year_group</code> and <code>house</code> carry the option the value step chose, so a file that wrote <code>Yr 9</code> hands back <code>Year 9</code>.</p>
<p><code>onComplete</code> receives this object, with one of the 384 rows kept.</p>
<pre><code class="language-ts">{
  sources: [
    {
      sourceId: "source_…",
      sourceName: "thornsett-academy.csv",
      rows: [
        {
          row: {
            student_ref: "TA-0001",
            first_name: "Bilal",
            last_name: "Fenwick",
            date_of_birth: "2013-06-28",
            year_group: "Year 9",
            house: "Bramley",
            guardian_email: "lorna.fenwick@holtmail.example",
          },
          isNew: true,
          isChanged: false,
          isDeleted: false,
          isValid: true,
        },
        // 383 more rows
      ],
    },
  ],
  counts: { new: 384, changed: 0, deleted: 0, invalid: 0 },
  learnedSynonyms: { columns: [], values: [] },
}</code></pre>
<p>The object names no table and no statement. Reading those flags into a write is the handler's job, and this one passes every valid row on.</p>
<p><a href="https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/">Import, edit and delete rows through a REST API</a> routes those flags against a backend that answers over HTTP, and it covers the deletion path this page leaves out.</p>
<h2 id="the-write-goes-to-a-function-you-own">The write goes to a function you own</h2>
<p><code>saveStudents</code> is the seam between the importer and wherever the roll ends up. It takes the rows and answers with nothing, and Updog Importer never learns what sits behind it.</p>
<pre><code class="language-ts">// src/lib/roll.ts
const roll = new Map&#x3C;string, Student>();

export const saveStudents = async (students: Student[]) => {
  for (const student of students) {
    roll.set(student.student_ref, student);
  }
};

export const loadStudents = async () => {
  return [...roll.values()];
};</code></pre>
<p>A Map over <code>student_ref</code> is the whole store here, and it lasts as long as the tab. Every row the grid held reached the roll page through it. Point that body at a Replit database, at a REST call, or at a file, and every section above stays as it is.</p>
<p>Editor state and storage state answer different questions. This run flags all 384 rows <code>isNew: true</code>, because nothing sat in the grid when it opened. <code>isNew</code> means new to the editor, and <code>saveStudents</code> still decides what to do with a <code>student_ref</code> it already holds.</p>
<p>Let a failed write reject <code>onComplete</code>. A rejection leaves every row on screen, and it takes back nothing <code>saveStudents</code> already stored. Resolving tells Updog Importer the submission finished, so wait for a successful write before closing the modal and reloading the roll.</p>
<h2 id="the-replit-url-runs-for-free">The Replit URL runs for free</h2>
<p>The editor asks its license endpoint when it starts. That request carries the API key, and the browser puts the page's origin on it. Nothing out of the file travels with it.</p>
<p>Updog holds a list of development and preview hosts, and a page served from one of them runs the importer free, with no row counted. Both Replit hosts sit on that list, <code>.replit.dev</code> for the development URL and <code>.replit.app</code> for the published app. While the app lives on either one, the placeholder key in the prompt is enough.</p>
<p>Replit writes the development URL as <code>UUID.servername.replit.dev</code>, it stays public to the web by default, and it can change each time you reopen the app. The editor opened on that host and on the published <code>replit.app</code> one, both on the placeholder key.</p>
<p>A custom domain changes that on both sides. Replit sells custom domains on its Autoscale, Reserved VM and Static deployments, and the hostname goes into your API key's domain list at <a href="https://console.updog.tech/">console.updog.tech</a>. The Free plan covers production domains up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains, with no row limit.</p>
<h2 id="the-roll-page-now-has-an-import-path">The roll page now has an import path</h2>
<p>Updog Importer installs into a Replit project as an npm package. Its columns spell the roll module's own field names, the office settles the file before submit, and <code>onComplete</code> hands the corrected rows and their state to a handler you own.</p>
<p>Parsing CSV and Excel, matching columns and values, checking cells and letting somebody correct them all stay inside the importer. Your project still owns <code>saveStudents</code>, the storage behind it, and what a repeat upload means there.</p>
<p>The first prompt above spells out, rule by rule, what building this flow yourself would ask for. Install the package and those rules stay in the package, while the Replit project keeps the students page and the write path behind it.</p>]]></content:encoded></item>
<item><title>What an Importer Should Do With a Ragged CSV Row</title><link>https://updog.tech/blog/how-to-handle-ragged-rows-in-csv-imports/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-handle-ragged-rows-in-csv-imports/</guid><pubDate>Wed, 02 Sep 2026 00:00:00 GMT</pubDate><description>Rows in a CSV do not always carry the same number of values. See how Updog Importer works out which column each value belongs to.</description><content:encoded><![CDATA[<p>A CSV names its columns once, in the header. A reader matches every row after it
to that header by counting from the left, so the first value belongs to the
first column and the second value to the second column. The count holds while
every line carries as many values as the header.</p>
<p>A ragged row carries a different number of values than the header carries
columns, and a row that carries fewer breaks the count. It appears wherever
something writes a line without counting the columns. A person adds a note or a
total under the last record, and that line arrives carrying one value. A program
joins the values a record holds, so a record with an optional field missing
comes out one value short and leaves no comma where that value would have been.
A hand edit in a text editor takes out a value together with its comma, and the
gap stays wherever that value stood.</p>
<p>Haverbrook Market keeps its stall register as a CSV, and the clerk edits it by
hand. It holds fourteen rows under seven columns, and three of those lines carry
fewer than seven values.</p>
<p><code>haverbrook-market.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Pitch</td><td class="sheet__cell">Trader</td><td class="sheet__cell">Stall</td><td class="sheet__cell">Goods</td><td class="sheet__cell">Pitch fee</td><td class="sheet__cell">First market</td><td class="sheet__cell">Contact</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">P-13</td><td class="sheet__cell">Ivy Halloway</td><td class="sheet__cell">Halloway &#x26; Vane</td><td class="sheet__cell">Cheese</td><td class="sheet__cell">42</td><td class="sheet__cell">2026-03-17</td><td class="sheet__cell">ivy@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">P-14</td><td class="sheet__cell">Otto Marsden</td><td class="sheet__cell">Roper Bakehouse</td><td class="sheet__cell">Bread</td><td class="sheet__cell">38</td><td class="sheet__cell">2026-03-17</td><td class="sheet__cell">otto@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">P-15</td><td class="sheet__cell">Nell Ferrand</td><td class="sheet__cell">Ferrand Flowers</td><td class="sheet__cell">Flowers</td><td class="sheet__cell">30</td><td class="sheet__cell">2026-03-24</td><td class="sheet__cell">nell@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">P-16</td><td class="sheet__cell">Rhys Coldharbour</td><td class="sheet__cell">Coldharbour Fish</td><td class="sheet__cell">Fish</td><td class="sheet__cell">55</td><td class="sheet__cell">2026-03-24</td><td class="sheet__cell">rhys@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">P-17</td><td class="sheet__cell">Silas Ashgrove</td><td class="sheet__cell">Ashgrove Greens</td><td class="sheet__cell">Vegetables</td><td class="sheet__cell">44</td><td class="sheet__cell">2026-03-31</td><td class="sheet__cell">silas@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">P-18</td><td class="sheet__cell">Della Bramwell</td><td class="sheet__cell">Bramwell Preserves</td><td class="sheet__cell">Preserves</td><td class="sheet__cell">26</td><td class="sheet__cell">2026-03-31</td><td class="sheet__cell">della@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">P-24</td><td class="sheet__cell">Cleo Windrush</td><td class="sheet__cell">Windrush Honey</td><td class="sheet__cell">Honey</td><td class="sheet__cell">24</td><td class="sheet__cell">2026-04-14</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">P-25</td><td class="sheet__cell">Auberon Petrie</td><td class="sheet__cell">Petrie Knives</td><td class="sheet__cell">Ironmongery</td><td class="sheet__cell">48</td><td class="sheet__cell">2026-04-14</td><td class="sheet__cell">auberon@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">P-26</td><td class="sheet__cell">Marisol Enfield</td><td class="sheet__cell">Enfield Ceramics</td><td class="sheet__cell">Pottery</td><td class="sheet__cell">35</td><td class="sheet__cell">2026-04-21</td><td class="sheet__cell">marisol@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">P-27</td><td class="sheet__cell">Tobias Renn</td><td class="sheet__cell">Coffee</td><td class="sheet__cell">40</td><td class="sheet__cell">2026-04-21</td><td class="sheet__cell">tobias@example.com</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell">P-28</td><td class="sheet__cell">Xanthe Ollerton</td><td class="sheet__cell">Ollerton Wool</td><td class="sheet__cell">Wool</td><td class="sheet__cell">28</td><td class="sheet__cell">2026-04-28</td><td class="sheet__cell">xanthe@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">P-29</td><td class="sheet__cell">Bram Kettlewell</td><td class="sheet__cell">Kettlewell Pies</td><td class="sheet__cell">Pies</td><td class="sheet__cell">46</td><td class="sheet__cell">2026-04-28</td><td class="sheet__cell">bram@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">14</th><td class="sheet__cell">P-30</td><td class="sheet__cell">Junia Foxwell</td><td class="sheet__cell">Foxwell Herbs</td><td class="sheet__cell">Herbs</td><td class="sheet__cell">22</td><td class="sheet__cell">2026-05-19</td><td class="sheet__cell">junia@example.com</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">15</th><td class="sheet__cell">Cash pitches are settled on the day</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr></tbody></table>
<p>Line 8 stops after six values. Line 11 carries six as well, and the value it is
missing sits in the middle of the row. Line 15 is the clerk's own note, one
value on a line of its own.</p>
<h2 id="the-format-asks-for-equal-width-and-never-enforces-it">The format asks for equal width and never enforces it</h2>
<p>RFC 4180 describes the file twice with the same verb. The fourth item of its
section 2 says that each line "should contain the same number of fields
throughout the file". The third item says the header "should contain the same
number of fields as the records in the rest of the file". The word is lower case
both times, and the document carries no RFC 2119 keyword anywhere, so nothing in
it turns an uneven file into an invalid one.</p>
<p>So each reader had to pick a policy of its own, and they disagree.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Reader</th>
<th>A row with fewer values than the header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Python <code>csv.DictReader</code></td>
<td>fills the missing fields with <code>restval</code>, which defaults to <code>None</code></td>
</tr>
<tr>
<td>pandas <code>read_csv</code></td>
<td>reads it, because <code>on_bad_lines</code> counts a bad line as one with too many fields</td>
</tr>
<tr>
<td><code>csv-parse</code></td>
<td>raises <code>CSV_RECORD_INCONSISTENT_FIELDS_LENGTH</code> when a record holds a different number of fields than the records before it, until <code>relax_column_count</code> is set</td>
</tr>
<tr>
<td>DuckDB</td>
<td>names the case <code>MISSING COLUMNS</code>, and <code>store_rejects</code> writes the line into <code>reject_errors</code></td>
</tr>
</tbody>
</table></div>
<p>Those four behaviours come from the documentation of Python 3.14.7, pandas
3.0.5, <code>csv-parse</code> and DuckDB, read on 2026-09-01. One of the four fills the
missing fields for you, and another does not count a short line as bad at all.
Once the fields are filled, a value missing from the middle of the row leaves
every value after it one column to the left.</p>
<h2 id="padding-by-position-moves-the-values-and-reports-the-wrong-cells">Padding by position moves the values and reports the wrong cells</h2>
<p>Line 11 is one value short, somewhere in the middle. Fill the missing field at
the end, and the fee, the date and the address each land one column to the left
of the field that fits them.</p>
<pre><code class="language-text">Pitch          P-27
Trader         Tobias Renn
Stall          Coffee
Goods          40
Pitch fee      2026-04-21
First market   tobias@example.com
Contact</code></pre>
<p>Two rules fire on that row. Pitch fee holds a date and fails the number check,
and First market holds an email address and fails the date check. Neither cell
is the one that went missing, and the person is asked to correct a fee that was
never wrong.</p>
<p>A schema of plain text columns fires nothing at all. The row is complete, the
count is right, and the trader's address is stored as the day they first traded.</p>
<h2 id="the-importer-keeps-the-rows-own-length">The importer keeps the row's own length</h2>
<p>Updog Importer parses a CSV with PapaParse under <code>header: false</code>. At version
5.6.0 PapaParse counts fields only while it builds each row into an object under
a header, and with <code>header: false</code> and no <code>dynamicTyping</code> or <code>transform</code> it
returns before that step. A three-column probe read in header mode answers with
<code>Too few fields: expected 3 fields but parsed 2</code>. Headerless, it raises no
field-count error at all, and every row reaches the import step carrying the
number of values the file wrote.</p>
<p>It matches each header to <a href="https://updog.tech/blog/csv-column-mapping-react/">one of your fields</a>
before importing a row, and then measures every raw row against the header of
its own file.</p>
<pre><code class="language-text">header values  7
row values     6
action         align</code></pre>
<p>A row carrying seven values is imported as it stands. Alignment never looks at
it, and an even file never reaches any of what follows.</p>
<h2 id="the-schema-removes-the-placements-it-cannot-hold">The schema removes the placements it cannot hold</h2>
<p>Alignment keeps the order of the values and moves only the gaps. Six values in
seven columns give seven placements of one gap, and each placement is a complete
row that can be checked.</p>
<p>Every candidate goes through the validators on all seven columns, the gap
included, which is how a required column rejects the placement that empties it.
A candidate survives when every cell passes every rule that can be evaluated on
the spot. The gap starts at the end of the row and walks left, and a placement
dies on the first column whose rule it breaks.</p>
<p>The placements multiply as the gap grows, and a wide schema meeting a row that
runs several values short reaches a count the engine will not enumerate. The
ceiling on SDK 0.1.91 is a thousand candidates. Above it the importer skips
alignment and writes the values by position, the first value into the first
column, and the row keeps whatever shift the missing value caused.</p>
<p>Line 8 is the honey stall, which the clerk entered before there was an address
for it.</p>
<pre><code class="language-text">line 8   P-24 · Cleo Windrush · Windrush Honey · Honey · 24 · 2026-04-14
         6 values · 7 columns · 7 placements

placement             first rule that rejects it
gap at Contact        every rule passes
gap at First market   First market is required
gap at Pitch fee      Pitch fee is required
gap at Goods          Pitch fee holds "Honey"
gap at Stall          Pitch fee holds "Honey"
gap at Trader         Trader is required
gap at Pitch          Pitch is required</code></pre>
<p>One placement survives. The importer applies it and marks nothing, and the row
lands with the honey stall in Stall, the fee in Pitch fee and an empty Contact,
which is what the six values in the file say. Nothing on the screen mentions the
repair, because one answer left nothing to ask.</p>
<h2 id="a-second-survivor-turns-the-repair-into-a-question">A second survivor turns the repair into a question</h2>
<p>Line 11 goes through the same seven placements against the same schema.</p>
<pre><code class="language-text">line 11  P-27 · Tobias Renn · Coffee · 40 · 2026-04-21 · tobias@example.com
         6 values · 7 columns · 7 placements

placement             first rule that rejects it
gap at Contact        Pitch fee holds "2026-04-21"
gap at First market   Pitch fee holds "2026-04-21"
gap at Pitch fee      Pitch fee is required
gap at Goods          every rule passes
gap at Stall          every rule passes
gap at Trader         Trader is required
gap at Pitch          Pitch is required</code></pre>
<p>Two placements survive. They agree on five columns of the seven, and both put
<code>40</code> in Pitch fee, the date in First market and the address in Contact. They
differ on Stall and Goods.</p>
<p>The importer keeps the first of the two, which leaves <code>Coffee</code> in Stall and
Goods empty, and it marks the two columns the survivors disagree about. A mark
puts a dashed outline on the cell and a line in the error panel. It counts as no
error, so a marked row reaches <code>onComplete</code> even when <code>blockSubmitOnError</code> is
set.</p>
<ul><li><strong>Line 11</strong>, Stall, <code>Coffee</code>: This might be in the wrong column.</li><li><strong>Line 11</strong>, Goods, empty: This might be in the wrong column.</li></ul>
<p>The five columns the candidates agree on carry no mark. Whether <code>Coffee</code> names
the stall or the goods sold at it is the only question the file leaves open on
that row, and it is the only question the person is asked. A failed rule fills
the cell, and the dashed outline keeps a placement question from reading as a
broken value. A screen reader adds "Misplaced: This might be in the wrong
column." to the cell announcement.</p>
<h2 id="a-line-that-fits-no-placement-is-a-validation-failure">A line that fits no placement is a validation failure</h2>
<p>Line 15 carries one value into seven columns, which is seven placements again.
Four of those columns are required, and one value cannot fill four columns, so
every placement leaves at least three of them empty and nothing survives.</p>
<pre><code class="language-text">line 15  Cash pitches are settled on the day
         1 value · 7 columns · 7 placements · 0 survivors

Trader         empty   This field is required
Pitch fee      empty   This field is required
First market   empty   This field is required</code></pre>
<p>The importer writes the first candidate, which puts the note in the first
column. It marks nothing as misplaced. Three required values are missing, and
<a href="https://updog.tech/blog/common-csv-import-errors/">ordinary validation</a> already says so. A
missing required value is validation's business, and a mark saying the values
sit in the wrong columns would answer a question this line never raised.</p>
<h2 id="the-validators-decide-how-much-of-a-row-survives">The validators decide how much of a row survives</h2>
<p>Five of the seven columns in this import declare a rule, and those five are what
alignment reads.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  { id: "pitchRef", title: "Pitch", validators: [{ type: "required" }] },
  { id: "trader", title: "Trader", validators: [{ type: "required" }] },
  { id: "stall", title: "Stall" },
  { id: "goods", title: "Goods" },
  {
    id: "pitchFee",
    title: "Pitch fee",
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", min: 0 }],
  },
  {
    id: "firstMarket",
    title: "First market",
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  { id: "contact", title: "Contact", validators: [{ type: "email" }] },
];</code></pre>
<p>Pruning reads the text as the file wrote it, before any value is converted, so
it runs the rules you declare and skips the ones an editor adds for itself. A
number editor on its own leaves the column open during alignment. The
<code>{ type: "number", min: 0 }</code> rule on that same column removes every candidate
that puts a date or a stall name in the fee.</p>
<p>A <code>function</code> validator runs during alignment against an empty row, because the
row is still being assembled, so a rule that reads another field finds nothing
in it. An <code>asyncFunction</code> rule counts as a pass.</p>
<p><code>required</code> is what settles line 11. Declared on Pitch fee and First market, it
takes the row down to two survivors and two marked cells. Without it on those
two columns, three placements survive, they disagree on Stall, Goods and Pitch
fee, and the person is asked about three cells. Both readings were measured in
Chrome on 2026-09-01 against SDK 0.1.91.</p>
<p>Stall and Goods hold free text and declare no rule, which is why the gap between
them stays open. Two unconstrained columns side by side leave the engine nothing
to tell them apart with.</p>
<p>A header the person leaves unmatched is unconstrained in the same way. Alignment
scores each value against the schema column standing at that header's position,
and a header matched to none of your fields carries no rules at all. Skipping a
column in the matching step widens the placements alignment has to choose
between.</p>
<h2 id="the-mark-waits-for-a-person">The mark waits for a person</h2>
<p>Editing a marked cell clears its mark. A right-click over that cell, or over a
range or a row holding one, offers Mark as correct. It clears the marks in that
scope and stays out of the undo history, because acknowledging a placement
changes no value.</p>
<p>The filter panel gains a "Rows with misplaced values" entry the moment such a
value exists, and it keeps that entry after the last mark is cleared. Running this file through the editor on SDK 0.1.91 ends with
fourteen rows, one row carrying errors, three rows carrying empty cells and one
row carrying a misplaced value.</p>
<h2 id="a-worksheet-stores-a-rectangle">A worksheet stores a rectangle</h2>
<p>An .xlsx sheet declares the range it covers, and Updog Importer builds every row
out to the width of that range. A row that ran short in the spreadsheet arrives
with empty cells at the end, so its length matches the header and alignment
leaves it alone. Only a delimited text file hands the importer a row of its own
length, and the sample file behind this article is written as CSV for that
reason.</p>
<h2 id="alignment-moves-values-and-never-invents-them">Alignment moves values and never invents them</h2>
<p>Line 8 lands with an empty Contact, and line 15 keeps its empty Trader. The file
never carried those values, and no rearrangement of the values it did carry can
produce them.</p>
<p>Alignment answers a placement question. A file whose <a href="https://updog.tech/blog/how-to-fix-csv-encoding-issues/">bytes arrived
misread</a> carries damage inside the values
themselves, and placement has no answer for that.</p>
<p>An export fixed at the source stops producing short rows, and every file after
it arrives whole. Until then, an importer that reads the schema narrows a broken
row to the question the file cannot answer, and it hands that question to the
person who knows the market.</p>
<p>The importer decides where a value can go, and it says so when more than one
answer survives. The person settles the cells the file left open. Your
application receives seven fields per row, with the fee in the fee column.</p>]]></content:encoded></item>
<item><title>How to Transform Rows During a CSV Import</title><link>https://updog.tech/blog/transform-rows-during-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/transform-rows-during-csv-import/</guid><pubDate>Tue, 01 Sep 2026 00:00:00 GMT</pubDate><description>A file cuts its columns its own way. See how Updog Importer lets your code transform rows during a CSV import.</description><content:encoded><![CDATA[<p>Column matching assumes that each file column maps to one field in your
schema. That works when the file and the schema split the data at the same
boundaries.</p>
<p>A <code>Full name</code> column breaks that assumption. If your schema stores
<code>firstName</code> and <code>lastName</code> separately, matching alone cannot produce both
values. Your code has to transform the cell before either field receives the
right value.</p>
<p>For the example we will use a record label's app that stores a royalty line
in six fields. The statement reference, the artist's first and last name, the
track, the currency and the amount. The statement a distributor sends carries
the same data in four columns.</p>
<p><code>royalties.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Ref</td><td class="sheet__cell">Artist</td><td class="sheet__cell">Track</td><td class="sheet__cell">Payment</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">RS-2041</td><td class="sheet__cell">Anna van der Berg</td><td class="sheet__cell">Slow Tide</td><td class="sheet__cell">$1,250.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">RS-2042</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">Harrow Lane</td><td class="sheet__cell">$980.40</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">RS-2043</td><td class="sheet__cell">Petr Havlik</td><td class="sheet__cell">Nightjar</td><td class="sheet__cell">$1,004.50</td></tr></tbody></table>
<p><code>Artist</code> contains both name fields. <code>Payment</code> contains both currency and
amount. The file packs four schema fields into two columns, so a one-to-one
mapping is not enough.</p>
<h2 id="two-columns-hold-four-fields">Two columns hold four fields</h2>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">Column matching</a> connects <code>Ref</code> to the
statement reference and <code>Track</code> to the track automatically. <code>Artist</code> and
<code>Payment</code> have no one-to-one match, so the person importing the file maps
them to the closest fields on offer, First name for <code>Artist</code> and Amount for
<code>Payment</code>.</p>
<p>The import still finishes with zero validation errors. The number reader
removes the dollar sign and the grouping comma from <code>$1,250.00</code>, and
<code>1250.00</code> is a valid amount. <code>Anna van der Berg</code> is a valid string for
<code>firstName</code>. The schema validates both values without knowing that either
cell held more than one field.</p>
<pre><code class="language-text">statementRef   RS-2041
firstName      Anna van der Berg
lastName       (empty)
track          Slow Tide
currency       (empty)
amount         1250.00</code></pre>
<p>The result is structurally valid but incomplete. The currency is gone, and
the whole artist name sits in <code>firstName</code>.</p>
<p>Mapping cannot fix this, because no choice of target field splits a cell. The
value itself has to be split before it reaches the fields, and the import has
one place built for that code.</p>
<h2 id="the-callback-runs-after-reading-before-the-rows-land">The callback runs after reading, before the rows land</h2>
<p><code>onRowImport</code> is a prop on the editor. The SDK calls it after parsing, column
mapping, value matching, and each column's <code>transformer</code>, but before the
resulting rows reach the editor.</p>
<pre><code class="language-text">file → parse → column mapping → value matching → transformer → onRowImport → column reader → editor</code></pre>
<p>For each imported row, the callback receives two representations. <code>row</code>
contains the values already mapped to your schema, such as <code>Slow Tide</code> under
<code>track</code>. <code>raw</code> contains the original cells keyed by the file headers,
unmapped columns included.</p>
<pre><code class="language-text">row.track       → "Slow Tide"
raw["Track"]    → "Slow Tide"
raw["Payment"]  → "$1,250.00"</code></pre>
<p>Both are inputs to the callback. Mutating them does not change the import.
<code>row</code> is a copy, and the import never reads <code>raw</code> again. To change the
imported row, return the fields that should be replaced.</p>
<p>The royalty schema has six fields. <code>currency</code> and <code>amount</code> also declare their
editor types.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  { id: "statementRef", title: "Statement" },
  { id: "firstName", title: "First name" },
  { id: "lastName", title: "Last name" },
  { id: "track", title: "Track" },
  { id: "currency", title: "Currency", editor: { type: "currency" } },
  { id: "amount", title: "Amount", editor: { type: "number" } },
];</code></pre>
<p>Keep <code>Payment</code> mapped to Amount. The importer reads that column with the
number format it detected across the file, so <code>row.amount</code> already holds
<code>1250.00</code> when the callback runs. The callback then supplies what the mapping
could not express, the two name fields and the currency.</p>
<pre><code class="language-tsx">onRowImport={(rows) =>
  rows.map(({ raw }) => {
    const [firstName, ...surname] = raw["Artist"].split(" ");

    return {
      firstName,
      lastName: surname.join(" "),
      currency: raw["Payment"].replace(/[\d\s.,'-]/g, ""),
    };
  })
}</code></pre>
<p>The currency line throws the number away and keeps what is left. It deletes
the digits, the spaces, the separators and the minus sign, so <code>$1,250.00</code>
leaves <code>$</code> and <code>EUR 1.250,00</code> leaves <code>EUR</code>. The amount survives that line
untouched, because the mapping already read it.</p>
<p>Each returned key replaces that field in the imported row. Fields the
callback does not return keep the values the import pipeline already
produced, so <code>statementRef</code>, <code>track</code> and the mapped <code>amount</code> need no
special handling.</p>
<p>The callback may also return a promise. The SDK waits for it before adding
the rows to the editor, with a 30-second timeout per call.</p>
<p>After the callback, the first row carries all six fields.</p>
<pre><code class="language-text">statementRef   RS-2041
firstName      Anna
lastName       van der Berg
track          Slow Tide
currency       USD
amount         1250.00</code></pre>
<p>The callback split <code>Artist</code> across the two name fields and took the currency
symbol out of <code>Payment</code>, while the mapping supplied the amount. The callback
returned <code>$</code>, and the row stores <code>USD</code>. The diagram's <code>column reader</code> step
made that conversion, and it reads every returned value the same way.</p>
<h2 id="each-returned-value-goes-through-the-columns-reader">Each returned value goes through the column's reader</h2>
<p>Values returned from <code>onRowImport</code> enter the column pipeline again. The
column reader first converts them to the type the cell expects, then the
column's <code>transformer</code> runs on the result.</p>
<p>Return the value in a form the reader understands. A currency column resolves
recognised forms such as <code>$</code>, <code>usd</code>, and <code>US Dollar</code> to <code>USD</code>. A number
column accepts a JavaScript number or canonical numeric text, so both
<code>1250.5</code> and <code>"1250.00"</code> are valid. A date column accepts an ISO date string
such as <code>2026-08-19</code>. A multiselect accepts an array of values.</p>
<p>If the reader cannot convert a value, it leaves that value in the cell for
validation to flag.</p>
<p>We measured that boundary on Updog Importer 0.1.90 with the royalty statement
used in this example.</p>
<pre><code class="language-text">returned                     stored                      validation
"1,250.00"                   1,250.00                    Invalid number
"1250.00"                    1250.00                     —
1250.5                       1250.5                      —
"$" / "usd" / "US Dollar"    USD                         —
new Date(…)                  2026-08-19T00:00:00.000Z    Invalid date</code></pre>
<p>That boundary is why the callback leaves the amount to the mapping. The
file's <code>$1,250.00</code> reads clean because the importer detects the column's
number format across the whole file before reading its cells. One value alone
carries no such evidence, since <code>1,250</code> is twelve hundred and fifty under one
convention and one and a quarter under another. A returned value arrives
without that verdict, so the number reader expects canonical numeric text or
a JavaScript number.</p>
<p>Map the column when the importer can read it, and return a value only where
mapping cannot express what the field needs. A callback that rebuilds the
amount by hand takes the file's convention on faith, and <code>replaceAll(",", "")</code>
turns a statement writing <code>1.250,00</code> into <code>1.25000</code>, which the reader takes
as <code>1.25</code> and validation accepts. That is the opening mapping's silent loss
again, one thousandth of the payment, with nothing on screen to catch it.</p>
<p>An empty string clears its field. <code>null</code> in place of a row object removes the
row. An object past the end of the input chunk appends a new row, and its
values pass through the same reader.</p>
<p>The reader resolves representation. It cannot decide where
<code>Anna van der Berg</code> splits between <code>firstName</code> and <code>lastName</code>. That decision
belongs in <code>onRowImport</code>.</p>
<h2 id="splitting-the-name-is-the-callbacks-decision">Splitting the name is the callback's decision</h2>
<p><code>Anna van der Berg</code> splits at the first space into <code>Anna</code> and <code>van der Berg</code>.
That rule lives in the callback. The column reader and the schema have no
opinion about where a name divides.</p>
<p>It is a heuristic. A Dutch particle may belong to the surname, a Spanish name
may carry two family names, and a multi-word given name breaks the same rule
from the other side.</p>
<p>Because <code>onRowImport</code> runs before the rows enter the editor, the result
remains reviewable. The imported row opens with <code>Anna</code> under First name and
<code>van der Berg</code> under Last name. If the heuristic gets a name wrong, the
person reviewing the statement can correct the cells before the data leaves
the editor.</p>
<p>The callback makes the initial split. The editor is where that decision can
be checked and corrected.</p>
<h2 id="one-call-per-5000-rows">One call per 5,000 rows</h2>
<p>The SDK processes imported rows in chunks of 5,000. It calls <code>onRowImport</code>
once per chunk, sequentially and in file order. The final chunk contains
whatever rows remain.</p>
<p>The callback's second argument, <code>meta</code>, describes the current chunk and the
import around it. <code>chunkIndex</code>, <code>chunkCount</code> and <code>isLastChunk</code> locate the
chunk within the file. <code>workbook</code> contains the file name and its headers.
<code>mapping</code> contains the resolved header-to-field mapping. <code>context</code> is the
object passed through the editor's <code>context</code> prop.</p>
<p><code>meta.signal</code> is an <code>AbortSignal</code>. It aborts when the import is cancelled and
when the callback exceeds its 30-second limit. A callback that starts its own
request passes the same signal to <code>fetch</code>, so that work stops with the
import.</p>
<pre><code class="language-ts">await fetch(url, {
  signal: meta.signal,
});</code></pre>
<p>A cancelled import then ends quietly, because the person stopped it. A
callback that runs out of time fails instead.</p>
<p>A callback failure stops further processing. Throwing, rejecting, timing out,
or returning an invalid value produces one <code>HOOK_ERROR</code> through <code>onError</code>.
Chunks that already reached the editor remain there. The unprocessed part of
the file is restored, and the wizard stays open so the import can be retried.</p>
<p>Return nothing and the chunk stays unchanged. Return an array at least as
long as the input and each element answers one row, a row object to keep the
row or <code>null</code> to drop it. Elements past the input length append new rows.</p>
<p>Anything outside that contract fails the chunk. The error identifies the
invalid result where it can, <code>element 0 is undefined</code> included.</p>
<h2 id="nothing-else-runs-the-callback">Nothing else runs the callback</h2>
<p><code>onRowImport</code> runs only for rows that come through the file import flow. Rows
supplied through <code>loadData</code>, pasted into the grid, or edited directly in a
cell bypass it.</p>
<p>The callback changes values alone. A returned key that matches no schema
field is ignored, and no returned value attaches an error to a cell. Once the
reader has taken those values, the column validators evaluate them the same
way they evaluate values that came straight from the file.</p>
<p>Not every import needs <code>onRowImport</code>. If the file's columns already match the
schema boundaries, column matching is enough.
<a href="https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/">Value matching resolves option values</a>,
and the currency reader normalizes
<a href="https://updog.tech/blog/normalize-currency-codes-and-symbols-during-import/">a currency symbol that arrives in its own column</a>.</p>
<p>Use the callback when the file's row and your schema disagree about
structure. One cell may hold values that belong in several fields, or several
cells may need combining before the row reaches the editor.</p>
<p>For this royalty statement, the importer reads the file, the mapping supplies
the amount, <code>onRowImport</code> splits <code>Artist</code> and takes the currency out of
<code>Payment</code>, and the row opens in the grid for review before your app receives
it.</p>
<p>If another distributor sends <code>First name</code> and <code>Last name</code> as separate
columns, mapping covers the artist directly. The callback then keeps to the
currency.</p>]]></content:encoded></item>
<item><title>Add CSV and Excel Import to a Bolt App</title><link>https://updog.tech/blog/add-csv-and-excel-import-to-a-bolt-app/</link><guid isPermaLink="true">https://updog.tech/blog/add-csv-and-excel-import-to-a-bolt-app/</guid><pubDate>Mon, 31 Aug 2026 00:00:00 GMT</pubDate><description>A warehouse takes over a client whose delivery bookings live in a spreadsheet. See how Updog Importer brings that file into an app built on Bolt.</description><content:encoded><![CDATA[<p>Bolt turns a prompt into a working web application. StackBlitz built it on WebContainers, so the install, the dev server and the preview all run inside the browser tab. Bolt attaches a Bolt Database when the project needs one, and it offers Supabase as the alternative at project creation.</p>
<p>Once that application has customers, some of their records already sit somewhere else. A haulage client may keep a season of delivery bookings in a spreadsheet exported from the warehouse system they ran before, and those rows belong in your <code>deliveries</code> table.</p>
<p>Updog Importer adds that path. The example is a goods-in page backed by an empty <code>deliveries</code> table in Bolt Database.</p>
<p>The Bolt agent can build that import screen, or it can install one.</p>
<h2 id="bolt-already-reads-files-in-chat">Bolt already reads files in chat</h2>
<p>Attach a <code>.csv</code> file to the Bolt chat and the agent reads it while it builds the application. The Tables screen works in the other direction, where selected rows leave the database as CSV or JSON.</p>
<p>Both of those serve the person building the app.</p>
<p>A customer import is a different path. The customer opens the finished goods-in page, picks a file you have never seen, reviews the rows, and writes the accepted data into your <code>deliveries</code> table.</p>
<p>Attaching a file to Bolt is therefore a step in building the product. The import screen below is part of the product.</p>
<h2 id="the-app-already-has-a-deliveries-table">The app already has a deliveries table</h2>
<p>One prompt to the Bolt agent produced the starting warehouse app.</p>
<pre><code class="language-text">Build a small warehouse goods-in app with one page, on Vite, React and
TypeScript.

Use Bolt Database. Create a table named deliveries with these columns, and
leave the table empty.

  delivery_ref     text primary key
  supplier_name    text not null
  carrier          text
  pallets          integer not null
  gross_weight_kg  numeric(10,2) not null
  booked_for       date not null
  dock             text
  status           text
  contact_email    text

The app has no sign-in, so add row level security policies on deliveries that
let the anonymous role select, insert, update and delete. Say in the chat which
policies you created.

Render /deliveries as a page that reads every row through the database client
and shows those nine columns in a table, with the row count above it and an
empty state while the table holds nothing. Redirect / to /deliveries.

Keep the styling plain, and give the app one primary color, #9c4221. No
authentication, no seed data, no extra pages.</code></pre>
<p>Bolt applied a migration, created <code>deliveries</code> empty, and wrote four row level security policies scoped to the anonymous and authenticated roles, one per operation. It generated a Supabase client at <code>src/lib/supabase.ts</code>. The project carries no router, so the redirect went into <code>App.tsx</code> as a few lines of its own. The page rendered as <code>0 deliveries</code> over an empty state.</p>
<p>Those nine column names carry through the whole example. The importer's column ids use the same <code>snake_case</code> names as the table, so a row the editor returns already has the shape the database expects, and no field gets renamed on the way.</p>
<p>The rest of the guide begins from that project, and from a file that knows nothing about it.</p>
<h2 id="the-file-brings-its-own-schema">The file brings its own schema</h2>
<p>The customer's file follows a schema your app does not control. Its headers may not match your field names, its dates may use another order, and its values may not match the options your fields accept.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>The screen has to</th>
<th>Because the file</th>
</tr>
</thead>
<tbody>
<tr>
<td>detect encoding and delimiter</td>
<td>arrives as UTF-8, Windows-1252, comma or semicolon</td>
</tr>
<tr>
<td>find the header row</td>
<td>carries a report title and an export date above it</td>
</tr>
<tr>
<td>read every sheet of a workbook</td>
<td>is <code>.xlsx</code> with one tab per depot</td>
</tr>
<tr>
<td>settle the date order per column</td>
<td>writes <code>04/11/2026</code> and means the fourth of November</td>
</tr>
<tr>
<td>keep leading zeros</td>
<td>holds <code>00417</code>, and a plain reader makes it <code>417</code></td>
</tr>
<tr>
<td>match headers onto your fields</td>
<td>says <code>Slot date</code> where your app says <code>booked_for</code></td>
</tr>
<tr>
<td>match values onto your options</td>
<td>says <code>Marden Freight Ltd</code> where your app says <code>Marden Freight</code></td>
</tr>
<tr>
<td>check and let the person fix</td>
<td>holds a row your database will reject</td>
</tr>
<tr>
<td>stay usable at scale</td>
<td>is a hundred thousand rows on a laptop</td>
</tr>
<tr>
<td>report new, changed and deleted rows</td>
<td>is the second import of a file that landed once already</td>
</tr>
</tbody>
</table></div>
<p>Each line in that table needs an implementation rule. Written out as a prompt, the fields come first and each part of the import gets its own stage.</p>
<pre><code class="language-text">Build a CSV and Excel import screen for the deliveries page. A button on that
page opens it as a modal wizard, our customers walk that wizard with the exports
their old warehouse system produced, and it leaves them in a spreadsheet where
they clean what came in.

Where the fields come from
- Read the field list from my code, so the same screen serves the deliveries
  page today and a despatches page later.
- Support text, whole numbers, decimals, dates and a fixed list of options, and
  let one field carry several rules at once.
- Check required, a range, a number of decimal places, uniqueness inside the
  file, and uniqueness against the deliveries we already store.
- Show the customer our label for a field, and hand my code back the field name.
- Take delivery_ref as the key, so a second upload of the same file finds those
  deliveries and updates them.
- Drop columns the file carries beyond that list.

Opening the files
- Take several files at once, by drop or by dialog, and show a card per file.
- Detect the encoding, strip a byte order mark, and read a Windows-1252 export
  without turning accented supplier names into question marks.
- Detect the delimiter. Commas, semicolons, tabs and pipes all arrive.
- Drop a first line shaped sep=; that Excel writes for some locales.
- Read .xlsx, .xls and .ods, open a workbook as one card per sheet, and let the
  customer choose which sheets go on.
- Find the real header row when a report title and an export date sit above it,
  and handle a file with duplicate headers or no header at all.
- Keep a row carrying one field too few, and say which fields it filled.

Reading what the cells hold
- Settle the date order per column, so 04/11/2026 does not become April.
- Read 1.240,50 and 1,240.50 as the same number.
- Keep 00417 as text, including a code Excel already turned into 417.
- Tell an empty cell apart from a cell holding the word null.

Matching the columns
- Map the file's headers onto my field list, one field per column.
- Match the obvious ones on arrival, and show the customer which of my fields
  reached nothing so they can point each one at a column by hand.
- Show a few values under every header, so the customer tells two similar
  columns apart.
- Remember the pairs the customer confirmed, so the next file of that shape
  arrives matched.

Matching the values
- Collect the distinct values of carrier, dock and status as the file spells
  them.
- Match each one to an option we allow, and let the customer place the rest.

Cleaning before the write
- Hand the finished file to a spreadsheet the customer works in, with my labels
  on top and every row in it.
- Mark what the customer changed. A new row, an edited cell and a deleted row
  each read differently at a glance.
- Run every rule the field list carries, and say which cell failed and why.
- Let the customer fix a cell in place, with the editor that fits the field. A
  date opens a calendar, a list opens its options, a number takes digits.
- Sort and filter, so the customer reaches the failing rows among the hundred
  thousand that pass.
- Copy and paste blocks between it and Excel or Google Sheets, and undo an edit.
- Stay smooth at a hundred thousand rows, with the reading off the main thread
  so the tab keeps responding.

Handing the rows over
- Tell me which rows are new, which changed, and which were deleted.
- Keep every row and every mapping on screen when my write to the database
  fails.</code></pre>
<p>Prompting that screen into existence is the right call for a fixed set of columns, a file you produced yourself, and one import a month. The rules above stop being optional once the files come from customers you have never met.</p>
<p>If you build the importer yourself, every rule in that prompt becomes application code you own, and each one has to survive the next file the client exports.</p>
<p><a href="https://updog.tech/blog/build-vs-buy-csv-importer/">Build or buy a CSV importer</a> weighs that ownership over a longer horizon.</p>
<p>The second approach gives those file-facing rules to a package.</p>
<h2 id="the-second-prompt-installs-the-importer">The second prompt installs the importer</h2>
<p>Bolt runs the project in a WebContainer, a WebAssembly-based runtime from StackBlitz that boots Node inside the browser tab. An npm install happens there, and Code View opens a terminal on the same container where <code>npm run build</code> runs by hand.</p>
<pre><code class="language-text">Add a spreadsheet import screen to the deliveries page with the npm package
@updog/data-editor. Read https://updog.tech/updog.md and
https://docs.updog.tech first, and use only props documented there.

1. Install @updog/data-editor and import "@updog/data-editor/styles.css".
2. Add an "Import deliveries" button above the table, holding one open state.
   The editor opens as a modal, which is its default: pass open={open} and an
   onClose that closes it. Do not pass mode="inline". Wrap it in nothing and
   give it no height of its own, because the modal sizes itself.
3. Render &#x3C;DataEditor /> with apiKey="updog-bolt-demo", which is all the key a
   Bolt preview or a bolt.host site needs, variant="uploader",
   primaryKey="delivery_ref", enableDeleteRow="all" and these nine columns,
   written as id, title, then type and rules:
   delivery_ref "Delivery ref" text, required, unique
   supplier_name "Supplier" text, required
   carrier "Carrier" select: Ravenhill Haulage, Copsey Transport,
     Marden Freight, Delwyn Logistics
   pallets "Pallets" number, whole, minimum 1, required
   gross_weight_kg "Gross weight" number, two decimals, minimum 0, required
   booked_for "Booking date" date, required
   dock "Dock door" select: Dock 1, Dock 2, Dock 3
   status "Status" select: Booked, Arrived, Unloaded
   contact_email "Contact email" text, email
   The ids are the deliveries table's own column names on purpose, so no field
   is renamed between the editor and the database.
4. In a stylesheet loaded after "@updog/data-editor/styles.css", set
   --updog-brand on :root to this app's primary color, written as a plain color
   value.
5. onComplete receives result.sources, and every entry in a source's rows is a
   wrapper shaped { row, isNew, isChanged, isDeleted, isValid }. Read the four
   flags off the wrapper and the cell values off entry.row. Skip an entry whose
   isValid is false.
6. entry.row is keyed by those same ids, so send it to the database as it is.
   Write no mapper and no Number call. Postgres casts a text parameter to the
   column's own type.
7. Write with the database client this project already has. Send the new and
   changed rows through one upsert on deliveries with delivery_ref as the
   conflict target, and delete the removed ones by delivery_ref. Both calls go
   straight from the browser, so they run under the row level security policies
   on the table.
8. Throw from onComplete when the write fails, and include the error the client
   returned. The editor clears its rows as soon as onComplete resolves, so a
   swallowed error loses the import. When it succeeds, close the modal and
   reload the deliveries list.
9. Do not build an uploader of your own, do not parse the file yourself, and do
   not invent props.</code></pre>
<p>The agent read <code>updog.md</code>, then the documentation site, then the package's own type declarations, installed the dependency and wrote the screen in one pass. The build and the typecheck passed with no prop corrected by hand.</p>
<p>A package is still code you did not write. What it does to a customer's file is yours to test before the first customer opens it.</p>
<h2 id="the-importer-mirrors-the-deliveries-table">The importer mirrors the deliveries table</h2>
<p>The nine table columns become nine importer columns. Each column points at one database column through its <code>id</code>, and <code>title</code> gives the customer the name shown in the grid.</p>
<pre><code class="language-tsx">import {
  DataEditor,
  type DataEditorColumn,
  type DataEditorResult,
} from "@updog/data-editor";
import "@updog/data-editor/styles.css";

type Delivery = {
  delivery_ref: string;
  supplier_name: string;
  carrier: string;
  pallets: string;
  gross_weight_kg: string;
  booked_for: string;
  dock: string;
  status: string;
  contact_email: string;
};

const columns: DataEditorColumn[] = [
  {
    id: "delivery_ref",
    title: "Delivery ref",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "supplier_name",
    title: "Supplier",
    validators: [{ type: "required" }],
  },
  {
    id: "carrier",
    title: "Carrier",
    editor: {
      type: "select",
      options: [
        "Ravenhill Haulage",
        "Copsey Transport",
        "Marden Freight",
        "Delwyn Logistics",
      ],
      enableCustomValue: false,
    },
  },
  {
    id: "pallets",
    title: "Pallets",
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 1, decimalPlaces: 0 },
    ],
  },
  {
    id: "gross_weight_kg",
    title: "Gross weight",
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "booked_for",
    title: "Booking date",
    editor: { type: "date" },
    validators: [{ type: "required" }],
  },
  {
    id: "dock",
    title: "Dock door",
    editor: {
      type: "select",
      options: ["Dock 1", "Dock 2", "Dock 3"],
      enableCustomValue: false,
    },
  },
  {
    id: "status",
    title: "Status",
    editor: {
      type: "select",
      options: ["Booked", "Arrived", "Unloaded"],
      enableCustomValue: false,
    },
  },
  {
    id: "contact_email",
    title: "Contact email",
    validators: [{ type: "email" }],
  },
];</code></pre>
<p>Some validators repeat rules the table already declares, and they run at a different boundary. <code>delivery_ref</code> is a primary key in Postgres, so two rows carrying one reference fail at the write and take the whole statement with them. <code>{ type: "unique" }</code> flags every row that shares a reference inside the file, before submit, on the rows that carry it.</p>
<p>The three option lists have no counterpart in the table, which stores plain text in those columns. <code>pallets</code> and <code>gross_weight_kg</code> map to <code>NOT NULL</code> columns, so both carry <code>{ type: "required" }</code>. The <code>numeric(10,2)</code> column gets <code>decimalPlaces: 2</code> beside it, which flags a third decimal in the grid where Postgres would round it silently. Those nine entries are one value now, ready for the page to pass.</p>
<h2 id="the-page-mounts-the-importer">The page mounts the importer</h2>
<p>The editor draws on canvas and needs the browser DOM. The Bolt project here is a Vite React bundle that runs in the browser already, so the component mounts with no directive of its own.</p>
<pre><code class="language-tsx">export function DeliveryImporter({ onImported }: Props) {
  const [open, setOpen] = useState(false);

  return (
    &#x3C;>
      &#x3C;button type="button" onClick={() => setOpen(true)}>
        Import deliveries
      &#x3C;/button>

      &#x3C;DataEditor&#x3C;Delivery>
        apiKey="updog-bolt-demo"
        variant="uploader"
        open={open}
        onClose={() => {
          setOpen(false);
        }}
        columns={columns}
        primaryKey="delivery_ref"
        enableDeleteRow="all"
        onComplete={handleComplete}
      />
    &#x3C;/>
  );
}</code></pre>
<p><code>primaryKey</code> names the column that identifies a delivery inside the editor, and the editor requires it. <code>enableDeleteRow</code> lets the customer remove a booking, which gives the submit handler a deleted row to route, and it defaults to <code>false</code>, so leaving it out keeps deletion away from the customer.</p>
<p>One CSS variable moves the app's primary color into the editor.</p>
<pre><code class="language-css">/* loaded after @updog/data-editor/styles.css */
:root {
  --updog-brand: #9c4221;
}</code></pre>
<p><a href="https://updog.tech/blog/style-updog-to-match-your-product/">Match the importer to your product</a> goes further into typography, the grid, shadows and a dark theme.</p>
<h2 id="the-file-uses-another-systems-vocabulary">The file uses another system's vocabulary</h2>
<p>The export carries 280 delivery bookings out of the client's old warehouse system, on one sheet of a workbook.</p>
<p><code>aldermere-goods-in.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Delivery no.</td><td class="sheet__cell">Supplier name</td><td class="sheet__cell">Carrier name</td><td class="sheet__cell">Pallets received</td><td class="sheet__cell">Gross weight (kg)</td><td class="sheet__cell">Slot date</td><td class="sheet__cell">Dock</td><td class="sheet__cell">Load status</td><td class="sheet__cell">Booking contact email</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">AG-0001</td><td class="sheet__cell">Tarnwick Packaging Ltd</td><td class="sheet__cell">Marden Freight</td><td class="sheet__cell">28</td><td class="sheet__cell">16162.76</td><td class="sheet__cell">2026-09-19</td><td class="sheet__cell">Dock 1</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@tarnwickpackagin.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">AG-0002</td><td class="sheet__cell">Beckhurst Coatings PLC</td><td class="sheet__cell">Delwyn Logistics</td><td class="sheet__cell">27</td><td class="sheet__cell">14327.37</td><td class="sheet__cell">2026-10-24</td><td class="sheet__cell">Dock 2</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@beckhurstcoating.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">AG-0008</td><td class="sheet__cell">Halverne Glassworks PLC</td><td class="sheet__cell">Delwyn Logistics</td><td class="sheet__cell">22</td><td class="sheet__cell">17602.38</td><td class="sheet__cell">2026-12-19</td><td class="sheet__cell">Dock 1</td><td class="sheet__cell">Unloaded</td><td class="sheet__cell">bookings@halverneglasswor.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">7 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">17</th><td class="sheet__cell">AG-0016</td><td class="sheet__cell">Pelsham Adhesives Works</td><td class="sheet__cell">Ravenhill Haulage</td><td class="sheet__cell">3</td><td class="sheet__cell">15168.71</td><td class="sheet__cell">2026-11-22</td><td class="sheet__cell">Dock 2</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@pelshamadhesives.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">26 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">44</th><td class="sheet__cell">AG-0043</td><td class="sheet__cell">Skelbrook Textiles Ltd</td><td class="sheet__cell">Marden Freight</td><td class="sheet__cell">13</td><td class="sheet__cell">7248.45</td><td class="sheet__cell">2026-10-16</td><td class="sheet__cell">Dock 2</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@skelbrooktextile.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">81 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">126</th><td class="sheet__cell">AG-0125</td><td class="sheet__cell">Elverton Seals LLP</td><td class="sheet__cell">Marden Freight</td><td class="sheet__cell">9</td><td class="sheet__cell">8414.99</td><td class="sheet__cell">2026-12-28</td><td class="sheet__cell">Dock 2</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@elvertonsealsllp.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">81 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">208</th><td class="sheet__cell">AG-0207</td><td class="sheet__cell">Orrell Insulation Group</td><td class="sheet__cell">Marden Freight</td><td class="sheet__cell">3</td><td class="sheet__cell">8641.15</td><td class="sheet__cell">2027-02-28</td><td class="sheet__cell">Dock 1</td><td class="sheet__cell">Arrived</td><td class="sheet__cell">bookings@orrellinsulation.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">72 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">281</th><td class="sheet__cell">AG-0280</td><td class="sheet__cell">Pelsham Adhesives Works</td><td class="sheet__cell">Marden Freight</td><td class="sheet__cell">5</td><td class="sheet__cell">10460.29</td><td class="sheet__cell">2027-01-26</td><td class="sheet__cell">Dock 1</td><td class="sheet__cell">Booked</td><td class="sheet__cell">bookings@pelshamadhesives.example</td></tr></tbody></table>
<p>Every one of the nine headers is written differently from the column it belongs to.</p>
<pre><code class="language-text">Delivery no.           →  Delivery ref
Supplier name          →  Supplier
Carrier name           →  Carrier
Pallets received       →  Pallets
Gross weight (kg)      →  Gross weight
Slot date              →  Booking date
Dock                   →  Dock door
Load status            →  Status
Booking contact email  →  Contact email</code></pre>
<p>The matcher resolves all nine against the importer schema, and the wizard reports <code>9/9 matched</code>. Seven headers score on the containment tier, where one normalized string of at least four characters sits inside the other, and <code>Delivery no.</code> and <code>Slot date</code> score on word overlap, where half the words are shared. <code>Carrier</code>, <code>Dock door</code> and <code>Status</code> carry closed lists, and the value step settles those as <code>4/4</code>, <code>3/3</code> and <code>3/3</code>, with nothing left to place by hand.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">Building a column mapping screen</a> covers what happens on the headers that reach nothing.</p>
<p>All 280 rows then reach the grid, with no validation error and no empty cell. The customer can filter, edit cells, undo changes, and paste blocks from a spreadsheet before submit. Submit prints the counts it is about to send, and on this file it read <code>280 new rows will be created</code>.</p>
<h2 id="submit-returns-the-rows-and-their-state">Submit returns the rows and their state</h2>
<p>Submit returns the edited rows grouped by source. Each row carries four independent flags describing whether it is new, changed, deleted and valid. Your handler decides what those states mean for the database.</p>
<pre><code class="language-tsx">const handleComplete = async (result: DataEditorResult&#x3C;Delivery>) => {
  const rows = result.sources.flatMap((source) => source.rows);

  const upserts = rows
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .filter((entry) => entry.isNew || entry.isChanged)
    .map((entry) => entry.row);

  const deletes = rows
    .filter((entry) => entry.isDeleted &#x26;&#x26; !entry.isNew)
    .map((entry) => entry.row.delivery_ref);

  await writeDeliveries(upserts, deletes);

  setOpen(false);
  await onImported();
};</code></pre>
<p>No mapper sits between the flags and the write. The keys of <code>entry.row</code> are the table's own column names, so <code>upserts</code> goes to the database as it is.</p>
<p>A number column hands back text. <code>pallets</code> arrives as <code>"28"</code> and <code>gross_weight_kg</code> as <code>"16162.76"</code>, and Postgres reads that text into the column's own type, so neither value passes through <code>Number</code> on the way. A date column hands back ISO, so <code>booked_for</code> arrives as <code>"2026-09-19"</code>, independent of how the date appeared in the grid.</p>
<p>This is the whole <code>result</code> object, with one of the 280 rows kept.</p>
<pre><code class="language-ts">{
  sources: [
    {
      sourceId: "source_…",
      sourceName: "aldermere-goods-in.xlsx",
      rows: [
        {
          row: {
            delivery_ref: "AG-0001",
            supplier_name: "Tarnwick Packaging Ltd",
            carrier: "Marden Freight",
            pallets: "28",
            gross_weight_kg: "16162.76",
            booked_for: "2026-09-19",
            dock: "Dock 1",
            status: "Booked",
            contact_email: "bookings@tarnwickpackagin.example",
          },
          isNew: true,
          isChanged: false,
          isDeleted: false,
          isValid: true,
        },
        // 279 more rows
      ],
    },
  ],
  counts: { new: 280, changed: 0, deleted: 0, invalid: 0 },
  learnedSynonyms: { columns: [], values: [] },
}</code></pre>
<p>Nothing in that object names a table or a statement, so the handler turns those four flags into a write of your own.</p>
<p><a href="https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/">Import, edit and delete rows through a REST API</a> routes those four flags against a backend that answers over HTTP.</p>
<h2 id="the-write-reaches-bolt-database">The write reaches Bolt Database</h2>
<p>Bolt applied a Postgres migration for this table, and the Tables screen shows the row level security policies each table carries. The write below runs in the customer's browser under the anonymous role, so those policies decide whether a row lands.</p>
<pre><code class="language-ts">const writeDeliveries = async (
  upserts: Delivery[],
  deletes: string[],
) => {
  if (upserts.length > 0) {
    const { error } = await supabase
      .from("deliveries")
      .upsert(upserts, { onConflict: "delivery_ref" });

    if (error) {
      throw new Error(error.message);
    }
  }

  if (deletes.length > 0) {
    const { error } = await supabase
      .from("deliveries")
      .delete()
      .in("delivery_ref", deletes);

    if (error) {
      throw new Error(error.message);
    }
  }
};</code></pre>
<p><code>supabase</code> is the client Bolt generated for the project, at <code>src/lib/supabase.ts</code>. The write is that client's call, and it runs under the policies the Tables screen lists.</p>
<p><code>onConflict: "delivery_ref"</code> needs a constraint the table declares, and <code>delivery_ref</code> is the primary key. Postgres refuses the upsert when no such constraint exists.</p>
<p>A policy that turns the write away answers through the same <code>error</code> field. The handler cannot tell a refused row from a malformed one, and it does not need to, because both leave the data where the customer can still see it.</p>
<p>An error from either call becomes a thrown <code>Error</code>, and the rows stay on screen because of it. A resubmit then starts from the same grid, against a table that may already hold some of those rows.</p>
<h2 id="the-database-decides-what-a-repeat-import-means">The database decides what a repeat import means</h2>
<p>Editor state and database state answer different questions. Every row on this run carries <code>isNew: true</code>, because the grid opened with nothing in it. The table already held the same <code>delivery_ref</code> on the second import, so the upsert updated those records and the count stayed at 280.</p>
<p><code>isNew</code> means new to the editor. It does not mean absent from the database.</p>
<p>You pick where a repeat import gets reconciled. The key settles it at write time in the database, or <code>loadData</code> pulls stored deliveries into the grid and settles it before submit. Updog Importer reports the row state and picks neither.</p>
<p>Let write errors reject <code>onComplete</code>. A rejected promise keeps the rows in the editor, and it undoes nothing the database already accepted. A resolved promise tells Updog Importer that submission finished, so close the modal and reload the page only after the write succeeds.</p>
<h2 id="the-bolt-url-runs-for-free">The Bolt URL runs for free</h2>
<p>Updog Importer makes one request to its license endpoint when the editor starts. It sends the API key, and the browser attaches the page's origin. No rows, headers or file contents go with it.</p>
<p>Updog keeps a list of development and preview hosts where the importer runs free, with no row counted. Both Bolt hosts are on it, <code>.webcontainer-api.io</code> for the in-editor preview and <code>.bolt.host</code> for the site you publish. The prompt can leave the placeholder API key in place while the app runs there.</p>
<p>The preview host is worth knowing by sight, because it is the first place the editor opens and it carries neither the word Bolt nor the project's name. Bolt forwards the WebContainer's port to a URL shaped <code>&#x3C;hash>--5173--&#x3C;hash>.local-credentialless.webcontainer-api.io</code>, where <code>5173</code> is the Vite port the project serves on.</p>
<p>A custom domain changes that on both sides. Bolt sells custom domains on its paid plans, and the hostname goes into your API key's domain list at <a href="https://console.updog.tech/">console.updog.tech</a>. The Free plan covers production domains up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains, with no row limit.</p>
<h2 id="the-app-now-has-an-import-path">The app now has an import path</h2>
<p>Updog Importer installs into a Bolt project as an npm package. Its columns carry the <code>deliveries</code> table's own names, the customer resolves the file before submit, and <code>onComplete</code> returns the edited rows and their state to a handler you own.</p>
<p>The importer handles the file-facing work, parsing CSV and Excel, matching columns and values, validating cells, and letting the customer correct the data. Your application still decides what those rows mean in the database, including updates, deletions and repeat imports.</p>
<p>You can build the same flow yourself, and the first prompt above names every rule that takes. Installing the package keeps those rules inside the importer, and leaves the Bolt project holding the goods-in page and its write path.</p>]]></content:encoded></item>
<item><title>How to Normalize Country Names and ISO Codes During Import</title><link>https://updog.tech/blog/normalize-country-names-and-iso-codes-during-import/</link><guid isPermaLink="true">https://updog.tech/blog/normalize-country-names-and-iso-codes-during-import/</guid><pubDate>Sun, 30 Aug 2026 00:00:00 GMT</pubDate><description>A country goes by several names and several codes. See how Updog Importer normalizes country names into one stored ISO code.</description><content:encoded><![CDATA[<p>Country data looks simple until it comes from more than one system. The same
country can arrive as <code>Germany</code>, <code>Deutschland</code>, <code>DE</code>, <code>DEU</code> or <code>276</code>. Names
change with language, and codes come in several formats. A spreadsheet drops
the leading zero from a numeric code, and a typo can sit one letter away from
more than one real country. The importer has to know what it can read exactly,
what it can correct safely, and what it should leave for a person to decide.</p>
<p>Twelve trial sites sit on the register, and the country column came back twelve
different ways. One site wrote <code>Deutschland</code>. One wrote <code>USA</code>. One wrote <code>040</code>,
and the spreadsheet that opened the file read it as a number and dropped the
zero.</p>
<p>The table behind the register holds two letters.</p>
<p><code>trial-sites.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Site ID</td><td class="sheet__cell">Institution</td><td class="sheet__cell">Country</td><td class="sheet__cell">PI</td><td class="sheet__cell">Enrolled</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">STE-1041</td><td class="sheet__cell">Mitte Clinical Centre</td><td class="sheet__cell">Deutschland</td><td class="sheet__cell">R. Hoffmann</td><td class="sheet__cell">84</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">STE-1042</td><td class="sheet__cell">Cascade Valley Medical</td><td class="sheet__cell">USA</td><td class="sheet__cell">L. Okonkwo</td><td class="sheet__cell">131</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">STE-1043</td><td class="sheet__cell">Cocody Research Unit</td><td class="sheet__cell">Côte d’Ivoire</td><td class="sheet__cell">A. Bamba</td><td class="sheet__cell">47</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">STE-1044</td><td class="sheet__cell">Moravská klinika</td><td class="sheet__cell">Czech Republic</td><td class="sheet__cell">J. Marek</td><td class="sheet__cell">62</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">STE-1045</td><td class="sheet__cell">Maasstroom Trial Centre</td><td class="sheet__cell">Ntherlands</td><td class="sheet__cell">W. de Bruin</td><td class="sheet__cell">58</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">STE-1046</td><td class="sheet__cell">Ljubljana Clinical Institute</td><td class="sheet__cell">Slovania</td><td class="sheet__cell">M. Zupan</td><td class="sheet__cell">66</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">STE-1047</td><td class="sheet__cell">Hanbit Medical Institute</td><td class="sheet__cell">Korea</td><td class="sheet__cell">H. Park</td><td class="sheet__cell">95</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">STE-1048</td><td class="sheet__cell">Kinshasa Referral Hospital</td><td class="sheet__cell">Congo</td><td class="sheet__cell">M. Lutete</td><td class="sheet__cell">38</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">STE-1049</td><td class="sheet__cell">St Alwyn's Trial Unit</td><td class="sheet__cell">UK</td><td class="sheet__cell">C. Bewley</td><td class="sheet__cell">73</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">STE-1050</td><td class="sheet__cell">Donauklinik Krems</td><td class="sheet__cell">40</td><td class="sheet__cell">S. Aigner</td><td class="sheet__cell">29</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell">STE-1051</td><td class="sheet__cell">Windhoek Central Research Unit</td><td class="sheet__cell">NA</td><td class="sheet__cell">T. Shipanga</td><td class="sheet__cell">54</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">STE-1052</td><td class="sheet__cell">Site pending activation</td><td class="sheet__cell">N/A</td><td class="sheet__cell"></td><td class="sheet__cell">0</td></tr></tbody></table>
<p>Most of those writings were correct when the site wrote them. Two are typos, and
one row has no country yet. The rest makes sense to the people who filled it in,
and the column as a whole still does not arrive in the shape the register needs.
Turning the column into <code>DE</code>, <code>US</code> and <code>AT</code> is the work, and the part worth
getting right is where that work has to stop.</p>
<h2 id="matching-against-a-list-of-codes-lands-on-the-wrong-country">Matching against a list of codes lands on the wrong country</h2>
<p>ISO 3166-1 assigns 249 alpha-2 codes. Kosovo has none, so a list that also
covers it borrows <code>XK</code> from the user-assigned range and reaches 250 entries.
Those 250 codes sit inside the 676 two-letter combinations the alphabet
allows, which fills 37 percent of the space.</p>
<p>That density is why a one-edit rule over the codes has so many candidates to
choose from. Measured across the list, one code has 23 other real codes one
substitution away, on average. <code>MM</code> has 38. Take any of the 676 combinations,
assigned or not, and it sits one substitution from 18 real codes on average,
from 5 at the sparsest. Those counts are for two-letter input, and a longer
value reaches the codes by deleting a character instead.</p>
<p>Declare the country column as a plain list of the 250 codes, in alphabetical
order, and let the generic value matcher compare each distinct value in the
column against them. On Updog Importer 0.1.88, the result looks like this.</p>
<pre><code class="language-text">USA   →  SA    Saudi Arabia
UK    →  CK    Cook Islands
N/A   →  NA    Namibia
TBD   →  BD    Bangladesh
CS    →  AS    American Samoa</code></pre>
<p><code>usa</code> reaches <code>sa</code> by deleting one character. It reaches <code>us</code> and <code>ua</code> the
same way. All three score 65, so the first one on the list wins, and
alphabetical order is the only reason Saudi Arabia becomes the answer. One
edit is the budget at four characters, and it widens as the string gets
longer. The score clears the acceptance threshold, the mapping is filled in,
and nothing on screen says that several countries were equally close.</p>
<p>Long country names fail in the opposite direction. <code>Deutschland</code>, <code>Czech Republic</code> and <code>Côte d’Ivoire</code> do not reach a two-letter code at all. A
two-character option is too short to share a word with the input, and the
edit budget refuses any pair whose lengths differ by more than one.</p>
<p>A wrong country that a person can see is a bad import. A wrong country that
looks decided is worse. Changing the candidates from codes to country names
fixes only half of the problem. The same generic matcher can read <code>Czech Republic</code> as Dominican Republic and <code>Korea</code> as North Korea.</p>
<p>The candidate pool decides what the matcher is allowed to reach. The matching
rules decide when one of those candidates is safe enough to choose.</p>
<h2 id="the-column-stores-the-code-and-prints-the-name">The column stores the code and prints the name</h2>
<p>Storing the name puts a value in your database that a later CLDR update can
change under you. CLDR 43, released on 12 April 2023, states that "in English,
Türkiye is now the primary country name for the country code TR, and Turkey is
available as an alternate". CLDR 42 had it the other way round.</p>
<p>Each browser reads that data from an ICU build of its own. Chrome bundles one,
Safari uses the one that ships with the operating system. A column filled from
two browsers can hold <code>Turkey</code> in one row and <code>Türkiye</code> in the next. The code
stayed <code>TR</code> through all of it.</p>
<p>So a country column in Updog Importer stores the alpha-2 code in upper case for
every value it resolves, and prints the CLDR name in the language you pass as
<code>locale</code>.</p>
<pre><code class="language-text">stored value      DE
locale: "en"      Germany
locale: "ar"      ألمانيا
CSV export        DE
onComplete        DE</code></pre>
<p>The person reads the name. Your handler receives <code>DE</code>. The displayed name can
change with language or CLDR version without changing the value stored in the
dataset.</p>
<h2 id="the-browser-already-holds-the-country-names">The browser already holds the country names</h2>
<p><code>Intl.DisplayNames</code> turns a region code into a name in a given language, and it
reads from the CLDR the engine already ships for the rest of <code>Intl</code>. It has been
available across browsers since April 2021.</p>
<p>That means the importer does not need to ship a table of translated country
names. Give <code>Intl.DisplayNames</code> the 250 country codes in one locale and it
builds a name index for that language at runtime, weighing nothing in the
bundle. Updog Importer builds that index across 26 languages and three name
styles the first time an imported value reaches this step.</p>
<p>On Node 24.19.0 with ICU 78.3, the resulting index contains 4,852 forms that
each name one country. Once built, a thousand lookups of <code>Deutschland</code> take
about a third of a millisecond.</p>
<p><code>Deutschland</code>, <code>Almanya</code>, <code>Niemcy</code>, <code>Duitsland</code> and <code>德国</code> all reach <code>DE</code>
through it. None of the five comes from a translation table shipped with
Updog.</p>
<p><code>Intl.DisplayNames</code> does not cover every form the importer needs. CLDR also
carries alternative English names such as <code>Czech Republic</code>, <code>Turkey</code>,
<code>Swaziland</code> and <code>Ivory Coast</code>, outside the long, short and narrow forms it
returns. Alpha-3 and numeric ISO codes are separate again. <code>Intl.DisplayNames</code>
throws for <code>DEU</code>, an alpha-3 code, and <code>040</code>, the numeric code for Austria,
comes back as <code>040</code> rather than Austria.</p>
<p>Updog therefore ships two small tables beside the runtime index. One holds 98
name forms the engine returns in none of its 26 languages, 1,146 bytes
gzipped. The other maps alpha-3 and numeric ISO codes to alpha-2, 249 records
at 1,301 bytes gzipped.</p>
<p><code>UK</code> sits in the same table for another reason. On this engine <code>UK</code> is the short
name for <code>GB</code>, and the index drops every form of plain Latin letters under four
characters. <code>Çad</code> and <code>Irã</code> normalize into <code>cad</code> and <code>ira</code>, and a file's
department code would read as a country.</p>
<p>The browser supplies most of the names. The importer adds the forms the
browser cannot reach, and removes the ones too short to trust.</p>
<h2 id="exact-reading-answers-before-the-matcher-does">Exact reading answers before the matcher does</h2>
<p>Each imported value goes through the same reading ladder, and the first step
that answers wins. A
<a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">date column votes on one format for the whole column</a>,
since <code>01/05/2026</code> cannot be read without knowing what its neighbours are. A
country column needs no such vote. <code>Deutschland</code> and <code>40</code> name their countries
whatever sits above or below them.</p>
<pre><code class="language-text">1  normalize the text
2  two letters      →  the alpha-2 list
3  three letters    →  the alpha-3 map
4  one to three digits, padded to three  →  the numeric map
5  name shared by two countries          →  ambiguity guard, hold both
6  the runtime name index, 26 languages
7  the alternative-forms table
8  nothing</code></pre>
<p>Normalization runs first for every step below it. It decomposes the text, drops
combining marks, reads apostrophes and hyphens as spaces, collapses runs of
space and lowercases the result. <code>Côte d’Ivoire</code> with a typographic apostrophe,
<code>Cote d'Ivoire</code> with a straight one and <code>Cote d Ivoire</code> with none all arrive at
the same key, and so do <code>ألمانيا</code> and <code>المانيا</code>.</p>
<p>The numeric step repairs a spreadsheet's own damage. Austria's record is <code>AT</code>,
<code>AUT</code>, <code>040</code>, and a spreadsheet can turn the numeric one into <code>40</code>. Padding a
one- to three-digit value back to three digits restores the lookup key and
resolves the row to <code>AT</code>.</p>
<p>This is the same loss of a leading zero that affects a
<a href="https://updog.tech/blog/preserving-leading-zeros-in-csv-and-excel-imports/">stock code or a barcode</a>.
A country column can repair it because ISO numeric codes have a fixed width of
three digits.</p>
<p>Seven of the twelve country values in the register are settled by this
exact-reading ladder, with no fuzzy matching anywhere in it. Two more reach the
ambiguity guard, step 5, where the importer deliberately refuses to choose one
country.</p>
<h2 id="a-correction-only-happens-when-one-country-is-close">A correction only happens when one country is close</h2>
<p><code>Ntherlands</code> is one missing letter from Netherlands, and the person who
uploaded the file should not have to spend a decision on it. Updog Importer
corrects that kind of value automatically, under rules narrow enough to state
in full.</p>
<p>The matcher searches country names in eight languages across three name
styles, plus the alternative forms that clear the same cut-offs, 70 of that
table's 98. Two-letter codes never enter that pool, so <code>N/A</code> never comes near
Namibia and <code>TBD</code> never comes near Bangladesh.</p>
<p>The distance is Damerau-Levenshtein. A deletion, an insertion, a substitution
or a swap of two neighbouring characters each cost one edit, so <code>Germnay</code>
reaches Germany. The allowed distance is one edit, and exactly one country has
to be that close.</p>
<p>That last rule is what makes the correction safe.</p>
<pre><code class="language-text">Ntherlands  →  NL    only Netherlands is one edit away
Slovania    →  none  Slovenia and Slovakia are both one edit away</code></pre>
<p>A person reading the full row may know that Ljubljana is in Slovenia. The
matcher does not use that context, because <code>Slovenia</code> and <code>Slovakia</code> are both
one edit from <code>Slovania</code>, and picking either one would be a coin toss printed
as a decision. The same rule keeps Austria away from Australia, Mali from
Malta, and Rwanda from Uganda.</p>
<p>Two cut-offs sit in front of the matcher, both read off the normalized value. A
value under four characters never reaches it, because <code>UL</code> stands one edit
from 17 real codes. Drop that floor and <code>Chd</code> becomes Chad. A value that still
carries anything besides letters and spaces never reaches it either, which
stops <code>Chad2</code>, <code>Ir4n</code> and <code>Peru?</code>.</p>
<p>The rules are tested against generated misspellings of every English country
name in the 250-code list. At each character position, the fixture drops the
character, doubles it, swaps it with its neighbour, or replaces it with one of
<code>a e i o s r n</code>, skipping a replacement that changes nothing and a swap at the
last position. That produces 22,578 generated values, 22,497 of them distinct,
and it is the fixture the matcher is tested against.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Outcome</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Read back to the right country</td>
<td>18,929</td>
</tr>
<tr>
<td>Refused</td>
<td>3,645</td>
</tr>
<tr>
<td>Landed on another exact country name</td>
<td>4</td>
</tr>
<tr>
<td>Fuzzy-corrected to the wrong country</td>
<td>0</td>
</tr>
</tbody>
</table></div>
<p>With the candidate pool already built, one pass over that corpus takes about
0.3 seconds on Node 24.19.0 with ICU 78.3.</p>
<p>The four values in the third row are not bad fuzzy corrections. Each mutation
becomes an exact name for another country before fuzzy matching runs. <code>Chile</code>
can become <code>Chine</code>, the French name for China. <code>Gambia</code> can become <code>sambia</code>,
the German name for Zambia. <code>Iraq</code> can become <code>Iran</code>, and <code>Iceland</code> can become
<code>Ireland</code>. Exact reading accepts those values because, by the time they
arrive, they are valid country names in their own right.</p>
<p>Most refusals are deliberate too. Of the 3,645 refused values, 3,399 fail the
letters-and-spaces cutoff before fuzzy matching starts. CLDR writes twenty
English names with an ampersand, a full stop or a bracket, <code>Antigua &#x26; Barbuda</code>
and <code>São Tomé &#x26; Príncipe</code> among them, and every misspelling of those keeps the
punctuation that stops it at the door. The uniqueness rule turns away 209
more.</p>
<p>The matcher gives up often on purpose. The useful number in the table is the
zero.</p>
<h2 id="a-word-that-names-two-countries-stays-a-question">A word that names two countries stays a question</h2>
<p><code>Korea</code> names two countries. So does <code>Congo</code>, and <code>Virgin Islands</code> names two
entries in the list. Nothing in the value itself picks one over the other, so
the importer keeps both open and leaves the decision to the person who has the
rest of the row.</p>
<p>A country value therefore leaves the matching step with one of four verdicts.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Verdict</th>
<th>Register value</th>
<th>What happens</th>
</tr>
</thead>
<tbody>
<tr>
<td>Exact</td>
<td><code>Deutschland</code>, <code>USA</code>, <code>Côte d’Ivoire</code>, <code>Czech Republic</code>, <code>UK</code>, <code>40</code>, <code>NA</code></td>
<td>the code lands, no tag</td>
</tr>
<tr>
<td>Corrected</td>
<td><code>Ntherlands</code></td>
<td>the code lands, tagged Corrected</td>
</tr>
<tr>
<td>Ambiguous</td>
<td><code>Korea</code>, <code>Congo</code></td>
<td>both codes marked Possible match, nothing chosen</td>
</tr>
<tr>
<td>Unresolved</td>
<td><code>Slovania</code>, <code>N/A</code></td>
<td>nothing marked, the text stays</td>
</tr>
</tbody>
</table></div>
<p><code>NA</code> exposes a different boundary. It is the alpha-2 code for Namibia, so the
importer reads it exactly when the string reaches the country column.</p>
<p>Some upstream tools remove it first. <code>pandas.read_csv</code> treats bare <code>NA</code> as
missing by default, along with values such as <code>N/A</code>, <code>NULL</code> and <code>nan</code>. Reading
it with <code>keep_default_na=False</code> keeps the string, and turns off recognition of
the rest of that list too.</p>
<p>If <code>NA</code> has already become a missing value before the file reaches the
importer, country matching cannot recover Namibia. That fix belongs upstream.</p>
<h2 id="the-column-takes-one-line-of-configuration">The column takes one line of configuration</h2>
<p>A country column is declared like any other column.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  { id: "siteRef", title: "Site ref", validators: [{ type: "required" }] },
  { id: "institution", title: "Institution" },
  { id: "country", title: "Country", editor: { type: "country" } },
  { id: "investigator", title: "Investigator" },
  {
    id: "enrolled",
    title: "Enrolled",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
];</code></pre>
<p><code>editor: { type: "country" }</code> enables the 250-code list, exact reading, safe
correction, built-in validation, and the country-specific matcher that runs
during value matching.</p>
<p>If none of those steps resolves a value, the importer keeps the original text
in the cell and flags it as invalid. The person still sees what the file wrote
and can choose the country by hand.</p>
<p>The list is closed by default. <code>enableCustomValue: true</code> adds a Create option to
the dropdown, and a value the person creates passes validation and reaches
<code>onComplete</code> as typed. <code>multiple: true</code> stores a <code>string[]</code>, splits a
multi-country cell on its delimiter, and resolves each token separately.</p>
<h2 id="the-matching-step-shows-what-it-decided">The matching step shows what it decided</h2>
<p>Value matching works on distinct values rather than rows. If the same country
spelling appears a hundred times, the importer decides it once and applies
that decision everywhere it occurs.
<a href="https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/">The same step handles enum columns</a>.
A country column uses its own reading and correction rules instead of the
generic value matcher.</p>
<p>The file value appears on the left and the resolved country on the right.</p>
<p><code>Ntherlands</code> is shown opposite Netherlands with a Corrected tag. The person
can change it or clear it.</p>
<p><code>Korea</code> sits opposite an empty box. Its list marks North Korea and South Korea
Possible match.</p>
<p><code>Slovania</code> also sits opposite an empty box. Nothing is marked, because the
matcher refused to prefer Slovenia over Slovakia.</p>
<p>Four rows reach the grid flagged, at file lines 7, 8, 9 and 13.</p>
<ul><li><strong>Row 7</strong>, Country, <code>Slovania</code>: Invalid country</li><li><strong>Row 8</strong>, Country, <code>Korea</code>: Invalid country</li><li><strong>Row 9</strong>, Country, <code>Congo</code>: Invalid country</li><li><strong>Row 13</strong>, Country, <code>N/A</code>: Invalid country</li></ul>
<p>Each one keeps its original text, so the person picking the country still has
what the site wrote.</p>
<h2 id="the-column-can-hold-fewer-than-250-codes">The column can hold fewer than 250 codes</h2>
<p>A trial runs in the countries its protocol names, and this register covers
eleven of them. The dropdown offers the other 239 all the same, and the
matcher weighs every one of them against each imported value.</p>
<p><code>only</code> on the country editor takes the codes the column accepts.</p>
<pre><code class="language-ts">const protocolCountries = [
  "AT", "CD", "CI", "CZ", "DE", "GB", "KR", "NA", "NL", "SI", "US",
];

const country: DataEditorColumn = {
  id: "country",
  title: "Country",
  editor: { type: "country", only: protocolCountries },
};</code></pre>
<p>The dropdown, the matching step and the built-in rule all work from that list.
<code>Switzerland</code> reaches no code on this column, stays in the cell as text, and
gets flagged.</p>
<p>The matcher builds its pool out of the codes the column takes, so a narrower
column hands it fewer countries to weigh. Three of the four flagged rows in
the register settle on their own.</p>
<pre><code class="language-text">Korea     →  KR    the protocol holds one Korea
Congo     →  CD    the protocol holds one Congo
Slovania  →  SI    Slovakia left the pool, Slovenia stands alone one edit away
N/A       →  none  still nothing to read</code></pre>
<p><code>Korea</code> and <code>Congo</code> stop being ambiguous because one of each pair remains.
<code>Slovania</code> gets corrected because the uniqueness rule now measures one edit
against eleven countries. The rules stayed as they were, and the list they run
over got shorter.</p>
<p>The importer drops a code ISO 3166-1 does not carry and names it in a console
warning, and an empty array means the whole list. It reads the array once per
identity, so keep it stable across renders the way you keep <code>options</code>.</p>
<p><code>only</code> decides which codes the column takes. The names those codes print come
from somewhere you do not control.</p>
<h2 id="the-rest-of-the-column-stays-fixed">The rest of the column stays fixed</h2>
<p>The names come from CLDR through the browser, politically contested wording
included. As of August 2026, an English screen on these engines carries the
CLDR wording for Taiwan, Palestinian Territories and Hong Kong SAR China. No
prop replaces one of those names.</p>
<p>A <code>formatter</code> can draw different text in the cell, but matching still runs
against the underlying CLDR names. That makes the pairing one-way, and find
and replace by the printed name does not work on this column. Display and
matching therefore remain separate.</p>
<p>Exact reading covers 26 languages, plus the current interface locale.
Correction covers a narrower set, eight languages. <code>Almanya</code> reads exactly,
and a misspelled <code>Almanyaa</code> does not.</p>
<p>Automatic correction also runs only during the upload wizard, where the
matching step shows the result to the person importing the file. A value such
as <code>Ntherlands</code> that arrives later through paste, <code>loadData</code>, or a formula
stays as typed and gets flagged. A correction the person never sees is a
change to their data made behind their back.</p>
<p>Two adjacent problems remain outside this column. Nationality uses demonyms
rather than country names, and <code>Intl.DisplayNames</code> has no demonym type, so
that stays a <code>select</code> over your own list. Subnational regions belong to ISO
3166-2 and depend on the selected country, so they need a separate data model.</p>
<h2 id="the-importer-reads-and-the-person-settles">The importer reads and the person settles</h2>
<p>The importer resolves what the file makes clear. It writes the country code
when the value is exact, marks a safe correction, shows both candidates when a
name is ambiguous, and leaves the value unresolved when it cannot choose
safely.</p>
<p>The person settles what remains open. On a column over all 250 codes, this
register hands them the two Koreas, the two Congos, and <code>Slovania</code>.</p>
<p>Your handler receives codes such as <code>DE</code>, <code>US</code> and <code>AT</code> for every country the
importer or the person resolved. Anything left unresolved reaches it as the
original text, flagged invalid. Your application still decides what a repeat
import of the same sites means in your table.</p>
<p>The next register may write <code>Alemania</code> instead of <code>Deutschland</code>. It is another
spelling of the same country, handled by the same column.</p>]]></content:encoded></item>
<item><title>How to Normalize Currency Codes and Symbols During Import</title><link>https://updog.tech/blog/normalize-currency-codes-and-symbols-during-import/</link><guid isPermaLink="true">https://updog.tech/blog/normalize-currency-codes-and-symbols-during-import/</guid><pubDate>Sun, 30 Aug 2026 00:00:00 GMT</pubDate><description>A currency gets written as a sign, a name or a code. See how Updog Importer reads each one and stores a single ISO 4217 code.</description><content:encoded><![CDATA[<p>ISO 4217 gives every currency it carries a three-letter code so that nothing
else has to identify it. A file carries that code sometimes. The rest of the
time it carries a sign, a name or a numeric code, because a person copied what
the receipt printed. The accounting system and the payment API ask for the
code, and something has to stand between the two.</p>
<p>Twelve travel claims came back from twelve cities, and the currency column came
back twelve different ways. One traveller wrote <code>€</code>. One wrote <code>Yen</code>. One wrote
<code>32</code>, because the numeric code for the Argentine peso is <code>032</code> and the
spreadsheet that opened the file read it as a number.</p>
<p>The table behind the register holds three letters.</p>
<p><code>travel-claims.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Claim</td><td class="sheet__cell">Traveller</td><td class="sheet__cell">City</td><td class="sheet__cell">Currency</td><td class="sheet__cell">Amount</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">EXP-2041</td><td class="sheet__cell">R. Almeida</td><td class="sheet__cell">Lisbon</td><td class="sheet__cell">€</td><td class="sheet__cell">214.50</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">EXP-2042</td><td class="sheet__cell">H. Nakagawa</td><td class="sheet__cell">Tokyo</td><td class="sheet__cell">Yen</td><td class="sheet__cell">31800</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">EXP-2043</td><td class="sheet__cell">P. Svoboda</td><td class="sheet__cell">Prague</td><td class="sheet__cell">Kč</td><td class="sheet__cell">4620</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">EXP-2044</td><td class="sheet__cell">L. Brunner</td><td class="sheet__cell">Zurich</td><td class="sheet__cell">SFr.</td><td class="sheet__cell">388.20</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">EXP-2045</td><td class="sheet__cell">V. Sosa</td><td class="sheet__cell">Buenos Aires</td><td class="sheet__cell">32</td><td class="sheet__cell">142900</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">EXP-2046</td><td class="sheet__cell">W. Otieno</td><td class="sheet__cell">Nairobi</td><td class="sheet__cell">KES</td><td class="sheet__cell">18400</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">EXP-2047</td><td class="sheet__cell">C. Rossi</td><td class="sheet__cell">Milan</td><td class="sheet__cell">Eruo</td><td class="sheet__cell">176.80</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">EXP-2048</td><td class="sheet__cell">D. Osorio</td><td class="sheet__cell">Bogota</td><td class="sheet__cell">Colombian Pesso</td><td class="sheet__cell">742000</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">EXP-2049</td><td class="sheet__cell">S. Kjaer</td><td class="sheet__cell">Copenhagen</td><td class="sheet__cell">kr</td><td class="sheet__cell">1840</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">EXP-2050</td><td class="sheet__cell">A. Kulkarni</td><td class="sheet__cell">Mumbai</td><td class="sheet__cell">Rs</td><td class="sheet__cell">9650</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell">EXP-2051</td><td class="sheet__cell">R. Dimitrova</td><td class="sheet__cell">Sofia</td><td class="sheet__cell">BGN</td><td class="sheet__cell">318</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">EXP-2052</td><td class="sheet__cell">T. Lim</td><td class="sheet__cell">Singapore</td><td class="sheet__cell">$</td><td class="sheet__cell">406.75</td></tr></tbody></table>
<p>Two of those writings are typos, one is a code that no longer exists, and one
is a dollar sign in a city that does not use the US dollar. Turning the column
into <code>EUR</code>, <code>JPY</code> and <code>CZK</code> is the work, and the part worth getting right is
where that work has to stop.</p>
<h2 id="a-code-list-reads-only-the-signs-that-spell-a-code">A code list reads only the signs that spell a code</h2>
<p>Declare the currency column as a plain list of the 178 codes in the current ISO
4217 list and let a generic value matcher compare each distinct value in the
column against them. On Updog Importer 0.1.88, the result splits in two.</p>
<pre><code class="language-text">$      →  nothing
€      →  nothing
zł     →  nothing
840    →  nothing
Yen    →  PEN    Peruvian Sol
kr     →  KHR    Cambodian Riel
Rs     →  ARS    Argentine Peso
SFr    →  SAR    Saudi Riyal
RMB    →  RUB    Russian Ruble
BTC    →  BTN    Bhutanese Ngultrum</code></pre>
<p>The bare signs score zero against every code, because no rule in a string
matcher connects <code>$</code> to <code>USD</code>. All 36 single-character signs the column ships
reach nothing.</p>
<p>Across the whole sign table, 118 of the 167 reach nothing and 17 reach the
wrong currency. <code>zk</code> is the Zambian kwacha and reaches <code>CZK</code>. <code>nkr</code> is the
Norwegian krone and reaches <code>LKR</code>. The 32 that land right already spell their
own code, <code>ca$</code>, <code>us$</code>, <code>jp¥</code>, <code>dkr</code>.</p>
<p>The words score too well. <code>Yen</code> and <code>PEN</code> are both three characters and one
substitution apart, which is inside the edit budget at that length, so the
Peruvian sol wins a column of Japanese yen. <code>Rs</code> reaches <code>ARS</code> on the same
rule, one insertion. Nothing on screen says the answer was a coin toss.</p>
<p>Swapping the option list from codes to currency names moves the failure.</p>
<pre><code class="language-text">Dollar  →  Australian Dollar
Pound   →  Egyptian Pound
Ruble   →  Belarusian Ruble
CAD     →  XAD
kr      →  nothing
$       →  nothing
USD     →  nothing</code></pre>
<p><code>Dollar</code> shares a word with 23 currency names, all 23 score alike, and the
option list runs in code order, so <code>AUD</code> answers first. <code>XAD</code> sits in that list
as a bare code, because it is the one ISO code the engine has no English name
for, and <code>CAD</code> lands on it one substitution away, as do <code>MAD</code> and <code>NAD</code>. On
this list 166 of the 167 signs reach nothing, and so does <code>USD</code>.</p>
<p>Currency codes sit sparse in their own space. The 178 fill 1.0 percent of the
17,576 three-letter combinations, and an ISO code has 1.65 other real codes one
substitution away on average. A
<a href="https://updog.tech/blog/normalize-country-names-and-iso-codes-during-import/">column of country codes has the opposite problem</a>,
with 250 codes packed into 676 two-letter strings.</p>
<p>The currency failure sits somewhere else. A currency column is a closed list
whose values arrive as signs, and ISO 4217 assigns no sign to a code.</p>
<h2 id="the-column-stores-the-code-and-shows-the-code">The column stores the code and shows the code</h2>
<p>A currency column in Updog Importer stores the three-letter ISO 4217 code in
upper case for every value it resolves, and the grid prints that same code.</p>
<pre><code class="language-text">stored value      CZK
grid              CZK
CSV export        CZK
onComplete        CZK</code></pre>
<p>Stripe wants a three-letter ISO code in lower case in every payment request. Microsoft Dynamics GP refuses every
web-service operation that touches currency until each currency carries a
unique three-character ISO code. A name would have to be translated, and it
would widen the column beside an amount for no gain.</p>
<p>The person reading the grid pays for that choice. <code>PEN</code> says less than <code>Sol</code>
to someone without finance experience, and an Arabic interface
shows a Latin code where the rest of the screen is Arabic. The column trades
that for a value that never changes with language or CLDR version.</p>
<h2 id="the-browser-already-holds-the-currency-names">The browser already holds the currency names</h2>
<p><code>Intl.DisplayNames</code> turns a currency code into a name in a given language, and
it reads from the CLDR the engine already ships for the rest of <code>Intl</code>. It has
been available across browsers since April 2021.</p>
<p>The importer therefore ships no table of names in 26 languages. Give
<code>Intl.DisplayNames</code> the 178 codes in one locale and it builds a name index for
that language at runtime, weighing nothing in the bundle. Updog Importer builds
that index across 26 languages and three name styles the first time any value
reaches a currency column.</p>
<p>On Node 24.19.0 with ICU 78.3, the index holds 4,249 forms and takes about 22
milliseconds to build. Once built, a thousand readings of <code>US Dollar</code> take
under half a millisecond.</p>
<p><code>Dólar estadounidense</code>, <code>Доллар США</code>, <code>美元</code> and <code>دولار أمريكي</code> all reach <code>USD</code>
through it, and none of the four ships with the SDK.</p>
<p><code>Intl.supportedValuesOf("currency")</code> returns 162 codes on this build. Six of them left ISO 4217 already, <code>ANG</code>,
<code>BGN</code>, <code>CUC</code>, <code>HRK</code>, <code>SLL</code> and <code>ZWL</code>. Twenty-two current codes are missing from
it, among them every fund code and <code>VED</code>. So the SDK ships its own 178 and asks
the engine only for names.</p>
<p>The standard writes some of those names differently. ISO 4217 calls <code>GBP</code> Pound
Sterling, <code>JPY</code> Yen, <code>PLN</code> Zloty and <code>ZAR</code> Rand, where CLDR calls them British
Pound, Japanese Yen, Polish Zloty and South African Rand. Updog Importer ships
the difference as one table of 82 forms, 902 bytes gzipped, and adds to it a
hand-written list of writings neither source names, <code>Sterling</code>, <code>RMB</code>, <code>NIS</code>,
<code>TL</code> and the four ways a file writes the Swiss franc among them.</p>
<h2 id="iso-4217-assigns-no-sign-so-the-column-ships-its-own-table">ISO 4217 assigns no sign, so the column ships its own table</h2>
<p>ISO 4217 defines alphabetic and numeric codes. Symbols sit outside it, and the
codes exist to remove the ambiguity a symbol carries. Reading a sign therefore
needs data the standard does not publish, and <code>Intl.NumberFormat</code> prints it.</p>
<p>The formatter prints a currency two ways. <code>currencyDisplay: "symbol"</code> hands the
bare sign to one dollar and prefixes the rest, so <code>$</code> belongs to <code>USD</code> while the
Canadian dollar prints <code>CA$</code> and the Australian dollar prints <code>A$</code>.
<code>currencyDisplay: "narrowSymbol"</code> drops the prefixes, and 29 of the 178
currencies then print a bare <code>$</code>.</p>
<p>Updog Importer reads both forms across the same 26 languages and keeps the 161
signs it can settle on one currency, 857 bytes gzipped. A sign several currencies
print goes to the English <code>symbol</code> rule, which settles <code>$</code> on <code>USD</code>, <code>¥</code> on
<code>JPY</code>, <code>£</code> on <code>GBP</code> and <code>₩</code> on <code>KRW</code>. The rule settles nothing for <code>kr</code>, since
English prints <code>DKK</code>, <code>ISK</code>, <code>NOK</code> and <code>SEK</code> in that style and hands the bare
sign to none of them. Six signs survive the rule and stay contested.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Sign</th>
<th>Currencies that print it</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>kr</code></td>
<td>Denmark, Iceland, Norway, Sweden</td>
</tr>
<tr>
<td><code>Rs</code></td>
<td>India, Sri Lanka, Mauritius, Nepal, Pakistan</td>
</tr>
<tr>
<td><code>C$</code></td>
<td>Canada, Nicaragua</td>
</tr>
<tr>
<td><code>L</code></td>
<td>Honduras, Romania</td>
</tr>
<tr>
<td><code>K</code></td>
<td>Myanmar, Zambia</td>
</tr>
<tr>
<td><code>Cf</code></td>
<td>Comoros, the Caribbean guilder</td>
</tr>
</tbody>
</table></div>
<p><code>kr</code>, <code>zł</code>, <code>Kč</code>, <code>Rs</code> and <code>Ft</code> carry no character of the Unicode currency
category <code>\p{Sc}</code>, so a number reader that strips symbols from an amount leaves
them behind.</p>
<p>The name lookup and the sign lookup normalize differently. A name loses its
accents, so <code>Kč</code> becomes <code>kc</code> and reaches nothing in the name index. A sign
keeps them and folds full-width characters instead, so <code>Kč</code> stays <code>kč</code> and
reaches <code>CZK</code>. One trailing dot comes off, so <code>Rs.</code> and <code>kr.</code> reach the table
as <code>rs</code> and <code>kr</code>.</p>
<h2 id="exact-reading-answers-before-the-matcher-does">Exact reading answers before the matcher does</h2>
<p>Each imported value goes through the same reading ladder, and the first step
that answers wins. A
<a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">date column votes on one format for the whole column</a>,
since <code>01/05/2026</code> cannot be read without knowing what its neighbours are. A
currency column needs no such vote. <code>€</code> and <code>840</code> name their currency whatever
sits above or below them.</p>
<pre><code class="language-text">1  normalize the text
2  three letters    →  the 178-code list
3  one to three digits, padded to three  →  the numeric map
4  a form several currencies share       →  ambiguity guard, hold them all
5  the runtime name index, 26 languages
6  the ISO name forms table
7  normalize the sign
8  a sign several currencies print       →  ambiguity guard, hold them all
9  the sign table
10 nothing</code></pre>
<p>The numeric step repairs a spreadsheet's own damage. The Argentine peso is
<code>ARS</code>, <code>032</code>, and a spreadsheet can turn the numeric code into <code>32</code>. Padding a
one- to three-digit value back to three digits restores the lookup key. A
<a href="https://updog.tech/blog/preserving-leading-zeros-in-csv-and-excel-imports/">stock code or a barcode</a>
loses its leading zeros the same way, and a currency column can repair the loss
because ISO numeric codes have a fixed width of three digits.</p>
<p>This ladder settles seven of the twelve values in the register with no fuzzy
matching anywhere in it. <code>Yen</code> is answered by the ISO forms table at step 6,
and so is <code>SFr.</code>, which sits there beside <code>fr</code>, <code>fr.</code> and <code>sfr</code> because files
write the Swiss franc that way. Two of the five it leaves are misspellings.</p>
<h2 id="a-correction-only-happens-when-one-currency-is-close">A correction only happens when one currency is close</h2>
<p><code>Eruo</code> is a swap of two letters away from Euro, and the person who uploaded the
file should not have to spend a decision on it. Updog Importer corrects that
kind of value during the matching step.</p>
<p>The matcher searches currency names in eight languages across three name
styles, plus the ISO forms table. The distance is Damerau-Levenshtein, so a
deletion, an insertion, a substitution or a swap of two neighbouring characters
each cost one edit. The allowed distance is one edit, and exactly one currency
has to be that close.</p>
<p>Two cut-offs sit in front of the matcher, both read off the normalized value. A
value under four characters never reaches it, which keeps every three-letter
code out. A value carrying anything besides letters and spaces never reaches it
either, which keeps <code>$</code> and <code>840</code> out.</p>
<pre><code class="language-text">Eruo             →  EUR   only Euro is one edit away
Colombian Pesso  →  COP   only Colombian Peso is one edit away
GPB              →  none  three characters, under the floor</code></pre>
<p><code>GPB</code> shows what the floor costs. A person meant <code>GBP</code>, the two letters are
swapped, and the matcher refuses.</p>
<p>Lowering the floor recovers nothing there. The pool holds names, <code>GBP</code> is a
code, and nothing in the pool stands one edit from <code>GPB</code>. Measured at a floor
of three, the value still reads as nothing.</p>
<p>A floor of three buys <code>yen</code>, <code>won</code>, <code>som</code>, <code>sfr</code>, <code>rmb</code> and <code>nis</code> in the pool,
and 582 of the 17,576 three-letter strings then land on one of them. <code>WAN</code>
becomes the Korean won.</p>
<p>A test in the SDK runs the rules against generated misspellings of every
English currency name the engine returns for the 178 codes. At each character position, the
fixture drops the character, doubles it, swaps it with its neighbour, or
replaces it with one of <code>a e i o s r n</code>, skipping a replacement that changes
nothing and a swap at the last position. That produces 25,837 generated values,
25,725 of them distinct.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Outcome</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Read back to the right currency</td>
<td>23,920</td>
</tr>
<tr>
<td>Refused</td>
<td>1,916</td>
</tr>
<tr>
<td>Landed on another exact currency name</td>
<td>1</td>
</tr>
<tr>
<td>Fuzzy-corrected to the wrong currency</td>
<td>0</td>
</tr>
</tbody>
</table></div>
<p>One pass over that corpus takes about 0.2 seconds on Node 24.19.0 with ICU 78.3.</p>
<p>The single value in the third row is <code>ouro</code>, a mutation of Euro and the
Portuguese name for gold, so exact reading answers <code>XAU</code> before the matcher
runs.</p>
<p>Of the 1,916 refusals, 1,880 fail the letters-and-spaces cutoff. Eight English
currency names carry a bracket, a full stop or an ampersand, <code>Chilean Unit of Account (UF)</code> and <code>São Tomé &#x26; Príncipe Dobra</code> among them, and every misspelling
of those keeps the punctuation that stops it at the door.</p>
<p>Not one of the 25,837 was corrected onto the wrong currency.</p>
<h2 id="a-word-that-names-a-family-stays-a-question">A word that names a family stays a question</h2>
<p><code>dollar</code> names 23 currencies. <code>franc</code> names 11, <code>pound</code> names 9, and <code>peso</code>
names 9. Nothing in the word itself picks one, so the importer keeps every
candidate open and leaves the decision to the person who has the rest of the
row.</p>
<p>A sign four countries print stays a question the same way. <code>kr</code> in the register comes from
Copenhagen, and a person reading the row knows it means Danish kroner. The
matcher does not read the city column, so it offers four candidates and chooses
none.</p>
<p>A currency value therefore leaves the matching step with one of four verdicts.</p>
<div class="blog-table blog-table--narrow blog-table--currency-verdicts"><table>
<thead>
<tr>
<th>Verdict</th>
<th>Register value</th>
<th>What happens</th>
</tr>
</thead>
<tbody>
<tr>
<td>Exact</td>
<td><code>€</code>, <code>Yen</code>, <code>Kč</code>, <code>SFr.</code>, <code>32</code>, <code>KES</code>, <code>$</code></td>
<td>the code lands, no tag</td>
</tr>
<tr>
<td>Corrected</td>
<td><code>Eruo</code>, <code>Colombian Pesso</code></td>
<td>the code lands, tagged Corrected</td>
</tr>
<tr>
<td>Ambiguous</td>
<td><code>kr</code>, <code>Rs</code></td>
<td>every candidate marked Possible match, nothing chosen</td>
</tr>
<tr>
<td>Unresolved</td>
<td><code>BGN</code></td>
<td>nothing marked, the text stays</td>
</tr>
</tbody>
</table></div>
<p><code>BGN</code> was valid when the file was written. Bulgaria adopted the euro on
1 January 2026, and the lev left the current ISO list with it. A withdrawn code
stays as text, because <code>100 BGN</code> and <code>100 EUR</code> are different amounts of money
and no importer can do that arithmetic without a rate. <code>HRK</code>, <code>ANG</code>, <code>SLL</code>,
<code>ZWL</code> and <code>MRO</code> behave the same way, and so does <code>BTC</code>, which ISO 4217 never
carried.</p>
<p><code>$</code> in the Singapore row exposes the opposite boundary. The importer reads it
exactly and writes <code>USD</code>, following the way English prints the sign, and for
that row the answer is wrong. A bare dollar sign from Singapore is ambiguous
to a person as much as to a matcher, and the matching step puts <code>$ → USD</code> on
screen where the person can change it.</p>
<h2 id="the-column-takes-one-line-of-configuration">The column takes one line of configuration</h2>
<p>You declare a currency column like any other column.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  { id: "claimRef", title: "Claim ref", validators: [{ type: "required" }] },
  { id: "traveller", title: "Traveller" },
  { id: "city", title: "City" },
  { id: "currency", title: "Currency", editor: { type: "currency" } },
  {
    id: "amount",
    title: "Amount",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0 }],
  },
];</code></pre>
<p><code>editor: { type: "currency" }</code> enables the 178-code list, exact reading, safe
correction, built-in validation, and the currency-specific matcher that runs
during value matching.</p>
<p>If none of those steps resolves a value, the importer keeps the original text in
the cell and flags it as invalid. The person still sees what the traveller
wrote and can pick the currency by hand.</p>
<p>The list is closed by default. <code>enableCustomValue: true</code> adds a Create option to
the dropdown, and a value the person creates passes validation and reaches
<code>onComplete</code> as typed. A finance team that still reports on a withdrawn code
opens the list that way, and so does anyone who needs a crypto ticker.</p>
<h2 id="the-matching-step-shows-what-it-decided">The matching step shows what it decided</h2>
<p>Value matching works on the distinct values a column carries. If the same sign
appears a hundred times, the importer decides it once and applies that decision
everywhere it occurs.
<a href="https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/">The same step handles enum columns</a>.
A currency column brings its own reading and correction rules to that step.</p>
<p>The file value sits on one side, the resolved currency on the other, an arrow
between them.</p>
<p>The step shows <code>Eruo</code> opposite <code>EUR</code> with a Corrected tag. The person can
change it or clear it.</p>
<p><code>kr</code> sits opposite an empty box, with <code>DKK</code>, <code>ISK</code>, <code>NOK</code> and <code>SEK</code> marked
Possible match in its list. <code>Rs</code> sits opposite an empty box with five.</p>
<p><code>BGN</code> also sits opposite an empty box, and nothing in its list is marked.</p>
<p>Three rows reach the grid flagged, at file lines 10, 11 and 12.</p>
<ul><li><strong>Row 10</strong>, Currency, <code>kr</code>: Invalid currency</li><li><strong>Row 11</strong>, Currency, <code>Rs</code>: Invalid currency</li><li><strong>Row 12</strong>, Currency, <code>BGN</code>: Invalid currency</li></ul>
<p>Each one keeps its original text, so the person picking the currency still has
what the receipt said.</p>
<h2 id="the-column-can-hold-fewer-than-178-codes">The column can hold fewer than 178 codes</h2>
<p>A company settles expenses in the currencies its offices bank in, and this
register covers eleven of them. The dropdown offers the other 167 all the same,
and the matcher weighs every one of them against each imported value.</p>
<p><code>only</code> on the currency editor takes the codes the column accepts.</p>
<pre><code class="language-ts">const settlementCurrencies = [
  "ARS", "CHF", "COP", "CZK", "DKK", "EUR",
  "INR", "JPY", "KES", "SGD", "USD",
];

const currency: DataEditorColumn = {
  id: "currency",
  title: "Currency",
  editor: { type: "currency", only: settlementCurrencies },
};</code></pre>
<p>The dropdown, the matching step, the built-in rule, the export sample and the
chat all work from that list. A value that reads to a code outside it stays in
the cell as text and gets flagged, so <code>NOK</code> on this column reaches nothing.</p>
<p>The narrowing happens before the matcher builds its pool, so a sign or a word
several currencies share settles when the column takes one of them.</p>
<pre><code class="language-text">kr      →  DKK   Iceland, Norway and Sweden left the list
Rs      →  INR   four rupees left the list
Franc   →  CHF   ten francs left the list
Dollar  →  none  Singapore and the United States both stayed
BGN     →  none  a withdrawn code is still withdrawn</code></pre>
<p><code>Dollar</code> shows the limit. Narrowing settles a shared word only when one
candidate survives, and this list keeps two dollars.</p>
<p>The importer drops a code that ISO 4217 does not carry and names it in a
console warning, so <code>only: ["BGN"]</code> narrows nothing. An empty array means the
whole list. The array is read once per identity, so keep it stable across
renders the way you keep <code>options</code>.</p>
<h2 id="the-rest-of-the-column-stays-fixed">The rest of the column stays fixed</h2>
<p>Automatic correction runs only during the upload wizard, where the matching step
shows the result to the person importing the file. A value such as <code>Eruo</code> that
arrives later through paste, <code>loadData</code> or a formula stays as typed and gets
flagged. A correction the person never sees is a change to their data made
behind their back.</p>
<p>Exact reading covers 26 languages, and correction covers eight. <code>Česká koruna</code>
reads exactly and a misspelled <code>Ceska korouna</code> reads as nothing, because Czech
is one of the 26 and none of the eight. <code>Schweizer Frankn</code> is corrected, because
German is both.</p>
<p>The importer holds open a fixed list of 26 family words. A word two currencies
share that sits outside it reaches nothing, so <code>Dirham</code> stays as text while the
United Arab Emirates and Morocco both use one.</p>
<p>Names come from CLDR through the browser, and each engine reads its own ICU
build. The same build decides which signs exist, so the shipped sign table
records the ICU version it was generated on. A <code>formatter</code> can draw different
text in the cell, which turns find and replace on the column one way. It
searches the text the formatter drew and cannot write back through it.</p>
<p>A cell holding <code>$100</code> carries an amount and a currency together, and splitting
it is a separate step over two columns. The currency column reads a sign that
arrives on its own.</p>
<h2 id="the-importer-reads-and-the-person-settles">The importer reads and the person settles</h2>
<p>The importer resolves what the file makes clear. It writes the currency code
when the value is exact, marks a safe correction, shows every candidate when a
sign or a word is shared, and leaves the value unresolved when it cannot choose.</p>
<p>The person settles what remains open. On a column over all 178 codes, this
register hands them <code>kr</code>, <code>Rs</code> and a lev that no longer exists.</p>
<p>Your handler receives codes such as <code>EUR</code>, <code>JPY</code> and <code>CZK</code> for every currency
the importer or the person resolved. Anything left unresolved reaches it as the
original text, flagged invalid. Your application still decides what those codes
mean when the amounts beside them reach your ledger.</p>
<p>The next register may write <code>Euros</code> where this one wrote <code>€</code>. The same column
reads it as another writing of the same currency.</p>]]></content:encoded></item>
<item><title>Add CSV and Excel Import to a v0 App</title><link>https://updog.tech/blog/add-csv-and-excel-import-to-a-v0-app/</link><guid isPermaLink="true">https://updog.tech/blog/add-csv-and-excel-import-to-a-v0-app/</guid><pubDate>Sat, 29 Aug 2026 00:00:00 GMT</pubDate><description>A subscription list arrives from whatever billing tool the customer used before. See how Updog Importer brings that file into an app built on v0.</description><content:encoded><![CDATA[<p>v0 turns a prompt into a working full-stack application. It defaults to Next.js and works with React, Tailwind CSS and shadcn/ui. For persistence, its built-in integrations include Neon, Supabase, Upstash and Vercel Blob.</p>
<p>Once that application has customers, some of their data already lives somewhere else. A customer may have hundreds of subscriptions in a spreadsheet exported from their previous billing system and need those rows inside your <code>subscriptions</code> table.</p>
<p>This guide adds that path with Updog Importer. The example is a billing page backed by an empty <code>subscriptions</code> table in Neon Postgres.</p>
<p>There are two ways to get there. The v0 agent can build an import screen, or it can install one.</p>
<h2 id="v0-already-reads-files-in-chat">v0 already reads files in chat</h2>
<p>Drop a CSV or spreadsheet into the v0 chat and the agent can read it while it builds the application. For a connected SQL database, v0 can also generate and run the SQL needed to create or change tables.</p>
<p>That workflow is for the person building the app. The file becomes context for the agent.</p>
<p>A customer import is a different path. The customer opens the finished subscriptions page, selects a file you have never seen, reviews the rows, and writes the accepted data into your <code>subscriptions</code> table.</p>
<p>Uploading a CSV to v0 is therefore not the same as uploading a CSV to your application. One helps build the product. The other is a feature of the product.</p>
<h2 id="the-app-already-has-a-subscriptions-table">The app already has a subscriptions table</h2>
<p>For this guide, I prepared a small v0 sandbox in advance. I attached the Neon integration and gave v0 one prompt to build the starting billing app.</p>
<pre><code class="language-text">Build a small subscription billing app with one page, on Next.js with the App
Router.

The Neon Postgres integration is already attached, so DATABASE_URL is set. Put a
SQL script in scripts/ that creates a table named subscriptions with these
columns, and leave the table empty.

  subscription_ref  text primary key
  customer_name     text not null
  plan              text
  billing_cycle     text
  quantity          integer not null
  unit_price        numeric(10,2) not null
  start_date        date not null
  renewal_date      date not null
  billing_email     text

Render /subscriptions as a server component that reads every row through
@neondatabase/serverless and shows those nine columns in a table, with the row
count above it and an empty state while the table holds nothing. Redirect / to
/subscriptions.

Keep the styling plain, and give the app one primary color, #2f5bd0. No
authentication, no seed data, no extra pages.</code></pre>
<p>v0 wrote the SQL, ran it against Neon, and created <code>/subscriptions</code> as a server component that reads through the Neon driver. The <code>subscriptions</code> table starts empty.</p>
<p>The rest of the guide begins from that sandbox.</p>
<p>The table has nine columns, and those names carry through the entire example. The importer's column ids use the same <code>snake_case</code> names as Postgres, so a row returned by the editor already has the shape the database expects, to keep it simple.</p>
<h2 id="the-file-brings-its-own-schema">The file brings its own schema</h2>
<p>The customer's file uses a schema your app does not control. Its headers may not match your field names, its dates may use another format, and its values may not match the options your fields accept.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>The screen has to</th>
<th>Because the file</th>
</tr>
</thead>
<tbody>
<tr>
<td>detect encoding and delimiter</td>
<td>arrives as UTF-8, Windows-1252, comma or semicolon</td>
</tr>
<tr>
<td>find the header row</td>
<td>carries a report title and an export date above it</td>
</tr>
<tr>
<td>read every sheet of a workbook</td>
<td>is <code>.xlsx</code> with one tab per billing entity</td>
</tr>
<tr>
<td>settle the date order per column</td>
<td>writes <code>04/11/2026</code> and means the fourth of November</td>
</tr>
<tr>
<td>keep leading zeros</td>
<td>holds <code>00417</code>, which Excel already turned into <code>417</code></td>
</tr>
<tr>
<td>match headers onto your fields</td>
<td>says <code>Account name</code> where your app says <code>customer_name</code></td>
</tr>
<tr>
<td>match values onto your options</td>
<td>says <code>Annual plan</code> where your app says <code>Annual</code></td>
</tr>
<tr>
<td>check and let the person fix</td>
<td>holds a row your database will reject</td>
</tr>
<tr>
<td>stay usable at scale</td>
<td>is a hundred thousand rows on a laptop</td>
</tr>
<tr>
<td>report new, changed and deleted rows</td>
<td>is the second import of a file that landed once already</td>
</tr>
</tbody>
</table></div>
<p>Each row in that table needs an implementation rule. Written as a prompt, with the fields on top and one stage for each part of the import, the same work reads like this.</p>
<pre><code class="language-text">Build a CSV and Excel import screen for the subscriptions page. A button on that
page opens it as a modal wizard, our customers walk that wizard with the exports
their old billing tool produced, and it leaves them in a spreadsheet where they
clean what came in.

Where the fields come from
- Read the field list from my code, so the same screen serves the subscriptions
  page today and an invoices page later.
- Support text, whole numbers, decimals, dates and a fixed list of options, and
  let one field carry several rules at once.
- Check required, a range, a number of decimal places, uniqueness inside the
  file, and uniqueness against the subscriptions we already store.
- Show the customer our label for a field, and hand my code back the field name.
- Take subscription_ref as the key, so a second upload of the same file finds
  those subscriptions and updates them.
- Drop columns the file carries beyond that list.

Opening the files
- Take several files at once, by drop or by dialog, and show a card per file.
- Detect the encoding, strip a byte order mark, and read a Windows-1252 export
  without turning accented company names into question marks.
- Detect the delimiter. Commas, semicolons, tabs and pipes all arrive.
- Drop a first line shaped sep=; that Excel writes for some locales.
- Read .xlsx, .xls and .ods, open a workbook as one card per sheet, and let the
  customer choose which sheets go on.
- Find the real header row when a report title and an export date sit above it,
  and handle a file with duplicate headers or no header at all.
- Keep a row carrying one field too few, and say which fields it filled.

Reading what the cells hold
- Settle the date order per column, so 04/11/2026 does not become April.
- Read 1.240,50 and 1,240.50 as the same number.
- Keep 00417 as text, including a code Excel already turned into 417.
- Tell an empty cell apart from a cell holding the word null.

Matching the columns
- Map the file's headers onto my field list, one field per column.
- Match the obvious ones on arrival, and show the customer which of my fields
  reached nothing so they can point each one at a column by hand.
- Show a few values under every header, so the customer tells two similar
  columns apart.
- Remember the pairs the customer confirmed, so the next file of that shape
  arrives matched.

Matching the values
- Collect the distinct values of plan and billing cycle as the file spells them.
- Match each one to an option we allow, and let the customer place the rest.

Cleaning before the write
- Hand the finished file to a spreadsheet the customer works in, with my labels
  on top and every row in it.
- Mark what the customer changed. A new row, an edited cell and a deleted row
  each read differently at a glance.
- Run every rule the field list carries, and say which cell failed and why.
- Let the customer fix a cell in place, with the editor that fits the field. A
  date opens a calendar, a list opens its options, a number takes digits.
- Sort and filter, so the customer reaches the failing rows among the hundred
  thousand that pass.
- Copy and paste blocks between it and Excel or Google Sheets, and undo an edit.
- Stay smooth at a hundred thousand rows, with the reading off the main thread
  so the tab keeps responding.

Handing the rows over
- Tell me which rows are new, which changed, and which were deleted.
- Keep every row and every mapping on screen when my write to the database
  fails.</code></pre>
<p>Each rule expands once real files arrive. Date parsing alone has to separate written date orders, spreadsheet serial dates, and columns whose values stay ambiguous after both.</p>
<p><a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">Parsing dates during import</a> walks one of those columns to a verdict.</p>
<p>If you build the importer yourself, every line of that prompt becomes application code you own, and it has to keep working when later files use different encodings, headers, values, dates and workbook layouts.</p>
<p>The second approach gives those file-facing rules to an importer package.</p>
<h2 id="the-second-prompt-installs-the-importer">The second prompt installs the importer</h2>
<p>v0 runs a VM-backed chat in Vercel Sandbox, a lightweight virtual machine that runs a full Node environment. It carries <code>pnpm</code>, <code>npm</code>, <code>yarn</code> and <code>bun</code> out of the box, and any dependency your project needs installs there. The install runs as a terminal command inside that sandbox, under one of three permission modes, Ask, Auto and Full, with Auto the default.</p>
<pre><code class="language-text">Add a spreadsheet import screen to the subscriptions page with the npm package
@updog/data-editor. Read https://updog.tech/updog.md and
https://docs.updog.tech first, and use only props documented there.

1. Install @updog/data-editor and import "@updog/data-editor/styles.css".
2. Put "use client" at the top of the file that renders the editor. The package
   ships no "use client" of its own, so a server component cannot hold it.
3. Add an "Import subscriptions" button above the table, holding one open state.
   The editor opens as a modal, which is its default: pass open={open} and an
   onClose that closes it. Wrap it in nothing and give it no height of its own,
   because the modal sizes itself.
4. Render &#x3C;DataEditor /> with apiKey="updog-v0-demo", which is all the key a v0
   preview or a vercel.app host needs, variant="uploader",
   primaryKey="subscription_ref", enableDeleteRow="all" and these nine columns,
   written as id, title, then type and rules:
   subscription_ref "Subscription ref" text, required, unique
   customer_name "Customer" text, required
   plan "Plan" select: Lite, Core, Agency
   billing_cycle "Billing cycle" select: Monthly, Quarterly, Annual
   quantity "Quantity" number, whole, minimum 1, required
   unit_price "Unit price" number, two decimals, minimum 0, required
   start_date "Start date" date, required
   renewal_date "Renewal date" date, required
   billing_email "Billing email" text, email
   The ids are the subscriptions table's own column names on purpose, so no
   field is renamed between the editor and the database.
5. In a stylesheet loaded after "@updog/data-editor/styles.css", set
   --updog-brand on :root to this app's primary color, written as a plain color
   value.
6. onComplete receives result.sources, and every entry in a source's rows is a
   wrapper shaped { row, isNew, isChanged, isDeleted, isValid }. Read the four
   flags off the wrapper and the cell values off entry.row. Skip an entry whose
   isValid is false.
7. entry.row is keyed by those same ids, so send it to the database as it is.
   Write no mapper and no Number call. Postgres casts a text parameter to the
   column's own type.
8. POST the rows to a route handler at app/api/subscriptions/route.ts, the new
   and changed ones as one list and the deleted subscription_ref values as
   another. The handler upserts with INSERT ... ON CONFLICT (subscription_ref)
   DO UPDATE and deletes by subscription_ref, both through the Neon serverless
   driver.
9. Throw from onComplete when the POST fails. The editor clears its rows as soon
   as onComplete resolves, so a swallowed error loses the import. When it
   succeeds, close the modal and call router.refresh(), so the subscriptions
   table reloads with the imported rows.
10. Do not build an uploader of your own, do not parse the file yourself, and do
    not invent props.</code></pre>
<p>The package is still third-party code. Testing what you install stays part of your application work.</p>
<h2 id="the-importer-mirrors-the-subscriptions-table">The importer mirrors the subscriptions table</h2>
<p>The nine table columns become nine importer columns. Each column points to one database column through its <code>id</code>, while <code>title</code> gives the customer the name shown in the grid.</p>
<pre><code class="language-tsx">import {
  DataEditor,
  type DataEditorColumn,
  type DataEditorResult,
} from "@updog/data-editor";
import "@updog/data-editor/styles.css";

type Subscription = {
  subscription_ref: string;
  customer_name: string;
  plan: string;
  billing_cycle: string;
  quantity: string;
  unit_price: string;
  start_date: string;
  renewal_date: string;
  billing_email: string;
};

const columns: DataEditorColumn[] = [
  {
    id: "subscription_ref",
    title: "Subscription ref",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "customer_name",
    title: "Customer",
    validators: [{ type: "required" }],
  },
  {
    id: "plan",
    title: "Plan",
    editor: {
      type: "select",
      options: ["Lite", "Core", "Agency"],
      enableCustomValue: false,
    },
  },
  {
    id: "billing_cycle",
    title: "Billing cycle",
    editor: {
      type: "select",
      options: ["Monthly", "Quarterly", "Annual"],
      enableCustomValue: false,
    },
  },
  {
    id: "quantity",
    title: "Quantity",
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 1, decimalPlaces: 0 },
    ],
  },
  {
    id: "unit_price",
    title: "Unit price",
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "start_date",
    title: "Start date",
    editor: { type: "date" },
    validators: [{ type: "required" }],
  },
  {
    id: "renewal_date",
    title: "Renewal date",
    editor: { type: "date" },
    validators: [{ type: "required" }],
  },
  {
    id: "billing_email",
    title: "Billing email",
    validators: [{ type: "email" }],
  },
];</code></pre>
<p>The validators repeat rules the table already declares, and they run at a different boundary. <code>subscription_ref</code> is a primary key in Postgres, so a duplicate reference fails at the write with the whole statement. <code>{ type: "unique" }</code> on the column flags the second row inside the file, before submit, on the row that carries it.</p>
<p><code>quantity</code> and <code>unit_price</code> carry <code>{ type: "required" }</code> for the same reason. Both map to a <code>NOT NULL</code> column, and a required rule stops an empty cell in the grid where the customer can fill it.</p>
<h2 id="the-page-mounts-the-importer">The page mounts the importer</h2>
<p>The editor draws on canvas and needs the browser DOM, and the package ships no <code>"use client"</code> directive of its own. In an App Router project the file that renders it declares the directive itself.</p>
<pre><code class="language-tsx">"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function SubscriptionImporter() {
  const [open, setOpen] = useState(false);
  const router = useRouter();

  return (
    &#x3C;>
      &#x3C;button type="button" onClick={() => setOpen(true)}>
        Import subscriptions
      &#x3C;/button>

      &#x3C;DataEditor&#x3C;Subscription>
        apiKey="updog-v0-demo"
        variant="uploader"
        open={open}
        onClose={() => {
          setOpen(false);
        }}
        columns={columns}
        primaryKey="subscription_ref"
        enableDeleteRow="all"
        onComplete={handleComplete}
      />
    &#x3C;/>
  );
}</code></pre>
<p><code>primaryKey</code> names the column that identifies a subscription. A second import of a corrected file matches on that column and updates the row it finds. <code>enableDeleteRow</code> lets the customer remove a subscription, which gives the submit handler a deleted row to route.</p>
<p>The editor takes the app's primary color through one CSS variable.</p>
<pre><code class="language-css">/* loaded after @updog/data-editor/styles.css */
:root {
  --updog-brand: #2f5bd0;
}</code></pre>
<p><a href="https://updog.tech/blog/style-updog-to-match-your-product/">Match the importer to your product</a> takes the theming further, through typography, the grid, shadows and a dark theme.</p>
<h2 id="the-file-uses-another-systems-vocabulary">The file uses another system's vocabulary</h2>
<p>The export carries 240 subscriptions out of the customer's old billing tool, on one sheet of a workbook.</p>
<p><code>larkmead-subscriptions.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Subscription ID</td><td class="sheet__cell">Account name</td><td class="sheet__cell">Plan</td><td class="sheet__cell">Billing frequency</td><td class="sheet__cell">Quantity</td><td class="sheet__cell">Price per unit</td><td class="sheet__cell">Contract start</td><td class="sheet__cell">Renewal due</td><td class="sheet__cell">Billing contact email</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">LM-0001</td><td class="sheet__cell">Ashvale Studio Ltd</td><td class="sheet__cell">Core</td><td class="sheet__cell">Monthly</td><td class="sheet__cell">9</td><td class="sheet__cell">8.14</td><td class="sheet__cell">2024-01-14</td><td class="sheet__cell">2026-09-14</td><td class="sheet__cell">billing@ashvalestudioltd.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">LM-0002</td><td class="sheet__cell">Brindon Bakery Group</td><td class="sheet__cell">Lite</td><td class="sheet__cell">Quarterly</td><td class="sheet__cell">105</td><td class="sheet__cell">60.38</td><td class="sheet__cell">2026-02-15</td><td class="sheet__cell">2026-11-15</td><td class="sheet__cell">billing@brindonbakerygro.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">LM-0007</td><td class="sheet__cell">Glenmore Garage Co</td><td class="sheet__cell">Lite</td><td class="sheet__cell">Monthly</td><td class="sheet__cell">21</td><td class="sheet__cell">26.55</td><td class="sheet__cell">2026-01-15</td><td class="sheet__cell">2026-09-15</td><td class="sheet__cell">billing@glenmoregarageco.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">6 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">15</th><td class="sheet__cell">LM-0014</td><td class="sheet__cell">Oakhanger Florists Group</td><td class="sheet__cell">Agency</td><td class="sheet__cell">Annual</td><td class="sheet__cell">19</td><td class="sheet__cell">33.9</td><td class="sheet__cell">2024-06-18</td><td class="sheet__cell">2027-06-18</td><td class="sheet__cell">billing@oakhangerflorist.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">26 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">42</th><td class="sheet__cell">LM-0041</td><td class="sheet__cell">Ashvale Print Ltd</td><td class="sheet__cell">Agency</td><td class="sheet__cell">Monthly</td><td class="sheet__cell">19</td><td class="sheet__cell">28.79</td><td class="sheet__cell">2025-01-28</td><td class="sheet__cell">2026-09-28</td><td class="sheet__cell">billing@ashvaleprintltd.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">77 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">120</th><td class="sheet__cell">LM-0119</td><td class="sheet__cell">Thurloxton Garage Co</td><td class="sheet__cell">Agency</td><td class="sheet__cell">Monthly</td><td class="sheet__cell">26</td><td class="sheet__cell">70.3</td><td class="sheet__cell">2026-02-17</td><td class="sheet__cell">2026-09-17</td><td class="sheet__cell">billing@thurloxtongarage.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">78 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">199</th><td class="sheet__cell">LM-0198</td><td class="sheet__cell">Southwick Bakery Group</td><td class="sheet__cell">Core</td><td class="sheet__cell">Monthly</td><td class="sheet__cell">112</td><td class="sheet__cell">8.73</td><td class="sheet__cell">2025-10-19</td><td class="sheet__cell">2026-09-19</td><td class="sheet__cell">billing@southwickbakeryg.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">41 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">241</th><td class="sheet__cell">LM-0240</td><td class="sheet__cell">Wilbraham Bakery LLP</td><td class="sheet__cell">Core</td><td class="sheet__cell">Quarterly</td><td class="sheet__cell">57</td><td class="sheet__cell">9.8</td><td class="sheet__cell">2025-09-21</td><td class="sheet__cell">2026-09-21</td><td class="sheet__cell">billing@wilbrahambakeryl.example</td></tr></tbody></table>
<p>Seven of the nine headers use names that appear nowhere in the <code>subscriptions</code> table.</p>
<pre><code class="language-text">Subscription ID        →  Subscription ref
Account name           →  Customer
Billing frequency      →  Billing cycle
Price per unit         →  Unit price
Contract start         →  Start date
Renewal due            →  Renewal date
Billing contact email  →  Billing email</code></pre>
<p>The matcher resolves all nine headers against the importer schema, and the wizard reports <code>9/9 matched</code>. <code>Plan</code> and <code>Billing frequency</code> carry closed lists, and the value step matches the distinct values of both, <code>3/3 matched</code> each. This export needs no manual mapping, so all 240 rows reach the grid with no validation errors.</p>
<p>The grid holds the parsed rows for review. The customer can filter validation errors, edit cells, undo changes, and paste blocks from a spreadsheet before submit. Submit shows the final row counts, and on this file it read <code>240 new rows will be created</code>.</p>
<h2 id="submit-returns-the-rows-and-their-state">Submit returns the rows and their state</h2>
<p>Submit returns the edited rows grouped by source. Each row carries four independent flags that describe whether it is new, changed, deleted, and valid. Your handler decides what those states mean for the database.</p>
<pre><code class="language-tsx">const handleComplete = async (result: DataEditorResult&#x3C;Subscription>) => {
  const rows = result.sources.flatMap((source) => source.rows);

  const upserts = rows
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .filter((entry) => entry.isNew || entry.isChanged)
    .map((entry) => entry.row);

  const deletes = rows
    .filter((entry) => entry.isDeleted &#x26;&#x26; !entry.isNew)
    .map((entry) => entry.row.subscription_ref);

  const response = await fetch("/api/subscriptions", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ upserts, deletes }),
  });

  if (!response.ok) {
    throw new Error(\`Import failed with \${response.status}\`);
  }

  setOpen(false);
  router.refresh();
};</code></pre>
<p>Nothing sits between the flags and the request body. The keys of <code>entry.row</code> are the table's column names, so the row is already the record, and <code>upserts</code> goes to the route handler as it is.</p>
<p>A number column hands back text. <code>quantity</code> arrives as <code>"9"</code> and <code>unit_price</code> as <code>"8.14"</code>, and Postgres casts a text parameter to the column's own type, so neither value passes through <code>Number</code> on the way. A date column hands back ISO, so <code>start_date</code> arrives as <code>"2024-01-14"</code>, independent of how the date appeared in the grid.</p>
<p>This is the whole <code>result</code> object from that run, with one of the 240 rows kept.</p>
<pre><code class="language-ts">{
  sources: [
    {
      sourceId: "source_…",
      sourceName: "larkmead-subscriptions.xlsx",
      rows: [
        {
          row: {
            subscription_ref: "LM-0001",
            customer_name: "Ashvale Studio Ltd",
            plan: "Core",
            billing_cycle: "Monthly",
            quantity: "9",
            unit_price: "8.14",
            start_date: "2024-01-14",
            renewal_date: "2026-09-14",
            billing_email: "billing@ashvalestudioltd.example",
          },
          isNew: true,
          isChanged: false,
          isDeleted: false,
          isValid: true,
        },
        // 239 more rows
      ],
    },
  ],
  counts: { new: 240, changed: 0, deleted: 0, invalid: 0 },
  learnedSynonyms: { columns: [], values: [] },
}</code></pre>
<p><a href="https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/">Import, edit and delete rows through a REST API</a> covers the routing of those four flags in more shapes than this one.</p>
<h2 id="the-route-handler-writes-to-postgres">The route handler writes to Postgres</h2>
<p>The Neon integration writes <code>DATABASE_URL</code> into the project, and <code>@neondatabase/serverless</code> reads it. <code>sql.transaction</code> takes an array of queries and runs them inside one non-interactive transaction.</p>
<pre><code class="language-ts">import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.DATABASE_URL!);

export async function POST(request: Request) {
  const { upserts, deletes } = await request.json();

  if (upserts.length > 0) {
    await sql.transaction(
      upserts.map((row) => {
        return sql\`
          INSERT INTO subscriptions (
            subscription_ref, customer_name, plan, billing_cycle,
            quantity, unit_price, start_date, renewal_date, billing_email
          )
          VALUES (
            \${row.subscription_ref}, \${row.customer_name}, \${row.plan},
            \${row.billing_cycle}, \${row.quantity}, \${row.unit_price},
            \${row.start_date}, \${row.renewal_date}, \${row.billing_email}
          )
          ON CONFLICT (subscription_ref) DO UPDATE SET
            customer_name = EXCLUDED.customer_name,
            plan = EXCLUDED.plan,
            billing_cycle = EXCLUDED.billing_cycle,
            quantity = EXCLUDED.quantity,
            unit_price = EXCLUDED.unit_price,
            start_date = EXCLUDED.start_date,
            renewal_date = EXCLUDED.renewal_date,
            billing_email = EXCLUDED.billing_email
        \`;
      }),
    );
  }

  if (deletes.length > 0) {
    await sql\`
      DELETE FROM subscriptions WHERE subscription_ref = ANY(\${deletes})
    \`;
  }

  return Response.json({
    upserted: upserts.length,
    deleted: deletes.length,
  });
}</code></pre>
<p><code>ON CONFLICT (subscription_ref) DO UPDATE</code> needs a conflict target the table declares, and <code>subscription_ref</code> is the primary key. Without that constraint a second import of the same file writes 240 more rows.</p>
<p>Neon caps a query over HTTP at 64 MB of request and response, so a file past a few tens of thousands of rows sends its upserts in chunks.</p>
<p><a href="https://updog.tech/blog/import-csv-into-postgresql/">Import CSV into PostgreSQL</a> covers the write side, including what a duplicate key inside one statement does.</p>
<h2 id="the-database-decides-what-a-repeat-import-means">The database decides what a repeat import means</h2>
<p>The editor state and the database state stay separate. On this run every row carries <code>isNew: true</code> because the editor opened empty. Postgres still finds the same <code>subscription_ref</code> in the table and updates that record, so a second pass of the same file leaves the table at 240.</p>
<p><code>isNew</code> means new to the editor. It does not mean absent from the database.</p>
<p>Your application chooses where repeat imports are reconciled. The database can resolve them at write time through the key, or <code>loadData</code> can bring stored subscriptions into the editor so the matching happens before submit. Updog Importer supplies the row state and chooses neither policy.</p>
<p>Let write errors reject <code>onComplete</code>. A rejected promise keeps the rows and mappings in the editor. A resolved promise tells Updog Importer that submission finished, so close the modal and refresh the page only after the write succeeds.</p>
<h2 id="the-v0-url-runs-for-free">The v0 URL runs for free</h2>
<p>Updog Importer makes one request to its license endpoint when the editor starts. It sends the API key and the page hostname. No rows, headers, or file contents go with it.</p>
<p>Updog keeps a list of development and preview hosts where the importer runs free, with no row counted. Both v0 hosts are on it, <code>.v0.build</code> for the chat preview and <code>.vercel.app</code> for the URL you publish to. The prompt can leave the placeholder API key in place while the app runs there.</p>
<p>A custom domain changes that. If the billing app moves to <code>app.yourcompany.com</code>, add that hostname at <a href="https://console.updog.tech/">console.updog.tech</a>. The Free plan covers production domains up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains, with no row limit.</p>
<h2 id="the-app-now-has-an-import-path">The app now has an import path</h2>
<p>Updog Importer installs into a v0 project as an npm package. Its columns mirror the <code>subscriptions</code> table, the customer resolves the file before submit, and <code>onComplete</code> returns the edited rows and their state to a route handler you own.</p>
<p>The importer handles the file-facing work, parsing CSV and Excel, matching columns and values, validating cells, and letting the customer correct the data. Your application still decides what those rows mean in the database, including updates, deletions, and repeat imports.</p>
<p>You can build the same flow yourself. The first prompt in this guide lists what that requires. Installing the package keeps those behaviors inside the importer and leaves the v0 code focused on the billing page and its write path.</p>]]></content:encoded></item>
<item><title>Build a Spreadsheet Data Editor for PGlite</title><link>https://updog.tech/blog/build-a-spreadsheet-data-editor-for-pglite/</link><guid isPermaLink="true">https://updog.tech/blog/build-a-spreadsheet-data-editor-for-pglite/</guid><pubDate>Fri, 28 Aug 2026 00:00:00 GMT</pubDate><description>A local-first app keeps its rows in the browser. See how Updog Data Editor puts them on screen and turns the edits back into SQL.</description><content:encoded><![CDATA[<p>PGlite is Postgres itself, compiled to WebAssembly and published as a TypeScript package. It starts inside the browser tab with no database server behind it. It parses SQL, enforces constraints, runs transactions, and can keep its files in IndexedDB, so the rows are still there on the next visit. It draws nothing.</p>
<p>A beekeeper with fourteen hives, four corrections to make and two inspections to add needs a screen, and the database has no opinion about that screen. The rows come out of a PGlite table, a person edits them as a spreadsheet, and the edits go back as <code>INSERT</code>, <code>UPDATE</code> and <code>DELETE</code> inside one transaction. No file goes near any of it.</p>
<h2 id="the-boot-line-settles-where-the-rows-live-and-what-shape-they-arrive-in">The boot line settles where the rows live and what shape they arrive in</h2>
<p>PGlite's documentation describes it as running in the browser, Node.js and Bun with no other dependencies. On version 0.5.8, <code>SELECT version()</code> answers a string that opens <code>PostgreSQL 18.3 (PGlite 0.5.8) on wasm32-unknown-emscripten</code> and goes on to name the emcc build. <a href="https://updog.tech/blog/import-csv-into-duckdb/">How to import CSV into DuckDB</a> covers the other database that runs inside the tab.</p>
<pre><code class="language-ts">import { PGlite, types } from "@electric-sql/pglite";

export const db = await PGlite.create("idb://apiary", {
  parsers: {
    [types.DATE]: (value) => value,
    [types.BOOL]: (value) => (value === "t" ? "Yes" : "No"),
  },
});</code></pre>
<p><code>PGlite.create()</code> is the static method the documentation prefers, because it resolves once the database has finished starting. The <code>idb://</code> prefix puts the data files in IndexedDB, so the table survives a page reload. Browsers treat that storage as evictable, so an app that has to survive a gap between visits calls <code>navigator.storage.persist()</code> first and reads the answer, because the browser can refuse. PGlite recommends IndexedDB for the browser today, because its OPFS filesystem does not work in Safari. The documentation names a Safari limit of 252 open sync access handles against a Postgres install of more than 300 files.</p>
<p>The two <code>parsers</code> entries decide the JavaScript value each column carries by the time it reaches the grid.</p>
<p>PGlite is single connection only, so the page shares one instance. An application that wants several tabs on one database runs PGlite inside <code>PGliteWorker</code> and lets the tabs elect a leader.</p>
<h2 id="the-table-decides-what-a-row-is">The table decides what a row is</h2>
<p>An apiary log records one inspection per hive per day.</p>
<pre><code class="language-sql">CREATE TABLE IF NOT EXISTS inspections (
    id           INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    hive_ref     TEXT NOT NULL,
    inspected_on DATE NOT NULL,
    queen_seen   BOOLEAN NOT NULL DEFAULT false,
    brood_frames INTEGER NOT NULL CHECK (brood_frames BETWEEN 0 AND 20),
    varroa_count INTEGER NOT NULL CHECK (varroa_count >= 0),
    action       TEXT,
    UNIQUE (hive_ref, inspected_on)
);</code></pre>
<p>The identity column generates <code>id</code>, so a plain <code>INSERT</code> that supplies a value of its own is refused. <code>CHECK</code> holds <code>brood_frames</code> between 0 and 20 and keeps <code>varroa_count</code> off negative numbers. <code>NOT NULL</code> stands on every column but <code>action</code>. <code>UNIQUE (hive_ref, inspected_on)</code> refuses a second row with the same hive reference and the same date.</p>
<p>Postgres enforces every one of those rules at the moment of the write. The person making the edit is somewhere else by then, looking at a screen that has already accepted their typing. Two of those rules move forward, to the cell the person is filling, and that is most of what the editor is for.</p>
<h2 id="a-database-row-is-not-yet-a-spreadsheet-row">A database row is not yet a spreadsheet row</h2>
<p>A grid paints text. Postgres holds types, and the client turns them into JavaScript. On PGlite 0.5.8 through Node 24.19.0, a <code>SELECT</code> over this table with no parser registered answers with four JavaScript shapes, and <code>null</code> wherever <code>action</code> is empty.</p>
<pre><code class="language-text">brood_frames  integer        7                       number
varroa_count  integer        4                       number
action        text           "Added super"           string
queen_seen    boolean        true                    boolean
inspected_on  date           Date object at UTC midnight</code></pre>
<p>The date is the one that breaks. Updog Data Editor paints a cell by taking its value as a string and running the date column's display codec over it, so a canonical <code>2026-08-17</code> reaches the screen in the browser locale's date order, always Gregorian and always in Latin digits. The codec hands back any value it cannot read as an ISO date, so a <code>Date</code> object reaches the canvas as the string JavaScript makes of it.</p>
<pre><code class="language-text">TZ=UTC
Mon Aug 17 2026 00:00:00 GMT+0000 (Coordinated Universal Time)

TZ=America/New_York
Sun Aug 16 2026 20:00:00 GMT-0400 (Eastern Daylight Time)</code></pre>
<p>In New York the table says the seventeenth of August and the cell says the sixteenth. A <code>Date</code> object is not an ISO date, so the date rule flags every date cell <code>Invalid date</code>, and this screen refuses to submit. The flag names the shape and never mentions the day.</p>
<p>PGlite documents <code>parsers</code>, an object mapping a Postgres type id to a function that receives the raw value as text. The two lines in the boot snippet use it. The parser registered under <code>types.DATE</code> hands back the wire text <code>2026-08-17</code> untouched, which is exactly the form the date column canonicalises. The one under <code>types.BOOL</code> receives <code>t</code> or <code>f</code> and answers <code>Yes</code> or <code>No</code>.</p>
<p>A Postgres boolean travels through the grid as a select. As of August 2026 a column's editor is text, date, time, select, multiselect or number, and a column with no editor behaves as text, so the parser turns <code>t</code> and <code>f</code> into the two words the dropdown holds, and the write turns the word back.</p>
<p>A <code>NUMERIC</code> column needs nothing at all, and this table carries none. PGlite hands one over as a string, and a number column keeps its cells as strings, so <code>59.90</code> makes the round trip with no float in the middle of it.</p>
<p>Shape the values once, at the client, and every query in the application gets the same shapes. The same overrides can travel per query through <code>QueryOptions</code> when only one screen wants them.</p>
<h2 id="one-select-fills-the-grid">One SELECT fills the grid</h2>
<p><code>loadData</code> receives an <code>onChunk</code> callback and can call it several times to stream a large table in batches. A table this size arrives in one call.</p>
<pre><code class="language-ts">const SELECT_INSPECTIONS = `
  SELECT id,
         hive_ref     AS "hiveRef",
         inspected_on AS "inspectedOn",
         queen_seen   AS "queenSeen",
         brood_frames AS "broodFrames",
         varroa_count AS "varroaCount",
         action
    FROM inspections
   ORDER BY hive_ref, inspected_on
`;

const loadInspections = useCallback(
  async (onChunk: (rows: Inspection[]) => void) => {
    const result = await db.query&#x3C;Inspection>(SELECT_INSPECTIONS);
    onChunk(result.rows);
  },
  [version],
);</code></pre>
<p><code>AS "hiveRef"</code> renames each column to the id the editor addresses it by. The table is written in <code>snake_case</code>, and quoting the alias keeps the case that Postgres would otherwise fold to lowercase.</p>
<p><code>loadInspections</code> is wrapped in <code>useCallback</code> on purpose. The editor loads again whenever it receives a different <code>loadData</code> function, and it clears the grid first, so a loader rebuilt on each render of your component would throw away an unsaved edit. The <code>version</code> dependency is what fires that reload here, and a commit is what moves it.</p>
<h2 id="identity-does-not-have-to-be-a-spreadsheet-column">Identity does not have to be a spreadsheet column</h2>
<p><code>columns</code> names six fields and <code>id</code> is not one of them. The rows still carry it.</p>
<pre><code class="language-text">what the SELECT returns   { id: 3, hiveRef: "WM-03", inspectedOn: "2026-08-19", … }
what the grid draws       Hive · Inspected on · Queen seen · Brood frames · Varroa · Action
what onComplete returns   { id: 3, hiveRef: "WM-03", inspectedOn: "2026-08-19", … }</code></pre>
<p>A row keeps every field you send it, whether or not a column claims it. The editor fills in the columns a row is missing and leaves the rest alone, so the primary key goes out with the row and comes back on it, and no cell edit can reach it.</p>
<p><code>primaryKey="id"</code> belongs to import matching. The prop points at a field no column declares, so the editor drops it and warns once when it mounts, <code>[updog] primaryKey names "id", which no column declares. Imported rows are appended instead of merged.</code> This screen takes no file yet, and when one arrives it carries no <code>id</code>, so appending is what it wants.</p>
<h2 id="the-editor-opens-with-no-import-surface">The editor opens with no import surface</h2>
<p>Updog Data Editor is a spreadsheet over an in-memory dataset. A file is one way to fill that dataset. A <code>SELECT</code> is another.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Inspection>
  apiKey={import.meta.env.VITE_UPDOG_KEY}
  mode="inline"
  variant="editor"
  columns={columns}
  primaryKey="id"
  loadData={loadInspections}
  onComplete={saveInspections}
  importFormats={false}
  enableAddSource={false}
  enableCreateColumn={false}
  enableAddRow
  enableDeleteRow="all"
  blockSubmitOnError
/></code></pre>
<p><code>variant="editor"</code> opens the grid directly, which is the default. <code>importFormats={false}</code> turns file import off, which closes both routes into the wizard, the add-source button and the drop target over the grid. <code>enableAddSource={false}</code> hides that button on its own, and a screen that keeps import uses it alone. <code>enableCreateColumn={false}</code> matters once the import surface comes back, and it stops an unmatched header from becoming a column the table does not have. What remains is a grid over the rows the <code>SELECT</code> returned.</p>
<p><code>enableAddRow</code> puts Insert row above and Insert row below in the right-click menu on any cell. Right-click the row number and the same menu also holds Duplicate row. <code>enableDeleteRow="all"</code> adds Delete row to the row-number menu, so the person can remove a row the database already holds, the way uniting two hives removes one of them. <code>blockSubmitOnError</code> keeps the submit button disabled while any rule fails or a remote check is still running.</p>
<p>For a screen that only shows the table, <code>variant="viewer"</code> renders the grid alone. It drops the sidebar, the footer and the AI assistant, and it stays read-only whatever <code>readonly</code> says.</p>
<p>This example uses the React component. The web component build takes the same props through <code>configure()</code> for Vue, Angular and Svelte, with <code>onClose</code> replaced by a <code>close</code> event.</p>
<h2 id="the-editor-checks-one-cell-postgres-checks-the-rest">The editor checks one cell, Postgres checks the rest</h2>
<p>The column definitions carry the table's per-cell rules into the place where a person can still act on them, and add one the table never had.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  {
    id: "hiveRef",
    title: "Hive",
    size: 110,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^WM-\\d{2}$" },
    ],
  },
  {
    id: "inspectedOn",
    title: "Inspected on",
    size: 150,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "queenSeen",
    title: "Queen seen",
    size: 130,
    editor: {
      type: "select",
      options: ["Yes", "No"],
      enableCustomValue: false,
    },
    validators: [{ type: "required" }],
  },
  {
    id: "broodFrames",
    title: "Brood frames",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, max: 20, decimalPlaces: 0 },
    ],
  },
  {
    id: "varroaCount",
    title: "Varroa",
    size: 110,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, decimalPlaces: 0 },
    ],
  },
  { id: "action", title: "Action", size: 220 },
];</code></pre>
<p><code>min: 0, max: 20</code> is the <code>CHECK (brood_frames BETWEEN 0 AND 20)</code> constraint, moved forward by one screen. <code>decimalPlaces: 0</code> stands for the <code>INTEGER</code>, and it refuses <code>8.0</code> in the cell as flatly as it refuses <code>21</code>. <code>{ type: "required" }</code> stands where <code>NOT NULL</code> does and reaches further, because it flags an empty string too. Nothing in the table constrains a hive reference, and <code>^WM-\d{2}$</code> is the editor's own rule. The dropdown holds <code>queenSeen</code> to the two words the write understands, and <code>enableCustomValue: false</code> takes away the entry that would let a person add a third.</p>
<ul><li><strong>Row 2</strong>, Brood frames, <code>24</code>: Out of range</li><li><strong>Row 4</strong>, Varroa, empty: This field is required</li></ul>
<p>Uniqueness across two columns stays behind in the database. A built-in rule reads one column, one cell at a time or the whole column for <code>{ type: "unique" }</code>, and never two columns at once. That rule can hold a hive reference or a date, and nothing holds the pair. <code>UNIQUE (hive_ref, inspected_on)</code> is left to Postgres, which raises <code>23505</code> when the pair repeats.</p>
<p>The blank cell has no rule on either side. Every row of a submitted result carries every column the editor declares. An untouched cell in a row the person added arrives as an empty string, and one in a row the <code>SELECT</code> filled keeps what Postgres handed over, which for an empty <code>action</code> is <code>null</code>. Postgres refuses <code>""</code> for an <code>integer</code> with <code>invalid input syntax for type integer: ""</code>, code <code>22P02</code>, and accepts <code>""</code> for a <code>NOT NULL</code> text column without complaint. The database rejects a missing count and stores a blank hive reference, which is why <code>{ type: "required" }</code> sits on both.</p>
<h2 id="submit-returns-the-changes-and-what-the-person-meant-by-them">Submit returns the changes and what the person meant by them</h2>
<p><code>onComplete</code> fires once per confirmed submit, from the confirmation the submit button opens, and receives the rows that moved, grouped by source. Each row carries <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. A row that came from <code>loadData</code> and nobody changed never appears. <a href="https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/">Import, edit and delete rows through your REST API</a> sets out the four flags and the request each one calls for.</p>
<p>Rows the person adds arrive under their own source, named Manually added, and a new row holds every declared column as an empty string and no <code>id</code> at all. That is what the identity column wants. A plain <code>INSERT</code> that supplied an <code>id</code> of its own would be refused with <code>cannot insert a non-DEFAULT value into column "id"</code>, code <code>428C9</code>, so the statement lists the six columns a person can fill and lets the table name the row.</p>
<p>Duplicate row copies the row as the editor holds it, including the fields no column claims. The copy is new to the editor, and it carries the same <code>id</code>, the same hive and the same date as the row it copies. New to the editor says nothing about the database. Build each statement from the fields the table accepts, and a stale <code>id</code> riding along in the JavaScript object costs nothing. The hive and the date are a different matter, and they surface at the write.</p>
<h2 id="the-whole-edit-session-commits-or-none-of-it-does">The whole edit session commits or none of it does</h2>
<p>Three statements cover the delta.</p>
<pre><code class="language-ts">const INSERT_INSPECTION = `
  INSERT INTO inspections
    (hive_ref, inspected_on, queen_seen, brood_frames, varroa_count, action)
  VALUES ($1, $2, $3 = 'Yes', $4, $5, nullif($6, ''))
`;

const UPDATE_INSPECTION = `
  UPDATE inspections
     SET hive_ref     = $2,
         inspected_on = $3,
         queen_seen   = $4 = 'Yes',
         brood_frames = $5,
         varroa_count = $6,
         action       = nullif($7, '')
   WHERE id = $1
`;

const DELETE_INSPECTION = `DELETE FROM inspections WHERE id = $1`;</code></pre>
<p><code>$3 = 'Yes'</code> turns the dropdown word back into a boolean. <code>nullif($6, '')</code> writes <code>NULL</code> when the cell is empty. Without it the column stores an empty string, and an application reading that column as absent never finds it. Postgres parses each parameter for the column it lands in, so the values need no cast in JavaScript, and <code>"9"</code> reaches an <code>integer</code> column as 9.</p>
<p>The handler walks the delta and hands each row to one statement.</p>
<pre><code class="language-tsx">const saveInspections = useCallback(
  async (result: DataEditorResult&#x3C;Inspection>) => {
    await db.transaction(async (tx) => {
      for (const source of result.sources) {
        for (const change of source.rows) {
          const row = change.row;

          if (change.isDeleted) {
            if (!change.isNew) {
              await tx.query(DELETE_INSPECTION, [row.id]);
            }
            continue;
          }

          const values = [
            row.hiveRef,
            row.inspectedOn,
            row.queenSeen,
            row.broodFrames,
            row.varroaCount,
            row.action,
          ];

          if (change.isNew) {
            await tx.query(INSERT_INSPECTION, values);
            continue;
          }

          await tx.query(UPDATE_INSPECTION, [row.id, ...values]);
        }
      }
    });

    setVersion((current) => current + 1);
  },
  [],
);</code></pre>
<p><code>db.transaction()</code> rolls back when your callback rejects, and commits when it resolves with every statement inside it having succeeded. A statement that raised aborts the block, so a callback that swallows the error resolves onto a rollback. Four corrected rows, two new inspections and one deletion are one unit of work. There is no endpoint and no chunk size, because the database is in the same tab. There is no half-applied batch to reconcile afterwards, because the whole delta goes through one <code>db.transaction()</code>.</p>
<p>The duplicated row lands here, in a submit after the one that went through.</p>
<pre><code class="language-text">duplicate key value violates unique constraint
"inspections_hive_ref_inspected_on_key"          code 23505
Key (hive_ref, inspected_on)=(WM-03, 2026-08-21) already exists.

rows in inspections after the failed submit      7
the valid new inspection that travelled with it  0</code></pre>
<p>One statement raised, the transaction rolled back, and the good row in the same delta was never written. Atomicity gives up partial success, and the person keeps a screen where every correction is still visible.</p>
<p>They keep it because the handler lets the error out. Updog Data Editor awaits the promise and clears the grid the moment it resolves. A handler that catches the failure and returns normally reads as a clean save, and the session is gone with the work unsaved, including the statements that had already succeeded. Let it reject and the editor keeps every row, every value and the undo history behind them.</p>
<h2 id="after-the-commit-the-grid-reads-the-table-again">After the commit the grid reads the table again</h2>
<p>The editor empties itself once the handler resolves. Nothing refills it on its own, so without the last line of the handler the screen stays empty where a table full of rows should be.</p>
<p><code>setVersion</code> gives <code>loadInspections</code> a new identity, and the editor's load effect is keyed on that function, so a new one sends it back to the database. The read that follows is the same plain <code>SELECT</code>, against a table that now holds the committed rows.</p>
<pre><code class="language-text">id  hiveRef  inspectedOn  queenSeen  broodFrames  varroaCount  action
1   WM-01    2026-08-17   Yes        8            4            Added super
7   WM-01    2026-08-21   Yes        9            3
2   WM-02    2026-08-17   Yes        5            9            Treated
3   WM-03    2026-08-19   Yes        9            2
8   WM-03    2026-08-21   No         7            5            Requeen
5   WM-05    2026-08-19   Yes        6            2
6   WM-06    2026-08-19   No         3            17           Requeen</code></pre>
<p><code>WM-04</code> was deleted, <code>WM-02</code> carries its corrected mite count and its note, and the two rows dated the twenty-first are the ones the person added, wearing the <code>id</code>s the table gave them. <code>WM-01</code> and <code>WM-03</code> each sit there twice on two dates, which is what a key built from the pair allows. Reload the page and the seven rows are still in the table, because IndexedDB kept the files PGlite writes.</p>
<p>The second read replaces whatever the grid was holding. The editor clears its rows before the new ones arrive, so an unsaved correction goes with them. Bump the version after a commit, and leave it alone while a person is typing.</p>
<h2 id="the-editor-holds-a-snapshot-of-the-table">The editor holds a snapshot of the table</h2>
<p><code>loadData</code> runs when the editor opens and when its identity changes. The rows it hands over pass into the editor's keeping for the length of the session, and they come back to the application at <code>onComplete</code>. A write from somewhere else in the application while the grid is open leaves the screen as the person left it.</p>
<p>PGlite has the machinery for a screen that follows the table instead. Its <code>live</code> extension offers <code>live.query</code>, <code>live.incrementalQuery</code> and <code>live.changes</code>, and the last of those emits insert, update and delete objects keyed on a column. That fits a dashboard, where the newest number wins. Wire <code>live.changes</code> to the version counter here and every write to <code>inspections</code>, the grid's own commit included, reloads the grid and drops unsaved edits and the undo history with them.</p>
<p>Treat the grid as an edit session over a snapshot. Open it on the slice a person is working on, let them finish, commit, and read again.</p>
<p>Updog Data Editor validates its licence key against <code>https://api.updog.tech/v1/validate</code> when the editor mounts, from a dev server as readily as from a production build, so the page does make one request, and the rows are not in it. And Updog ships no PGlite connector, no destination list and no adapter. <code>loadData</code> and <code>onComplete</code> are the only two props that touch the database, and the SQL on both sides is yours.</p>
<p>A migration nobody reviews, run once against a table the application owns, belongs in SQL and needs no screen at all.</p>
<h2 id="a-file-can-still-arrive-on-the-same-screen">A file can still arrive on the same screen</h2>
<p>The inspector who walks the apiary keeps notes in a phone app, and the phone app exports CSV.</p>
<p><code>apiary-24-08.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Hive</td><td class="sheet__cell">Date</td><td class="sheet__cell">Queen</td><td class="sheet__cell">Brood</td><td class="sheet__cell">Varroa</td><td class="sheet__cell">Notes</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">WM-06</td><td class="sheet__cell">24/08/2026</td><td class="sheet__cell">Y</td><td class="sheet__cell">8</td><td class="sheet__cell">1</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">WM-07</td><td class="sheet__cell">24/08/2026</td><td class="sheet__cell">N</td><td class="sheet__cell">4</td><td class="sheet__cell">17</td><td class="sheet__cell">Requeen</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">WM-08</td><td class="sheet__cell">24/08/2026</td><td class="sheet__cell">Y</td><td class="sheet__cell">11</td><td class="sheet__cell">3</td><td class="sheet__cell">Added super</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">WM-09</td><td class="sheet__cell">25/08/2026</td><td class="sheet__cell">Y</td><td class="sheet__cell">7</td><td class="sheet__cell">0</td><td class="sheet__cell"></td></tr></tbody></table>
<p>Two of the props the mount switched off come back on, and <code>synonyms</code> joins them. <code>enableCreateColumn</code> stays off, so a header the schema does not know stays out of the grid instead of becoming a column the table has no room for.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Inspection>
  /* everything above stays */
  importFormats={["csv", "xlsx"]}
  enableAddSource
  synonyms={{
    columns: {
      inspectedOn: ["date"],
      action: ["notes"],
    },
  }}
/></code></pre>
<p>The file lands as a second source beside the rows from the table, and the person works on both in one grid. Drop the two synonym lines and four of the six headers still reach a column, each header measured against the column id and the column title. <code>Hive</code> and <code>Varroa</code> match a title outright, and <code>Queen</code> and <code>Brood</code> are contained by one.</p>
<pre><code class="language-text">Hive    hiveRef      100
Varroa  varroaCount  100
Queen   queenSeen     80
Brood   broodFrames   80
Date    inspectedOn    0
Notes   action         0</code></pre>
<p>A header needs 60 to be accepted. Neither <code>Date</code> nor <code>inspectedOn</code> contains the other, and nor do <code>Notes</code> and <code>action</code>, so both score zero and the two synonym entries name the pairs by hand. The values need nothing. <code>Y</code> and <code>N</code> reach <code>Yes</code> and <code>No</code> through the built-in synonym table, and so does <code>TRUE</code>. <a href="https://updog.tech/blog/csv-column-mapping-react/">How to build CSV column mapping in React</a> runs the same matcher over a different file, and builds the screen a person fixes it on.</p>
<p>The file carries no <code>id</code>, so every line in it is a new row, and the same handler inserts it. The import is one more way to fill the same dataset.</p>
<h2 id="each-side-keeps-the-rules-it-can-explain">Each side keeps the rules it can explain</h2>
<p>The integration is one table, six editor columns, two type parsers, one <code>SELECT</code>, three write statements, two callbacks and a version counter. You wrote the mapping between them, in the column aliases, the two parsers and one <code>= 'Yes'</code> on each write. Neither side ships a connector for the other.</p>
<p>PGlite owns the identity, the transaction, the files in IndexedDB and every rule that needs the whole table. The editor holds the rules it can explain in one cell, the hive-reference pattern the table never checks included. Updog Data Editor owns the screen where a person reads the rows, sorts them, filters them, fixes four of them and adds two more.</p>
<p>The boundary is <code>loadData</code> in one direction and <code>onComplete</code> in the other. One runs a <code>SELECT</code> and hands the rows over. The other reads two flags off each changed row and runs the statement they call for. The SQL on both sides is yours.</p>
<p>The same grid ships through the <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> component or the web component build. The beekeeper walks the apiary again, and the table is where they left it.</p>]]></content:encoded></item>
<item><title>How to Fix CSV Encoding Issues: UTF-8, BOM, and Windows-1252</title><link>https://updog.tech/blog/how-to-fix-csv-encoding-issues/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-fix-csv-encoding-issues/</guid><pubDate>Fri, 28 Aug 2026 00:00:00 GMT</pubDate><description>A file says nothing about the alphabet it was written in. See how Updog Importer works out which one it is.</description><content:encoded><![CDATA[<p>An author's name reaches a CSV importer as bytes. The decoder decides which
characters those bytes become.</p>
<pre><code class="language-text">Böll, Heinrich      what the shop typed
BÃ¶ll, Heinrich     UTF-8 bytes decoded as Windows-1252
B�ll, Heinrich      Windows-1252 bytes decoded as UTF-8</code></pre>
<p>The first broken value is mojibake. Its bytes still hold the original
information, and the importer read them with the wrong character encoding. The
second holds <code>�</code>, the Unicode replacement character, which a UTF-8 decoder
writes when the input carries a byte sequence it cannot decode. Once an earlier
conversion has replaced a character with <code>?</code> or <code>�</code> and saved the result, the
original character is gone.</p>
<p>CSV itself requires no one encoding. RFC 4180 registers <code>charset</code> as an optional
parameter of the <code>text/csv</code> media type, so a sender can declare an encoding
while the file travels with MIME metadata. A file picked from a desktop reaches
the importer as bytes with no such parameter. A byte order mark can identify
some Unicode files, UTF-8 among them, and the Unicode consortium states the rest
in one line. "If there is no BOM, the encoding could be anything."</p>
<p>The file in this guide makes that harder. It holds 26 rows from an antiquarian
bookshop, assembled from two exports that were concatenated without transcoding
either of them. The newer system wrote UTF-8. The old till wrote Windows-1252.
The encoding therefore changes partway down the byte stream.</p>
<p><code>cawdray-books--merged.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Cat. no.</td><td class="sheet__cell">Author</td><td class="sheet__cell">Title</td><td class="sheet__cell">Lang</td><td class="sheet__cell">Price (EUR)</td><td class="sheet__cell">Shelf</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">CB-0208</td><td class="sheet__cell">Достоевский, Фёдор</td><td class="sheet__cell">Записки из подполья</td><td class="sheet__cell">ru</td><td class="sheet__cell">€27.00</td><td class="sheet__cell">D1</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">CB-0211</td><td class="sheet__cell">Ōe, Kenzaburō</td><td class="sheet__cell">The Silent Cry</td><td class="sheet__cell">en</td><td class="sheet__cell">€33.00</td><td class="sheet__cell">C4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">2 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">CB-0223</td><td class="sheet__cell">Fauré, Gabriel</td><td class="sheet__cell">Lettres à ses éditeurs</td><td class="sheet__cell">fr</td><td class="sheet__cell">€45.00</td><td class="sheet__cell">B4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">2 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">CB-0236</td><td class="sheet__cell">JosÃ© Ãlvarez</td><td class="sheet__cell">Cartas de invierno</td><td class="sheet__cell">es</td><td class="sheet__cell">€13.40</td><td class="sheet__cell">B1</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">6 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">16</th><td class="sheet__cell">CB-0104</td><td class="sheet__cell">Böll, Heinrich</td><td class="sheet__cell">Ansichten eines Clowns</td><td class="sheet__cell">de</td><td class="sheet__cell">€18.50</td><td class="sheet__cell">A3</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">3 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">20</th><td class="sheet__cell">CB-0121</td><td class="sheet__cell">O’Brien, Flann</td><td class="sheet__cell">The Third Policeman</td><td class="sheet__cell">en</td><td class="sheet__cell">€19.00</td><td class="sheet__cell">C2</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">1 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">22</th><td class="sheet__cell">CB-0130</td><td class="sheet__cell">?e, Kenzabur?</td><td class="sheet__cell">A Personal Matter</td><td class="sheet__cell">en</td><td class="sheet__cell">€31.00</td><td class="sheet__cell">C4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">27</th><td class="sheet__cell">CB-0151</td><td class="sheet__cell">Undset, Sigrid</td><td class="sheet__cell">Kransen</td><td class="sheet__cell">no</td><td class="sheet__cell">€17.30</td><td class="sheet__cell">D1</td></tr></tbody></table>
<p>The rows fail in different ways. Row 2 needs UTF-8 for Cyrillic and row 3 needs
it for two macrons. Row 6 writes <code>é</code> as <code>e</code> plus a combining accent, which is
valid Unicode and changes how the value compares. Row 9 already holds mojibake
from an earlier conversion. Rows 16 to 27 came off the Windows-1252 export,
including the curly apostrophe in row 20. Row 22 is worse. Its two macrons
became question marks before the file reached the importer, so no decoder
recovers them.</p>
<h2 id="a-bom-is-an-encoding-signature-inside-the-file">A BOM is an encoding signature inside the file</h2>
<p>A byte order mark sits at the front of the byte stream itself, which is the one
place a media type never reaches. Unicode defines it as "a signature defining
the byte order and encoding form" and gives it a sequence for each Unicode
encoding form.</p>
<pre><code class="language-text">EF BB BF       UTF-8
FF FE          UTF-16 little-endian
FE FF          UTF-16 big-endian
FF FE 00 00    UTF-32 little-endian
00 00 FE FF    UTF-32 big-endian</code></pre>
<p>The two little-endian marks overlap, since <code>FF FE</code> opens both of them, so a
reader has to test the four-byte sequence before the two-byte one or it reads
every UTF-32 file as UTF-16. UTF-8 has no byte order to mark, because a decoder
reads it one byte at a time. Its mark carries the signature and nothing else.</p>
<p>Excel makes the effect visible. Microsoft's API lists the CSV save formats as
<code>xlCSV</code>, <code>xlCSVWindows</code>, <code>xlCSVMac</code>, <code>xlCSVMSDOS</code> and <code>xlCSVUTF8</code>, described as
"CSV", "Windows CSV", "Macintosh CSV", "MSDOS CSV" and "UTF8 CSV". Its support
page says a UTF-8 CSV opens normally in Excel when the file was saved with a
BOM. Without that signature the normal open path can read the same bytes as
something else.</p>
<p>NetSuite documents that failure in its own exports. It writes CSV as UTF-8 with
no BOM, and its documentation says Excel then uses a different encoding, so
non-ASCII characters may not show correctly. Its recommendation is to export to
Excel first and save the workbook back to CSV, because Excel adds a BOM to what
it writes.</p>
<p>The CSV data did not change between those two paths. The extra bytes at the
front changed what the reader knew before decoding the first field.</p>
<h2 id="a-few-bytes-can-change-the-detectors-answer">A few bytes can change the detector's answer</h2>
<p>Updog Importer resolves an unmarked file in a fixed order, and the order decides
how much of the answer is a guess.</p>
<p>The importer checks the opening bytes for a BOM first. Without one, it tries a
strict UTF-8 decode of the first 64KB, and a sample that survives that decode
settles the encoding with no statistics involved. Only a sample that fails goes
to <code>chardet</code>, which returns the encoding with the highest confidence for those
bytes.</p>
<p>A UTF-8 verdict then gets one more check, against the whole file, and it makes
no difference whether the verdict came from the mark or from the sample. A
sample can be ASCII-clean while legacy bytes sit deeper in, so the importer
decodes every byte in strict mode before it accepts the verdict. When that
decode succeeds, its output becomes the file text. When it fails, the importer
re-detects over a window anchored at the first non-ASCII byte. A byte order mark
is a hypothesis here like any other, and a file that fails the strict decode
loses it.</p>
<p>The strict pass reads the whole file, so it is not free. What it is not is a
second decode thrown away. Its output is the text the importer keeps.</p>
<p>When <code>chardet</code> has no answer at all, the fallback is Windows-1252. In the web
encoding model its decoder maps every byte value to a code point, so no byte
sequence can make that fallback fail.</p>
<p><a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> covers the rest of
the opening pass, and
<a href="https://updog.tech/blog/import-csv-into-mysql/">how to import a CSV into MySQL</a> shows the same
chain inside a complete import flow.</p>
<p>The statistical step carries less certainty than the rest. These results come
from <code>chardet</code> 2.2.0, the version Updog Importer ships, called directly rather
than through the chain above. Each file holds the header shown, then its rows,
then a trailing newline, encoded to Windows-1251 or Windows-1252 before
detection. The Cyrillic rows in order are <code>Иван Петров</code>, <code>Анна Смирнова</code> and
<code>Ольга Кузнецова</code>. The Western European rows are <code>René;Zürich</code>, <code>Hervé;Genève</code>,
<code>Noël;Fribourg</code>, <code>Chloé;Nyon</code> and <code>Amélie;Sion</code>.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>File</th>
<th>Bytes</th>
<th>chardet verdict</th>
<th>Decoded text</th>
</tr>
</thead>
<tbody>
<tr>
<td>Windows-1252, <code>Name;City</code>, 1 to 5 rows</td>
<td>22 to 72</td>
<td><code>iso-8859-1</code> at every size</td>
<td>correct</td>
</tr>
<tr>
<td>Windows-1251, <code>name</code>, 1 row</td>
<td>17</td>
<td><code>windows-1251</code></td>
<td>correct</td>
</tr>
<tr>
<td>Windows-1251, <code>name</code>, 2 rows</td>
<td>31</td>
<td><code>GB18030</code></td>
<td><code>肉囗 襄蝠钼</code></td>
</tr>
<tr>
<td>Windows-1251, <code>id;name</code>, 1 row</td>
<td>22</td>
<td><code>iso-8859-1</code></td>
<td><code>1;Èâàí Ïåòðîâ</code></td>
</tr>
<tr>
<td>Windows-1251, <code>id;name</code>, 2 rows</td>
<td>38</td>
<td><code>GB18030</code></td>
<td><code>2;理磬 鸯桊眍忄</code></td>
</tr>
<tr>
<td>Windows-1251, <code>id;name</code>, 3 rows</td>
<td>56</td>
<td><code>windows-1251</code></td>
<td>correct</td>
</tr>
</tbody>
</table></div>
<p>More bytes did not steadily improve the answer. One Windows-1251 row was
classified correctly. A second row moved the verdict to <code>GB18030</code>. A third moved
it back. Changing the header from <code>name</code> to <code>id;name</code>, two ASCII characters,
moved the one-row file from <code>windows-1251</code> onto a Latin table.</p>
<p>The Windows-1252 sample shows a different case. <code>chardet</code> calls it <code>iso-8859-1</code>
and the browser still produces the intended text. Under the WHATWG Encoding
Standard the labels <code>latin1</code>, <code>iso-8859-1</code>, <code>cp819</code> and <code>ascii</code> all select the
Windows-1252 decoder. "These are synonyms: <code>latin1</code> and <code>ascii</code> are just labels
for windows-1252." A wrong label reached the right decoder.</p>
<p>The Windows-1251 samples have no equivalent alias. When the detector answers
<code>GB18030</code> or <code>iso-8859-1</code>, the same bytes go through a different table and
become different characters.</p>
<p>That is the limit of statistical detection. It returns the encoding that best
explains the bytes it sampled, and a few more bytes can change that explanation.
Treat the result as a hypothesis. For UTF-8, a strict decode proves the byte
sequence is valid UTF-8. For a legacy encoding, the importer has no equivalent
proof.</p>
<h2 id="the-corruption-pattern-points-to-the-decoder">The corruption pattern points to the decoder</h2>
<p>Two failures leave different text behind, and each one starts from different
bytes.</p>
<pre><code class="language-text">Ã©    UTF-8 bytes decoded as Windows-1252
�     Windows-1252 bytes decoded as UTF-8</code></pre>
<p>Take <code>é</code>. UTF-8 stores it as the two bytes <code>C3 A9</code>. Windows-1252 assigns a
character to each byte on its own, so <code>C3</code> becomes <code>Ã</code> and <code>A9</code> becomes <code>©</code>. The
decoder accepts both bytes and returns valid Unicode text. The result is
readable, reversible mojibake.</p>
<p>Windows-1252 stores the same <code>é</code> as the single byte <code>E9</code>, which cannot stand
alone in UTF-8. A UTF-8 decoder running in replacement mode substitutes U+FFFD,
the replacement character, for that malformed input.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Original text</th>
<th>UTF-8 bytes decoded as Windows-1252</th>
<th>Windows-1252 bytes decoded as UTF-8</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>José</code></td>
<td><code>JosÃ©</code></td>
<td><code>Jos�</code></td>
</tr>
<tr>
<td><code>München</code></td>
<td><code>MÃ¼nchen</code></td>
<td><code>M�nchen</code></td>
</tr>
<tr>
<td><code>€</code></td>
<td><code>â‚¬</code></td>
<td><code>�</code></td>
</tr>
<tr>
<td><code>’</code></td>
<td><code>â€™</code></td>
<td><code>�</code></td>
</tr>
</tbody>
</table></div>
<p>The two failures preserve different amounts of information. In <code>JosÃ©</code> the
characters still map back to the original bytes once you know Windows-1252 was
the wrong decoder. Re-encode <code>Ã©</code> as Windows-1252 and the bytes are <code>C3 A9</code>
again. Decode those as UTF-8 and <code>é</code> returns.</p>
<p><code>Jos�</code> is different. U+FFFD records that decoding failed, and it records nothing
about which byte was there. An application that saves the decoded string and
drops the original bytes cannot reconstruct the missing <code>E9</code> from <code>�</code>.</p>
<p>That difference is what the strict decode in the previous section is for. During
detection Updog Importer never accepts malformed UTF-8 and papers over it with
<code>�</code>. The strict decoder rejects the UTF-8 hypothesis instead, which leaves the
bytes available for another encoding. The decode that finally produces the text
runs in replacement mode, so a file whose UTF-8 verdict survives the strict check
can still come back carrying replacement characters. The next section is that
file.</p>
<h2 id="one-encoding-decision-covers-the-whole-file">One encoding decision covers the whole file</h2>
<p>A CSV parser applies one character encoding to the whole byte stream. This file
does not have one.</p>
<p>The mark at its front says UTF-8, and that is where the importer starts. The
strict decode of the whole file then fails, because the twelve Windows-1252 rows
hold byte sequences no UTF-8 decoder accepts. A byte order mark is a hypothesis
in this chain, and this file is where the hypothesis loses. What decides the
outcome after that is <code>chardet</code>, running on the same bytes.</p>
<p>When it answers UTF-8, the fourteen UTF-8 rows decode correctly and the twelve
Windows-1252 rows do not.</p>
<pre><code class="language-text">CB-0104,"B�ll, Heinrich",Ansichten eines Clowns,de,�18.50,A3
CB-0121,"O�Brien, Flann",The Third Policeman,en,�19.00,C2</code></pre>
<p>When it answers Windows-1252, the opposite half loses. Those twelve rows survive
intact, and the UTF-8 sequences above them break apart, so <code>C3 A9</code> reads as
<code>Ã©</code>.</p>
<p>The balance moves with a small change in the byte stream. Holding the twelve
Windows-1252 rows fixed and varying only the number of UTF-8 rows above them,
through the full decode chain on chardet 2.2.0 under Node 24.19.0, the file
crosses over between the eighth row and the ninth.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>UTF-8 rows above</th>
<th>Bytes</th>
<th>With the mark</th>
<th>With the mark removed</th>
</tr>
</thead>
<tbody>
<tr>
<td>8</td>
<td>1,252</td>
<td><code>windows-1252</code></td>
<td><code>windows-1252</code></td>
</tr>
<tr>
<td>9</td>
<td>1,308</td>
<td><code>utf-8</code></td>
<td><code>windows-1252</code></td>
</tr>
<tr>
<td>14</td>
<td>1,627</td>
<td><code>utf-8</code></td>
<td><code>windows-1252</code></td>
</tr>
</tbody>
</table></div>
<p>Fifty-six bytes of new rows moved the loss from one half of the file to the
other. The right-hand column is the same experiment with the three mark bytes
deleted, and it never crosses over. That is worth reading twice. The mark's
value as a signature was already rejected by the strict decode, so what those
three bytes do here is act as three more bytes of evidence in a statistical
count.</p>
<p>On a file that is genuinely UTF-8 the mark behaves the way it is meant to. The
strict decode confirms it, detection never runs, and no distribution of bytes
can overrule it. The mark loses its authority only on a file that is not what it
claims to be.</p>
<p>Detecting each row separately does not fix this. A single row gives the detector
far less evidence than the whole file, and the earlier table already showed
short samples moving between <code>windows-1251</code>, <code>GB18030</code> and <code>iso-8859-1</code> after a
two-character change. Updog Importer therefore keeps one encoding decision for
the file. Where different parts of a file were written with different encodings,
detection can identify the encoding that best explains the bytes as a whole. It
cannot make both halves correct at once.</p>
<h2 id="a-correct-decode-cannot-recover-earlier-data-loss">A correct decode cannot recover earlier data loss</h2>
<p>A decoder can reinterpret the bytes that remain. It cannot reconstruct
characters that an earlier step already replaced.</p>
<p>Row 22 of the bookshop file contains <code>?e, Kenzabur?</code>. Windows-1252 has no byte
for <code>Ō</code>, which is U+014C, so the old till substituted a question mark before the
current CSV existed. The byte in the file is <code>3F</code>, an ordinary ASCII question
mark, and nothing in that byte says whether the shop typed it or an encoder put
it there. The macron is not in the file to be found.</p>
<p>Row 9 fails differently. It contains <code>JosÃ© Ãlvarez</code>, and those characters are
valid UTF-8, so the detector chooses UTF-8 and chooses correctly. The decoded
text is still wrong, because the mojibake was made earlier and then saved as
text.</p>
<pre><code class="language-text">original text
José

UTF-8 bytes decoded as Windows-1252
JosÃ©

that damaged string saved as UTF-8
JosÃ©</code></pre>
<p>The current decoder sees only the last step. Nothing available to it says that
<code>Ã©</code> was once <code>é</code>.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>What arrives</th>
<th>What happened earlier</th>
<th>What remains possible</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>JosÃ©</code> in valid UTF-8</td>
<td>UTF-8 bytes were decoded through a single-byte encoding and the result was saved</td>
<td>the original bytes come back when that encoding is known and maps every byte value</td>
</tr>
<tr>
<td><code>Jos�</code></td>
<td>malformed input was replaced during an earlier decode and the decoded text was saved</td>
<td>the replaced byte sequence is no longer present</td>
</tr>
<tr>
<td><code>Jos?</code></td>
<td>an earlier encoder replaced a character it could not represent</td>
<td>the original character is no longer present</td>
</tr>
</tbody>
</table></div>
<p>The first case keeps enough information for a mechanical reversal. Re-encode
<code>JosÃ©</code> through Windows-1252 and the bytes are <code>4A 6F 73 C3 A9</code> again, which
read as <code>José</code>. That works here because Windows-1252 assigns a character to all
256 byte values, so nothing was dropped on the way through it.</p>
<p>The other two are lossy. <code>�</code> records that decoding failed and keeps no copy of
the bytes it replaced, and one <code>�</code> does not always stand for one lost byte. <code>?</code>
says even less, because it is also a character a person could have typed.</p>
<p>Encoding detection is finished at that point. Recovering <code>Ōe</code> or deciding that
<code>JosÃ©</code> means <code>José</code> is a correction to the data, and that decision belongs to
the person who knows what the value was meant to say.</p>
<h2 id="nfc-gives-equivalent-text-one-representation">NFC gives equivalent text one representation</h2>
<p>Decoding produces Unicode text, and the same visible value can still have more
than one representation. Updog Importer normalises every cell after the decode.
It removes a defined set of zero-width characters, replaces non-breaking spaces
with ordinary spaces, normalises the value to NFC, and trims the ends.</p>
<p>Row 6 shows why NFC matters. In this file <code>Fauré</code> arrives as six code points,
because the final <code>é</code> is stored as <code>e</code> followed by U+0301, the combining acute
accent.</p>
<pre><code class="language-text">Fauré    F a u r e ◌́     6 code points
Fauré     F a u r é        5 code points</code></pre>
<p>The two strings render the same and are canonically equivalent in Unicode. They
are not the same sequence of code points, so binary or code-point equality tells
them apart while a collation-aware comparison can treat them as equal. NFC
converts both representations to the same form.</p>
<p>That matters when a value takes part in identity. Where an application matches
imported rows on a name, a reference or any other text field, two visually
identical values should not become different keys because one source used a
combining character.</p>
<p>Updog Importer hands over normalised text. Your application and your database
still decide which fields identify a row and how equality is evaluated. NFC
removes one source of accidental difference before that decision is made.</p>
<h2 id="a-misdecoded-bom-becomes-ordinary-text">A misdecoded BOM becomes ordinary text</h2>
<p>U+FEFF sits in the set of zero-width characters that cleanup removes from a
cell, which handles a mark that survives into the middle of a merged file.</p>
<p>A mark at byte zero takes a different path, since the importer reads it before
any cell exists. Three bytes of <code>EF BB BF</code> make UTF-8 the first candidate.</p>
<p>The rest of the file can contradict that candidate. Put Windows-1252 data behind
those three bytes and the strict decode fails on the body, so the importer
rejects UTF-8 and carries on through detection. When detection settles on
Windows-1252, that decoder has no concept of a signature. It reads the three
bytes as three characters.</p>
<pre><code class="language-text">EF BB BF    a UTF-8 byte order mark

decoded as Windows-1252

ï » ¿</code></pre>
<p>A header of <code>Author</code> therefore reaches column matching as <code>ï»¿Author</code>. Cleanup
cannot help, because U+FEFF is no longer in the string. The same cleanup turns
<code>\uFEFFAuthor</code> back into <code>Author</code> and leaves <code>ï»¿Author</code> exactly as it is.</p>
<p>The bytes began as encoding metadata, and the wrong decoder turned them into
data.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">How to build CSV column mapping in React</a>
follows the next boundary and shows what happens when a header reaches the
matcher under a name the schema does not hold.</p>
<h2 id="a-successful-decode-can-still-produce-the-wrong-text">A successful decode can still produce the wrong text</h2>
<p>The importer always reaches a decoded string. A UTF-8 candidate can fail its
strict check inside the chain, and the fallback path then continues until a
decoder accepts the bytes. Windows-1252 is the last of them, so an import never
fails because the encoding could not be decoded.</p>
<p>Encoding damage therefore arrives in the grid as ordinary text.</p>
<p>The bookshop file reports 26 rows, 6 of 6 columns matched, and 0 rows with
validation errors. Twelve rows hold a replacement character after the decode,
and nine hold an author name different from the one the shop wrote.</p>
<pre><code class="language-text">CB-0231   Sebald, W. G.              Die Ausgewanderten
CB-0236   JosÃ© Ãlvarez              Cartas de invierno
CB-0104   B�ll, Heinrich             Ansichten eines Clowns
CB-0107   M�rquez, Gabriel Garc�a    El coronel no tiene quien le escriba</code></pre>
<p>All four rows are valid CSV. All four author values are valid strings. The
importer can check the shape of a row and still have no basis for deciding
whether <code>B�ll</code> or <code>JosÃ©</code> is the name the shop intended.</p>
<p>As of August 2026, Updog Importer does not show the chosen encoding and takes no
prop for overriding it. The decode runs in a worker before header detection
starts. That worker returns the decoded text, the detected delimiter and the
encoding verdict, and the CSV parser takes the text and the delimiter. The
verdict stops at that boundary, so nothing downstream can tell the person which
decoder produced what they are reading.</p>
<p>The values become the only visible clue. A run of <code>Ã©</code>, <code>Ã¼</code> or <code>â€™</code> points
towards UTF-8 bytes read through a single-byte decoder. A run of <code>�</code> points
towards malformed input that went through a replacement-mode decode somewhere in
the file's history.</p>
<p>Those patterns can tell a person that the text deserves attention. They cannot
prove what the original value was.</p>
<h2 id="text-formats-do-not-all-leave-the-same-encoding-question">Text formats do not all leave the same encoding question</h2>
<p>The chain in this article exists because the importer receives an unlabelled
byte stream and still has to turn it into text. A CSV commonly arrives that way.
The other formats do not, and Updog Importer currently runs the same decoding
stage ahead of its CSV, JSON and XML parsers even though the formats define
encoding differently.</p>
<p>JSON has the narrowest contract of the three. RFC 8259 states that "JSON text
exchanged between systems that are not part of a closed ecosystem MUST be
encoded using UTF-8", and that implementations "MUST NOT add a byte order mark
(U+FEFF) to the beginning of a networked-transmitted JSON text". A JSON reader
can treat UTF-8 as the format rule rather than infer a legacy encoding from the
bytes.</p>
<p>XML carries more information of its own. A document can declare its encoding,
every processor "MUST be able to read entities in both the UTF-8 and UTF-16
encodings", and entities in UTF-16 "MUST" begin with a byte order mark while
UTF-8 entities "MAY". An entity with no declaration and no external information
has to be legal UTF-8 or UTF-16 or the processor reports a fatal error. The
spec's appendix on recognising an encoding from the opening bytes is
non-normative, so it describes the technique rather than requiring it.</p>
<p>An <code>.xlsx</code> takes a different path again. It is an Open XML package rather than
one text stream, so the importer opens the package and parses its workbook,
worksheet and shared-string parts under the XML rules above. No encoding
detector runs over the workbook as a whole.</p>
<p>That leaves the unlabelled desktop CSV as the case this article is really about.
A file can hold text with no in-band declaration, no byte order mark, and no
transport metadata left beside it. The importer has bytes and has to choose how
to read them.</p>
<p>A team that controls its own exports can remove the ambiguity. A UTF-8 CSV with
a byte order mark hands the reader an in-band signature that survives the strict
decode. An <code>.xlsx</code> keeps its text inside a package whose parts carry their own
encoding rules.</p>
<p>A team receiving whatever an older till, ERP or desktop application wrote does
not control that boundary, and detection can only choose the encoding that best
explains the bytes it was given.</p>
<h2 id="the-order-is-part-of-the-encoding-policy">The order is part of the encoding policy</h2>
<p>A detector does not settle the encoding on its own. It supplies a candidate, and
the importer decides which evidence outranks which.</p>
<p>The pass in this article uses a fixed order. A byte order mark gets the first
vote. Without one, the detector proposes a candidate from the bytes it samples.
A UTF-8 candidate then has to survive a strict decode of the whole file. When
the browser cannot decode the candidate at all, or the detector produces no
usable answer, Windows-1252 closes the chain.</p>
<pre><code class="language-ts">import { detect } from "chardet";

export async function decodeCsvFile(file: File): Promise&#x3C;string> {
  const bytes = new Uint8Array(await file.arrayBuffer());

  const hasUtf8Bom =
    bytes[0] === 0xef &#x26;&#x26; bytes[1] === 0xbb &#x26;&#x26; bytes[2] === 0xbf;

  if (hasUtf8Bom) {
    try {
      return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
    } catch {
      // The signature and the body disagree. Continue with detection.
    }
  }

  const label = detect(bytes);

  if (label?.toLowerCase() === "utf-8") {
    try {
      return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
    } catch {
      // UTF-8 was only a statistical candidate.
    }
  }

  if (label) {
    try {
      return new TextDecoder(label).decode(bytes);
    } catch {
      // The detector can name an encoding the browser cannot decode.
    }
  }

  return new TextDecoder("windows-1252").decode(bytes);
}</code></pre>
<p><code>fatal: true</code> turns UTF-8 decoding into a validity check. Without it, malformed
sequences become U+FFFD and the decoder returns a string anyway. With it, a
malformed sequence rejects the candidate and the original bytes stay available
for another decoder.</p>
<p>That check proves less than it looks. It proves the bytes form a valid UTF-8
sequence, and not that the source wrote UTF-8. UTF-16LE holding ASCII is the
clearest case, since <code>69 00 64 00</code> is valid UTF-8 that decodes to <code>i</code>, a null,
<code>d</code>, a null. A strict decode accepts it. That is why the mark votes first, and
why a UTF-16 file with no mark is the case this pass does not settle.</p>
<p>The second <code>try</code> covers a different boundary. <code>chardet</code> and the browser do not
support the same set of encodings. <code>chardet</code> 2.2.0 can return <code>UTF-32LE</code> or
<code>UTF-32BE</code>, the WHATWG Encoding API defines no UTF-32 decoder, and
<code>new TextDecoder(label)</code> throws a <code>RangeError</code> on a label it does not know. A
detector can recognise an encoding the browser refuses to build.</p>
<p>Windows-1252 closes the chain because its web decoder maps the full byte range.
The importer can always produce text, and producing text does not prove the text
is correct.</p>
<p>With Updog Importer this pass runs before the schema sees the file. The
application defines the six bookshop fields.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  {
    id: "catalogRef",
    title: "Cat. no.",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  { id: "author", title: "Author", validators: [{ type: "required" }] },
  { id: "title", title: "Title", validators: [{ type: "required" }] },
  { id: "language", title: "Lang" },
  { id: "priceEur", title: "Price (EUR)" },
  { id: "shelf", title: "Shelf" },
];</code></pre>
<p>The schema validates those six fields after the decode. It cannot tell from the
string alone whether <code>Böll</code>, <code>BÃ¶ll</code> or <code>B�ll</code> is the author's intended name.</p>
<p>Those three forms bring the article back to where it started. <code>Böll</code> is the
value the shop meant to keep. <code>BÃ¶ll</code> and <code>B�ll</code> expose different losses and
reinterpretations somewhere in the file's encoding history.</p>
<p>The importer can make its decoding policy deterministic. It cannot ask the bytes
what the person meant. Once decoding has exhausted what the bytes can prove,
correcting the value belongs to the person who knows the data.</p>]]></content:encoded></item>
<item><title>Add CSV and Excel Import to a Base44 App</title><link>https://updog.tech/blog/add-csv-and-excel-import-to-a-base44-app/</link><guid isPermaLink="true">https://updog.tech/blog/add-csv-and-excel-import-to-a-base44-app/</guid><pubDate>Thu, 27 Aug 2026 00:00:00 GMT</pubDate><description>A supplier list arrives from whatever system the buyer used before. See how Updog Importer brings that file into an app built on Base44.</description><content:encoded><![CDATA[<p>Base44 turns a prompt into a working app with a UI, database, backend logic and authentication. Its data lives in entities, so a procurement app might have a <code>Supplier</code> entity behind its suppliers page.</p>
<p>Once that app has customers, some of their data already lives elsewhere. A buyer may have hundreds of approved vendors in a CSV or Excel file and need those rows inside <code>Supplier</code>.</p>
<p>This guide adds that path with Updog Importer. There are two ways to get there. You can ask the Base44 agent to build the import flow, or have it install and wire up the importer.</p>
<h2 id="base44-already-has-two-ways-to-import-data">Base44 already has two ways to import data</h2>
<p>Base44 has two built-in import paths for the person building the app. Upload a CSV, Excel or JSON file to the AI chat and ask it to create or extend an entity and load the rows. CSV and JSON files can be up to 10 MB, while Excel files can be up to 15 MB. You can also open Dashboard, then Data, choose a table, and import a CSV from More Actions.</p>
<p>Both imports append records. Base44 does not update or overwrite existing rows during an import. Replacing a table means clearing its records first and importing the file again.</p>
<p>Those tools are for bringing data into the app while you build or administer it. The import screen in this guide serves the people who use the finished product. They open it inside the procurement app, bring vendor files you have never seen, review the rows, and write the accepted data into <code>Supplier</code>.</p>
<h2 id="the-app-already-has-a-supplier-entity">The app already has a Supplier entity</h2>
<p>The procurement app in this guide starts from one Base44 prompt.</p>
<pre><code class="language-text">Build a small procurement app with one page.

Create an entity named Supplier with these fields.
  supplier_ref     text, required
  supplier_name    text, required
  category         text, enum: Packaging, Logistics, Raw materials, Maintenance
  incoterm         text, enum: EXW, FOB, DAP, DDP
  lead_time_days   integer, minimum 0
  approved_on      text, format date
  status           text, enum: Approved, Pending, Suspended
  contact_name     text
  contact_email    text, email format
Leave the entity empty.

Render /suppliers as a table of every record with those nine fields, the record
count above it, and an empty state while the entity holds nothing. Redirect / to
/suppliers. Keep the styling plain, and give the app one primary color, #1f6f5c.</code></pre>
<p>Base44 creates the <code>Supplier</code> entity with nine fields and renders the suppliers page around it. The entity starts empty. The import screen gives the buyer a way to fill it from the vendor list they already have.</p>
<h2 id="the-file-brings-its-own-schema">The file brings its own schema</h2>
<p>The buyer's file comes from a purchasing system you have never seen. Its headers use that system's names. Its dates use that system's format. Its values may not match the options your <code>Supplier</code> fields accept.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>The screen has to</th>
<th>Because the file</th>
</tr>
</thead>
<tbody>
<tr>
<td>detect encoding and delimiter</td>
<td>arrives as UTF-8, Windows-1252, comma or semicolon</td>
</tr>
<tr>
<td>find the header row</td>
<td>carries a report title and an export date above it</td>
</tr>
<tr>
<td>read every sheet of a workbook</td>
<td>is <code>.xlsx</code> with one tab per buying site</td>
</tr>
<tr>
<td>settle the date order per column</td>
<td>writes <code>04/11/2026</code> and means the fourth of November</td>
</tr>
<tr>
<td>keep leading zeros</td>
<td>holds <code>00417</code>, which Excel already turned into <code>417</code></td>
</tr>
<tr>
<td>match headers onto your fields</td>
<td>says <code>Vendor code</code> where your app says <code>supplierRef</code></td>
</tr>
<tr>
<td>match values onto your options</td>
<td>says <code>Raw mats</code> where your app says <code>Raw materials</code></td>
</tr>
<tr>
<td>check and let the person fix</td>
<td>holds a row your entity will reject</td>
</tr>
<tr>
<td>stay usable at scale</td>
<td>is a hundred thousand rows on a laptop</td>
</tr>
<tr>
<td>report new, changed and deleted rows</td>
<td>is the second import of a file that landed once already</td>
</tr>
</tbody>
</table></div>
<p>Each row in that table needs a rule. Written as a prompt, with the entity fields first and one stage for each part of the import, the same work looks like this.</p>
<pre><code class="language-text">Build a CSV and Excel import screen for the suppliers page. A button on that
page opens it as a modal wizard, our buyers walk that wizard with the vendor
lists their old purchasing system produced, and it leaves them in a
spreadsheet where they clean what came in.

Where the fields come from
- Read the field list from my code, so the same screen serves the suppliers
  page today and a contracts page later.
- Support text, whole numbers, dates and a fixed list of options, and let one
  field carry several rules at once.
- Check required, a pattern, a range, uniqueness inside the file, and
  uniqueness against the vendors we already store.
- Show the buyer our label for a field, and hand my code back the field name.
- Take supplier_ref as the key, so a second upload of the same vendors finds
  them and updates them.
- Drop columns the file carries beyond that list.

Opening the files
- Take several files at once, by drop or by dialog, and show a card per file.
- Detect the encoding, strip a byte order mark, and read a Windows-1252 export
  without turning accented company names into question marks.
- Detect the delimiter. Commas, semicolons, tabs and pipes all arrive.
- Drop a first line shaped sep=; that Excel writes for some locales.
- Read .xlsx, .xls and .ods, open a workbook as one card per sheet, and let
  the buyer choose which sheets go on.
- Find the real header row when a report title and an export date sit above
  it, and handle a file with duplicate headers or no header at all.
- Keep a row carrying one field too few, and say which fields it filled.

Reading what the cells hold
- Settle the date order per column, so 04/11/2026 does not become April.
- Read 1.240,50 and 1,240.50 as the same number.
- Keep 00417 as text, including a code Excel already turned into 417.
- Tell an empty cell apart from a cell holding the word null.

Matching the columns
- Map the file's headers onto my field list, one field per column.
- Match the obvious ones on arrival, and show the buyer which of my fields
  reached nothing so they can point each one at a column by hand.
- Show a few values under every header, so the buyer tells two similar
  columns apart.
- Remember the pairs the buyer confirmed, so the next file of that shape
  arrives matched.

Matching the values
- Collect the distinct values of category, incoterm and status as the file
  spells them.
- Match each one to an option we allow, and let the buyer place the rest.

Cleaning before the write
- Hand the finished file to a spreadsheet the buyer works in, with my labels
  on top and every row in it.
- Mark what the buyer changed. A new row, an edited cell and a deleted row
  each read differently at a glance.
- Run every rule the field list carries, and say which cell failed and why.
- Let the buyer fix a cell in place, with the editor that fits the field. A
  date opens a calendar, a list opens its options, a number takes digits.
- Sort and filter, so the buyer reaches the failing rows among the hundred
  thousand that pass.
- Copy and paste blocks between it and Excel or Google Sheets, and undo an
  edit.
- Stay smooth at a hundred thousand rows, with the reading off the main
  thread so the tab keeps responding.

Handing the rows over
- Tell me which rows are new, which changed, and which were deleted.
- Keep every row and every mapping on screen when my write to the entity
  fails.</code></pre>
<p>The prompt still hides the variations inside each field. A lead time may arrive as <code>14</code>, <code>14 days</code>, <code>2 weeks</code>, or an empty cell because the supplier never agreed to one. A status may use the buyer's own vocabulary. A country may arrive as a name, code, or abbreviation.</p>
<p>Those differences belong to the source file, not to your <code>Supplier</code> entity. The import has to map them before the rows are written.</p>
<p><a href="https://updog.tech/blog/csv-import-for-procurement-vendor-management-software/">CSV import for procurement software</a> follows a supplier export header by header and shows where those mappings come from.</p>
<p>If you build the flow yourself, every rule in the prompt becomes application code you own. The other path gives the same requirements to an importer package.</p>
<h2 id="the-second-prompt-installs-the-importer">The second prompt installs the importer</h2>
<pre><code class="language-text">Add a spreadsheet import screen to the suppliers page with the npm package
@updog/data-editor. Read https://updog.tech/updog.md and
https://docs.updog.tech first, and use only props documented there.

1. Install @updog/data-editor and import "@updog/data-editor/styles.css".
2. Render &#x3C;DataEditor /> with apiKey="updog-base44-demo", which is all the
   key a base44.app host needs, variant="uploader", primaryKey="supplierRef",
   enableDeleteRow="all" and these nine columns, written as id, title, then
   type and rules:
   supplierRef "Supplier ref" text, required, unique
   supplierName "Supplier name" text, required
   category "Category" select: Packaging, Logistics, Raw materials, Maintenance
   incoterm "Incoterm" select: EXW, FOB, DAP, DDP
   leadTimeDays "Lead time" number
   approvedOn "Approved" date
   status "Status" select: Approved, Pending, Suspended
   contactName "Contact" text
   contactEmail "Contact email" text, email
3. In a stylesheet loaded after "@updog/data-editor/styles.css", set
   --updog-brand on :root to this app's primary color, written as a plain
   color value.
4. onComplete receives result.sources, and every entry in a source's rows is a
   wrapper shaped { row, isNew, isChanged, isDeleted, isValid }. Read the four
   flags off the wrapper and the cell values off entry.row. Skip an entry whose
   isValid is false.
5. entry.row is keyed by the column id in camelCase, and the Supplier entity
   fields are snake_case, so write one mapper that renames all nine fields
   explicitly and passes lead_time_days through Number.
6. Route the rows into the entity. New ones through bulkCreate. Changed ones
   need their record id, so read the stored records back with a filter on
   supplier_ref and send them through bulkUpdate. Deleted ones through
   deleteMany on supplier_ref. Batch every call at 500, skip an empty batch,
   and close the modal once the writes return.
7. Throw from onComplete when a write fails. The editor clears its rows as
   soon as onComplete resolves, so a swallowed error loses the import.
8. Do not build an uploader of your own, do not parse the file yourself,
   and do not invent props.</code></pre>
<p>Base44 can install public npm packages from the AI chat. Name the package, approve the installation when Base44 asks, and the dependency becomes part of the app. You do not open a terminal or edit the dependency list by hand.</p>
<p>That keeps the second prompt short. Updog Importer ships as a React component with its stylesheet, and Base44 apps use React with Vite, so the agent can install the package and mount the importer inside the project it already generated.</p>
<p>The package is still third-party code. Base44 does not guarantee its quality, reliability, security, or compatibility, and its documentation leaves testing and validation to you.</p>
<h2 id="the-importer-mirrors-the-entity">The importer mirrors the entity</h2>
<p>The nine <code>Supplier</code> fields become nine importer columns. Each column points to one field through its <code>id</code>, while <code>title</code> gives the buyer the name they see in the grid.</p>
<pre><code class="language-tsx">import {
  DataEditor,
  type DataEditorColumn,
  type DataEditorResult,
} from "@updog/data-editor";
import "@updog/data-editor/styles.css";

type SupplierRow = {
  supplierRef: string;
  supplierName: string;
  category: string;
  incoterm: string;
  leadTimeDays: string;
  approvedOn: string;
  status: string;
  contactName: string;
  contactEmail: string;
};

const columns: DataEditorColumn[] = [
  {
    id: "supplierRef",
    title: "Supplier ref",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "supplierName",
    title: "Supplier name",
    validators: [{ type: "required" }],
  },
  {
    id: "category",
    title: "Category",
    editor: {
      type: "select",
      options: ["Packaging", "Logistics", "Raw materials", "Maintenance"],
    },
  },
  {
    id: "incoterm",
    title: "Incoterm",
    editor: {
      type: "select",
      options: ["EXW", "FOB", "DAP", "DDP"],
    },
  },
  {
    id: "leadTimeDays",
    title: "Lead time",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
  {
    id: "approvedOn",
    title: "Approved",
    editor: { type: "date" },
  },
  {
    id: "status",
    title: "Status",
    editor: {
      type: "select",
      options: ["Approved", "Pending", "Suspended"],
    },
  },
  {
    id: "contactName",
    title: "Contact",
  },
  {
    id: "contactEmail",
    title: "Contact email",
    validators: [{ type: "email" }],
  },
];</code></pre>
<p>Most of these rules repeat constraints the app already knows. Base44 entity schemas support rules such as <code>minLength</code>, <code>pattern</code>, <code>format</code>, <code>enum</code>, <code>minimum</code> and <code>maximum</code>. Its documented schema options do not include a uniqueness constraint. Every record does receive a unique Base44 <code>id</code>, but that does not stop two <code>Supplier</code> records from carrying the same <code>supplier_ref</code>.</p>
<p>That check therefore happens before the import reaches the entity. <code>{ type: "unique" }</code> on <code>supplierRef</code> flags a reference that already belongs to another supplier. It runs after the other validators on the column have passed.</p>
<h2 id="the-mapper-crosses-the-naming-seam">The mapper crosses the naming seam</h2>
<p>The editor and the entity use different names for the same fields. An editor row uses camelCase keys such as <code>supplierRef</code> and <code>leadTimeDays</code>. The Base44 entity stores <code>supplier_ref</code> and <code>lead_time_days</code>. Number fields also leave the editor as text.</p>
<p>One small mapper keeps those conversions in one place.</p>
<pre><code class="language-tsx">const toSupplierRecord = (row: SupplierRow) => ({
  supplier_ref: row.supplierRef,
  supplier_name: row.supplierName,
  category: row.category,
  incoterm: row.incoterm,
  lead_time_days: Number(row.leadTimeDays),
  approved_on: row.approvedOn,
  status: row.status,
  contact_name: row.contactName,
  contact_email: row.contactEmail,
});</code></pre>
<p>It turns an edited row into the shape Base44 expects, and <code>lead_time_days</code> passes through <code>Number</code> on the way. Nothing outside that function needs to know how the entity names its fields.</p>
<h2 id="the-page-mounts-the-importer">The page mounts the importer</h2>
<p><code>primaryKey="supplierRef"</code> tells the editor which column identifies a supplier when an imported row meets a row the grid already holds. <code>enableDeleteRow</code> lets the buyer remove a supplier, which gives the submit handler a deleted row to route back to Base44.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;SupplierRow>
  apiKey="updog-base44-demo"
  variant="uploader"
  open={open}
  onClose={() => {
    setOpen(false);
  }}
  columns={columns}
  primaryKey="supplierRef"
  enableDeleteRow="all"
  onComplete={handleComplete}
/></code></pre>
<p>The first prompt gave the app one primary color, <code>#1f6f5c</code>. One CSS variable carries it into the editor's buttons, selected cells, wizard cards and matched values.</p>
<pre><code class="language-css">/* loaded after @updog/data-editor/styles.css */
:root {
  --updog-brand: #1f6f5c;
}</code></pre>
<h2 id="the-file-uses-somebody-elses-vocabulary">The file uses somebody else's vocabulary</h2>
<p>The buyer exports 640 approved vendors from their old purchasing system in one Excel sheet.</p>
<p><code>harrowden-suppliers.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Vendor code</td><td class="sheet__cell">Vendor name</td><td class="sheet__cell">Spend category</td><td class="sheet__cell">Incoterm</td><td class="sheet__cell">Lead time (days)</td><td class="sheet__cell">Approved on</td><td class="sheet__cell">Status</td><td class="sheet__cell">Buyer contact</td><td class="sheet__cell">E-mail</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">HW-0001</td><td class="sheet__cell">Ambleforth Cartons Ltd</td><td class="sheet__cell">Packaging</td><td class="sheet__cell">DDP</td><td class="sheet__cell">12</td><td class="sheet__cell">2024-03-26</td><td class="sheet__cell">Pending</td><td class="sheet__cell">Anselm Ambleside</td><td class="sheet__cell">anselm.ambleside@ambleforthcart.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">HW-0002</td><td class="sheet__cell">Barrowden Couriers Oy</td><td class="sheet__cell">Logistics</td><td class="sheet__cell">DAP</td><td class="sheet__cell">31</td><td class="sheet__cell">2025-05-21</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Deryn Lockhart</td><td class="sheet__cell">deryn.lockhart@barrowdencouri.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">HW-0003</td><td class="sheet__cell">Cheswick Glassworks SRL</td><td class="sheet__cell">Raw materials</td><td class="sheet__cell">DAP</td><td class="sheet__cell">46</td><td class="sheet__cell">2024-09-26</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Gwilym Gadsby</td><td class="sheet__cell">gwilym.gadsby@cheswickglassw.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">HW-0008</td><td class="sheet__cell">Hartshorne Polymers Oy</td><td class="sheet__cell">Raw materials</td><td class="sheet__cell">FOB</td><td class="sheet__cell">37</td><td class="sheet__cell">2024-09-19</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Ffion Nettleford</td><td class="sheet__cell">ffion.nettleford@hartshornepoly.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">6 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">16</th><td class="sheet__cell">HW-0015</td><td class="sheet__cell">Oswaldkirk Filters SRL</td><td class="sheet__cell">Maintenance</td><td class="sheet__cell">DDP</td><td class="sheet__cell">15</td><td class="sheet__cell">2024-07-21</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Kester Kinnaird</td><td class="sheet__cell">kester.kinnaird@oswaldkirkfilt.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">84 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">101</th><td class="sheet__cell">HW-0100</td><td class="sheet__cell">Vaynor Timber BV</td><td class="sheet__cell">Raw materials</td><td class="sheet__cell">DAP</td><td class="sheet__cell">58</td><td class="sheet__cell">2025-03-12</td><td class="sheet__cell">Pending</td><td class="sheet__cell">Jolanta Barrowclough</td><td class="sheet__cell">jolanta.barrowclough@vaynortimberbv.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">216 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">318</th><td class="sheet__cell">HW-0317</td><td class="sheet__cell">Edgeworth Pigments Group</td><td class="sheet__cell">Raw materials</td><td class="sheet__cell">DAP</td><td class="sheet__cell">50</td><td class="sheet__cell">2025-08-06</td><td class="sheet__cell">Suspended</td><td class="sheet__cell">Eamon Elverton</td><td class="sheet__cell">eamon.elverton@edgeworthpigme.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">322 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">641</th><td class="sheet__cell">HW-0640</td><td class="sheet__cell">Penrhos Timber BV</td><td class="sheet__cell">Raw materials</td><td class="sheet__cell">EXW</td><td class="sheet__cell">35</td><td class="sheet__cell">2025-03-29</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Nessa Fanshawe</td><td class="sheet__cell">nessa.fanshawe@penrhostimberb.example</td></tr></tbody></table>
<p>Seven of the nine headers use names that do not appear in your <code>Supplier</code> schema.</p>
<pre><code class="language-text">Vendor code       →  Supplier ref
Vendor name       →  Supplier name
Spend category    →  Category
Lead time (days)  →  Lead time
Approved on       →  Approved
Buyer contact     →  Contact
E-mail            →  Contact email</code></pre>
<p>The matcher resolves eight of the nine columns. <code>Vendor code</code> stays open because <code>code</code> and <code>ref</code> share no useful lexical match. The buyer maps it to <code>Supplier ref</code> from the dropdown, and the import reaches 9 of 9 columns.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">Building a column mapping screen</a> covers the matching state behind that step.</p>
<p><code>Spend category</code>, <code>Incoterm</code>, and <code>Status</code> use closed lists. The importer matches the distinct values in all three columns against the options your schema allows. A value such as <code>Raw mats</code> has no accepted target, so it stays unresolved until the buyer maps it.</p>
<p><a href="https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/">Mapping values onto a fixed list</a> shows how those value matches are scored.</p>
<p>This export is internally consistent, so the mapping screens do most of the work. A file that mixes date formats or introduces unknown values follows the same path, but leaves more decisions for the buyer before the rows reach the grid.</p>
<p>The grid then holds all 640 rows. The buyer can sort, filter to validation errors, edit a cell, undo a change, or paste a block from a spreadsheet. Submit shows the final row counts before the import is written.</p>
<h2 id="submit-returns-the-rows-and-their-state">Submit returns the rows and their state</h2>
<p>Submit returns the edited rows grouped by source. Each row carries four independent flags that tell your handler whether it is new, changed, deleted, and valid.</p>
<pre><code class="language-tsx">const handleComplete = async (result: DataEditorResult&#x3C;SupplierRow>) => {
  const rows = result.sources.flatMap((source) => source.rows);

  const inserts = rows
    .filter((r) => r.isValid &#x26;&#x26; r.isNew &#x26;&#x26; !r.isDeleted)
    .map((r) => toSupplierRecord(r.row));

  const updates = rows
    .filter((r) => r.isValid &#x26;&#x26; r.isChanged &#x26;&#x26; !r.isNew &#x26;&#x26; !r.isDeleted)
    .map((r) => toSupplierRecord(r.row));

  const deletes = rows
    .filter((r) => r.isDeleted &#x26;&#x26; !r.isNew)
    .map((r) => r.row.supplierRef);

  await writeSuppliers({ inserts, updates, deletes });
  setOpen(false);
};</code></pre>
<p><code>toSupplierRecord</code> is the mapper defined earlier. <code>leadTimeDays</code> leaves the editor as <code>"12"</code> and passes through <code>Number</code> before Base44 receives the integer. <code>approvedOn</code> leaves as <code>"2024-03-26"</code>, independent of how the date appeared in the grid.</p>
<p>This workbook contributes one source with 640 rows. The result looks like this, with one of those rows expanded.</p>
<pre><code class="language-ts">{
  sources: [
    {
      sourceId: "source_…",
      sourceName: "harrowden-suppliers.xlsx - Suppliers",
      rows: [
        {
          row: {
            supplierRef: "HW-0001",
            supplierName: "Ambleforth Cartons Ltd",
            category: "Packaging",
            incoterm: "DDP",
            leadTimeDays: "12",
            approvedOn: "2024-03-26",
            status: "Pending",
            contactName: "Anselm Ambleside",
            contactEmail: "anselm.ambleside@ambleforthcart.example",
          },
          isNew: true,
          isChanged: false,
          isDeleted: false,
          isValid: true,
        },
        // 639 more rows
      ],
    },
  ],
  counts: { new: 640, changed: 0, deleted: 0, invalid: 0 },
  learnedSynonyms: { columns: [], values: [] },
}</code></pre>
<h2 id="the-write-into-a-base44-entity">The write into a Base44 entity</h2>
<p>Base44 gives every entity a <code>bulkCreate</code> method that accepts an array of records. New rows can go straight through it.</p>
<p>Changed rows need one more step. The entity SDK documents <code>create</code>, <code>bulkCreate</code>, <code>update</code>, <code>updateMany</code>, <code>bulkUpdate</code>, <code>delete</code>, and <code>deleteMany</code>, but no upsert. <code>bulkUpdate</code> needs the <code>id</code> Base44 generated, while the file carries <code>supplier_ref</code>. The handler therefore looks up the stored suppliers by reference, builds a map from <code>supplier_ref</code> to <code>id</code>, and attaches those ids before the update. Deletions need no map because <code>deleteMany</code> accepts a query.</p>
<p><a href="https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/">Import, edit and delete rows through an API</a> follows the same routing against an endpoint you own.</p>
<pre><code class="language-ts">import { base44 } from "@/api/base44Client";

const BATCH = 500;

const batches = (items, size) => {
  const out = [];

  for (let i = 0; i &#x3C; items.length; i += size) {
    out.push(items.slice(i, i + size));
  }

  return out;
};

export async function writeSuppliers({ inserts, updates, deletes }) {
  for (const chunk of batches(inserts, BATCH)) {
    await base44.entities.Supplier.bulkCreate(chunk);
  }

  if (updates.length > 0) {
    const idOf = new Map();

    for (const chunk of batches(
      updates.map((record) => record.supplier_ref),
      BATCH,
    )) {
      const stored = await base44.entities.Supplier.filter({
        supplier_ref: { $in: chunk },
      });

      for (const record of stored) {
        idOf.set(record.supplier_ref, record.id);
      }
    }

    const edits = updates
      .filter((record) => idOf.has(record.supplier_ref))
      .map((record) => ({
        ...record,
        id: idOf.get(record.supplier_ref),
      }));

    for (const chunk of batches(edits, BATCH)) {
      await base44.entities.Supplier.bulkUpdate(chunk);
    }
  }

  for (const chunk of batches(deletes, BATCH)) {
    await base44.entities.Supplier.deleteMany({
      supplier_ref: { $in: chunk },
    });
  }
}</code></pre>
<p>Base44 caps <code>bulkUpdate</code> at 500 records per request, so the handler slices updates into batches of 500. The same batch size is used for creates and deletes here to keep the write path uniform. <code>filter</code> returns at most 5,000 records per request, so a larger lookup has to page through the matching suppliers.</p>
<p>The <code>Supplier</code> entity is empty on the first import. The editor also opens without stored rows, so all 640 vendors arrive with <code>isNew: true</code>. The handler routes them to <code>bulkCreate</code>, first 500 and then 140.</p>
<p>Send the same file again and Base44 gets another 640 records. The editor starts empty again, so the same vendors are still new from its point of view. They arrive with <code>isNew: true</code>, and the handler sends them through <code>bulkCreate</code> again. Base44 has no declared unique field on <code>supplier_ref</code>, and this handler performs no reconciliation for new rows, so nothing collapses the repeat.</p>
<p>That behavior is deliberate here. <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code> describe what happened inside the editor. They do not decide what a row means in your database.</p>
<p>If a second import should update the existing suppliers, your app can choose that policy. Load the stored suppliers into the editor through <code>loadData</code> and matching on <code>supplierRef</code> can turn file rows into changes. Reconcile <code>supplier_ref</code> against Base44 before writing and the handler can choose create or update there instead. Updog Importer supplies the row state and leaves that decision to your application.</p>
<p>Failed writes follow the same boundary. Let the error escape from <code>onComplete</code>. A rejected promise keeps the grid, mappings, and buyer edits in place, while a resolved promise tells the importer that submission finished. Base44 requests that already succeeded are not rolled back, so the handler still owns any retry or partial-write policy. Close the modal only after the write path completes.</p>
<h2 id="the-base44-url-runs-for-free">The Base44 URL runs for free</h2>
<p>Updog Importer makes one request to its license endpoint when the editor starts. It sends the API key and the page hostname. No rows, headers, or file contents go with it.</p>
<p>Updog keeps a list of development and preview hosts where the importer runs free, with no row counted. <code>.base44.app</code> is on that list, so the URL Base44 gives the app can use the importer without adding a domain in the Updog console. The prompt can leave the placeholder API key in place while the app runs there.</p>
<p>A custom domain changes that. If the procurement app moves to <code>app.yourcompany.com</code>, add that hostname at <a href="https://console.updog.tech/">console.updog.tech</a>. The Free plan covers production domains up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains, with no row limit.</p>
<p>Base44 treats the custom domain separately. Connecting one requires a paid plan, starting with Starter.</p>
<h2 id="the-app-now-has-an-import-path">The app now has an import path</h2>
<p>Updog Importer installs from the Base44 AI chat as an npm package. Its columns mirror the <code>Supplier</code> entity, <code>onComplete</code> returns the edited rows and their state, and your handler routes those rows into Base44 through the entity SDK.</p>
<p>The importer handles the file-facing work: parsing CSV and Excel, matching columns and values, validating cells, and letting the buyer correct the data before submit. Your application still decides what those rows mean when they reach <code>Supplier</code>, including how to treat updates, deletions, and repeat imports.</p>
<p>You can build the same flow yourself. The first prompt in this guide lists what that requires. Installing the package keeps those pieces inside the importer and leaves the Base44 code focused on the entity and the write path.</p>]]></content:encoded></item>
<item><title>How to Import Inventory from CSV</title><link>https://updog.tech/blog/how-to-import-inventory-from-csv/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-inventory-from-csv/</guid><pubDate>Wed, 26 Aug 2026 00:00:00 GMT</pubDate><description>One item code can name three different counts at once. See how Updog Importer keeps them apart.</description><content:encoded><![CDATA[<p>Stock sits in more than one place at once. A retailer holds the same jacket in
its shops and in its warehouse, a fulfilment company holds one client's goods
across two buildings, and a food wholesaler holds the same flour at every site
it delivers from. Every one of those pairings carries its own count.</p>
<p>The counting happens away from your app. Someone walks the aisles with a scanner
or a clipboard, and the numbers reach you as a file, because the tool that counts
and the tool that sells are separate systems. That file is a CSV or a workbook,
exported after the count and handed to whoever keeps the system of record.</p>
<p>It writes one line per item per place, so an item code takes as many lines as
the places that hold it.</p>
<p>Wistow Provisions supplies bakeries across the north of England and counts stock
at three sites. In its file <code>WP-FLR-T55</code> holds 480 at Wistow Mill, 96 at Ryburn
Depot and zero at Fenton Cold Store, all at the same moment. An item code does
not name a stock level, and an import that keys on the item alone writes a new
row where a new count belongs.</p>
<h2 id="two-fields-name-the-record">Two fields name the record</h2>
<pre><code class="language-ts">type StockLevel = {
  sku: string;
  warehouse: string;
  onHand: number;
  allocated: number;
  reorderLevel: number;
  unit: string;
};</code></pre>
<p><code>sku</code> and <code>warehouse</code> carry the identity. <code>onHand</code> is what the counter found on
the shelf, <code>allocated</code> is what open orders have already claimed, and
<code>reorderLevel</code> is where buying starts again. <code>unit</code> says whether the count runs
in pieces or in kilograms, and that field decides which counts are valid.</p>
<p>Your stock table holds one unique index over the two columns together. The
import has to arrive with the same idea of identity, so <code>primaryKey</code> takes both.</p>
<pre><code class="language-ts">primaryKey={["sku", "warehouse"]}</code></pre>
<h2 id="the-file-carries-both">The file carries both</h2>
<p>The counter at Wistow Provisions exports one file after every count, one line
per shelf.</p>
<p><code>wistow-stock-count.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Item code</td><td class="sheet__cell">Site</td><td class="sheet__cell">On hand</td><td class="sheet__cell">Allocated</td><td class="sheet__cell">Reorder at</td><td class="sheet__cell">Unit</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">WP-FLR-T55</td><td class="sheet__cell">Wistow Mill</td><td class="sheet__cell">480</td><td class="sheet__cell">120</td><td class="sheet__cell">200</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">WP-FLR-T55</td><td class="sheet__cell">Ryburn Depot</td><td class="sheet__cell">96</td><td class="sheet__cell">24</td><td class="sheet__cell">60</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">WP-FLR-T55</td><td class="sheet__cell">Fenton Cold Store</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">40</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">WP-FLR-WHM</td><td class="sheet__cell">Wistow Mill</td><td class="sheet__cell">212.5</td><td class="sheet__cell">45</td><td class="sheet__cell">100</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">WP-BTR-25</td><td class="sheet__cell">Fenton Cold Store</td><td class="sheet__cell">12.5</td><td class="sheet__cell">4</td><td class="sheet__cell">10</td><td class="sheet__cell">kg</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">WP-YST-FRS</td><td class="sheet__cell">Fenton Cold Store</td><td class="sheet__cell">(4)</td><td class="sheet__cell">0</td><td class="sheet__cell">20</td><td class="sheet__cell">kg</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">WP-YST-FRS</td><td class="sheet__cell">Ryburn Depot</td><td class="sheet__cell">30</td><td class="sheet__cell">6</td><td class="sheet__cell">20</td><td class="sheet__cell">kg</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">WP-SGR-CST</td><td class="sheet__cell">Wistow Mill</td><td class="sheet__cell">640</td><td class="sheet__cell">0</td><td class="sheet__cell">250</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">WP-SGR-CST</td><td class="sheet__cell"></td><td class="sheet__cell">75</td><td class="sheet__cell">0</td><td class="sheet__cell">250</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">WP-CHC-70</td><td class="sheet__cell">Ryburn Depot</td><td class="sheet__cell">144</td><td class="sheet__cell">36</td><td class="sheet__cell">60</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell">WP-CHC-70</td><td class="sheet__cell">Ryburn Depot</td><td class="sheet__cell">150</td><td class="sheet__cell">36</td><td class="sheet__cell">60</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">WP-CHC-70</td><td class="sheet__cell">Wistow Mill</td><td class="sheet__cell">60</td><td class="sheet__cell">12</td><td class="sheet__cell">60</td><td class="sheet__cell">each</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">14</th><td class="sheet__cell">WP-CHC-70</td><td class="sheet__cell">Fenton</td><td class="sheet__cell">26</td><td class="sheet__cell">0</td><td class="sheet__cell">60</td><td class="sheet__cell">each</td></tr></tbody></table>
<p>Six items fill these thirteen rows, and twelve of the lines write both halves
of the pair. An item code comes back further down under a different site, a
site comes back under a different item, and neither column names a row on its
own.</p>
<p>Row 5 counts a half of something sold in pieces. Row 6 counts a half of
something weighed. Row 7 writes its count in brackets. Row 10 leaves the site
blank, and row 14 writes a site name short.</p>
<p>Header wording carries the smaller half of the work here.
<a href="https://updog.tech/blog/csv-column-mapping-react/">CSV column mapping in React</a> covers the
matcher that gets <code>Item code</code> onto <code>sku</code> and <code>Reorder at</code> onto <code>reorderLevel</code>.</p>
<h2 id="normalize-the-site-before-building-the-key">Normalize the site before building the key</h2>
<p>Row 14 says <code>Fenton</code>. The three sites your app knows are <code>Wistow Mill</code>,
<code>Ryburn Depot</code> and <code>Fenton Cold Store</code>. A key built from the file's own spelling
would open a fourth site that no warehouse matches.</p>
<p>The site column is a <code>select</code> with <code>enableCustomValue: false</code>, so the list stays
closed to those three names.</p>
<pre><code class="language-text">"Wistow Mill"        → Wistow Mill
"Ryburn Depot"       → Ryburn Depot
"Fenton Cold Store"  → Fenton Cold Store
"Fenton"             → Fenton Cold Store</code></pre>
<p>Three of those match on the name alone. <code>Fenton</code> reaches <code>Fenton Cold Store</code>
through the built-in matcher, and the person confirms it on the value screen
before any row lands. The importer builds the key from the confirmed option, so
row 14 joins the Fenton records and the short spelling never reaches the key.</p>
<p>A closed list drops a value that reaches no option, and the cell arrives empty.
That is why <code>required</code> sits on the site column.</p>
<p><strong>A composite key needs every part filled.</strong> One empty part and the key is
nothing at all, so the row matches no stored record. Row 10 carries a count of
75 for <code>WP-SGR-CST</code> and no site. It stays an unmatched new row in the editor
until the person picks a site, and until then it reaches no request. The count
is real and the record it belongs to is unknowable, which is work only a person
can finish.</p>
<h2 id="the-unit-decides-what-number-is-valid">The unit decides what number is valid</h2>
<p>Row 5 counts 212.5 of a flour sold in pieces. Row 6 counts 12.5 kilograms of
butter. Both write a half, and only one of them is wrong.</p>
<p>A fixed <code>decimalPlaces: 0</code> on the count would refuse them both and tell a
warehouse that its butter is a bad number. The rule the domain holds reads
two fields at once, so it goes in a <code>function</code> validator, which receives
the cell value and the row around it.</p>
<pre><code class="language-ts">if (row.unit === "kg") return null;</code></pre>
<p><code>dependentFields: COUNTS</code> sits on the unit column and names the three count
columns. Change a line from <code>each</code> to <code>kg</code> and the counts beside it are judged
again, so a verdict never goes stale behind an edit.</p>
<p>The second rule stays flat, because no unit makes a negative count meaningful.
A number column reduces a value on the way in. Spaces, currency symbols and
percent signs come off, the file's own grouping character comes off, and
accounting brackets around a value make it negative.</p>
<pre><code class="language-text">cell     stored     verdict
480      480        whole pieces, valid
12.5     12.5       weighed in kilograms, valid
212.5    212.5      a half of something counted in pieces
(4)      -4         out of range</code></pre>
<p>Row 7 writes a loss of four kilograms of fresh yeast as <code>(4)</code>. The brackets are
read before the digits, so the cell holds <code>-4</code>, and <code>min: 0</code> rejects it. The two
rules carry their own messages, so the person reads a different sentence on row
5 and on row 7.</p>
<p>Every decision lands in one array.</p>
<pre><code class="language-ts">import type {
  DataEditorColumn,
  DataEditorRow,
  ValidationError,
} from "@updog/data-editor";

const SITES = ["Wistow Mill", "Ryburn Depot", "Fenton Cold Store"];
const UNITS = ["each", "kg"];
const COUNTS = ["onHand", "allocated", "reorderLevel"];

const wholeUnlessWeighed = (
  value: unknown,
  row: DataEditorRow,
): ValidationError | null => {
  if (row.unit === "kg") return null;

  const count = Number(value);
  if (!Number.isFinite(count) || Number.isInteger(count)) return null;

  return {
    level: "error",
    message: "Count whole pieces. A half belongs on a line weighed in kilograms.",
  };
};

const quantity: DataEditorColumn["validators"] = [
  { type: "function", fn: wholeUnlessWeighed },
  {
    type: "number",
    min: 0,
    message: "A count starts at zero. Send a loss as an adjustment.",
  },
];

export const columns: DataEditorColumn[] = [
  { id: "sku", title: "Item code", validators: [{ type: "required" }] },
  {
    id: "warehouse",
    title: "Site",
    editor: { type: "select", options: SITES, enableCustomValue: false },
    validators: [{ type: "required" }],
  },
  {
    id: "onHand",
    title: "On hand",
    editor: { type: "number" },
    validators: [{ type: "required" }, ...quantity],
  },
  {
    id: "allocated",
    title: "Allocated",
    editor: { type: "number" },
    validators: quantity,
  },
  {
    id: "reorderLevel",
    title: "Reorder at",
    editor: { type: "number" },
    validators: quantity,
  },
  {
    id: "unit",
    title: "Unit",
    editor: { type: "select", options: UNITS, enableCustomValue: false },
    dependentFields: COUNTS,
  },
];</code></pre>
<p><code>editor: { type: "number" }</code> makes those three columns numeric. A column with a
number validator and no editor stays text, and a value in brackets never becomes
a negative number there. <code>(4)</code> reaches the number rule as text, fails to parse,
and carries that rule's own message, so the person reads a sentence about a
count starting at zero over a cell that never went negative.</p>
<h2 id="the-same-key-updates-the-stored-row">The same key updates the stored row</h2>
<p>Stock counts arrive again and again, and the key decides what each arrival does.
The person meets that choice once the import has something to merge into, which
is either rows already in the grid or a second file in the same upload. The step
is called Add or update, and it offers two cards.</p>
<pre><code class="language-text">Add every row
Every row becomes a new entry, even if it repeats one you already have.

Update by Item code + Site
WP-FLR-T55 + Wistow Mill
WP-FLR-T55 + Ryburn Depot
...
WP-CHC-70 + Fenton</code></pre>
<p>The second card carries the key you declared, titled with the column headings
joined by a plus sign. Its examples are the file's own values, twelve pairs for
thirteen rows, and the last one still reads <code>Fenton</code> because the site names
settle in the step before it. Row 10 is
missing from that list, because a row with no site has no key to show.</p>
<p>Hold three records, one of them a count of 18 for <code>WP-CHC-70</code> at Fenton Cold
Store, and import this file over them. The grid lands on fourteen rows, and one
of the three moves.</p>
<pre><code class="language-text">WP-CHC-70 + Fenton Cold Store   18 → 26    isChanged
WP-FLR-T55 + Ryburn Depot       96 → 96    matched, nothing moved
WP-OAT-50 + Wistow Mill         untouched by the file</code></pre>
<p>A matched row keeps the record it matched. The stored row updates in place and
holds its id, so nothing downstream sees a delete and an insert. A row counts as
changed when a value moves, and the two rows that stood still stay out of the
result altogether. <code>isNew</code> and <code>isChanged</code> are what your handler reads to tell
the three apart.</p>
<p>The card needs every one of its parts mapped. Drop the site column and the card
goes with it. A file with no <code>unique</code> column left loses the step, and an item
code repeats by design here, so that rule never sits on it. One file landing in
an empty grid skips the step too, and the key you declared still anchors the
merge.</p>
<h2 id="duplicate-keys-inside-one-file-need-another-check">Duplicate keys inside one file need another check</h2>
<p>Rows 11 and 12 both read <code>WP-CHC-70</code> at Ryburn Depot, with counts of 144 and
150. An import anchors against rows that came from somewhere else, and skips
every row belonging to the file being imported, so those two never merge into
each other. Both reach the grid and neither is flagged.</p>
<p><code>{ type: "unique" }</code> reads one column, and an item code is meant to repeat
here, so putting the rule on <code>sku</code> would flag every item held at more than one
site. The pair drives the merge and
paints no error cell, which leaves rows 11 and 12 valid and sharing one key.</p>
<p>Nothing in the grid knows what a stock level means either. On hand against
allocated is a rule your domain owns, and a row claiming 36 allocated against 0
on hand passes every validator on the page. Checking an item code against your
catalogue is also yours, and it belongs in an <code>asyncFunction</code> check, batched
once per column.</p>
<p>So the duplicate pair reaches your database silently unless you look for it. The
handler builds a key over the same two columns the merge uses, walks the valid
rows once, and returns every pair that arrived more than once. Joining the two
into one string needs a separator no value can carry, so the key here is the two
values as an array.</p>
<pre><code class="language-ts">const pairOf = (level: StockLevel) => {
  return JSON.stringify([level.sku, level.warehouse]);
};</code></pre>
<h2 id="missing-is-different-from-zero">Missing is different from zero</h2>
<p>A stock file is a statement about the rows it carries. Row 4 sets <code>WP-FLR-T55</code>
at Fenton Cold Store to zero. That is a count, and the record exists with
nothing on the shelf behind it.</p>
<p>The pairs the file never mentions carry no count at all. A zero is data, and an
omitted row is silence, so the safe reading leaves the stored record alone.
State that rule in your API and the counter can send a short file after counting
one aisle.</p>
<p>The decision lands in your handler, because the editor hands you the rows it
holds. A row loaded from your backend that nobody touched stays out of the
result, so silence in the file arrives as silence in the payload.</p>
<h2 id="submit-sends-the-validated-changes">Submit sends the validated changes</h2>
<p>Three rows carry an error, and the grid names each one.</p>
<ul><li><strong>Row 5</strong>, On hand, <code>212.5</code>: Count whole pieces. A half belongs on a line weighed in kilograms.</li><li><strong>Row 7</strong>, On hand, <code>-4</code>: A count starts at zero. Send a loss as an adjustment.</li><li><strong>Row 10</strong>, Site, empty: This field is required</li></ul>
<p><code>onComplete</code> fires once, with the rows grouped by source. Each row carries
<code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>, and the flags are independent.</p>
<pre><code class="language-ts">import { DataEditor } from "@updog/data-editor";
import type { DataEditorResult } from "@updog/data-editor";
import { columns } from "./columns";

type StockRow = {
  sku: string;
  warehouse: string;
  onHand: string;
  allocated: string;
  reorderLevel: string;
  unit: string;
};

type StockLevel = {
  sku: string;
  warehouse: string;
  onHand: number;
  allocated: number;
  reorderLevel: number;
  unit: string;
};

const pairOf = (level: StockLevel) => {
  return JSON.stringify([level.sku, level.warehouse]);
};

const toLevels = (result: DataEditorResult&#x3C;StockRow>): StockLevel[] => {
  const levels: StockLevel[] = [];

  for (const source of result.sources) {
    for (const { row, isValid, isDeleted } of source.rows) {
      if (!isValid || isDeleted) continue;

      levels.push({
        sku: row.sku,
        warehouse: row.warehouse,
        onHand: Number(row.onHand),
        allocated: Number(row.allocated),
        reorderLevel: Number(row.reorderLevel),
        unit: row.unit,
      });
    }
  }

  return levels;
};

const repeatedPairs = (levels: StockLevel[]): string[] => {
  const seen = new Set&#x3C;string>();
  const repeated = new Set&#x3C;string>();

  for (const level of levels) {
    const pair = pairOf(level);
    if (seen.has(pair)) repeated.add(pair);
    seen.add(pair);
  }

  return [...repeated];
};

const saveStock = async (result: DataEditorResult&#x3C;StockRow>) => {
  const levels = toLevels(result);
  const repeated = repeatedPairs(levels);

  if (repeated.length > 0) {
    throw new Error(repeated.length + " item and site pairs arrive twice");
  }

  const response = await fetch("/api/stock-levels", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(levels),
  });
  if (!response.ok) throw new Error(await response.text());
};

type Props = { open: boolean; onClose: () => void };

export function StockImport({ open, onClose }: Props) {
  return (
    &#x3C;DataEditor&#x3C;StockRow>
      apiKey={import.meta.env.VITE_UPDOG_KEY}
      open={open}
      onClose={onClose}
      variant="uploader"
      columns={columns}
      primaryKey={["sku", "warehouse"]}
      onComplete={saveStock}
    />
  );
}</code></pre>
<p>Submit this count with the three flagged rows left as they are. Thirteen rows
reach the handler, <code>toLevels</code> returns the ten that are valid, and
<code>repeatedPairs</code> answers with <code>WP-CHC-70</code> and <code>Ryburn Depot</code>. The throw that
follows keeps the grid open with all thirteen rows and all three errors where
they were.</p>
<p>Throw when your backend fails, for the same reason. A handler that swallows its
own error reads as success. The SDK clears the grid with the counts unsaved.</p>
<h2 id="the-next-stock-count-follows-the-same-rules">The next stock count follows the same rules</h2>
<p>Thirteen rows of a stock count become one record per item and site, once the
counter clears the three rows the grid flagged and settles which of the two
counts for <code>WP-CHC-70</code> at Ryburn Depot is the real one. You named two columns
as the key, closed the site list to three names so the key parts stay
comparable, let
the unit decide which halves are real, and counted the repeated pairs yourself
before the request went out.</p>
<p>Send this count twice in one upload, as the CSV and as the workbook it came
from, and the grid lands on fourteen rows. Twelve rows of the second file reach
the records the first one made. The thirteenth carries no site, so it holds no
key, and it arrives again.</p>
<p><a href="https://updog.tech/blog/excel-import-for-logistics-supply-chain-saas/">Excel import for logistics and supply chain software</a>
covers the files that arrive from the other side of the warehouse, and
<a href="https://updog.tech/blog/how-to-import-product-catalogs-from-csv-and-excel/">importing product catalogs</a>
covers the item codes themselves. Those levels land in a table with a unique
index over the item and the site, and
<a href="https://updog.tech/blog/import-csv-into-postgresql/">importing CSV into PostgreSQL</a> covers the
insert side of it.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into DuckDB</title><link>https://updog.tech/blog/import-csv-into-duckdb/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-duckdb/</guid><pubDate>Wed, 26 Aug 2026 00:00:00 GMT</pubDate><description>A lab writes its results in its own shorthand. See how Updog Importer turns a file of them into rows a DuckDB table accepts.</description><content:encoded><![CDATA[<p>DuckDB is an analytical SQL database that runs inside the process that queries it. There is no server to start, no port to open, and no connection string to configure. A database can live in a single file or entirely in memory. On disk, DuckDB stores data in a compressed columnar format, while its query engine processes data in vectors rather than one row at a time. For analytical queries, this means the engine can often read only the columns the query actually needs instead of scanning entire rows. DuckDB is open source under the MIT license.</p>
<p>DuckDB makes the basic case small. <code>SELECT * FROM 'readings.csv'</code> opens a CSV and infers its dialect and column types. If inference needs help, <code>read_csv</code> accepts explicit options for delimiters, headers, and types. <code>DESCRIBE SELECT * FROM read_csv('input.csv')</code> shows the inferred schema before a table is created. <code>CREATE TABLE readings AS FROM read_csv('input.csv')</code> creates a table from the file. <code>INSERT INTO readings SELECT * FROM read_csv('input.csv')</code> appends the rows to an existing table.</p>
<p>All of these examples assume DuckDB can already address the file. In a browser, the CSV starts as a <code>File</code> selected by the user, while DuckDB-Wasm has its own file system. The application must first register the file or pass its contents to DuckDB. Only then can SQL read it.</p>
<p>That gap is where Updog Importer sits.</p>
<h2 id="the-database-runs-in-the-browser">The database runs in the browser</h2>
<p>DuckDB-Wasm compiles DuckDB to WebAssembly and runs queries in a Web Worker. Updog Importer runs on the client as well. The user selects a file, Updog Importer parses and validates it, and the accepted rows can move directly into DuckDB. The CSV does not need to pass through an application server.</p>
<pre><code class="language-ts">import * as duckdb from "@duckdb/duckdb-wasm";

const bundle = await duckdb.selectBundle(
  duckdb.getJsDelivrBundles(),
);

const workerUrl = URL.createObjectURL(
  new Blob(
    [`importScripts("${bundle.mainWorker}");`],
    { type: "text/javascript" },
  ),
);

const worker = new Worker(workerUrl);
const db = new duckdb.AsyncDuckDB(
  new duckdb.ConsoleLogger(),
  worker,
);

await db.instantiate(
  bundle.mainModule,
  bundle.pthreadWorker,
);

URL.revokeObjectURL(workerUrl);

await db.open({
  path: "opfs://catchment.db",
  accessMode: duckdb.DuckDBAccessMode.READ_WRITE,
});</code></pre>
<p><code>selectBundle</code> checks the browser's WebAssembly features and chooses a compatible DuckDB build. With the default jsDelivr bundles, that means either the baseline <code>mvp</code> build or the faster <code>eh</code> build with WebAssembly exception handling. A threaded <code>coi</code> build is available separately for pages configured for cross-origin isolation.</p>
<p>The <code>opfs://</code> path stores the database in the browser's Origin Private File System instead of keeping it only in memory. A later session can reopen the same database. Before relying on recent writes being durable, issue a <code>CHECKPOINT</code>.</p>
<p>This changes the shape of the import. There is no CSV upload endpoint, request body, or network transfer between Updog Importer and the database. Updog Importer prepares the rows in the browser, and DuckDB receives them in the browser.</p>
<p>The remaining question is how to cross that boundary.</p>
<h2 id="the-csv-does-not-fit-the-schema">The CSV does not fit the schema</h2>
<p>A catchment partnership collects river samples and sends them to a lab. At the end of the month, the lab returns a CSV.</p>
<p><code>wye-lab-march.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Site</td><td class="sheet__cell">Date sampled</td><td class="sheet__cell">Det.</td><td class="sheet__cell">Result</td><td class="sheet__cell">Method</td><td class="sheet__cell">Lab ref</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">WYE-114</td><td class="sheet__cell">04 Mar 2026</td><td class="sheet__cell">NO3-N</td><td class="sheet__cell">6.31</td><td class="sheet__cell">Ion chromatography</td><td class="sheet__cell">L-8841</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">WYE-114</td><td class="sheet__cell">04 Mar 2026</td><td class="sheet__cell">NO3-N</td><td class="sheet__cell">6.90</td><td class="sheet__cell">Ion chromatography</td><td class="sheet__cell">L-8902</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">WYE-118</td><td class="sheet__cell">04 Mar 2026</td><td class="sheet__cell">PO4-P</td><td class="sheet__cell">&#x3C;0.05</td><td class="sheet__cell">Colorimetric</td><td class="sheet__cell">L-8843</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">WYE-118</td><td class="sheet__cell">05 Mar 2026</td><td class="sheet__cell">NH4-N</td><td class="sheet__cell">0.42 mg/l</td><td class="sheet__cell">Colorimetric</td><td class="sheet__cell">L-8850</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">LUG-207</td><td class="sheet__cell">05 Mar 2026</td><td class="sheet__cell">DO</td><td class="sheet__cell">9.8</td><td class="sheet__cell">Probe</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">473 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">480</th><td class="sheet__cell">LUG-207</td><td class="sheet__cell">29 Mar 2026</td><td class="sheet__cell">NO3-N</td><td class="sheet__cell">4.02</td><td class="sheet__cell">Ion chromatography</td><td class="sheet__cell">L-9310</td></tr></tbody></table>
<p>The file makes sense to the people who produced it. It does not yet match the shape the application needs.</p>
<p><code>Det.</code> is the lab's abbreviation for the measured substance, and the values below it use chemical codes such as <code>NO3-N</code> and <code>PO4-P</code>. Rows 2 and 3 look almost identical, but they are separate measurements with different results and lab references. <code>&#x3C;0.05</code> is not a number. It reports that the measurement fell below a stated laboratory threshold. The next row puts the unit inside the value as <code>0.42 mg/l</code>. Row 6 has no lab reference at all.</p>
<p>None of these makes the CSV invalid. They make its meaning dependent on the lab that produced it.</p>
<h2 id="the-schema-defines-a-reading">The schema defines a reading</h2>
<p>Suppose the application allows one reading per site, day, and substance. Those three fields form the key.</p>
<pre><code class="language-sql">CREATE TABLE readings (
    site_code   VARCHAR NOT NULL,
    sampled_on  DATE NOT NULL,
    determinand VARCHAR NOT NULL,
    value_mg_l  DECIMAL(9, 3),
    method      VARCHAR,
    lab_ref     VARCHAR,
    loaded_at   TIMESTAMP DEFAULT current_timestamp,
    PRIMARY KEY (site_code, sampled_on, determinand)
);</code></pre>
<p>DuckDB creates an Adaptive Radix Tree index for a primary key or unique constraint. The index enforces uniqueness, and <code>ON CONFLICT</code> can use that constraint to decide whether an insert becomes an update. The trade-off is write cost. DuckDB has to maintain the index as rows are inserted or changed, and its documentation recommends adding indexes after bulk loading when possible.</p>
<p><code>value_mg_l</code> is <code>DECIMAL(9, 3)</code>, which holds at most nine digits in total, with three after the decimal point. DuckDB rounds a value when it is converted to that scale, so <code>6.3149</code> becomes <code>6.315</code>. That is valid database behavior, but it is a poor place to discover unwanted precision loss. Updog Importer can reject a fourth decimal before the row reaches DuckDB.</p>
<h2 id="updog-importer-enforces-the-schema-first">Updog Importer enforces the schema first</h2>
<p>Updog Importer defines the same constraints before a row reaches DuckDB.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const DETERMINANDS = [
  "Nitrate",
  "Phosphate",
  "Ammonia",
  "Dissolved oxygen",
];

export const columns: DataEditorColumn[] = [
  {
    id: "siteCode",
    title: "Site code",
    size: 130,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^[A-Z]{3}-\\d{3}$" },
    ],
  },
  {
    id: "sampledOn",
    title: "Sampled on",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "determinand",
    title: "Determinand",
    size: 170,
    editor: {
      type: "select",
      options: DETERMINANDS,
      enableCustomValue: false,
    },
    validators: [
      { type: "required" },
      { type: "oneOf", values: DETERMINANDS },
    ],
  },
  {
    id: "valueMgL",
    title: "Result mg/l",
    size: 130,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 3 }],
  },
  { id: "method", title: "Method", size: 180 },
  { id: "labRef", title: "Lab ref", size: 120 },
];</code></pre>
<p><code>decimalPlaces: 3</code> mirrors the scale of <code>DECIMAL(9, 3)</code>. The grid can flag a fourth decimal while preserving the value the lab supplied. <code>min: 0</code> rejects negative measurements. <code>04 Mar 2026</code> becomes <code>2026-03-04</code>. The determinand is a closed list, so <code>enableCustomValue: false</code> prevents an unknown code from becoming a new option.</p>
<p>That last rule matters because <code>determinand</code> is part of the primary key. If a chemical code is not mapped, the row has no complete identity. It should not reach DuckDB, since primary-key columns cannot be <code>NULL</code> and the table would reject it anyway. The mapping therefore has to resolve <code>NO3-N</code>, <code>PO4-P</code>, and every other accepted lab code before insertion.</p>
<p>Numbers have a different problem. <code>&#x3C;0.05</code> is not a decimal value. <code>0.42 mg/l</code> combines a number with its unit. Updog Importer does not silently turn either into a number, so both remain visible as validation errors.</p>
<ul><li><strong>Row 4</strong>, Result mg/l, <code>&#x3C;0.05</code>: Invalid number</li><li><strong>Row 5</strong>, Result mg/l, <code>0.42 mg/l</code>: Invalid number</li></ul>
<p>DuckDB rejects <code>&#x3C;0.05</code> when it is cast to <code>DECIMAL(9, 3)</code> as well. A failed cast raises a conversion error.</p>
<p>The difference is where the error appears. In SQL, a failed conversion stops the statement. In Updog Importer, it marks the cell before insertion. The person reviewing the file can then apply the rule that dataset follows, whether that is preserving the reporting limit, replacing the value, or leaving the cell empty.</p>
<p>DuckDB enforces the table. Updog Importer catches the mismatch before the table sees it.</p>
<h2 id="string-matching-does-not-know-chemistry">String matching does not know chemistry</h2>
<p>Five of the six headers map automatically. <code>Det.</code> does not.</p>
<pre><code class="language-text">"Method"       → method        100
"Lab ref"      → labRef        100
"Site"         → siteCode       80
"Result"       → valueMgL       80
"Date sampled" → sampledOn      70
"Det."         → determinand     0</code></pre>
<p>Updog Importer accepts a match at 60 or above. <code>Det.</code> never gets there. Containment requires at least four characters on the shorter side, while <code>det</code> has three. It shares no complete word with <code>determinand</code>, and their edit distance is too large for a typo match.</p>
<p>The values fail for a more fundamental reason. <code>NO3-N</code> and <code>Nitrate</code> are semantically related, but their strings are not. The same is true of <code>DO</code> and <code>Dissolved oxygen</code>. No edit-distance rule can infer that relationship from the text alone.</p>
<p>The missing information belongs to the domain, not the matching algorithm. The application has to supply it as mapping data.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">Column matching in React</a> explains the scoring algorithm in detail.</p>
<h2 id="the-editor-opens-on-the-table">The editor opens on the table</h2>
<p>The editor gets the same columns, identity rules, and domain mappings that the table expects.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Reading>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey={["siteCode", "sampledOn", "determinand"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      determinand: ["Det.", "Analyte"],
    },
    values: {
      Nitrate: ["NO3-N", "NO3"],
      Phosphate: ["PO4-P", "SRP"],
      Ammonia: ["NH4-N", "NH3-N"],
      "Dissolved oxygen": ["DO"],
    },
  }}
  loadData={loadFromDuckDb}
  onComplete={onComplete}
/></code></pre>
<p>Column and value synonyms stay separate. <code>Det.</code> can map to the <code>determinand</code> column without competing with <code>DO</code>, <code>NO3-N</code>, or the other values inside it.</p>
<p><code>primaryKey</code> uses the same fields as the DuckDB table. <code>blockSubmitOnError</code> prevents a row with an unresolved value such as <code>&#x3C;0.05</code> from reaching <code>onComplete</code>. <code>enableDeleteRow="all"</code> lets the reviewer remove a row before submission.</p>
<p><code>loadData</code> works in the other direction. When the editor opens, it reads the rows already stored in DuckDB.</p>
<pre><code class="language-ts">const CURRENT = `
  SELECT
    site_code                     AS siteCode,
    sampled_on::VARCHAR           AS sampledOn,
    determinand,
    (value_mg_l::DOUBLE)::VARCHAR AS valueMgL,
    method,
    lab_ref                       AS labRef
  FROM readings
  ORDER BY sampled_on, site_code, determinand;
`;

const loadFromDuckDb = useCallback(async (onChunk) => {
  const conn = await db.connect();

  try {
    const table = await conn.query(CURRENT);

    onChunk(
      table.toArray().map((row) => row.toJSON()),
      { source: "DuckDB", done: true },
    );
  } finally {
    await conn.close();
  }
}, []);</code></pre>
<p>DuckDB-Wasm returns query results as Apache Arrow tables. <code>toArray().map(row => row.toJSON())</code> converts those rows into plain JavaScript objects for the editor.</p>
<p><code>sampled_on</code> is cast to <code>VARCHAR</code>, so the editor receives the date in DuckDB's text representation. <code>value_mg_l</code> passes through <code>DOUBLE</code> before becoming text to remove the fixed three-place display of <code>DECIMAL(9, 3)</code>, so a stored <code>6.310</code> can return to the editor as <code>6.31</code>. The database still keeps the column as a fixed-point decimal.</p>
<p>This example uses the React component. The same configuration can pass through the Updog Importer web component build in Vue, Angular, or Svelte.</p>
<h2 id="submit-returns-a-delta">Submit returns a delta</h2>
<p><code>onComplete</code> receives the rows that changed, grouped by source. Each row carries <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code>. Rows imported from the CSV appear under the file's source as new. An existing table row that nobody touched does not appear at all.</p>
<pre><code class="language-tsx">import type {
  DataEditorResult,
  ResultRow,
} from "@updog/data-editor";

type Reading = {
  siteCode: string;
  sampledOn: string;
  determinand: string;
  valueMgL: string;
  method: string;
  labRef: string;
};

const toRow = (
  entry: ResultRow&#x3C;Reading>,
  n: number,
) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];

  return [{
    n,
    site_code: entry.row.siteCode,
    sampled_on: entry.row.sampledOn,
    determinand: entry.row.determinand,
    value_mg_l: entry.row.valueMgL,
    method: entry.row.method,
    lab_ref: entry.row.labRef,
    deleted: entry.isDeleted,
  }];
};

const onComplete = useCallback(
  async (result: DataEditorResult&#x3C;Reading>) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .flatMap((entry, index) => toRow(entry, index));

    const conn = await db.connect();

    await db.registerFileText(
      "rows.json",
      JSON.stringify(rows),
    );

    try {
      await conn.query("BEGIN TRANSACTION");

      try {
        await conn.query("DROP TABLE IF EXISTS staging");

        await conn.insertJSONFromPath("rows.json", {
          name: "staging",
        });

        await conn.query(UPSERT_READINGS);
        await conn.query(DELETE_REMOVED);
        await conn.query("COMMIT");
      } catch (error) {
        await conn.query("ROLLBACK");
        throw error;
      }

      await conn.query("CHECKPOINT");
    } finally {
      await db.dropFile("rows.json");
      await conn.close();
    }
  },
  [],
);</code></pre>
<p>The changed rows become one JSON document. <code>registerFileText</code> places it in DuckDB-Wasm's virtual file system, and <code>insertJSONFromPath</code> reads that document into the staging table. DuckDB-Wasm documents this as a two-step import, where the data is registered with the database and then ingested through a connection.</p>
<p>Nothing crosses the network, but the copy is not free. The JSON string lives in the JavaScript heap while DuckDB builds its own representation inside WebAssembly. For this file, 479 rows serialize to 77,756 bytes, or about 162 bytes per row. At the same density, 100,000 changed rows would produce roughly 16 MB of JSON before accounting for the grid, JavaScript objects, DuckDB, or temporary allocations.</p>
<p>That matters in a browser. DuckDB-Wasm documents a 4 GB WebAssembly memory ceiling, and a browser may impose a lower limit. A single JSON handover is reasonable for this dataset, and at larger sizes the same boundary may need batching instead.</p>
<p>Errors have to escape the handler as well. Updog Importer waits for the <code>onComplete</code> promise. If the handler catches an error and resolves normally, it has no failure to report. If it rejects, the editor can remain in place with the user's mappings and corrections intact.</p>
<p>The rows stay on screen until DuckDB has accepted them.</p>
<h2 id="duckdb-applies-the-delta">DuckDB applies the delta</h2>
<p>Two statements apply the changes.</p>
<pre><code class="language-ts">const UPSERT_READINGS = `
  INSERT INTO readings
    (site_code, sampled_on, determinand, value_mg_l, method, lab_ref)
  SELECT
    site_code,
    sampled_on::DATE,
    determinand,
    nullif(value_mg_l, '')::DECIMAL(9, 3),
    nullif(method, ''),
    nullif(lab_ref, '')
  FROM staging
  WHERE NOT deleted
  QUALIFY row_number() OVER (
    PARTITION BY site_code, sampled_on, determinand
    ORDER BY n DESC
  ) = 1
  ON CONFLICT (site_code, sampled_on, determinand) DO UPDATE SET
    value_mg_l = excluded.value_mg_l,
    method     = excluded.method,
    lab_ref    = excluded.lab_ref,
    loaded_at  = now();
`;

const DELETE_REMOVED = `
  DELETE FROM readings
  WHERE (site_code, sampled_on, determinand) IN (
    SELECT
      site_code,
      sampled_on::DATE,
      determinand
    FROM staging
    WHERE deleted
  );
`;</code></pre>
<p><code>nullif(value_mg_l, '')</code> turns an empty editor value into <code>NULL</code> before the decimal cast. Without it, an empty string cannot be converted to <code>DECIMAL(9, 3)</code> and the statement fails. The same conversion stores an empty <code>method</code> or <code>lab_ref</code> as <code>NULL</code> rather than as an empty string. DuckDB treats <code>NULL</code> as missing data, and most aggregates ignore it.</p>
<p>The <code>QUALIFY</code> clause handles duplicate keys inside the submitted delta. If several staged rows identify the same site, day, and determinand, only the last one survives into the upsert. <code>ON CONFLICT</code> then inserts a new reading or updates the existing row with the same primary key.</p>
<p>The upsert and delete run inside one transaction. If either statement fails, neither change remains. There is no application-level upload protocol or partial batch state to reconcile, since the browser hands DuckDB one staged delta and DuckDB applies it atomically. <code>CHECKPOINT</code> runs after the commit to synchronize the write-ahead log with the database file in OPFS.</p>
<p><code>loaded_at</code> uses <code>now()</code> deliberately. DuckDB supports <code>current_timestamp</code>, but inside <code>ON CONFLICT ... DO UPDATE</code> it binds the bare keyword against the target table and answers <code>Binder Error: Table "readings" does not have a column named "current_timestamp"</code>. <code>now()</code> avoids that ambiguity.</p>
<h2 id="deduplicate-before-on-conflict">Deduplicate before ON CONFLICT</h2>
<p>The lab reissued one nitrate result and left both rows in the file. Updog Importer keeps both. Primary-key matching runs against rows from other sources, so two rows of one file never merge into each other and both reach the staging table.</p>
<p>What happens next is less obvious.</p>
<p>On DuckDB 1.5.5 through the Node client, and again on 1.4.3 in DuckDB-Wasm, this statement runs without error.</p>
<pre><code class="language-sql">INSERT INTO readings
VALUES (key, 6.310), (key, 6.900)
ON CONFLICT (key) DO UPDATE
SET value_mg_l = excluded.value_mg_l;</code></pre>
<p>The table keeps the first of the two values.</p>
<pre><code class="language-text">readings holds  6.310</code></pre>
<p>Reverse the two input rows and <code>6.900</code> remains. In these tests, the first row for a key won and later rows with the same key inside the statement had no effect. Run the rows as separate statements and the second update wins instead. With <code>DO NOTHING</code>, the first row wins. Without <code>ON CONFLICT</code>, the duplicate key raises a constraint error.</p>
<p>Treat this behavior as an observation rather than as part of the contract. DuckDB's current documentation contains an <code>ON CONFLICT DO UPDATE</code> example with two input rows sharing the same key, but does not state which result should remain. An older report, issue #8147, shows DuckDB 0.8.2-dev rejecting duplicate keys inside one statement and describes that behavior as a known limitation at the time.</p>
<p>The safe rule is simpler. Do not make <code>ON CONFLICT</code> resolve duplicates inside the incoming batch.</p>
<p>The staging query does that first.</p>
<pre><code class="language-sql">QUALIFY row_number() OVER (
  PARTITION BY site_code, sampled_on, determinand
  ORDER BY n DESC
) = 1</code></pre>
<p><code>n</code> preserves the submitted row order. For each key, the row with the highest <code>n</code> reaches the upsert. The conflict clause then has only one incoming row to compare with the table.</p>
<p>The same staging table can expose the collisions before anything is written.</p>
<pre><code class="language-sql">SELECT
  site_code,
  sampled_on,
  determinand,
  count(*) AS rows
FROM staging
GROUP BY
  site_code,
  sampled_on,
  determinand
HAVING count(*) > 1;</code></pre>
<p>That gives the application the duplicate keys directly. It can resolve them automatically, or show them to the person reviewing the import.</p>
<h2 id="the-browser-sets-the-limit">The browser sets the limit</h2>
<p>Updog Importer does not ship a DuckDB connector. There is no destination to select and no webhook to configure. <code>onComplete</code> returns the edited rows to your code, and the SQL between that callback and DuckDB belongs to the application.</p>
<p>Keeping the whole path in the browser also puts the browser's limits on it. DuckDB-Wasm has at most 4 GB of WebAssembly memory, and browsers may impose a lower ceiling. It runs queries on a single thread by default, and multithreading is available through the cross-origin-isolated build but remains experimental.</p>
<p>Updog Importer has its own memory cost. The grid can hold roughly a million rows, while the imported rows, existing rows returned by <code>loadData</code>, and the JSON used for the handover all consume browser memory. Loading an entire <code>readings</code> table therefore stops making sense long before the table itself has to stop growing.</p>
<p>Load only what the person needs to edit. If they are correcting one catchment for one season, put that condition in <code>loadData</code>. DuckDB can keep years of readings while the editor opens only the relevant slice.</p>
<p>The other case does not need an importer at all. If your own system already has a clean CSV and nobody needs to inspect or correct it, DuckDB can infer the dialect and types with its CSV reader and insert the result directly into a table. Native DuckDB can also spill intermediate data to a temporary directory when grouping, joining, sorting, or windowing exceeds available memory.</p>
<p>Use Updog Importer where a person has to resolve the file before it becomes table data. Use DuckDB directly where the file is already trusted.</p>
<p><a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> separates the workloads that fit each model. <a href="https://updog.tech/blog/browser-first-csv-import/">A different way to think about CSV import</a> explains why the browser can be the right boundary when the file needs human review.</p>
<h2 id="the-next-export-uses-the-same-path">The next export uses the same path</h2>
<p>The integration comes to one DuckDB table, six Updog Importer columns, two synonym maps, one read query, one submit handler, and two write statements. There is no upload endpoint between the CSV and the database. Updog Importer and DuckDB already run in the browser, and <code>onComplete</code> is the boundary between them.</p>
<p>The same path works through the <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> component or the web component build. Only the host UI changes.</p>
<p>In April, the lab sends another export. Some March readings appear again with corrected results. The chemical codes already have mappings. If the file contains the same key twice, the staging query resolves it before the upsert. The rest follows the same path of inspect, correct, submit, and commit.</p>
<p>The next CSV is not a new integration. It is new data.</p>]]></content:encoded></item>
<item><title>Add CSV and Excel Import to a Lovable App</title><link>https://updog.tech/blog/add-csv-and-excel-import-to-a-lovable-app/</link><guid isPermaLink="true">https://updog.tech/blog/add-csv-and-excel-import-to-a-lovable-app/</guid><pubDate>Tue, 25 Aug 2026 00:00:00 GMT</pubDate><description>An account list arrives from whatever system the customer used before. See how Updog Importer brings that file into an app built on Lovable.</description><content:encoded><![CDATA[<p>Lovable turns a prompt into a working application with a frontend and a database. Once that app has customers, some of their data already lives elsewhere. A customer may have hundreds of accounts in a CSV or Excel file and need those rows inside your accounts table.</p>
<p>This guide adds that path with Updog Importer. The example is a CRM with an accounts page and an empty accounts table in Lovable Cloud.</p>
<p>You get there two ways. The agent builds an import screen for you, or the agent installs one.</p>
<h2 id="lovable-already-reads-files-in-chat">Lovable already reads files in chat</h2>
<p>Drop a CSV or a spreadsheet into the chat and Lovable turns it into database tables, up to 20 MB each on the free plan, 256 MB on a paid one and 1 GB on Enterprise.</p>
<p>That workflow serves the person building the app. It is useful for files you already have while you create or administer the project.</p>
<p>The import screen serves the customers of the finished app. They open it from the accounts page, bring files you have never seen, review the rows, and write the accepted data into the accounts table.</p>
<h2 id="the-app-already-has-an-accounts-table">The app already has an accounts table</h2>
<p>The CRM in this guide starts from one Lovable prompt.</p>
<pre><code class="language-text">Build a small CRM with one page. Use Lovable Cloud for the database.

Create a table named accounts with these columns.
  account_ref      text, unique, not null
  account_name     text, not null
  website          text
  tier             text
  seats            integer
  renewal_date     date
  region           text
  primary_contact  text
  contact_email    text
Leave the table empty.

Render /accounts as a table of every row with those nine columns, the row count
above it, and an empty state while the table holds nothing. Redirect / to
/accounts. Keep the styling plain and give the app one primary color.</code></pre>
<p>Lovable enables Cloud from the prompt, creates the accounts table with those nine columns, and renders the accounts page. The table starts empty.</p>
<h2 id="the-file-brings-its-own-schema">The file brings its own schema</h2>
<p>The customer's file uses a schema your app does not control. Its headers may not match your field names, its dates may use another format, and its values may not match the options your fields accept.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>The screen has to</th>
<th>Because the file</th>
</tr>
</thead>
<tbody>
<tr>
<td>detect encoding and delimiter</td>
<td>arrives as UTF-8, Windows-1252, comma or semicolon</td>
</tr>
<tr>
<td>find the header row</td>
<td>carries a title and an export date above it</td>
</tr>
<tr>
<td>read every sheet of a workbook</td>
<td>is <code>.xlsx</code> with three tabs</td>
</tr>
<tr>
<td>settle the date order per column</td>
<td>writes <code>04/11/2026</code> and means the fourth of November</td>
</tr>
<tr>
<td>keep leading zeros</td>
<td>holds <code>00417</code>, which Excel already turned into <code>417</code></td>
</tr>
<tr>
<td>match headers onto your fields</td>
<td>says <code>Company name</code> where your app says <code>accountName</code></td>
</tr>
<tr>
<td>match values onto your options</td>
<td>says <code>Enterprise plan</code> where your app says <code>Enterprise</code></td>
</tr>
<tr>
<td>check and let the person fix</td>
<td>holds a row your database will reject</td>
</tr>
<tr>
<td>stay usable at scale</td>
<td>is a hundred thousand rows on a laptop</td>
</tr>
<tr>
<td>report new, changed and deleted rows</td>
<td>is the second import of a file that landed once already</td>
</tr>
</tbody>
</table></div>
<p>Each row in that table needs an implementation rule. Written as a prompt, with the schema on top and a screen for each stage, it reads like this.</p>
<pre><code class="language-text">Build a CSV and Excel import screen for the accounts page. A button on that
page opens it as a modal wizard, our customers walk that wizard with the files
their old CRM produced, and it leaves them in a spreadsheet where they clean
what came in.

The schema it works from
- Take the fields from a list my code hands it, so the same screen serves the
  accounts page today and any other page later.
- Support a field of text, number, date, time, or a list of options we allow,
  and let one field carry several rules at once.
- Support required, a pattern, a range, uniqueness inside the file, and
  uniqueness against the records we already store.
- Show the person our title for a field, and hand my code back its name.
- Take one field as the key, so a second import of the same records finds them
  and updates them.
- Drop the columns a file carries beyond the schema.

Screen 1, the files
- Take several files at once, by drop or by dialog, and show a card per file.
- Detect the encoding, strip a byte order mark, and read a Windows-1252
  file without turning accented letters into question marks.
- Detect the delimiter. Commas, semicolons, tabs and pipes all arrive.
- Drop a first line shaped sep=; that Excel writes for some locales.
- Read .xlsx, .xls and .ods, open a workbook as one card per sheet, and let
  the person choose which sheets go on.
- Find the real header row when title rows sit above it, and handle a file
  that carries duplicate headers or no header at all.
- Keep a row that carries one field too few, and say which fields it filled.

Reading the values
- Settle the date order per column, so 04/11/2026 does not become April.
- Read 1.240,50 and 1,240.50 as the same number.
- Keep 00417 as text, including a code Excel already turned into 417.
- Tell an empty cell apart from a cell holding the word null.

Screen 2, the columns
- Map the file's headers onto the schema's fields, one field per column.
- Match the obvious ones on arrival, and show the person which of our fields
  reached nothing so they can point each one at a column by hand.
- Show a few values under every header, so the person tells two similar
  columns apart.
- Remember the pairs the person confirmed, so the next file of that shape
  arrives matched.

Screen 3, the values
- Collect the distinct values of every list field as the file spells them.
- Match each one to an option we allow, and let the person place the rest.

Data cleaning
- Hand the finished file to a spreadsheet the person works in, with our field
  titles on top and every row in it.
- Mark what the person changed. A new row, an edited cell and a deleted row
  each read differently at a glance.
- Run every rule the schema carries, and say which cell failed and why.
- Let the person fix a cell in place, with the editor that fits the field. A
  date opens a calendar, a list opens its options, a number takes digits.
- Sort and filter, so the person reaches the failing rows among the hundred
  thousand that pass.
- Copy and paste blocks between it and Excel or Google Sheets, and undo an
  edit.
- Stay smooth at a hundred thousand rows, with the reading off the main
  thread so the tab keeps responding.

Submitting
- Tell me which rows are new, which changed, and which were deleted.
- Keep every row and every mapping on screen when my write to the database
  fails.</code></pre>
<p>Each rule expands once real files arrive. Date parsing alone has to distinguish written date orders, spreadsheet serial dates, and columns whose values remain ambiguous.</p>
<p><a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> walks a few of those categories.</p>
<p>If you build the importer yourself, every rule in the prompt becomes application code you own. That code has to keep working when later files use different encodings, headers, values, dates, or workbook layouts.</p>
<p>The second approach gives those file-facing rules to an importer package.</p>
<h2 id="the-second-prompt-installs-the-importer">The second prompt installs the importer</h2>
<pre><code class="language-text">Add a spreadsheet import screen to the accounts page with the npm package
@updog/data-editor. Read https://updog.tech/updog.md and
https://docs.updog.tech first, and use only props documented there.

1. Install @updog/data-editor and import "@updog/data-editor/styles.css".
2. Render &#x3C;DataEditor /> with apiKey="updog-lovable-demo", which is all the
   key a lovable.app host needs, variant="uploader", primaryKey="accountRef"
   and these columns:
   accountRef (text, required, unique), accountName (text, required),
   website (text), tier (select: Starter, Growth, Enterprise),
   seats (number), renewalDate (date), region (select: EMEA, AMER, APAC),
   primaryContact (text), contactEmail (text, email).
3. In a stylesheet loaded after "@updog/data-editor/styles.css", set
   --updog-brand on :root to this app's primary color, written as a plain
   color value.
4. In onComplete, walk result.sources, split each source's rows on isNew,
   isChanged and isDeleted, write them to the accounts table, and close the
   modal once the write returns.
5. Throw from onComplete when that write fails. The editor clears its rows
   as soon as onComplete resolves, so a swallowed error loses the import.
6. Do not build an uploader of your own, do not parse the file yourself,
   and do not invent props.</code></pre>
<p>Lovable can add public npm packages from chat. There is no terminal step and no <code>package.json</code> to edit, which keeps the second prompt short. Updog Importer ships as a React component and a stylesheet, so the agent can install the dependency and mount the importer inside the app it already generated.</p>
<p>The package is still third-party code. Lovable's documentation warns that a package built for another environment installs without an error and then does nothing in the published app, so testing what you install stays part of your application work.</p>
<h2 id="the-importer-mirrors-the-accounts-table">The importer mirrors the accounts table</h2>
<p>The nine accounts fields become nine importer columns. Each column points to one field through its <code>id</code>, while <code>title</code> gives the customer the name shown in the grid.</p>
<pre><code class="language-tsx">import {
  DataEditor,
  type DataEditorColumn,
  type DataEditorResult,
} from "@updog/data-editor";
import "@updog/data-editor/styles.css";

type Account = {
  accountRef: string;
  accountName: string;
  website: string;
  tier: string;
  seats: string;
  renewalDate: string;
  region: string;
  primaryContact: string;
  contactEmail: string;
};

const columns: DataEditorColumn[] = [
  {
    id: "accountRef",
    title: "Account ref",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "accountName",
    title: "Account name",
    validators: [{ type: "required" }],
  },
  {
    id: "website",
    title: "Website",
  },
  {
    id: "tier",
    title: "Tier",
    editor: {
      type: "select",
      options: ["Starter", "Growth", "Enterprise"],
      enableCustomValue: false,
    },
  },
  {
    id: "seats",
    title: "Seats",
    editor: { type: "number" },
  },
  {
    id: "renewalDate",
    title: "Renewal date",
    editor: { type: "date" },
  },
  {
    id: "region",
    title: "Region",
    editor: {
      type: "select",
      options: ["EMEA", "AMER", "APAC"],
      enableCustomValue: false,
    },
  },
  {
    id: "primaryContact",
    title: "Primary contact",
  },
  {
    id: "contactEmail",
    title: "Contact email",
    validators: [{ type: "email" }],
  },
];</code></pre>
<p><code>accountRef</code> identifies an account inside the editor. The database stores the same value as <code>account_ref</code> and enforces its own unique constraint there. The two rules solve related problems at different boundaries.</p>
<h2 id="the-page-mounts-the-importer">The page mounts the importer</h2>
<p><code>primaryKey</code> names the column that identifies a row. A second import of a corrected file matches on that column and updates the row it finds. The editor renders wherever the accounts page opens it.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Account>
  apiKey="updog-lovable-demo"
  variant="uploader"
  open={open}
  onClose={() => {
    setOpen(false);
  }}
  columns={columns}
  primaryKey="accountRef"
  onComplete={handleComplete}
/></code></pre>
<p>The editor also inherits the app's primary color through <code>--updog-brand</code>.</p>
<pre><code class="language-css">/* loaded after @updog/data-editor/styles.css */
:root {
  --updog-brand: #0f172b;
}</code></pre>
<p><a href="https://updog.tech/blog/style-updog-to-match-your-product/">Match the importer to your product</a> takes the theming further, through typography, the grid, shadows and a dark theme.</p>
<h2 id="the-file-uses-another-systems-vocabulary">The file uses another system's vocabulary</h2>
<p>The export carries 180 accounts out of the customer's old system, on one sheet of a workbook.</p>
<p><code>calderbrook-accounts.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Account ref</td><td class="sheet__cell">Company name</td><td class="sheet__cell">Website URL</td><td class="sheet__cell">Subscription tier</td><td class="sheet__cell">Seats</td><td class="sheet__cell">Renewal date</td><td class="sheet__cell">Region</td><td class="sheet__cell">Main contact</td><td class="sheet__cell">Contact email</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">CB-0001</td><td class="sheet__cell">Alverston Analytics Ltd</td><td class="sheet__cell">alverstonanaly.example</td><td class="sheet__cell">Starter</td><td class="sheet__cell">310</td><td class="sheet__cell">2027-02-13</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Adela Ashgrove</td><td class="sheet__cell">adela.ashgrove@alverstonanaly.example</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">CB-0002</td><td class="sheet__cell">Bramfield Instruments GmbH</td><td class="sheet__cell">bramfieldinstr.example</td><td class="sheet__cell">Enterprise</td><td class="sheet__cell">306</td><td class="sheet__cell">2027-04-27</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Delphine Lymington</td><td class="sheet__cell">delphine.lymington@bramfieldinstr.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">CB-0007</td><td class="sheet__cell">Garsdale Networks Ltd</td><td class="sheet__cell">garsdalenetwor.example</td><td class="sheet__cell">Growth</td><td class="sheet__cell">273</td><td class="sheet__cell">2026-10-31</td><td class="sheet__cell">APAC</td><td class="sheet__cell">Corin Crandale</td><td class="sheet__cell">corin.crandale@garsdalenetwor.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">6 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">15</th><td class="sheet__cell">CB-0014</td><td class="sheet__cell">Northwold Optics GmbH</td><td class="sheet__cell">northwoldoptic.example</td><td class="sheet__cell">Starter</td><td class="sheet__cell">651</td><td class="sheet__cell">2027-04-10</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Halvard Pennington</td><td class="sheet__cell">halvard.pennington@northwoldoptic.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">26 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">42</th><td class="sheet__cell">CB-0041</td><td class="sheet__cell">Ottermill Labs Group</td><td class="sheet__cell">ottermilllabsg.example</td><td class="sheet__cell">Enterprise</td><td class="sheet__cell">4</td><td class="sheet__cell">2027-08-18</td><td class="sheet__cell">EMEA</td><td class="sheet__cell">Isolde Ivenshaw</td><td class="sheet__cell">isolde.ivenshaw@ottermilllabsg.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">34 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">77</th><td class="sheet__cell">CB-0076</td><td class="sheet__cell">Yeadon Systems Holdings</td><td class="sheet__cell">yeadonsystemsh.example</td><td class="sheet__cell">Enterprise</td><td class="sheet__cell">687</td><td class="sheet__cell">2027-07-27</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Bram Jerrold</td><td class="sheet__cell">bram.jerrold@yeadonsystemsh.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">42 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">120</th><td class="sheet__cell">CB-0119</td><td class="sheet__cell">Ottermill Networks Group</td><td class="sheet__cell">ottermillnetwo.example</td><td class="sheet__cell">Growth</td><td class="sheet__cell">130</td><td class="sheet__cell">2027-05-06</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Corin Crandale</td><td class="sheet__cell">corin.crandale@ottermillnetwo.example</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">60 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">181</th><td class="sheet__cell">CB-0180</td><td class="sheet__cell">Yeadon Freight PLC</td><td class="sheet__cell">yeadonfreightp.example</td><td class="sheet__cell">Growth</td><td class="sheet__cell">824</td><td class="sheet__cell">2026-12-05</td><td class="sheet__cell">AMER</td><td class="sheet__cell">Jorin Bellweather</td><td class="sheet__cell">jorin.bellweather@yeadonfreightp.example</td></tr></tbody></table>
<p>Four headers use names that do not appear in the accounts schema.</p>
<pre><code class="language-text">Company name       →  Account name
Website URL        →  Website
Subscription tier  →  Tier
Main contact       →  Primary contact</code></pre>
<p>The matcher resolves all nine headers against the importer schema. <code>Region</code> and <code>Tier</code> carry closed lists, and the value step matches the distinct values of those two columns as well. This export needs no manual mapping, so all 180 rows reach the grid without validation errors.</p>
<p>A file that mixes date formats follows the same path but leaves a decision unresolved before the rows reach the grid.</p>
<p><a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">Parsing dates during import</a> and <a href="https://updog.tech/blog/csv-column-mapping-react/">building a column mapping screen</a> cover those two steps.</p>
<p>The grid holds the parsed rows for review. The customer can filter validation errors, edit cells, undo changes, and paste blocks from a spreadsheet before submit. Submit shows the final row counts, and on this file it read <code>180 new rows will be created</code>.</p>
<h2 id="submit-returns-the-rows-and-their-state">Submit returns the rows and their state</h2>
<p>Submit returns the edited rows grouped by source. Each row carries four independent flags that describe whether it is new, changed, deleted, and valid. Your handler decides what those states mean for the database.</p>
<pre><code class="language-tsx">const handleComplete = async (result: DataEditorResult&#x3C;Account>) => {
  const inserts: AccountRecord[] = [];
  const updates: AccountRecord[] = [];
  const deletes: string[] = [];

  for (const source of result.sources) {
    for (const resultRow of source.rows) {
      const record = toAccountRecord(resultRow.row);

      if (resultRow.isDeleted) {
        if (!resultRow.isNew) deletes.push(record.account_ref);
      } else if (resultRow.isValid &#x26;&#x26; resultRow.isNew) {
        inserts.push(record);
      } else if (resultRow.isValid &#x26;&#x26; resultRow.isChanged) {
        updates.push(record);
      }
    }
  }

  await writeImportedAccounts({ data: { inserts, updates, deletes } });
  setOpen(false);
};</code></pre>
<p><code>toAccountRecord</code> renames each field to its column in the table. A number column hands back text, so <code>seats</code> arrives as <code>"310"</code> and the mapper runs it through <code>Number</code>. A date column hands back ISO, so <code>renewalDate</code> arrives as <code>"2027-02-13"</code>, independent of how the date appeared in the grid.</p>
<p>This is the whole <code>result</code> object from that run, with one of the 180 rows kept.</p>
<pre><code class="language-ts">{
  sources: [
    {
      sourceId: "source_…",
      sourceName: "calderbrook-accounts.xlsx",
      rows: [
        {
          row: {
            accountRef: "CB-0001",
            accountName: "Alverston Analytics Ltd",
            website: "alverstonanaly.example",
            tier: "Starter",
            seats: "310",
            renewalDate: "2027-02-13",
            region: "AMER",
            primaryContact: "Adela Ashgrove",
            contactEmail: "adela.ashgrove@alverstonanaly.example",
          },
          isNew: true,
          isChanged: false,
          isDeleted: false,
          isValid: true,
        },
        // 179 more rows
      ],
    },
  ],
  counts: { new: 180, changed: 0, deleted: 0, invalid: 0 },
  learnedSynonyms: { columns: [], values: [] },
}</code></pre>
<h2 id="the-database-decides-what-a-repeat-import-means">The database decides what a repeat import means</h2>
<p>Lovable Cloud runs on Supabase's foundation, and the code the agent generated reaches it with <code>@supabase/supabase-js</code>. The handler sends the rows to a server function, which writes them with a Supabase upsert.</p>
<pre><code class="language-ts">const upserts = [...data.inserts, ...data.updates];

if (upserts.length > 0) {
  const { error } = await supabaseAdmin
    .from("accounts")
    .upsert(upserts, { onConflict: "account_ref" });

  if (error) throw new Error(`Failed to save accounts: ${error.message}`);
}</code></pre>
<p>The editor state and the database state are separate. On this run every row has <code>isNew: true</code> because the editor opened empty. PostgreSQL can still find the same <code>account_ref</code> in the table and update that record through <code>upsert</code>, so a second pass of the same file leaves the table at 180.</p>
<p><code>isNew</code> means new to the editor. It does not mean absent from the database.</p>
<p>Your application chooses where repeat imports are reconciled. The database can resolve them at write time through the unique key, or <code>loadData</code> can bring stored accounts into the editor so matching happens before submit. Updog Importer supplies the row state and chooses neither policy.</p>
<p>Let write errors reject <code>onComplete</code>. A rejected promise keeps the rows and mappings in the editor. A resolved promise tells Updog Importer that submission finished. Close the modal only after the write succeeds.</p>
<h2 id="the-lovable-url-runs-for-free">The Lovable URL runs for free</h2>
<p>Updog Importer makes one request to its license endpoint when the editor starts. It sends the API key and the page hostname. No rows, headers, or file contents go with it.</p>
<p>Updog keeps a list of development and preview hosts where the importer runs free, with no row counted. Both Lovable suffixes are on it, <code>.lovableproject.com</code> for the editor's own preview and <code>.lovable.app</code> for the URL you open and the one you publish. The prompt can leave the placeholder API key in place while the app runs there.</p>
<p>A custom domain changes that. If the CRM moves to <code>app.yourcompany.com</code>, add that hostname at <a href="https://console.updog.tech/">console.updog.tech</a>. The Free plan covers production domains up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains, with no row limit.</p>
<h2 id="the-app-now-has-an-import-path">The app now has an import path</h2>
<p>Updog Importer installs from the Lovable chat as an npm package. Its columns mirror the accounts table, the customer resolves the file before submit, and <code>onComplete</code> returns the edited rows and their state to your code.</p>
<p>The importer handles the file-facing work: parsing CSV and Excel, matching columns and values, validating cells, and letting the customer correct the data. Your application still decides what those rows mean in the database, including how to handle updates, deletions, and repeat imports.</p>
<p>You can build the same flow yourself. The first prompt in this guide lists what that requires. Installing the package keeps those behaviors inside the importer and leaves the Lovable code focused on the application and its write path.</p>]]></content:encoded></item>
<item><title>How to Map CSV Values to Enums During Import</title><link>https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-map-csv-values-to-enums-during-import/</guid><pubDate>Tue, 25 Aug 2026 00:00:00 GMT</pubDate><description>A file writes its categories in its own words. See how Updog Importer connects them to the options your app holds.</description><content:encoded><![CDATA[<p>A museum writes the status of a loan in the words its registrar uses. The
application behind the register holds four.</p>
<pre><code class="language-text">Requested   Approved   Declined   Returned</code></pre>
<p>One line of this register says <code>Not approved</code>. It imports as <code>Approved</code>.</p>
<p>The characters of <code>Approved</code> sit inside <code>Not approved</code>, and a matcher built on
characters cannot see the word in front of them. The loan was refused,
the row says the loan was granted, and the file gave the importer everything it
needed to get this wrong.</p>
<p>The register lists objects out on loan. One row is one object, and three of its
columns carry a closed list.</p>
<p><code>museum-loan-register.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Object no.</td><td class="sheet__cell">Object title</td><td class="sheet__cell">Lender</td><td class="sheet__cell">Condition</td><td class="sheet__cell">Loan status</td><td class="sheet__cell">Handling notes</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">7 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">MLR-00008</td><td class="sheet__cell">View of a Weaver</td><td class="sheet__cell">Ivelet House</td><td class="sheet__cell">Fragile</td><td class="sheet__cell">Not approved</td><td class="sheet__cell">Crate only</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">14</th><td class="sheet__cell">MLR-00013</td><td class="sheet__cell">Interior of a Standing Figure</td><td class="sheet__cell">Rowan &#x26; Vale Estate</td><td class="sheet__cell">Stable</td><td class="sheet__cell">Rejected</td><td class="sheet__cell">No flash</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">8 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">23</th><td class="sheet__cell">MLR-00022</td><td class="sheet__cell">Study of Two Sisters</td><td class="sheet__cell">Ashgrove Trust</td><td class="sheet__cell">Stable</td><td class="sheet__cell">Denied</td><td class="sheet__cell">No flash; Gloves</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">7 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">31</th><td class="sheet__cell">MLR-00030</td><td class="sheet__cell">Interior of a Weaver</td><td class="sheet__cell">Pellworth Collection</td><td class="sheet__cell">Unstable</td><td class="sheet__cell">RET</td><td class="sheet__cell">Gloves</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">14 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">46</th><td class="sheet__cell">MLR-00045</td><td class="sheet__cell">View of Two Sisters</td><td class="sheet__cell">Pellworth Collection</td><td class="sheet__cell">Un-stable</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Two-person lift</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">20 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">67</th><td class="sheet__cell">MLR-00066</td><td class="sheet__cell">Sketch of Two Sisters</td><td class="sheet__cell">Halstow Foundation</td><td class="sheet__cell">In treatment</td><td class="sheet__cell">Returned</td><td class="sheet__cell">No flash</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">27 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">95</th><td class="sheet__cell">MLR-00094</td><td class="sheet__cell">Sketch of the Old Mill</td><td class="sheet__cell">Pellworth Collection</td><td class="sheet__cell">Fragile</td><td class="sheet__cell">Returned</td><td class="sheet__cell">Gloves; flash</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">22 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">118</th><td class="sheet__cell">MLR-00117</td><td class="sheet__cell">View of a Harbour</td><td class="sheet__cell">Halstow Foundation</td><td class="sheet__cell">Fragile</td><td class="sheet__cell">Returned</td><td class="sheet__cell">Gloves; no photography</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">23 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">142</th><td class="sheet__cell">MLR-00141</td><td class="sheet__cell">View of a Winter Field</td><td class="sheet__cell">Marden Bequest</td><td class="sheet__cell">Fragile</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Gloves; Keep upright</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">44 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">187</th><td class="sheet__cell">MLR-00186</td><td class="sheet__cell">Study of a Reading Room</td><td class="sheet__cell">Marden Bequest</td><td class="sheet__cell">Under treatment</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Crate only</td></tr></tbody></table>
<p>Line 9 writes its status as <code>Not approved</code> and line 14 writes <code>Rejected</code>.
Line 23 writes <code>Denied</code>, line 31 writes <code>RET</code>. Line 46 hyphenates its condition
as <code>Un-stable</code> and line 67 shortens it to <code>In treatment</code>. Three handling cells
carry a second instruction the list has no option for, on lines 95, 118 and 142.</p>
<h2 id="what-the-importer-decides">What the importer decides</h2>
<p>The register holds 186 rows over six columns. <code>Condition</code>, <code>Loan status</code> and
<code>Handling notes</code> map onto option lists, which puts 558 cells in front of the
matcher.</p>
<p>Updog Importer collects the distinct values of each of those columns and decides
each one once. <code>Condition</code> holds 6 distinct values, <code>Loan status</code> holds 8, and
<code>Handling notes</code> splits into 7 tokens. The whole file comes down to 21
decisions, and one of them settles the 111 rows reading <code>Stable</code>.</p>
<p>Updog Importer merges the distinct values of every file in one upload, so a
decision made here holds for every row carrying that value anywhere in the
batch. Header matching works the other way. It solves a board of headers against
fields all at once, and <a href="https://updog.tech/blog/csv-column-mapping-react/">the column step</a> is
where that happens.</p>
<p>Values reach the screen as the file wrote them. <code>Un-stable</code> on line 46 and the
<code>Unstable</code> on line 31 hold two of the six rows the condition column draws, and
they land on the same option. The screen asks for the work twice.</p>
<p><code>Handling notes</code> writes two instructions into one cell. Updog Importer tries a
comma, a semicolon, a pipe, a newline and a tab against the column and keeps the
one splitting the most cells into known options. This file settles on the
semicolon, and its 19 distinct cells become 7 tokens. The <code>delimiter</code> prop on
the column fixes the character when you already know it.</p>
<h2 id="how-a-value-finds-an-option">How a value finds an option</h2>
<p>Updog Importer normalizes a value before it compares it. It lowercases the
string and drops whitespace, underscores, hyphens and dots. <code>Un-stable</code> becomes
<code>unstable</code>, which is the whole reason line 46 lands on the right option. Digits,
accents and every other punctuation mark stay.</p>
<p>Then it scores the value against each option and keeps the highest. Five
tiers can produce a winning score.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Score</th>
<th>What matched</th>
</tr>
</thead>
<tbody>
<tr>
<td>100</td>
<td>the two normalized strings are equal</td>
</tr>
<tr>
<td>90</td>
<td>both strings sit in one synonym group</td>
</tr>
<tr>
<td>80</td>
<td>one normalized string contains the other, and the shorter one runs to four characters</td>
</tr>
<tr>
<td>70</td>
<td>the two share half of their words</td>
</tr>
<tr>
<td>65</td>
<td>the two sit within the edit budget</td>
</tr>
</tbody>
</table></div>
<p>The word tier reads the original text, splitting it on those same characters
and comparing whole words. The other four read the normalized form.</p>
<p>The edit budget grows with the longer string. One edit up to four characters,
two up to eight, three up to fifteen, four beyond that. The winning option has
to reach 60, so a value scoring under that reaches no option at all.</p>
<p>The synonym tier carries a vocabulary the SDK ships with, covering gender,
seniority, employment type, status, marital status, priority and yes or no.
<code>Y</code> and <code>TRUE</code> reach an option named <code>Yes</code> on that tier. A column coded <code>1</code> and
<code>0</code> reaches nothing, because a bare digit shares no characters, no words and no
synonym group with <code>Yes</code> or <code>No</code>.</p>
<p>Three of the five tiers can put a value on an option nobody wrote.</p>
<h2 id="where-a-tier-lands-on-the-wrong-option">Where a tier lands on the wrong option</h2>
<p>The register writes nine values outside its option lists. Each one is scored
against its own column.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Value</th>
<th>Column</th>
<th>Rows</th>
<th>Score</th>
<th>Lands on</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Un-stable</code></td>
<td>Condition</td>
<td>1</td>
<td>100</td>
<td><code>Unstable</code></td>
</tr>
<tr>
<td><code>In treatment</code></td>
<td>Condition</td>
<td>1</td>
<td>70</td>
<td><code>Under treatment</code></td>
</tr>
<tr>
<td><code>Not approved</code></td>
<td>Loan status</td>
<td>1</td>
<td>80</td>
<td><code>Approved</code></td>
</tr>
<tr>
<td><code>Rejected</code></td>
<td>Loan status</td>
<td>1</td>
<td>65</td>
<td><code>Requested</code></td>
</tr>
<tr>
<td><code>Denied</code></td>
<td>Loan status</td>
<td>1</td>
<td>0</td>
<td>nothing</td>
</tr>
<tr>
<td><code>RET</code></td>
<td>Loan status</td>
<td>1</td>
<td>0</td>
<td>nothing</td>
</tr>
<tr>
<td><code>flash</code></td>
<td>Handling</td>
<td>1</td>
<td>80</td>
<td><code>No flash</code></td>
</tr>
<tr>
<td><code>no photography</code></td>
<td>Handling</td>
<td>1</td>
<td>70</td>
<td><code>No flash</code></td>
</tr>
<tr>
<td><code>Keep upright</code></td>
<td>Handling</td>
<td>1</td>
<td>0</td>
<td>nothing</td>
</tr>
</tbody>
</table></div>
<p>Two of the nine land where a registrar would put them. Three reach nothing.
Four land on an option this file never meant.</p>
<p><code>Not approved</code> and <code>flash</code> fail the same way. The option contains the value or
the value contains the option, and containment holds no opinion about the <code>not</code>
and the <code>no</code> in front. <code>Rejected</code> and <code>Requested</code> are two real words three edits
apart, which is inside the budget for a string of that length. <code>no photography</code>
shares the word <code>no</code> with <code>No flash</code>, and one word out of two is half.</p>
<p><code>Denied</code> and <code>Keep upright</code> share no word with any option and sit outside the
edit budget, and <code>RET</code> is three characters, one short of the floor the
containment tier holds.</p>
<p>None of this is a parsing failure. Every one of those nine values is a
suggestion the matcher can defend, and four of them are wrong about the world.</p>
<h2 id="what-lands-in-the-row">What lands in the row</h2>
<p>Run those lines through the import and read what the row holds.</p>
<pre><code class="language-text">line 9     file  Not approved             row  loanStatus "Approved"
line 14    file  Rejected                 row  loanStatus "Requested"
line 23    file  Denied                   row  loanStatus ""
line 31    file  RET                      row  loanStatus ""
line 95    file  Gloves; flash            row  handling ["Gloves", "No flash"]
line 118   file  Gloves; no photography   row  handling ["Gloves", "No flash"]
line 142   file  Gloves; Keep upright     row  handling ["Gloves"]</code></pre>
<p>Updog Importer writes a select value to the row only when it maps. Lines 23 and
31 leave the cell empty, and every built-in rule except <code>required</code> passes an
empty value, so <code>oneOf</code> on its own says yes to a loan with no status. The
employee import carries
<a href="https://updog.tech/blog/how-to-import-employees-from-csv-and-excel/">the same gap</a>, and
<code>required</code> turns it into a row somebody has to fix.</p>
<p>A multiselect cell splits into tokens and each token maps on its own. Line 142
holds two instructions and arrives with one, and the array around it stays
non-empty, so a rule that reads the cell finds one good option and reports
nothing. Line 118 arrives with an instruction about flash photography that the
file never carried.</p>
<h2 id="what-you-declare">What you declare</h2>
<p>Three columns declare their lists, and the two select columns close them.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const CONDITION = ["Stable", "Unstable", "Fragile", "Under treatment"];
const STATUS = ["Requested", "Approved", "Declined", "Returned"];
const HANDLING = ["Gloves", "Two-person lift", "No flash", "Crate only"];

export const columns: DataEditorColumn[] = [
  { id: "objectRef", title: "Object reference", validators: [{ type: "required" }] },
  { id: "title", title: "Title" },
  { id: "lender", title: "Lender" },
  {
    id: "condition",
    title: "Condition",
    editor: { type: "select", options: CONDITION, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: CONDITION }],
  },
  {
    id: "loanStatus",
    title: "Loan status",
    editor: { type: "select", options: STATUS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: STATUS }],
  },
  {
    id: "handling",
    title: "Handling",
    editor: { type: "multiselect", options: HANDLING, delimiter: ";" },
  },
];</code></pre>
<p><code>enableCustomValue: false</code> makes the column a strict list, so the person maps
every off-list value to an existing option and creates none. Leaving it at its
default lets them create an option for a value the list is missing, which is the
right setting for a vocabulary you expect to grow. <code>oneOf</code> checks membership,
<code>required</code> catches the empty cell, and <code>delimiter: ";"</code> fixes the splitting
character on the handling column.</p>
<p>None of that repairs <code>Not approved</code>. The <code>synonyms</code> prop does, by putting the
register's vocabulary on the synonym tier at 90, above the containment tier that
was getting it wrong.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey="objectRef"
  synonyms={{
    values: {
      Declined: ["Not approved", "Denied", "Rejected"],
      Returned: ["RET"],
    },
  }}
  onComplete={handleComplete}
/></code></pre>
<pre><code class="language-text">              before          after
Not approved  Approved        Declined
Rejected      Requested       Declined
Denied        nothing         Declined
RET           nothing         Returned</code></pre>
<p>The <code>values</code> table feeds option matching and the <code>columns</code> table feeds header
matching, and the two stay apart, so an alias learned inside a dropdown never
competes for a column. Every entry you add merges with the built-in vocabulary.</p>
<p>Once the person has settled the values, the row is ready for a database holding
the same list. A <a href="https://updog.tech/blog/import-csv-into-postgresql/">PostgreSQL enum type</a>
rejects what the browser let through, and settling those four values here keeps
that rejection from arriving after the person has closed the tab.</p>
<h2 id="what-the-person-sees">What the person sees</h2>
<p>The match step draws one row per distinct value. The imported text sits on the
left, and a dropdown of the column's options sits on the right holding the
proposal. This register builds 21 of those rows.</p>
<p>A row reaching no option is marked, and its icon carries a warning. A row
holding a proposal is drawn the same way whatever tier produced it, so the
<code>Not approved</code> row and the <code>Stable</code> row look alike. The score stays inside the
matcher.</p>
<p>A column opens closed once every one of its values has found an option.
Condition does that here, because all six of its values landed somewhere. Loan
status and Handling open on the strength of the three values that reached
nothing, which puts 15 of the 21 rows on screen. A column whose wrong proposals
all scored above 60 hides itself the same way, and <code>Not approved</code> is on screen
only because two of the values beside it failed.</p>
<p>Rows with a proposal are visible inside an open column, and the person can hide
them and work the unmatched list alone. Above 500 distinct values in one column,
the step draws three rows, says how many the column holds, and puts the rest
behind a drawer. That many distinct values in a dropdown column points at a
column of free text that reached the wrong field.</p>
<p>Every correction that changes the machine's answer comes back through
<code>onComplete</code> under <code>learnedSynonyms</code>, as a source and a target. Group them by
target, feed them in through <code>synonyms</code> on the next mount, and the register maps
itself the second time.</p>
<h2 id="where-matching-stops">Where matching stops</h2>
<p>No tier reads meaning. <code>Not approved</code> scores 80 against <code>Approved</code> because those
characters are there, and a matcher built on characters will keep saying so. The same holds for every option list carrying a word and its negation, and
for two options sitting inside each other's edit budget.</p>
<p>An importer can propose, show the proposal, and make it one click to change.
Everything past that needs the vocabulary in the <code>synonyms</code> table, or a person
on the screen, or your own <code>onValueMatch</code> deciding the column with knowledge the
file does not carry.</p>
<p>Line 9 of this register sits one dropdown away from the truth. It reaches the
person as a finished proposal, and they are the only reader who knows the loan
was refused.</p>]]></content:encoded></item>
<item><title>How to Import Product Catalogs from CSV and Excel</title><link>https://updog.tech/blog/how-to-import-product-catalogs-from-csv-and-excel/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-product-catalogs-from-csv-and-excel/</guid><pubDate>Mon, 24 Aug 2026 00:00:00 GMT</pubDate><description>A catalog row holds a product and one of its variants, and the file never says which is which. See how Updog Importer gets both out.</description><content:encoded><![CDATA[<p>A catalog row carries a product, a variant of that product, and the SKU that
names the variant.</p>
<p>Some cells hold the same value down a run of rows, the coffee name and the
origin and the roast. The bag size, the grind and the price change on every
line. Those repeating cells describe the product, the changing ones describe the
variant, and the file draws no line between them.</p>
<p>The SKU is the only one of the three the file names outright. The product gets
spelled out again on every row it owns, and it arrives with no id of its own.
You decide first where that id comes from, and every product row you write
follows from it.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>Marchmont Roastery sells wholesale in the United Kingdom, the euro area and
Czechia, and prices each market in its own currency. Their catalog reaches
your distributor app as one export.</p>
<p><code>marchmont-wholesale.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Product</td><td class="sheet__cell">Origin</td><td class="sheet__cell">Roast</td><td class="sheet__cell">SKU</td><td class="sheet__cell">Size</td><td class="sheet__cell">Grind</td><td class="sheet__cell">Unit price</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">Ndaro Peaberry</td><td class="sheet__cell">Kenya</td><td class="sheet__cell">Medium</td><td class="sheet__cell">MR-NDA-250-WB</td><td class="sheet__cell">250g</td><td class="sheet__cell">Whole bean</td><td class="sheet__cell">£16.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">Ndaro Peaberry</td><td class="sheet__cell">Kenya</td><td class="sheet__cell">Medium</td><td class="sheet__cell">MR-NDA-1KG-WB</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Whole bean</td><td class="sheet__cell">£52.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">Ndaro Peaberry</td><td class="sheet__cell">Kenya</td><td class="sheet__cell">Med</td><td class="sheet__cell">MR-NDA-1KG-FL</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Filter</td><td class="sheet__cell">£52.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">Ndaro Peaberry</td><td class="sheet__cell">Kenya</td><td class="sheet__cell">Medium</td><td class="sheet__cell">MR-NDA-5KG-WB</td><td class="sheet__cell">5kg</td><td class="sheet__cell"></td><td class="sheet__cell">£240.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">Marchmont Ndaro</td><td class="sheet__cell">Kenya</td><td class="sheet__cell">Medium</td><td class="sheet__cell">MR-NDA-250-ES</td><td class="sheet__cell">250g</td><td class="sheet__cell">Espresso</td><td class="sheet__cell">£16.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">Sela Wash</td><td class="sheet__cell">Ethiopia</td><td class="sheet__cell">Light</td><td class="sheet__cell">MR-SEL-250-WB</td><td class="sheet__cell">250g</td><td class="sheet__cell">Whole bean</td><td class="sheet__cell">18,50 EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">Sela Wash</td><td class="sheet__cell">Ethiopia</td><td class="sheet__cell">Light</td><td class="sheet__cell">MR-SEL-1KG-WB</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Whole bean</td><td class="sheet__cell">58,00 EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">Sela Wash</td><td class="sheet__cell">Ethiopia</td><td class="sheet__cell">Light</td><td class="sheet__cell">MR-SEL-1KG-FL</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Filter</td><td class="sheet__cell">58,00 EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">Cerro Alto</td><td class="sheet__cell">Colombia</td><td class="sheet__cell">Medium-Dark</td><td class="sheet__cell">MR-CER-250-WB</td><td class="sheet__cell">250g</td><td class="sheet__cell">Whole bean</td><td class="sheet__cell">1 250,00 CZK</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">Cerro Alto</td><td class="sheet__cell">Colombia</td><td class="sheet__cell">Medium-Dark</td><td class="sheet__cell">MR-CER-1KG-ES</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Espresso</td><td class="sheet__cell">4 100,00 CZK</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell">Tarn Hollow Blend</td><td class="sheet__cell">Blend</td><td class="sheet__cell">Dark</td><td class="sheet__cell">MR-TAR-1KG-ES</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Espresso</td><td class="sheet__cell">£49.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">Tarn Hollow Blend</td><td class="sheet__cell">Blend</td><td class="sheet__cell">Dark</td><td class="sheet__cell">MR-TAR-1KG-ES</td><td class="sheet__cell">1kg</td><td class="sheet__cell">Espresso</td><td class="sheet__cell">£49.00</td></tr></tbody></table>
<p>Four coffees fill these twelve rows. Ndaro Peaberry takes five of them, one per
bag size and grind, and writes its name, origin and roast out again on every
one. The SKU changes on each row, so it names a single bag. No column marks
those five rows as one coffee.</p>
<p>Shopify tells merchants to fill every field on the first row, then repeat the
URL handle below it and "skip the Title, Description, Vendor, and Tags columns",
so the handle carries the grouping. WooCommerce writes a <code>Type</code> column holding
<code>variable</code> on the parent and <code>variation</code> on the child, beside a <code>Parent</code> column
holding the parent SKU. Google Merchant Center publishes <code>item_group_id</code>, an
"ID for a group of products that come in different versions (variants)", and
recommends "the parent SKU where possible". The file above carries none of those
three columns.
<a href="https://updog.tech/blog/excel-import-for-ecommerce-pim-software/">Excel import for ecommerce and PIM software</a>
measures what a 196,000-row export in the Shopify shape costs to read.</p>
<h2 id="the-two-entities-the-file-becomes">The two entities the file becomes</h2>
<p>Your catalog splits into a product and its variants, and this one flat file
carries both.</p>
<pre><code class="language-ts">type Product = {
  productRef: string;
  name: string;
  origin: string;
  roast: string;
};

type Variant = {
  sku: string;
  productRef: string;
  bagSize: string;
  grind: string;
  price: number;
  currency: string;
};</code></pre>
<p>No column stands behind <code>productRef</code>. Everything else on <code>Product</code> repeats down
the rows of its group, and everything on <code>Variant</code> changes row by row.</p>
<h2 id="what-each-column-has-to-become">What each column has to become</h2>
<div class="blog-table blog-table--fixed blog-table--catalog-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your app needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Product</code></td>
<td>the name written out on every row, and once in a second wording</td>
<td>one <code>name</code> per product</td>
</tr>
<tr>
<td><code>Origin</code></td>
<td>repeated down the group</td>
<td>one <code>origin</code> per product</td>
</tr>
<tr>
<td><code>Roast</code></td>
<td><code>Medium</code> on three rows and <code>Med</code> on a fourth</td>
<td>one of four roast levels</td>
</tr>
<tr>
<td><code>SKU</code></td>
<td><code>MR-NDA-250-WB</code>, and one value on two rows</td>
<td><code>required</code> and <code>unique</code></td>
</tr>
<tr>
<td><code>Size</code></td>
<td><code>250g</code>, <code>1kg</code>, <code>5kg</code></td>
<td>one of three sizes</td>
</tr>
<tr>
<td><code>Grind</code></td>
<td>three grinds, and one empty cell</td>
<td>one of three grinds</td>
</tr>
<tr>
<td><code>Unit price</code></td>
<td><code>£16.00</code>, <code>18,50 EUR</code>, <code>1 250,00 CZK</code></td>
<td>an amount and an ISO 4217 code</td>
</tr>
<tr>
<td>No column</td>
<td>nothing</td>
<td><code>productRef</code>, on both entities</td>
</tr>
</tbody>
</table></div>
<p>The last row decides the shape of everything else, so it goes first.</p>
<h2 id="the-product-the-file-never-names">The product the file never names</h2>
<p>The product name and the SKU prefix can each stand in for the missing id.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Candidate</th>
<th>What groups correctly</th>
<th>What breaks</th>
</tr>
</thead>
<tbody>
<tr>
<td>The product name</td>
<td>four groups, while the spelling holds</td>
<td>row 6 says <code>Marchmont Ndaro</code> and leaves the group</td>
</tr>
<tr>
<td>The SKU prefix</td>
<td>four groups, including row 6</td>
<td>a roaster who numbers each variant separately</td>
</tr>
</tbody>
</table></div>
<p>Row 6 decides it. <code>MR-NDA-250-ES</code> belongs to the same coffee as the four rows
above it, and its <code>Product</code> cell carries a second wording of the name. Group on
the name and that espresso grind becomes a fifth product with one variant under
it. Group on <code>MR-NDA</code> and it lands where it belongs.</p>
<p>The SKU prefix wins here, because this roaster builds the SKU out of a product
part and a variant part. A supplier who numbers variants independently gives you
nothing to cut, and the grouping moves back to the name.</p>
<h2 id="the-price-that-carries-its-own-currency">The price that carries its own currency</h2>
<p>Google Merchant Center states the price format as "Number plus currency (use ISO
4217)" and publishes <code>15.00 USD</code> as the example. A price typed by a person
carries a symbol. Both forms reach one column.</p>
<p>A number column reduces a value on the way in. Currency symbols, percent signs,
accounting parentheses and the file's own grouping all come off, and what stays
is digits with a dot. It reads a symbol by the Unicode currency-symbol category,
so <code>£</code> and <code>€</code> come off and <code>EUR</code> stays as three ordinary letters.</p>
<pre><code class="language-text">cell            stored on a number column
£16.00          16.00
18,50 €         18.50
18,50 EUR       18,50 EUR, flagged
1 250,00 CZK    1 250,00 CZK, flagged</code></pre>
<p>Both halves of that table lose something. The two symbol forms parse, and the
currency they carried is gone from the row. The two ISO forms keep the currency
and reach validation as text a number rule cannot read.</p>
<p><strong>Money belongs in a text column when the currency travels with it.</strong> A
transformer puts every incoming form into one canonical shape, and a regex rule
holds that shape.</p>
<pre><code class="language-ts">const SYMBOLS: Record&#x3C;string, string> = {
  "£": "GBP",
  "€": "EUR",
  "$": "USD",
};

const MONEY = /^([^\d\s]*)\s*([\d.,\s']+?)\s*([A-Z]{3})?$/;

// The decimal separator is whichever of . and , sits further right.
const canonicalAmount = (digits: string): string => {
  const clean = digits.replace(/[\s']/g, "");
  const decimal = clean.lastIndexOf(",") > clean.lastIndexOf(".") ? "," : ".";
  const group = decimal === "," ? "." : ",";
  return clean.split(group).join("").replace(decimal, ".");
};

export const toCanonicalPrice = (value: unknown): string => {
  const raw = String(value).trim();
  const match = MONEY.exec(raw);
  if (!match) return raw;

  const [, symbol, digits, code] = match;
  const currency = code ?? SYMBOLS[symbol];
  if (!currency) return raw;

  return canonicalAmount(digits) + " " + currency;
};</code></pre>
<p>Each value names its own decimal separator. <code>1 250,00</code> groups with a space and
splits with a comma, <code>1,250.00</code> does the reverse, and the two are the same
amount. Whichever of the dot and the comma sits further right is the decimal
one, and that settles both.</p>
<p>The transformer runs on every value arriving from outside the editor. A file
import, <code>loadData</code>, a remote source and a paste from another app all call it,
and a value the person types in the grid reaches the cell untouched. The
transformer also runs before validation, so the regex judges the canonical form.</p>
<h2 id="the-roast-written-two-ways">The roast written two ways</h2>
<p><code>Med</code> and <code>Medium</code> are the same roast level, and the file carries both. The
roast column is a <code>select</code> with <code>enableCustomValue: false</code>, so the vocabulary is
closed to the four levels your catalog uses.</p>
<pre><code class="language-text">"Medium"      → Medium
"Med"         → Medium
"Medium-Dark" → Medium-Dark
"Light"       → Light</code></pre>
<p>Three of those four match on the name alone. <code>Med</code> reaches <code>Medium</code> through the
built-in fuzzy matcher, and the person confirms it on the value screen before
any row lands.</p>
<p>A closed select drops a value that reaches no option. The row still arrives with
its roast cell empty, so <code>required</code> sits on that column. Without it, a coffee
with an unrecognized roast reaches your API with the field blank.</p>
<h2 id="what-the-schema-should-look-like">What the schema should look like</h2>
<p>Every decision so far lands in one array, and the mount below imports it from
<code>./columns</code>.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { toCanonicalPrice } from "./price";

const ROASTS = ["Light", "Medium", "Medium-Dark", "Dark"];
const SIZES = ["250g", "1kg", "5kg"];
const GRINDS = ["Whole bean", "Filter", "Espresso"];

export const columns: DataEditorColumn[] = [
  {
    id: "name",
    title: "Product",
    validators: [{ type: "required" }],
  },
  { id: "origin", title: "Origin" },
  {
    id: "roast",
    title: "Roast",
    editor: { type: "select", options: ROASTS, enableCustomValue: false },
    validators: [{ type: "required" }],
  },
  {
    id: "sku",
    title: "SKU",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "bagSize",
    title: "Size",
    editor: { type: "select", options: SIZES, enableCustomValue: false },
    validators: [{ type: "required" }],
  },
  {
    id: "grind",
    title: "Grind",
    editor: { type: "select", options: GRINDS, enableCustomValue: false },
    validators: [{ type: "required" }],
  },
  {
    id: "price",
    title: "Unit price",
    transformer: toCanonicalPrice,
    validators: [
      {
        type: "regex",
        pattern: "^\\d+(\\.\\d{1,2})? (GBP|EUR|CZK)$",
        message: "Write the price as 16.00 GBP",
      },
    ],
  },
];</code></pre>
<p><code>Origin</code> is the one field with no rule on it. A coffee whose origin cell arrives
empty still reaches your API, and the roaster fixes it later.</p>
<h2 id="the-key-that-decides-the-second-upload">The key that decides the second upload</h2>
<p><code>primaryKey</code> decides what a second upload does. Name the SKU and the second
upload of this catalog updates the twelve variants it already wrote.</p>
<pre><code class="language-text">sku = MR-NDA-1KG-WB   already stored      → update
sku = MR-NDA-2KG-WB   new                 → create
sku = MR-TAR-1KG-ES   twice in one file   → both land, both flagged</code></pre>
<p>Hold three of these variants already, then import the file over them. Two SKUs
match and stay in the stored source, ten rows arrive as new, and one row counts
as changed, because <code>MR-NDA-250-WB</code> moved from <code>15.00 GBP</code> to <code>16.00 GBP</code>. The
other matched row rewrote its price with the value it already held, so nothing
about it changed.</p>
<p>An import anchors against rows that came from somewhere else, and it skips
every row belonging to the file being imported. So the two <code>MR-TAR-1KG-ES</code> rows
never merge into each other. Both reach the grid, and <code>{ type: "unique" }</code> flags
them.</p>
<p>Uniqueness runs last on a column, once every other rule there has passed. A
blank SKU reports that it is required and never reports that it is a duplicate.</p>
<p>A supplier file with no SKU column needs a key built from several columns.</p>
<pre><code class="language-ts">primaryKey={["name", "bagSize", "grind"]}</code></pre>
<p>Row 5 shows what that costs. Its <code>Grind</code> cell is empty, and a composite key
needs every part filled. One empty part and the key is nothing, so the row
matches no stored row and arrives as new. That happens on this upload and on
every upload after it, which turns one 5kg bag into a fresh row each time the
catalog lands. Prefer the SKU wherever the file carries one.</p>
<h2 id="the-rows-the-person-fixes">The rows the person fixes</h2>
<p>The person who sent the catalog fixes it before anything reaches your API.</p>
<ul><li><strong>Row 5</strong>, Grind, empty: Required. Choose Whole bean, Filter or Espresso.</li><li><strong>Row 12, Row 13</strong>, SKU, <code>MR-TAR-1KG-ES</code>: Value must be unique.</li></ul>
<p>Row 7 stays out of that list. Its price cell arrived as <code>18,50 EUR</code>, the
transformer rewrote it to <code>18.50 EUR</code>, and the regex passed. Rows 5, 12 and 13
stay, because a missing grind and a repeated SKU are decisions only the roaster
can make.</p>
<h2 id="what-updog-importer-does-not-ship">What Updog Importer does not ship</h2>
<p>There is no product and variant model in the grid. Updog Importer holds one flat
table of rows, and your code builds the second level once the rows are
validated. No catalog connector, no attribute library and no taxonomy comes with
it.</p>
<p>Uniqueness is the only rule that reads more than one row. A <code>function</code> validator
receives the cell value and the row around it, and nothing else, so two rows of
one group disagreeing on a product-level value pass every rule you can write.
Row 6 carries <code>Marchmont Ndaro</code> where the four rows above it carry <code>Ndaro Peaberry</code>, and the grid reports nothing. Your grouping code picks a winner, and
<code>toCatalog</code> below picks the first row of each group.</p>
<p>Padded SKUs are their own problem, and
<a href="https://updog.tech/blog/preserving-leading-zeros-in-csv-and-excel-imports/">preserving leading zeros</a>
covers what a spreadsheet does to <code>00422</code> before the file ever reaches you.</p>
<h2 id="the-handoff-to-your-backend">The handoff to your backend</h2>
<p><code>onComplete</code> fires once, with the rows grouped by source. Each row carries
<code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>, and the flags are independent.</p>
<pre><code class="language-ts">import { DataEditor } from "@updog/data-editor";
import type { DataEditorResult } from "@updog/data-editor";
import { columns } from "./columns";
import type { Product, Variant } from "./catalog";

type CatalogRow = {
  name: string;
  origin: string;
  roast: string;
  sku: string;
  bagSize: string;
  grind: string;
  price: string;
};

type Catalog = { products: Product[]; variants: Variant[] };

const productRefOf = (sku: string) => sku.split("-").slice(0, 2).join("-");

const toCatalog = (result: DataEditorResult&#x3C;CatalogRow>): Catalog => {
  const products = new Map&#x3C;string, Product>();
  const variants: Variant[] = [];

  for (const source of result.sources) {
    for (const { row, isValid, isDeleted } of source.rows) {
      if (!isValid || isDeleted) continue;

      const productRef = productRefOf(row.sku);
      const [amount, currency] = row.price.split(" ");

      if (!products.has(productRef)) {
        products.set(productRef, {
          productRef,
          name: row.name,
          origin: row.origin,
          roast: row.roast,
        });
      }

      variants.push({
        sku: row.sku,
        productRef,
        bagSize: row.bagSize,
        grind: row.grind,
        price: Number(amount),
        currency,
      });
    }
  }

  return { products: [...products.values()], variants };
};

const saveCatalog = async (result: DataEditorResult&#x3C;CatalogRow>) => {
  const response = await fetch("/api/catalog", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(toCatalog(result)),
  });
  if (!response.ok) throw new Error(await response.text());
};

type Props = { open: boolean; onClose: () => void };

export function CatalogImport({ open, onClose }: Props) {
  return (
    &#x3C;DataEditor&#x3C;CatalogRow>
      apiKey={import.meta.env.VITE_UPDOG_KEY}
      open={open}
      onClose={onClose}
      variant="uploader"
      columns={columns}
      primaryKey="sku"
      onComplete={saveCatalog}
    />
  );
}</code></pre>
<p><code>toCatalog</code> does the work the file could not. It cuts <code>MR-NDA</code> out of each SKU,
writes one <code>Product</code> the first time a group appears, splits the canonical price
back into an amount and a code, and pushes one <code>Variant</code> per row. It touches no
network, so your tests hand it a result object and read the two arrays back.</p>
<p><code>isValid</code> decides who reaches the arrays. Submit this catalog with the three
flagged rows left as they are, and <code>toCatalog</code> returns three products and nine
variants. Tarn Hollow Blend disappears, because both of its rows carry the
duplicate SKU and neither one is valid. A product survives the handoff only
while one of its variants does.</p>
<p>Throw when your backend fails. A handler that swallows its own error reads as
success, and the SDK clears the grid with the rows unsaved. A throw keeps every
row where it is, so the person can submit again.</p>
<p>You decide next where those two arrays land, and
<a href="https://updog.tech/blog/import-csv-into-postgresql/">importing CSV into PostgreSQL</a> covers the
insert side of it.</p>
<h2 id="what-you-built">What you built</h2>
<p>Twelve flat rows become four products and twelve variants, once the person
clears the three rows the grid flagged. You chose the SKU prefix as the grouping
key, moved money into a text column so the currency survived the trip, closed
the roast vocabulary to four values, and named the SKU as the key that makes the
second upload an update.</p>
<p><a href="https://updog.tech/blog/csv-column-mapping-react/">CSV column mapping in React</a> covers the header
aliases that get a roaster's own wording onto those seven fields. No matcher can
do the grouping for you, because the product the file never named has to be
built out of the columns it did.</p>]]></content:encoded></item>
<item><title>Import, Edit and Delete Rows Through Your REST API</title><link>https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/</link><guid isPermaLink="true">https://updog.tech/blog/import-edit-and-delete-rows-through-a-rest-api/</guid><pubDate>Mon, 24 Aug 2026 00:00:00 GMT</pubDate><description>A port's arrival list keeps changing. Updog Importer fetches it, takes the edits and the deletions, and hands your API one list of changes.</description><content:encoded><![CDATA[<p>A port's arrival list lives behind a REST API and keeps changing. An agent sends the next week as a file, a vessel arrives that nobody booked, and two calls get cancelled before they happen.</p>
<p>All of it lands on one screen. Your API fills the grid, the person imports the agent's file into the same grid, corrects what is already there, removes the calls that are off, and submits once. Your handler receives the rows that moved, one list of what was added, changed and removed, and turns it into POST, PATCH and DELETE requests.</p>
<p>The agent's file arrives looking like this.</p>
<p><code>ravensgate-arrivals.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Call Ref</td><td class="sheet__cell">Vessel</td><td class="sheet__cell">IMO</td><td class="sheet__cell">Berth</td><td class="sheet__cell">ETA</td><td class="sheet__cell">Status</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">PC-2026-0413</td><td class="sheet__cell">Kestrel Bay</td><td class="sheet__cell">IMO 9074729</td><td class="sheet__cell">Quay 3</td><td class="sheet__cell">2026-04-02</td><td class="sheet__cell">Expected</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">PC-2026-0414</td><td class="sheet__cell">Aldervik</td><td class="sheet__cell">9182741</td><td class="sheet__cell">Quay 1</td><td class="sheet__cell">2026-04-02</td><td class="sheet__cell">Along side</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">PC-2026-0415</td><td class="sheet__cell">Marisol Trader</td><td class="sheet__cell">9331556</td><td class="sheet__cell">Quay 4</td><td class="sheet__cell">2026-04-03</td><td class="sheet__cell">Expected</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">PC-2026-0415</td><td class="sheet__cell">Marisol Trader</td><td class="sheet__cell">9331556</td><td class="sheet__cell">Quay 4</td><td class="sheet__cell">2026-04-03</td><td class="sheet__cell">Expected</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">52 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">58</th><td class="sheet__cell">PC-2026-0469</td><td class="sheet__cell">Sable Point</td><td class="sheet__cell">9448023</td><td class="sheet__cell">Quay 2</td><td class="sheet__cell">2026-04-05</td><td class="sheet__cell">Expected</td></tr></tbody></table>
<p>The file opens with six headers and runs 57 lines. The IMO number on row 2 arrives as <code>IMO 9074729</code>, with the prefix the agent's system prints. Row 3 gives the status the old berthing book used, <code>Along side</code>. Rows 4 and 5 are the same call written twice, both under <code>PC-2026-0415</code>.</p>
<p>Your endpoint answers the GET. Updog Importer paints those rows. The person drops the file in beside them, fixes what is flagged, and presses submit. Your handler reads that list and calls your API.</p>
<p>Between that browser and your API there is no Updog server.</p>
<h2 id="step-1-describe-the-columns">Step 1. Describe the columns</h2>
<p>The <code>columns</code> array describes your resource to the person looking at it. Each entry names the title they read, the editor that shapes typing in a cell, and the validators that mark a value your API would refuse.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

type PortCall = {
  callRef: string;
  vessel: string;
  imo: string;
  berth: string;
  eta: string;
  status: string;
};

const STATUSES = ["Expected", "Berthed", "Departed"];

export const columns: DataEditorColumn[] = [
  {
    id: "callRef",
    title: "Call ref",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "unique" },
    ],
  },
  {
    id: "vessel",
    title: "Vessel",
    size: 170,
    validators: [{ type: "required" }],
  },
  {
    id: "imo",
    title: "IMO",
    size: 120,
    transformer: (value) => String(value).replace(/^IMO\s*/i, "").trim(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^\\d{7}$", message: "Seven digits" },
    ],
  },
  {
    id: "berth",
    title: "Berth",
    size: 120,
    validators: [{ type: "required" }],
  },
  {
    id: "eta",
    title: "ETA",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "status",
    title: "Status",
    size: 140,
    editor: { type: "select", options: STATUSES, enableCustomValue: false },
    validators: [
      { type: "required" },
      { type: "oneOf", values: STATUSES },
    ],
  },
];</code></pre>
<p>The transformer on <code>imo</code> strips the <code>IMO </code> prefix before validation runs, so <code>IMO 9074729</code> reaches the regex as seven digits. The transformer on <code>callRef</code> trims and uppercases, so the key compares the same however the agent typed it. <code>unique</code> marks a reference that appears twice in the grid, and the last step of the wizard decides whether the repeated <code>PC-2026-0415</code> becomes two rows.</p>
<p><code>Along side</code> matches no option on its own, so <code>synonyms</code> teaches it. The person sees the mapping in the value-matching step of the import, with <code>Along side</code> pointing at <code>Berthed</code>, and can change it there.</p>
<h2 id="step-2-fill-the-grid-from-your-api">Step 2. Fill the grid from your API</h2>
<p><code>loadData</code> runs when the editor opens, and <code>onChunk</code> takes the rows.</p>
<pre><code class="language-tsx">import type { ChunkSourceOptions } from "@updog/data-editor";

type OnChunk = (rows: PortCall[], options?: ChunkSourceOptions) => void;

const loadData = useCallback(async (onChunk: OnChunk) => {
  const response = await fetch("/api/port-calls?week=2026-W14", {
    credentials: "same-origin",
  });
  const { calls } = await response.json();

  onChunk(calls, { source: "Port calls", done: true });
}, []);</code></pre>
<p>You can call <code>onChunk</code> as many times as your API pages, and the editor processes each chunk without freezing the grid. The <code>source</code> name is what the person reads in the data sources panel, and <code>done</code> closes that source's loading state.</p>
<p>Each key in a row is a column id, so the answer your endpoint sends needs no mapping on the way in.</p>
<pre><code class="language-json">{
  "calls": [
    {
      "callRef": "PC-2026-0390",
      "vessel": "Corvid Star",
      "imo": "9210338",
      "berth": "Quay 1",
      "eta": "2026-03-30",
      "status": "Departed"
    }
  ]
}</code></pre>
<p>Typed columns read those values the same way an import does. The <code>date</code> column canonicalizes <code>2026-03-30</code>, and the <code>select</code> column takes <code>Departed</code> as the option it already knows.</p>
<p>Rows loaded this way set the baseline. Nothing marks them, the counters read zero, and submit stays disabled until somebody changes something.</p>
<h2 id="step-3-let-the-person-add-change-and-remove-rows">Step 3. Let the person add, change and remove rows</h2>
<p><code>enableAddRow</code> decides what the person may add, and <code>enableDeleteRow</code> what they may remove. Editing a cell needs no prop.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;PortCall>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="callRef"
  loadData={loadData}
  enableAddRow
  enableDeleteRow="all"
  synonyms={{
    values: { Berthed: ["along side", "alongside", "a/side"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>enableAddRow</code> is on by default. It gives the person Insert row above, Insert row below and Duplicate row in the right-click menu, and an Add row button while the grid is still empty. A row added any of those ways takes <code>isNew</code> from the moment it appears.</p>
<p>The agent's file arrives through the data sources panel. Add data source opens the import wizard, the person maps the headers, and the file lands as its own source next to the rows your API sent. The last step of the wizard asks how the file meets the grid. Add every row makes each line a row of its own. The wizard preselects Update by Call ref, because <code>primaryKey</code> names that column. That option drops a line onto the row whose reference it already matches, and the row keeps its place and its source. A reference your API never sent becomes a new row either way.</p>
<p>That choice decides the repeated <code>PC-2026-0415</code>. Under Update by Call ref both lines land on the call your API already has, and the second line wins. Under Add every row both lines stay, and <code>unique</code> marks them together with the call already in the grid, three rows reading Value must be unique.</p>
<p><code>enableDeleteRow</code> is off by default, and it takes <code>"all"</code> or <code>"new"</code>. With <code>"new"</code> the person can only remove rows they added or imported. With <code>"all"</code> they can remove a call your API holds, which is what a cancelled arrival needs.</p>
<p>A deleted row moves into a bin. The editor flags it, hides it from the grid, and keeps it in memory with everything else. The person opens the deleted-rows filter to look at what they removed, restores a row they took out by mistake, and undo works on the whole operation. Submit empties that bin into your handler, every row in it carrying <code>isDeleted</code> whatever your validators said about it.</p>
<h2 id="step-4-read-the-flags">Step 4. Read the flags</h2>
<p>Submit hands your handler every row that moved, grouped by source and flagged independently. <code>isNew</code> says where the row came from, and it never flips back. <code>isChanged</code> says a cell moved, and typing the original value back into it clears the flag. <code>isDeleted</code> is the person's own mark. <code>isValid</code> reports the verdict of your validators.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>What the row carries</th>
<th>What happened</th>
<th>The request</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>isNew</code></td>
<td>added in the grid, or imported under a new call ref</td>
<td>POST</td>
</tr>
<tr>
<td><code>isChanged</code></td>
<td>a cell differs from what your API sent</td>
<td>PATCH</td>
</tr>
<tr>
<td><code>isDeleted</code> without <code>isNew</code></td>
<td>a call your API holds, removed by the person</td>
<td>DELETE</td>
</tr>
<tr>
<td><code>isDeleted</code> with <code>isNew</code></td>
<td>added and removed inside one session</td>
<td>nothing to send</td>
</tr>
<tr>
<td><code>isValid</code> false</td>
<td>a validator marked the row</td>
<td>your call</td>
</tr>
</tbody>
</table></div>
<p>Rows nobody touched stay out of the result, so absence means there is nothing to do with them.</p>
<p>A week of calls reaches the handler as a list this short.</p>
<pre><code class="language-text">Call ref       Flags on submit      Request
PC-2026-0414   isNew                POST   /api/port-calls
PC-2026-0415   isChanged            PATCH  /api/port-calls/PC-2026-0415
PC-2026-0390   isDeleted            DELETE /api/port-calls/PC-2026-0390
PC-2026-0413   isNew, isDeleted     none</code></pre>
<p>Watch the fourth line. A row the person added or imported and then removed carries both flags, and your API has never seen its reference. Sending it to DELETE addresses a resource your API never created, which is why the delete filter reads <code>isDeleted &#x26;&#x26; !isNew</code>.</p>
<h2 id="step-5-send-one-round-of-requests">Step 5. Send one round of requests</h2>
<p>The handler groups the diff by verb and walks each group in order.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const send = async (method: string, path: string, body?: PortCall) => {
  const response = await fetch(path, {
    method,
    credentials: "same-origin",
    headers: body ? { "Content-Type": "application/json" } : undefined,
    body: body ? JSON.stringify(body) : undefined,
  });

  const gone = method === "DELETE" &#x26;&#x26; response.status === 404;

  if (!response.ok &#x26;&#x26; !gone) {
    throw new Error(method + " " + path + " answered " + response.status);
  }
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;PortCall>) => {
  const entries = result.sources.flatMap((source) => source.rows);

  const created = entries.filter((e) => e.isNew &#x26;&#x26; !e.isDeleted &#x26;&#x26; e.isValid);
  const changed = entries.filter(
    (e) => !e.isNew &#x26;&#x26; e.isChanged &#x26;&#x26; !e.isDeleted &#x26;&#x26; e.isValid,
  );
  const removed = entries.filter((e) => e.isDeleted &#x26;&#x26; !e.isNew);

  for (const entry of created) {
    await send("POST", "/api/port-calls", entry.row);
  }

  for (const entry of changed) {
    await send("PATCH", "/api/port-calls/" + entry.row.callRef, entry.row);
  }

  for (const entry of removed) {
    await send("DELETE", "/api/port-calls/" + entry.row.callRef);
  }
}, []);</code></pre>
<p>POST sends the whole row, since your API is creating a call it has never seen. PATCH sends that same whole row under its call ref. The result hands you the row and no field-level diff, so your endpoint reads the body as the call's new state. DELETE sends the reference alone.</p>
<p><code>credentials: "same-origin"</code> sends the session your app already has. It works while your API answers on the app's own origin, and no key travels to the browser for any of it.</p>
<p>This handler lets a 404 on DELETE pass. Somebody cancelled the call in another screen while the session was open, and the outcome the person asked for is the outcome your API already holds.</p>
<p>Submit opens a dialog counting the rows to create, the rows to update and the rows to delete, and the handler starts when the person confirms.</p>
<p><strong>Throw when your API refuses.</strong> Updog Importer awaits your handler and empties the editor the instant that promise resolves. A handler that swallows the failure and returns reads as a clean save, and the grid clears with the week unsent. Throwing keeps every row, every mapping and every correction on the screen, so the person submits again on data they can still see. Copy anything you want to keep inside the handler, because the editor lets go of its rows, its sources and its history once the promise resolves.</p>
<p>The person waits with that dialog open and a spinner on the button while the requests run. A diff too big for one round wants each group posted as one request, and a retry path for the group that fails.</p>
<h2 id="step-6-open-again-where-the-person-stopped">Step 6. Open again where the person stopped</h2>
<p>The person gets called away with the file half corrected. Your app stores the diff, and the next session hands it back.</p>
<pre><code class="language-tsx">const loadData = useCallback(async (onChunk: OnChunk) => {
  const response = await fetch("/api/port-calls?week=2026-W14&#x26;draft=1", {
    credentials: "same-origin",
  });
  const { calls, draft } = await response.json();

  onChunk(calls, {
    source: "Port calls",
    done: true,
    changes: draft.changes,
  });
}, []);</code></pre>
<p><code>changes</code> is sparse, so it lists the rows that moved and says nothing about the rest.</p>
<pre><code class="language-json">{
  "changes": [
    { "index": 2, "originalValues": { "berth": "Quay 1" } },
    { "index": 5, "isNew": true },
    { "index": 8, "isDeleted": true }
  ]
}</code></pre>
<p><code>originalValues</code> marks a row as edited and keeps the values your API had before the person touched them. <code>isNew</code> marks a row they added. <code>isDeleted</code> marks one they removed. The editor opens reading Changed rows 1, New rows 1 and Deleted rows 1, with the marks already in the grid and the removed row already in the bin.</p>
<p><code>index</code> counts inside the chunk it travels with. Loading the week in three calls and numbering the changes from the whole set marks the wrong rows, and nothing on screen says so.</p>
<p>Seeded changes are the baseline of that session, so undo does not reach past them. A person who types the original value back into a seeded cell clears the mark the same way they clear their own.</p>
<h2 id="what-this-screen-does-not-carry">What this screen does not carry</h2>
<p>Updog Importer integrates with nobody. There is no REST connector, no destination list and no webhook. <code>onComplete</code> hands your code an object, and both endpoints here are yours to write.</p>
<p>The editor keeps no draft of its own. Step 6 reads one your app stored, written by a handler of yours that stored the diff and sent nothing.</p>
<p>The wizard offers the columns carrying a <code>unique</code> validator and preselects the one <code>primaryKey</code> names. A file that identifies a call by vessel and date needs that key built before the rows reach the grid.</p>
<p>The handler here sends one request per row. A berthing week affords that. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> covers what moves when the volume climbs past it, and <a href="https://updog.tech/blog/import-csv-into-postgresql/">how to import CSV into PostgreSQL</a> writes the chunked version of this handler against a database.</p>
<h2 id="what-the-round-trip-gives-you">What the round trip gives you</h2>
<p>You wrote six columns, a <code>loadData</code> that fills the grid from your collection, two props that let the person add and remove rows, and one handler that turns four flags into three requests. The mount and the handler here are React. The web component build takes the same props, so a Vue, Angular or Svelte app writes the same schema and the same handler.</p>
<p>The agent's file and the calls your API already has share one grid, and the person works on both without knowing which is which. Your API sees the difference, one verb at a time.</p>]]></content:encoded></item>
<item><title>How to Parse Time Correctly During CSV Import</title><link>https://updog.tech/blog/how-to-parse-time-correctly-during-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-parse-time-correctly-during-csv-import/</guid><pubDate>Sun, 23 Aug 2026 00:00:00 GMT</pubDate><description>Time can be written a dozen ways. See how Updog Importer reads each and settles the column on one format.</description><content:encoded><![CDATA[<p>There are five ways to write five in the morning.</p>
<pre><code class="language-text">5:00 AM   5:00 a.m.   5.00am   05:00   5:00</code></pre>
<p>There are four ways to write nine in the evening.</p>
<pre><code class="language-text">9:00 PM   9:00 p.m.   9.00pm   21:00</code></pre>
<p>Which writing appears in a file depends on the program that wrote it. A
spreadsheet prints the hour according to the format on the cell, and a web form
keeps the characters the person typed.</p>
<p>Updog Importer picks one writing per column and converts every cell with it. A
value that writing does not match stays as text and fails the column check.</p>
<p>This is a freelance studio's timesheet. One row is one shift, and the file goes
into a payroll system. The two time columns use two different writings, and one
value matches neither.</p>
<p><code>netherby-studio.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Freelancer</td><td class="sheet__cell">Work Date</td><td class="sheet__cell">Started</td><td class="sheet__cell">Finished</td><td class="sheet__cell">Hours</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">R. Ashwell</td><td class="sheet__cell">2026-03-10</td><td class="sheet__cell">9:00 AM</td><td class="sheet__cell">5:15 PM</td><td class="sheet__cell">8.25</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">P. Lindqvist</td><td class="sheet__cell">2026-03-09</td><td class="sheet__cell">8:15 AM</td><td class="sheet__cell">5:30</td><td class="sheet__cell">9.25</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">10 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">19</th><td class="sheet__cell">P. Lindqvist</td><td class="sheet__cell">2026-03-23</td><td class="sheet__cell">9:00 AM PST</td><td class="sheet__cell">4:00 PM</td><td class="sheet__cell">7</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">25</th><td class="sheet__cell">P. Lindqvist</td><td class="sheet__cell">2026-03-09</td><td class="sheet__cell">8:00 PM</td><td class="sheet__cell">12:00 AM</td><td class="sheet__cell">4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">21 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">47</th><td class="sheet__cell">P. Lindqvist</td><td class="sheet__cell">2026-03-27</td><td class="sheet__cell">9:00 AM</td><td class="sheet__cell">3:45 PM</td><td class="sheet__cell">6:45</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">15 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">63</th><td class="sheet__cell">M. Tarrant</td><td class="sheet__cell">2026-03-15</td><td class="sheet__cell">10:00 AM</td><td class="sheet__cell">6:30 AM</td><td class="sheet__cell">8.5</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">10 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">74</th><td class="sheet__cell">R. Ashwell</td><td class="sheet__cell">2026-03-10</td><td class="sheet__cell"></td><td class="sheet__cell">6:45 PM</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">94 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">169</th><td class="sheet__cell">M. Tarrant</td><td class="sheet__cell">2026-03-25</td><td class="sheet__cell">8:45 AM</td><td class="sheet__cell">3:30 PM</td><td class="sheet__cell">6.75</td></tr></tbody></table>
<p>Line 8 finishes at <code>5:30</code>, with no marker. Line 19 starts at <code>9:00 AM PST</code>.
Line 25 runs from <code>8:00 PM</code> to <code>12:00 AM</code>. Line 47 writes its hours cell as
<code>6:45</code>. Line 74 has no start at all. Line 63 starts at <code>10:00 AM</code>, finishes at
<code>6:30 AM</code> and claims <code>8.5</code> hours.</p>
<h2 id="what-a-twelve-hour-value-leaves-out">What a twelve-hour value leaves out</h2>
<p><code>7:30</code> on a twelve-hour clock is either 07:30 or 19:30. The digits record no
difference between the two, and the marker that would decide it is gone before
the file is written. Both readings are valid times of day.</p>
<p>Updog Importer stores a time of day in ISO form and keeps the precision the
value was written with, so <code>09:00</code>, <code>09:00:05</code> and <code>09:00:05.250</code> are all stored
forms. A value already written that way is stored as it stands in any column,
and <code>13:30</code> and <code>11:00</code> pass through a column of markers unchanged. <code>7:30</code> has a
one-digit hour, which no ISO time has, so it goes through the writing the column
settled on. In a column of markers it matches none of them and stays as text.</p>
<h2 id="which-writings-a-time-column-reads">Which writings a time column reads</h2>
<p>Updog Importer reads seven writings in a time column. A file written any other
way stays as text.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Written as</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>HH:MM</code></td>
<td><code>09:00</code></td>
</tr>
<tr>
<td><code>H:MM</code></td>
<td><code>9:00</code></td>
</tr>
<tr>
<td><code>HH:MM:SS</code></td>
<td><code>09:00:05</code></td>
</tr>
<tr>
<td><code>H:MM:SS</code></td>
<td><code>9:00:05</code></td>
</tr>
<tr>
<td><code>HH:MM:SS.fff</code></td>
<td><code>09:00:05.250</code>, <code>09:00:05,250</code></td>
</tr>
<tr>
<td><code>h:MM AM/PM</code></td>
<td><code>9:00 AM</code>, <code>9:00 a.m.</code>, <code>9.00am</code></td>
</tr>
<tr>
<td><code>h:MM:SS AM/PM</code></td>
<td><code>9:00:05 AM</code></td>
</tr>
</tbody>
</table></div>
<p>Two of the seven use a marker. The marker goes before the digits or after them,
and a dot works in place of the colon. Updog Importer builds the marker list
from its own language and accepts <code>am</code>, <code>pm</code>, <code>a.m.</code> and <code>p.m.</code> in addition. An
English importer has no marker for <code>오후</code>, so <code>오후 2:30</code> stays as text. A marker
beside an hour outside 1 to 12 fails as well, so <code>00:30 PM</code> stays as text.</p>
<p>Updog Importer removes a leading date and a trailing offset before it tries the
seven writings.</p>
<pre><code class="language-text">2026-03-02T09:00:00Z    →   09:00:00
2026-03-02 09:00:00     →   09:00:00
09:00+02:00             →   09:00
9:00 AM PST             →   9:00 AM PST</code></pre>
<p>The offset is removed and the digits are stored as they are, so <code>09:00+02:00</code>
stores <code>09:00</code>. A lettered zone stays in the value and matches no writing, so
<code>9:00 AM PST</code> stays as text.</p>
<h2 id="how-a-column-picks-one-writing">How a column picks one writing</h2>
<p>Updog Importer counts how many values each writing reads, and the writing with
the highest count converts the column. The count covers the first 1000 rows of
the source and skips empty cells. This file has 168 rows, so both time columns
are counted in full.</p>
<p><code>Started</code> has 167 values, and <code>h:MM AM/PM</code> reads 166 of them. Every other
writing reads none. The value left over is the <code>9:00 AM PST</code> on line 19.</p>
<p><code>Finished</code> has 168 values. <code>h:MM AM/PM</code> reads 167 of them and <code>H:MM</code> reads one,
the <code>5:30</code> on line 8. The count ends 167 to 1, so <code>h:MM AM/PM</code> converts the
column. The values it reads become ISO times and the rest stay as text.</p>
<pre><code class="language-text">Started    line 25    8:00 PM       →   20:00
Finished   line 25    12:00 AM      →   00:00
Finished   line 63    6:30 AM       →   06:30
Started    line 19    9:00 AM PST   →   9:00 AM PST
Finished   line 8     5:30          →   5:30</code></pre>
<p><code>12:00 AM</code> stores <code>00:00</code> and <code>12:00 PM</code> stores <code>12:00</code>.</p>
<p>Put the same <code>9:00</code> in two columns of three values and it converts in one of
them.</p>
<pre><code class="language-text">9:00 AM   1:30 PM   9:00     →   09:00   13:30   9:00
9:00      13:30     7:30     →   09:00   13:30   07:30</code></pre>
<p>The first column settles on <code>h:MM AM/PM</code>, which reads two of its three values.
The second settles on <code>H:MM</code>, which reads all three. The <code>9:00</code> cell is
identical in both, and the values around it decide what happens to it.</p>
<p>Two writings can tie. Updog Importer applies the first of them and reports the
tie to your <code>onError</code>, the same way it reports
<a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">a tied date column</a>.
<code>HH:MM</code> and <code>H:MM</code> tie without a report, and so do <code>HH:MM:SS</code> and <code>H:MM:SS</code>,
because each pair returns the same value for everything both members read. A
marker writing tied with a digit writing is reported,
because each of the two reads what the other leaves as text. A column holding
one <code>9:00 AM</code> and one <code>13:30</code> converts under <code>HH:MM</code> and names <code>h:MM AM/PM</code> as
the writing it passed over. Over both columns of this file, the detector reports
nothing.</p>
<p>Updog Importer remembers the winning writing per source and per column. A second
file is counted on its own, and a paste into the grid is counted again.</p>
<h2 id="which-values-stay-as-text">Which values stay as text</h2>
<p>Three cells of this file stay unconverted and two of them are in time columns.
The two time columns contain 336 cells, of which 333 convert and one is empty.</p>
<div class="blog-table blog-table--narrow blog-table--time-values"><table>
<thead>
<tr>
<th>Value</th>
<th>Line</th>
<th>Column</th>
<th>Why it stays as text</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>5:30</code></td>
<td>8</td>
<td>Finished</td>
<td>a one-digit hour and no marker, in a column that settled on <code>h:MM AM/PM</code></td>
</tr>
<tr>
<td><code>9:00 AM PST</code></td>
<td>19</td>
<td>Started</td>
<td>a lettered zone matches no writing, and only an offset is removed</td>
</tr>
<tr>
<td><code>6:45</code></td>
<td>47</td>
<td>Hours</td>
<td>a duration written as a clock, in a column of numbers</td>
</tr>
</tbody>
</table></div>
<p>The validator on each column reports the value that column rejects.</p>
<pre><code class="language-text">line 8     Finished    "5:30"          Invalid time
line 19    Started     "9:00 AM PST"   Invalid time
line 47    Hours       "6:45"          Invalid number</code></pre>
<p>The grid displays the original string in every cell the column could not
convert, so the person sees the characters that have to change. Three cells out
of a 168-row file are <a href="https://updog.tech/blog/common-csv-import-errors/">flagged</a> by the check on
their own column, and the 333 time values around them are ISO.</p>
<h2 id="how-an-xlsx-file-stores-a-time">How an .xlsx file stores a time</h2>
<p>An .xlsx cell does not store <code>9:00 AM</code>. It stores the hour as a number, a
fraction of a day, and a format code that says how to draw that number. Midday
is <code>0.5</code>, because half of the day has gone by, and nine in the morning is
<code>0.375</code>. Excel, Google Sheets and every other app that opens the file render the
text from the two.</p>
<p>A fraction on its own gives no date. A reader that takes it for a moment in time
returns day zero of the file's calendar plus those hours, which is why Updog
Importer reads the format code first.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Format code</th>
<th>What the cell is</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>hh:mm</code>, <code>h:mm</code>, <code>h:mm AM/PM</code>, <code>[Red]h:mm</code>, <code>[$-409]h:mm AM/PM;@</code></td>
<td>a time of day</td>
</tr>
<tr>
<td><code>[h]:mm</code>, <code>[hh]:mm:ss</code></td>
<td>an elapsed value, kept on the number path</td>
</tr>
<tr>
<td><code>yyyy-mm-dd hh:mm</code></td>
<td>a timestamp, kept in ISO</td>
</tr>
<tr>
<td><code>General</code>, <code>0.00</code></td>
<td>a plain number</td>
</tr>
</tbody>
</table></div>
<p>A cell whose code names a time of day is read from its rendered text. In the
.xlsx of this timesheet the <code>Started</code> cell on line 2 is the number <code>0.375</code> under
<code>h:mm AM/PM</code>, rendered as <code>9:00 AM</code>. The CSV spells out those same seven
characters. Both files import as <code>09:00</code>.</p>
<p>The <code>Finished</code> cell on line 8 is <code>0.22916666666666666</code> under an <code>h:mm</code> format, so the
.xlsx records half past five in the morning. Updog Importer takes the rendered
<code>5:30</code>, the same text the CSV spells out, so both files produce the same
unconverted value.</p>
<h2 id="what-you-declare">What you declare</h2>
<p>Two declarations make a column a time column. This timesheet goes into
<a href="https://updog.tech/blog/csv-import-for-hr-payroll-saas/">a payroll system</a> that needs both clocks
and the hours between them.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { agrees } from "./agrees";

export const columns: DataEditorColumn[] = [
  { id: "freelancer", title: "Freelancer", validators: [{ type: "required" }] },
  {
    id: "workDate",
    title: "Work date",
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "startedAt",
    title: "Started",
    editor: { type: "time", hourCycle: "h23" },
    dependentFields: ["hours"],
    validators: [{ type: "time", precision: "minutes" }],
  },
  {
    id: "finishedAt",
    title: "Finished",
    editor: { type: "time", hourCycle: "h23" },
    dependentFields: ["hours"],
    validators: [{ type: "time", precision: "minutes" }],
  },
  {
    id: "hours",
    title: "Hours",
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, max: 16, decimalPlaces: 2 },
      { type: "function", fn: agrees },
    ],
  },
];</code></pre>
<p><code>editor: { type: "time" }</code> is the declaration that converts. A column with only
the <code>{ type: "time" }</code> validator is checked and never converted, so its
<code>9:00 AM</code> values fail that check. A time editor without a validator of its own
gets one, so an unconverted value is flagged in either case.</p>
<p><code>precision: "minutes"</code> flags a value that includes seconds and never trims it,
the same way an extra decimal is flagged on a number column. <code>hourCycle: "h23"</code>
fixes the clock the grid draws, so a person in Chicago and a person in Berlin
both see line 25 as <code>20:00</code>. The import ignores this setting and reads all seven
writings.</p>
<p><code>min</code> and <code>max</code> bound the column and compare by the millisecond of the day, so
<code>09:00</code> and <code>09:00:00</code> are the same bound. These two columns declare neither,
because a lower bound would flag the shift that finishes at <code>00:00</code> on line 25.</p>
<h2 id="where-parsing-ends-and-the-schema-begins">Where parsing ends and the schema begins</h2>
<p>Line 63 converts cleanly. <code>10:00 AM</code> stores <code>10:00</code>, <code>6:30 AM</code> stores <code>06:30</code>,
<code>8.5</code> is a number, and every rule that reads one cell passes.</p>
<p>The row still disagrees with itself. 10:00 to 06:30 the next morning is twenty
hours and thirty minutes, and the Hours column says 8.5. A rule that reads one
cell cannot detect this. A <code>function</code> rule reads the whole row.</p>
<pre><code class="language-ts">import type { CellValidator } from "@updog/data-editor";

// A stored time always writes its hour with two digits, so the first five
// characters are enough. Anything the importer left as text reads as nothing.
const minuteOfDay = (value: unknown): number | null => {
  const match = /^(\d{2}):(\d{2})/.exec(String(value ?? ""));
  if (!match) return null;
  return Number(match[1]) * 60 + Number(match[2]);
};

// A finish earlier than the start ran through midnight.
const spanMinutes = (from: number, to: number): number => {
  if (to >= from) return to - from;
  return to + 1440 - from;
};

export const agrees: CellValidator = (value, row) => {
  const from = minuteOfDay(row.startedAt);
  const to = minuteOfDay(row.finishedAt);
  if (from === null || to === null) return null;

  const claimed = Number(value);
  if (value === "" || Number.isNaN(claimed)) return null;

  const drift = Math.abs(spanMinutes(from, to) - claimed * 60);
  if (drift &#x3C;= 5) return null;
  return { level: "error", message: "Hours do not match the shift" };
};</code></pre>
<pre><code class="language-text">line 25    8:00 PM → 12:00 AM      Hours 4
           span across midnight     4:00
           hours claimed            4:00
           agree

line 63    10:00 AM → 6:30 AM      Hours 8.5
           span across midnight    20:30
           hours claimed            8:30
           disagree by             12:00</code></pre>
<p>Both rows finish earlier than they start. On line 25 that is a night shift and
on line 63 it is a missing <code>PM</code>, and the Hours column is what separates them.</p>
<p><code>dependentFields: ["hours"]</code> on both time columns re-runs the rule when a time
is edited. Without it, fixing the marker on line 63 leaves the old verdict on
the Hours cell.</p>
<h2 id="what-the-person-sees">What the person sees</h2>
<p>An unconverted cell displays the string from the file. The editor opens with a
mask that takes digits into fixed slots and writes the separators itself.</p>
<pre><code class="language-text">typed   189     shows   18:09      a one-digit hour takes a leading zero
typed   25      shows   2          an hour above 23 is rejected as typed
typed   18      blur    18:00      the minutes fill with zeros
typed   143     blur    14:30      the remaining digit fills with a zero</code></pre>
<p>The mask takes digits only, and it never adds seconds or fractions to a value
that had none. An <code>h12</code> column draws a button for the half of the day and takes
the A and P keys for it, so <code>09:30</code> with the button on PM stores <code>21:30</code>. An
unconverted value opens in a plain text field and keeps every character, so the
<code>9:00 AM PST</code> on line 19 is still there to be corrected.</p>
<p>The three unconverted cells state what is wrong with them, and a person fixes
them in the grid before the rows are submitted. Line 63 carries no unconverted
value at all. It converts, it passes every rule that reads one cell, and the
message on its Hours cell comes from the rule that reads two clocks against a
third column.</p>]]></content:encoded></item>
<item><title>Embedded Importer Pricing Compared in 2026</title><link>https://updog.tech/blog/embedded-importer-pricing-compared/</link><guid isPermaLink="true">https://updog.tech/blog/embedded-importer-pricing-compared/</guid><pubDate>Sat, 22 Aug 2026 00:00:00 GMT</pubDate><description>Embedded importers charge by files, rows, cells, or a flat fee, so two quotes rarely compare. Every published price sits in one matrix, at the same volumes.</description><content:encoded><![CDATA[<p>Embedded data importers charge for different things. Some count files, some count every row, and some multiply rows by columns to count cells. Flat plans count none of them.</p>
<p>Every product carries its own features and limits. The prices below compare the bill alone.</p>
<p>Two numbers set each workload, the number of imports in a month and the rows in each file. Every pair in the matrix was applied to the prices each company published on its public price page in August 2026.</p>
<figure class="price-matrix"><div class="price-matrix__panel" role="region" aria-label="Dollars a month by import count and rows per file"><table class="price-matrix__table"><caption class="price-matrix__caption">Dollars a month at every vendor, by the imports a month and the rows in one file.</caption><thead><tr><th class="price-matrix__vendor price-matrix__vendor--head" scope="col">Importer</th><th class="price-matrix__band" colspan="5" scope="colgroup"><span class="price-matrix__band-count">10</span> <span class="price-matrix__band-unit">imports a month</span></th><th class="price-matrix__band" colspan="5" scope="colgroup"><span class="price-matrix__band-count">100</span> <span class="price-matrix__band-unit">imports a month</span></th><th class="price-matrix__band" colspan="5" scope="colgroup"><span class="price-matrix__band-count">1,000</span> <span class="price-matrix__band-unit">imports a month</span></th></tr><tr><th class="price-matrix__vendor price-matrix__vendor--sub" scope="col">rows per file</th><th class="price-matrix__size" scope="col">100</th><th class="price-matrix__size" scope="col">1K</th><th class="price-matrix__size" scope="col">10K</th><th class="price-matrix__size" scope="col">50K</th><th class="price-matrix__size" scope="col">100K</th><th class="price-matrix__size" scope="col">100</th><th class="price-matrix__size" scope="col">1K</th><th class="price-matrix__size" scope="col">10K</th><th class="price-matrix__size" scope="col">50K</th><th class="price-matrix__size" scope="col">100K</th><th class="price-matrix__size" scope="col">100</th><th class="price-matrix__size" scope="col">1K</th><th class="price-matrix__size" scope="col">10K</th><th class="price-matrix__size" scope="col">50K</th><th class="price-matrix__size" scope="col">100K</th></tr></thead><tbody><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">CSVbox</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$19</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$99</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Dromo</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$599</td><td class="price-matrix__cell">$2,849</td><td class="price-matrix__cell">$2,849</td><td class="price-matrix__cell">$2,849</td><td class="price-matrix__cell">$2,849</td><td class="price-matrix__cell">$2,849</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">EasyCSV</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$29</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$29</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$29</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">FileFeed</span> <span class="price-matrix__meter">OSS</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Flatfile</span> <span class="price-matrix__meter">cells</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Fuse</span> <span class="price-matrix__meter">cells</span></th><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$79</td><td class="price-matrix__cell">$159</td><td class="price-matrix__cell">$259</td><td class="price-matrix__cell">$979</td><td class="price-matrix__cell">$979</td><td class="price-matrix__cell">$1,159</td><td class="price-matrix__cell">$1,959</td><td class="price-matrix__cell">$2,959</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">HelloCSV</span> <span class="price-matrix__meter">OSS</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name" aria-label="Impler, self-hosted version available">Impler<sup class="price-matrix__self-hosted" aria-hidden="true">*</sup></span> <span class="price-matrix__meter">rows</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$35</td><td class="price-matrix__cell">$39</td><td class="price-matrix__cell">$67</td><td class="price-matrix__cell">$102</td><td class="price-matrix__cell">$35</td><td class="price-matrix__cell">$39</td><td class="price-matrix__cell">$102</td><td class="price-matrix__cell">$318</td><td class="price-matrix__cell">$568</td><td class="price-matrix__cell">$39</td><td class="price-matrix__cell">$102</td><td class="price-matrix__cell">$568</td><td class="price-matrix__cell">$2,568</td><td class="price-matrix__cell">$5,068</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name" aria-label="ImportCSV, self-hosted version available">ImportCSV<sup class="price-matrix__self-hosted" aria-hidden="true">*</sup></span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">ImportKit</span> <span class="price-matrix__meter">rows</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$149</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$149</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">$149</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">ImportOK</span> <span class="price-matrix__meter">flat</span></th><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td><td class="price-matrix__cell" aria-label="174 dollars a year">$174<span class="price-matrix__year" aria-hidden="true">yr</span></td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Ivandt</span> <span class="price-matrix__meter">flat</span></th><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td><td class="price-matrix__cell">$399</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name" aria-label="Mildport, self-hosted version available">Mildport<sup class="price-matrix__self-hosted" aria-hidden="true">*</sup></span> <span class="price-matrix__meter">rows</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$149</td><td class="price-matrix__cell">$209</td><td class="price-matrix__cell">$499</td><td class="price-matrix__cell">$749</td><td class="price-matrix__cell">$349</td><td class="price-matrix__cell">$409</td><td class="price-matrix__cell">$749</td><td class="price-matrix__cell">$2,749</td><td class="price-matrix__cell">$5,249</td><td class="price-matrix__cell">$2,499</td><td class="price-matrix__cell">$2,749</td><td class="price-matrix__cell">$7,249</td><td class="price-matrix__cell">$27,249</td><td class="price-matrix__cell">$52,249</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">react-csv-importer</span> <span class="price-matrix__meter">OSS</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Rowporter</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$35</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$35</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$15</td><td class="price-matrix__cell">$35</td><td class="price-matrix__cell">$100</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Rowslint</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$45</td><td class="price-matrix__cell">$45</td><td class="price-matrix__cell">$45</td><td class="price-matrix__cell">$45</td><td class="price-matrix__cell">$45</td></tr><tr class="price-matrix__row price-matrix__row--own"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Updog Importer</span> <span class="price-matrix__meter">rows</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td><td class="price-matrix__cell">$100</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">UseCSV</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$0</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td><td class="price-matrix__cell">$99</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">WeTransform</span> <span class="price-matrix__meter">rows</span></th><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$1,736</td><td class="price-matrix__cell">$1,736</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$921</td><td class="price-matrix__cell">$1,736</td><td class="price-matrix__cell">—</td><td class="price-matrix__cell">—</td></tr><tr class="price-matrix__row"><th class="price-matrix__vendor" scope="row"><span class="price-matrix__name">Xlork</span> <span class="price-matrix__meter">files</span></th><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$9</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td><td class="price-matrix__cell">$49</td></tr></tbody></table></div><figcaption class="price-matrix__notes"><ul class="price-matrix__legend"><li class="price-matrix__legend-item"><span class="price-matrix__meter">files</span> priced by imports a month</li><li class="price-matrix__legend-item"><span class="price-matrix__meter">rows</span> priced by rows a month</li><li class="price-matrix__legend-item"><span class="price-matrix__meter">cells</span> priced by cells a month</li><li class="price-matrix__legend-item"><span class="price-matrix__meter">flat</span> one price at every volume</li><li class="price-matrix__legend-item"><span class="price-matrix__meter">OSS</span> open source, free at every volume</li></ul><p class="price-matrix__self-hosted-note">* A self-hosted version is also available. Self-hosted pricing is not included in the matrix unless it is the vendor's only published option.</p></figcaption></figure>
<p>Each cell shows the cheapest published hosted price for that volume. The total includes overage wherever a vendor publishes its rate. Plain figures use each vendor's published month-to-month price. Annual discounts stay outside the matrix. A <strong>yr</strong> mark means the vendor sells the plan as one full yearly sum. Cell-based prices assume ten columns per file, and euro prices use an exchange rate of 1.1654 (the rate at the time of writing). A $0 means a free tier or an open-source project you host yourself.</p>
<p>Sales-led vendors quote on request and publish no figure, so the matrix leaves them out.</p>
<p>Updog Importer sits in the grid too, and this is our blog. <a href="https://updog.tech/pricing/">Our pricing</a> is free up to 100,000 rows a month, then $100 a month for any number of domains with no row limit, so our row never passes $100. Updog's figures follow the plan published in October 2026. Any vendor can change a plan after publication.</p>]]></content:encoded></item>
<item><title>How to Build a CSV Column Mapping UI in React</title><link>https://updog.tech/blog/csv-column-mapping-react/</link><guid isPermaLink="true">https://updog.tech/blog/csv-column-mapping-react/</guid><pubDate>Fri, 21 Aug 2026 00:00:00 GMT</pubDate><description>A file names its columns its own way. See how Updog Importer connects them to the fields your app asks for.</description><content:encoded><![CDATA[<p>A depot keeps sending the fleet team its vehicle list, 214 vehicles over seven columns. Your app holds seven fields for a vehicle, and three of those columns reach a field by name alone.</p>
<p><code>depot-fleet.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Vehicle #</td><td class="sheet__cell">Reg</td><td class="sheet__cell">Make/Model</td><td class="sheet__cell">Odo</td><td class="sheet__cell">In Service</td><td class="sheet__cell">Home Depot</td><td class="sheet__cell">Home Depot</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">FL-0001</td><td class="sheet__cell">LS24 TBK</td><td class="sheet__cell">Mercedes Sprinter 315</td><td class="sheet__cell">21 759</td><td class="sheet__cell">08/11/2025</td><td class="sheet__cell">East</td><td class="sheet__cell">DEP-E</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">FL-0002</td><td class="sheet__cell">LS19 SOK</td><td class="sheet__cell">Renault Trafic SL28</td><td class="sheet__cell">15 217</td><td class="sheet__cell">29/01/2024</td><td class="sheet__cell">East</td><td class="sheet__cell">DEP-E</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">FL-0003</td><td class="sheet__cell">MK18 WVT</td><td class="sheet__cell">Renault Trafic SL28</td><td class="sheet__cell">229 850</td><td class="sheet__cell">06/08/2023</td><td class="sheet__cell">East</td><td class="sheet__cell">DEP-E</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">FL-0004</td><td class="sheet__cell">BX17 ESG</td><td class="sheet__cell">Ford Transit Custom 300</td><td class="sheet__cell">162 995</td><td class="sheet__cell">21/07/2023</td><td class="sheet__cell">Wakefield</td><td class="sheet__cell">DEP-WF</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">FL-0005</td><td class="sheet__cell">MK24 WHJ</td><td class="sheet__cell">Mercedes Sprinter 315</td><td class="sheet__cell">20 090</td><td class="sheet__cell">25/01/2025</td><td class="sheet__cell">North</td><td class="sheet__cell">DEP-N</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">FL-0006</td><td class="sheet__cell">SN16 LWY</td><td class="sheet__cell">Vauxhall Vivaro 2900</td><td class="sheet__cell">196 856</td><td class="sheet__cell">23/08/2022</td><td class="sheet__cell">South</td><td class="sheet__cell">DEP-S</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">FL-0007</td><td class="sheet__cell">LT25 SYU</td><td class="sheet__cell">Ford Transit Custom 300</td><td class="sheet__cell">192 785</td><td class="sheet__cell">31/07/2021</td><td class="sheet__cell">Wakefield</td><td class="sheet__cell">DEP-WF</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">FL-0008</td><td class="sheet__cell">MK25 LJV</td><td class="sheet__cell">Ford Transit Custom 300</td><td class="sheet__cell">187 511</td><td class="sheet__cell">08/05/2021</td><td class="sheet__cell">East</td><td class="sheet__cell">DEP-E</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">205 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">215</th><td class="sheet__cell">FL-0214</td><td class="sheet__cell">YD22 NPZ</td><td class="sheet__cell">Vauxhall Vivaro 2900</td><td class="sheet__cell">88 402</td><td class="sheet__cell">14/03/2022</td><td class="sheet__cell">South</td><td class="sheet__cell">DEP-S</td></tr></tbody></table>
<p><code>Vehicle #</code> is your <code>assetTag</code>. <code>Reg</code> is your <code>plate</code>. <code>Make/Model</code> is two of your fields inside one column. <code>Odo</code> is a kilometre reading with a space in it. The depot appears twice, once as a name and once as a code, under one header printed twice. Nothing in that file was written with your schema in mind, and nothing about it is unusual.</p>
<p>The screen that connects the two sides is the mapping step, and it is state before it is anything else. That state, the write path that keeps it honest, and the React row on top of them are what this guide builds. The <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">React import guide</a> covers getting the parsed rows in the first place.</p>
<h2 id="step-1-write-down-the-two-sides">Step 1. Write down the two sides</h2>
<p>Your fields are fixed, they carry a label a person can read, and some of them are required.</p>
<pre><code class="language-ts">export type Field = {
  id: string;
  label: string;
  required?: boolean;
};

export const fields: Field[] = [
  { id: "assetTag", label: "Asset tag", required: true },
  { id: "plate", label: "Registration", required: true },
  { id: "make", label: "Make" },
  { id: "model", label: "Model" },
  { id: "odometerKm", label: "Odometer (km)" },
  { id: "inServiceDate", label: "In service", required: true },
  { id: "depot", label: "Depot" },
];</code></pre>
<p>The file side arrives from your parser as an array of header strings. Two of those strings are <code>Home Depot</code>. Any structure keyed by header text collapses them into one key, so the second column disappears before a person sees it. Give every column a distinct key first.</p>
<pre><code class="language-ts">export const dedupeHeaders = (headers: string[]): string[] => {
  const used = new Set&#x3C;string>();
  return headers.map((header) => {
    let candidate = header;
    let n = 2;
    while (used.has(candidate)) {
      candidate = header + " (" + n + ")";
      n++;
    }
    used.add(candidate);
    return candidate;
  });
};</code></pre>
<p>The headers now read <code>Home Depot</code> and <code>Home Depot (2)</code>. PapaParse 5.6.0 does the same thing on its own when you parse with <code>header: true</code>, renaming the repeat to <code>Home Depot_1</code> and recording the pair in <code>meta.renamedHeaders</code>. Either way the rule holds. One file column, one key, and the suffix is visible to the person on the screen.</p>
<h2 id="step-2-store-the-mapping-as-one-relation">Step 2. Store the mapping as one relation</h2>
<p>A mapping is a relation between two sets, and a person edits it one row at a time. One entry per file column, in file order, is the shape the screen already has.</p>
<pre><code class="language-ts">export type Mapping = {
  /** One entry per file column, in file order. */
  sourceColumn: string;
  /** A field id, or null while the column reaches nothing. */
  targetField: string | null;
  /** What the matcher scored the pair, 0 to 100. */
  confidence?: number;
};

export type MappingState = Mapping[];</code></pre>
<p><code>targetField</code> is <code>null</code> while a column reaches nothing, which is where every column starts. <code>confidence</code> is what the matcher scored the pair, and it exists so the screen can mark its own guesses apart from a person's answers.</p>
<p>Keying by file column is what makes the list renderable. Every entry is a row, unmapped columns hold their place in that list, and a field with no column stays a derived fact.</p>
<h2 id="step-3-enforce-one-field-per-column-on-write">Step 3. Enforce one field per column on write</h2>
<p>Two file columns cannot both fill <code>depot</code>. Left alone, the second one wins during the import and the first one is lost with no message. The place to settle that is the write path, so no caller can produce a state where a field is claimed twice.</p>
<pre><code class="language-ts">export const assign = (
  state: MappingState,
  sourceColumn: string,
  targetField: string | null,
): MappingState =>
  state.map((entry) => {
    if (entry.sourceColumn === sourceColumn) {
      return { sourceColumn, targetField, confidence: undefined };
    }
    if (targetField !== null &#x26;&#x26; entry.targetField === targetField) {
      return { ...entry, targetField: null, confidence: undefined };
    }
    return entry;
  });</code></pre>
<p>Assigning a field takes it from whichever column held it. The row that lost it goes back to <code>null</code> and shows as unmapped on the next render.</p>
<pre><code class="language-text">before   Home Depot → depot        Home Depot (2) → (none)
assign   Home Depot (2) → depot
after    Home Depot → (none)       Home Depot (2) → depot</code></pre>
<p>The rule you pick decides what the person sees, and two of the three keep one column per field.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Rule</th>
<th>What the person sees</th>
<th>What lands</th>
</tr>
</thead>
<tbody>
<tr>
<td>Steal</td>
<td>the losing row clears itself in front of them</td>
<td>one column per field</td>
</tr>
<tr>
<td>Refuse</td>
<td>the field is greyed out until they clear it themselves</td>
<td>one column per field</td>
</tr>
<tr>
<td>Allow both</td>
<td>two rows claiming one field, no warning</td>
<td>whichever column runs last</td>
</tr>
</tbody>
</table></div>
<p>Allowing both is the one to avoid. Stealing and refusing carry the same guarantee, and the steal takes fewer clicks.</p>
<h2 id="step-4-derive-the-screen-from-the-mapping">Step 4. Derive the screen from the mapping</h2>
<p>Everything the screen shows is a function of that one array. A separate count of matched columns, or a stored list of free fields, is a second copy that drifts the moment a person edits a row.</p>
<pre><code class="language-ts">export const takenFields = (state: MappingState): Set&#x3C;string> =>
  new Set(state.flatMap((e) => (e.targetField ? [e.targetField] : [])));

export const unmappedColumns = (state: MappingState): string[] =>
  state.filter((e) => e.targetField === null).map((e) => e.sourceColumn);

export const missingRequired = (
  state: MappingState,
  fields: Field[],
): Field[] => {
  const taken = takenFields(state);
  return fields.filter((f) => f.required &#x26;&#x26; !taken.has(f.id));
};</code></pre>
<p><code>missingRequired</code> is the one to keep in front of the person. The mapping step exists to settle whether the file can fill the fields your app cannot do without, and that list is the answer.</p>
<h2 id="step-5-render-one-row-per-file-column">Step 5. Render one row per file column</h2>
<p>The row carries the header, a few real values from under it, and the field picker. Sample values are what a person maps by. <code>Home Depot</code> and <code>Home Depot (2)</code> are the same word twice, and <code>East</code> against <code>DEP-E</code> tells them apart.</p>
<pre><code class="language-tsx">type RowProps = {
  entry: Mapping;
  fields: Field[];
  samples: string[];
  onAssign: (sourceColumn: string, targetField: string | null) => void;
};

export function MappingRow({ entry, fields, samples, onAssign }: RowProps) {
  const labelId = "map-" + entry.sourceColumn;

  return (
    &#x3C;div className="mapping-row">
      &#x3C;div>
        &#x3C;strong id={labelId}>{entry.sourceColumn}&#x3C;/strong>
        &#x3C;p>{samples.slice(0, 3).join(", ")}&#x3C;/p>
      &#x3C;/div>

      &#x3C;select
        aria-labelledby={labelId}
        value={entry.targetField ?? ""}
        onChange={(event) => {
          onAssign(entry.sourceColumn, event.target.value || null);
        }}
      >
        &#x3C;option value="">Do not import&#x3C;/option>
        {fields.map((field) => (
          &#x3C;option key={field.id} value={field.id}>
            {field.label}
            {field.required ? " *" : ""}
          &#x3C;/option>
        ))}
      &#x3C;/select>
    &#x3C;/div>
  );
}</code></pre>
<p>A native <code>&#x3C;select></code> gets keyboard support and the platform picker for nothing. The custom alternative owes the whole combobox pattern, which the <a href="https://www.w3.org/WAI/ARIA/apg/patterns/combobox/">ARIA Authoring Practices Guide</a> builds from <code>role="combobox"</code> and <code>aria-expanded</code>, plus <code>aria-controls</code> pointing at the popup while it is open, <code>aria-activedescendant</code> tracking the focused option, and <code>aria-autocomplete</code> describing what typing does. Take that on when a schema grows past what a person can scan, and pay it with a filter box.</p>
<p><code>aria-labelledby</code> points at the header alone, so a screen reader announces which column the dropdown belongs to. Put that id on the wrapper and the sample values underneath join the name.</p>
<h2 id="step-6-decide-what-happens-to-an-unmapped-column">Step 6. Decide what happens to an unmapped column</h2>
<p>The mapping is also the import plan. A column with <code>targetField: null</code> writes nothing.</p>
<pre><code class="language-ts">export const buildRecords = (
  rows: Record&#x3C;string, string>[],
  state: MappingState,
): Record&#x3C;string, string>[] => {
  const plan = state.flatMap((entry) =>
    entry.targetField === null
      ? []
      : [{ from: entry.sourceColumn, to: entry.targetField }],
  );

  return rows.map((row) => {
    const record: Record&#x3C;string, string> = {};
    for (const { from, to } of plan) {
      record[to] = row[from] ?? "";
    }
    return record;
  });
};</code></pre>
<p>That is the moment the file loses data, and it is silent by construction.</p>
<pre><code class="language-text">file value      Reg = "LS24 TBK"
mapping         Reg → (none)
imported row    { assetTag: "FL-0001", make: "Mercedes Sprinter 315" }</code></pre>
<p>The registration number is in the file, on the screen, and absent from the record. A mapping step catches that either before the person moves on or after the rows land.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Rule</th>
<th>Cost</th>
<th>Fits</th>
</tr>
</thead>
<tbody>
<tr>
<td>Block the step while a required field is unmapped</td>
<td>the person cannot move on, and cannot see the rows either</td>
<td>a schema whose required fields are few and obvious</td>
</tr>
<tr>
<td>Let them through and validate the rows</td>
<td>the empty cell arrives with a row number and a message</td>
<td>a schema where a person needs the data in front of them to decide</td>
</tr>
</tbody>
</table></div>
<p>Blocking early is the stricter guarantee. Validating later shows the person which rows are affected before they go back and fix the mapping. Pick one, and say which on the screen.</p>
<h2 id="step-7-rebuild-the-mapping-when-the-file-changes">Step 7. Rebuild the mapping when the file changes</h2>
<p>The mapping is derived from a specific list of headers, and that list changes under it.</p>
<p>The header row moves. A person tells you row 1 was a title and the real headers sit on row 3. Every key in the mapping changes, and the answers they typed by hand have to survive under the headers that still read the same.</p>
<p>A second file arrives. Its headers are its own, and its <code>Depot</code> is not the first file's <code>Depot</code>. One mapping per file keeps the one-field-per-column rule true where it is true, which is inside a file. A single mapping keyed by header text across two files lets one file's <code>Work</code> take <code>company</code> from the other file's own <code>Company</code> header.</p>
<p>The person starts over. Then the mapping goes with the file that produced it.</p>
<p>One rule covers all three changes. Treat a fresh proposal as the base and lift the person's own answers on top of it. An answer whose header no longer exists drops out with it.</p>
<h2 id="what-one-column-to-one-field-cannot-do">What one column to one field cannot do</h2>
<p><code>Make/Model</code> holds <code>Mercedes Sprinter 315</code>. Your schema wants <code>make</code> and <code>model</code>. A one-to-one mapping has no way to express that, so one of the two fields stays empty whatever the person picks. Splitting a column is a transform, and it belongs after the mapping step or before the file arrives. Saying that out loud beats a dropdown that silently drops half the value.</p>
<p>The same limit runs the other way. Two columns that both belong in <code>notes</code> need a join, and a mapping step that steals the field from one of them is telling the truth about what it can do.</p>
<p>Matching itself has a floor. <code>Vehicle #</code>, <code>Reg</code> and <code>Odo</code> reach nothing in this schema by string similarity alone. Normalization strips spaces and a few separators and leaves the <code>#</code> standing, so <code>vehicle#</code> meets <code>assettag</code>, and a three-letter header is too short to be contained by <code>Registration</code> or <code>Odometer (km)</code>. No table of synonyms is complete, and every mapping step needs the dropdown behind it.</p>
<h2 id="the-same-screen-with-updog-importer">The same screen with Updog Importer</h2>
<p>Updog Importer ships this step. You describe the same fields as columns, and the words your schema invented go in as synonyms.</p>
<pre><code class="language-tsx">import { DataEditor, type DataEditorColumn } from "@updog/data-editor";

const columns: DataEditorColumn[] = [
  { id: "assetTag", title: "Asset tag", validators: [{ type: "required" }] },
  { id: "plate", title: "Registration", validators: [{ type: "required" }] },
  { id: "make", title: "Make" },
  { id: "model", title: "Model" },
  { id: "odometerKm", title: "Odometer (km)", editor: { type: "number" } },
  { id: "inServiceDate", title: "In service", editor: { type: "date" } },
  {
    id: "depot",
    title: "Depot",
    editor: {
      type: "select",
      options: ["North", "South", "East", "Wakefield"],
    },
  },
];

type Props = { open: boolean; onClose: () => void };

export function FleetImport({ open, onClose }: Props) {
  return (
    &#x3C;DataEditor
      apiKey="your-license-key"
      open={open}
      onClose={onClose}
      columns={columns}
      primaryKey="assetTag"
      synonyms={{
        columns: {
          assetTag: ["vehicle #", "vehicle no", "fleet number"],
          plate: ["reg", "reg no", "number plate"],
          odometerKm: ["odo", "mileage"],
        },
      }}
      onComplete={async (result) => {
        await saveVehicles(result.sources);
      }}
    />
  );
}</code></pre>
<p>Against the depot file, <code>In Service</code> reaches <code>inServiceDate</code> on its own, scoring 100 against the column title. <code>Make/Model</code> scores 80 against both <code>make</code> and <code>model</code> and takes one of them. <code>Home Depot</code> reaches <code>depot</code>, and <code>Home Depot (2)</code> finds it taken. The three synonym lists above cover <code>Vehicle #</code>, <code>Reg</code> and <code>Odo</code>, which score zero without them.</p>
<pre><code class="language-text">Vehicle #        → assetTag        (synonym)
Reg              → plate           (synonym)
Make/Model       → make            (80, model stays empty)
Odo              → odometerKm      (synonym)
In Service       → inServiceDate   (100)
Home Depot       → depot           (80)
Home Depot (2)   → (none)</code></pre>
<p>The screen shows a matched count per file, a green Best match tag on the option the matcher chose, a header that opens a panel of real values from that column, and a Show matched checkbox, on from the start, that clears the answered rows out of the list once a person turns it off. A column mapped to nothing imports nothing, and its data never reaches the grid. Nothing on that step blocks Next, so a required field left empty is caught by validation in the grid instead, where the person can see the rows.</p>
<p>The pairs a person fixes by hand come back in <code>learnedSynonyms</code> on submit, and go into the <code>synonyms</code> prop on the next open, which is what <a href="https://updog.tech/blog/remember-csv-import-mappings/">remembering a mapping between uploads</a> is built on.</p>
<h2 id="what-you-built">What you built</h2>
<p>One array holding one entry per file column. A write path that keeps a field to a single column. Three derived lists that the screen reads and never stores. A row with a real label on a real select. A build step that says out loud which columns land and which do not.</p>
<p>The dropdowns are the part a person sees, and the invariant is the part that decides whether the file arrives whole. <a href="https://updog.tech/blog/csv-import-is-more-than-parsing/">Parsing hands you the columns</a>, and this step is where they stop being strings and start being your data.</p>]]></content:encoded></item>
<item><title>How to Preserve Leading Zeros in CSV and Excel Imports</title><link>https://updog.tech/blog/preserving-leading-zeros-in-csv-and-excel-imports/</link><guid isPermaLink="true">https://updog.tech/blog/preserving-leading-zeros-in-csv-and-excel-imports/</guid><pubDate>Fri, 21 Aug 2026 00:00:00 GMT</pubDate><description>A stock file arrives with 422 where 00422 belongs. See how Updog Importer puts the zeros back.</description><content:encoded><![CDATA[<p>A stock code written <code>00422</code> reaches an import as one of two values.</p>
<pre><code class="language-text">00422   →   00422     five characters, all of them still there
00422   →   422       read as a number somewhere along the way</code></pre>
<p>Only one of those two can be repaired by better parsing. The other one lost its
zeros before the file was handed over, and no reader recovers them from the
value alone. Search the problem and the answers arrive from inside the
spreadsheet window, telling you to format a column as text before the file is
opened. That stops the second line from happening on your own screen, and does
nothing for a file that arrives on it already.</p>
<p>This is a builders' merchant stock export, 184 rows, shipped as a CSV and as a
workbook of the same sheet.</p>
<p><code>padgate-supply.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Stock code</td><td class="sheet__cell">Barcode</td><td class="sheet__cell">Bin</td><td class="sheet__cell">Description</td><td class="sheet__cell">Cost centre</td><td class="sheet__cell">Pack qty</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">00401</td><td class="sheet__cell">05012340000000</td><td class="sheet__cell">0123</td><td class="sheet__cell">Copper pipe 15mm x 3m</td><td class="sheet__cell">0115</td><td class="sheet__cell">30</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">6 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">422</td><td class="sheet__cell">05012340000959</td><td class="sheet__cell">0031</td><td class="sheet__cell">Push-fit tee 15mm</td><td class="sheet__cell">0115</td><td class="sheet__cell">28</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">14</th><td class="sheet__cell">00437</td><td class="sheet__cell">5012340001644</td><td class="sheet__cell">0179</td><td class="sheet__cell">Copper pipe 22mm x 3m</td><td class="sheet__cell">0080</td><td class="sheet__cell">27</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">20</th><td class="sheet__cell">00455</td><td class="sheet__cell">05012340002466</td><td class="sheet__cell">0155</td><td class="sheet__cell">Solvent cement 250ml</td><td class="sheet__cell">'0075</td><td class="sheet__cell">22</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">26</th><td class="sheet__cell">00473</td><td class="sheet__cell">05012340003288</td><td class="sheet__cell">0152</td><td class="sheet__cell">PTFE tape 12mm x 12m</td><td class="sheet__cell">0115</td><td class="sheet__cell">7</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">31</th><td class="sheet__cell">00488</td><td class="sheet__cell">05012340003973</td><td class="sheet__cell">0212</td><td class="sheet__cell">Isolating valve 15mm</td><td class="sheet__cell">="0115"</td><td class="sheet__cell">20</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">36</th><td class="sheet__cell">00503</td><td class="sheet__cell">05012340004658</td><td class="sheet__cell">42</td><td class="sheet__cell">Backnut 1/2 inch</td><td class="sheet__cell">0080</td><td class="sheet__cell">5</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">42</th><td class="sheet__cell">00422</td><td class="sheet__cell">05012340005480</td><td class="sheet__cell">0160</td><td class="sheet__cell">Push-fit tee 15mm</td><td class="sheet__cell">0080</td><td class="sheet__cell">31</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">10 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">53</th><td class="sheet__cell">00554</td><td class="sheet__cell">05012340006987</td><td class="sheet__cell">0041</td><td class="sheet__cell">Compression stop end 28mm</td><td class="sheet__cell"></td><td class="sheet__cell">20</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">131 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">185</th><td class="sheet__cell">00950</td><td class="sheet__cell">05012340025071</td><td class="sheet__cell">0068</td><td class="sheet__cell">Solder ring coupler 28mm</td><td class="sheet__cell">0075</td><td class="sheet__cell">42</td></tr></tbody></table>
<p>Line 2 is the file behaving. Line 9 holds a stock code that is three characters
where every other one is five. Line 14 holds a barcode one digit short. Line 20
carries an apostrophe in front of the padding, line 31 wraps it in a formula,
line 36 drops the bin down to two digits, and line 42 is the same item as line 9
under a code that still has its zeros.</p>
<h2 id="where-the-zeros-go">Where the zeros go</h2>
<p>Of the three moments that can take them, only the last one belongs to your code.</p>
<p>Microsoft documents the first. Excel "automatically removes leading zeros, and
converts large numbers to scientific notation, like 1.23E+15, in order to allow
formulas and math operations to work on them". A system exporting through
a spreadsheet engine inherits that.</p>
<p>The second is the file being opened between the export and you. Opening a CSV
directly "uses the current default data format settings to interpret how to
import each column of data", so <code>00422</code> becomes the number 422 on screen. Save
that workbook back to CSV and the bytes now hold <code>422</code>.</p>
<p>The third is your own reader, and it is the easiest to rule out. Our CSV parser
runs PapaParse with <code>dynamicTyping</code> left at its default of <code>false</code>, which means
every field comes back as a string and a padded value stays padded.</p>
<p>There is a thread on Microsoft's own support site where a person with "part
numbers that are numbers stored as text with leading zeros" reports that the
zeros disappear when they save as CSV. They tried the text format, the Text to
Columns wizard, and a <code>=LEFT(A2,LEN(A2))</code> formula.</p>
<p>Two different files can produce that report. One holds text cells and writes
the padding into the CSV, where it comes back the moment anything other than a
spreadsheet opens it. The other lost the zeros before the Text format was
applied, because that format
"will not change numbers that have already been entered". Nothing on screen
separates the two, and the second one is the only one that needs the export
fixed. Telling them apart starts inside the cell.</p>
<h2 id="what-a-spreadsheet-holds-under-what-you-see">What a spreadsheet holds under what you see</h2>
<p>Microsoft's own worked example for a postal code is "00123 with custom number
format 00000". The format is what puts the zeros on screen, and the value under
it is the number 123. The padding is a rendering instruction.</p>
<p>That gives a workbook two answers per cell, and picking the wrong one throws the
padding away. Reading the same file with SheetJS, the library we use for
workbooks, shows both.</p>
<pre><code class="language-text">A2   t=n   v=401              w="00401"
A9   t=n   v=422              w="422"
A26  t=s   v="00473"          w="00473"
B2   t=n   v=5012340000000    w="05012340000000"
B14  t=n   v=5012340001644    w="5.01234E+12"
C36  t=n   v=42               w="42"</code></pre>
<p><code>v</code> is the raw value, <code>w</code> is the formatted text, and <code>t</code> is the cell type, where
<code>n</code> is a number and <code>s</code> is a string. A2 and B2 are numbers wearing a padded
format. A9 and C36 are numbers with nothing to pad them, which is what a lost
zero looks like from the inside. A26 is the one cell the exporting system wrote
as text.</p>
<p>Updog Importer reads <code>w</code>, the text the person saw in the spreadsheet, and falls
back to <code>v</code> only where there is no formatted text. So A2 arrives as <code>00401</code> and
A9 arrives as <code>422</code>, which is the honest answer for both.</p>
<p>B14 is the exception written into the reader. Its format is General, and a
General number that long renders as <code>5.01234E+12</code>, so the displayed text there
would keep six of its thirteen digits. Where the formatted text carries an
exponent and the raw value is finite, the raw value wins. B14 arrives as
<code>5012340001644</code>.</p>
<p>Run the CSV and the workbook through the importer and the rows come back the
same, down to the apostrophe on line 20 and the formula wrapper on line 31. The
one difference is line 53's empty cost centre, which the CSV gives as an empty
string and the workbook as <code>null</code>. The workbook carries more information about
its cells, and none of it reaches the values. The type waiting on the other side
decides what the value becomes.</p>
<h2 id="which-columns-are-text">Which columns are text</h2>
<p>A field is a number when someone will do arithmetic on it. A quantity gets added
up, and a stock code gets looked up.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Field</th>
<th>Type</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>stockCode</code></td>
<td>string</td>
<td>five digits by the merchant's own numbering</td>
</tr>
<tr>
<td><code>barcode</code></td>
<td>string</td>
<td>fourteen digits that identify a product</td>
</tr>
<tr>
<td><code>binRef</code></td>
<td>string</td>
<td>an aisle and a shelf, written as digits</td>
</tr>
<tr>
<td><code>costCentre</code></td>
<td>string</td>
<td>an accounting reference</td>
</tr>
<tr>
<td><code>packQty</code></td>
<td>number</td>
<td>you multiply it by a price</td>
</tr>
</tbody>
</table></div>
<p>Digits alone decide nothing. GS1 makes that visible inside one organisation's
own standards. In GS1 XML a trade item number "can only contain 14 numeric
characters. Thus, whether the actual number is 13, 12 or 8 digits long, it has
to be right justified and filled with zeroes up to 14 digits". In GS1 EANCOM the
same identifier is declared <code>n..14</code> and "all the leading zeroes in the GTIN
number have to be suppressed". One identifier, two documents from one body, and
the leading zero is required by one and forbidden by the other.</p>
<p>The width belongs to whoever owns the field. Your schema is where it gets
written down.</p>
<h2 id="what-a-number-column-does-to-a-padded-value">What a number column does to a padded value</h2>
<p>A number column leaves the padding alone and then flags every row that has it.</p>
<p>The importer canonicalises a number column into a form JavaScript can parse, and
the grammar it works to allows a leading zero only where that zero is the whole
integer part. <code>00401</code> fails it, and a value that fails comes back exactly as it
arrived. The padding survives the normalizer.</p>
<p>The number validator that runs next rejects it.</p>
<pre><code class="language-text">line 2 · Stock code · "00401" · Invalid number
line 3 · Stock code · "00404" · Invalid number
line 4 · Stock code · "00407" · Invalid number</code></pre>
<p>Measured over this file, a <code>{ type: "number" }</code> rule on <code>stockCode</code> flags 183 of
184 rows. The row it passes is line 9, the one whose zeros are already gone. The
grid also refuses to group a value like that into <code>00,123</code>, because grouping a
flagged identifier would corrupt the thing the person has to fix.</p>
<p>183 flagged rows are the visible version of this mistake. A column that
renumbers every item in the file and reports nothing is the version nobody
catches.</p>
<h2 id="how-the-loss-becomes-visible">How the loss becomes visible</h2>
<p>A width is a rule, so write it as one.</p>
<pre><code class="language-ts">{
  id: "stockCode",
  title: "Stock code",
  validators: [
    { type: "required" },
    { type: "regex", pattern: "^\\d{5}$", message: "Five digits" },
  ],
}</code></pre>
<p><code>^\d{5}$</code> accepts five digits and nothing else. A padded value passes. A value
that lost its padding is three or four characters long and lands on screen with
its line number and its own message.</p>
<p>Over the 184 rows, with a width rule on each of the four text columns, five
cells stop.</p>
<pre><code class="language-text">line 9   Stock code    "422"             Five digits
line 14  Barcode       "5012340001644"   Fourteen digits
line 20  Cost centre   "'0075"           Four digits
line 31  Cost centre   "=\"0115\""       Four digits
line 36  Bin           "42"              Four digits</code></pre>
<p>Five out of 184, each one a cell where something took the padding away, and each
one now sitting in the grid in front of a person who knows what the code should
be. Line 53's cost centre is empty and passes, because every built-in rule
except <code>required</code> lets an empty value through.</p>
<h2 id="when-a-zero-can-be-put-back">When a zero can be put back</h2>
<p>Three of those five are a character or two short of a width that never changes,
and that is enough to rebuild them.</p>
<pre><code class="language-ts">const pad = (width: number) => {
  return (value: unknown): unknown => {
    const text = String(value ?? "").trim();
    return /^\d+$/.test(text) &#x26;&#x26; text.length &#x3C; width
      ? text.padStart(width, "0")
      : value;
  };
};</code></pre>
<p><code>transformer</code> runs on the way into the store, so the stored value is the padded
one and everything downstream sees it. The guard matters more than the padding.
A value holding anything other than digits comes back untouched, so <code>'0075</code> and
<code>="0115"</code> reach a person exactly as they arrived.</p>
<p>With <code>pad</code> on the three fixed-width columns, the same file fails two width rules
instead of five, and both are on the column that has no transformer. The barcode
repair follows GS1's own rule, right justified and filled with zeroes up to
fourteen digits.</p>
<p>The padded file also reports a duplicate.</p>
<pre><code class="language-text">line 9    stockCode "422"     →   "00422"
line 42   stockCode "00422"
unique    "00422" appears on lines 9 and 42</code></pre>
<p>Line 9 and line 42 are one item. Under the codes as they arrived they were two
keys, and <code>{ type: "unique" }</code> had nothing to report. Putting the zeros back
made the duplicate reachable.</p>
<h2 id="what-padding-cannot-decide">What padding cannot decide</h2>
<p>Nothing in the importer knows how wide your codes are. There is no detector that
reads a column and concludes it should be five digits. The width comes from your
schema or it does not exist, and <code>pad(5)</code> over a numbering scheme that runs from
four digits to six invents a zero and hands you a wrong code that validates.</p>
<p>The tail is worse than the head. Excel "has a maximum precision of 15
significant digits, which means that for any number containing 16 or more
digits, such as a credit card number, any numbers past the 15th digit are
rounded down to zero". A short value at least tells you how many characters are
missing. Sixteen digits with three zeros on the end are still sixteen digits, so
a width rule waves them through and the account they name does not exist. That
one belongs on the wider list of
<a href="https://updog.tech/blog/common-csv-import-errors/">things a CSV import gets wrong</a>.</p>
<p>An apostrophe in front of a value is a convention that lives in a spreadsheet
window. Written into a CSV it is a character like any other, and <code>'0075</code> reaches
the schema as five characters. Same for <code>="0115"</code>, which is an export trying to
protect its own padding from the next spreadsheet that opens the file. Both stay
flagged on purpose.</p>
<p>And the whole defence rests on the file having kept its zeros. When the export
that produced it already dropped them, the width rule tells you which rows are
affected and a person tells you what they should be. Fixing the export is the
only thing that stops it happening again.</p>
<h2 id="what-you-write">What you write</h2>
<p>Four text columns with a width rule, three of them repaired on the way in, and
one real number.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  {
    id: "stockCode",
    title: "Stock code",
    transformer: pad(5),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^\\d{5}$", message: "Five digits" },
      { type: "unique" },
    ],
  },
  {
    id: "barcode",
    title: "Barcode",
    transformer: pad(14),
    validators: [{ type: "regex", pattern: "^\\d{14}$", message: "Fourteen digits" }],
  },
  {
    id: "binRef",
    title: "Bin",
    transformer: pad(4),
    validators: [{ type: "regex", pattern: "^\\d{4}$", message: "Four digits" }],
  },
  { id: "description", title: "Description" },
  {
    id: "costCentre",
    title: "Cost centre",
    validators: [{ type: "regex", pattern: "^\\d{4}$", message: "Four digits" }],
  },
  {
    id: "packQty",
    title: "Pack qty",
    editor: { type: "number" },
    validators: [{ type: "number", min: 1 }],
  },
];</code></pre>
<p><code>transformer</code> runs first, then the validators run against what it produced, then
<code>unique</code> runs against the stored value. Which of the file's headers becomes each
of these columns is settled one step earlier, in
<a href="https://updog.tech/blog/csv-column-mapping-react/">column matching</a>, and the same shape of
problem in a date column is
<a href="https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/">a file that cannot say what order it is written in</a>.</p>
<p>A leading zero is the difference between finding a record and creating a second
one. Both files here still carried theirs. Keeping them took a column that was
never told to add anything up.</p>]]></content:encoded></item>
<item><title>How to Import Contacts from CSV into Your SaaS</title><link>https://updog.tech/blog/how-to-import-contacts-from-csv/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-contacts-from-csv/</guid><pubDate>Thu, 20 Aug 2026 00:00:00 GMT</pubDate><description>A contact list arrives with no id column. See how Updog Importer decides which of those people you already hold.</description><content:encoded><![CDATA[<p>A staff export carries a staff number. An invoice carries an invoice number. A
product export carries a SKU. The contact list below carries a name, an address,
a phone number, and no id column.</p>
<p>Which column stands in for that id is your decision. Every merge in every upload
after the first one follows from it, and so does every person a merge takes off
the list.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>Saltmere Safety Training left a mailing tool and a booking spreadsheet, and both
exports went into one file. 186 rows, eight headers. The first eight rows
carry most of the problem, and rows 112 and 113 carry the rest.</p>
<p><code>saltmere-contacts.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">First name</td><td class="sheet__cell">Surname</td><td class="sheet__cell">Organisation</td><td class="sheet__cell">E-mail</td><td class="sheet__cell">Work Email</td><td class="sheet__cell">Mobile</td><td class="sheet__cell">Account manager</td><td class="sheet__cell">Interests</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">Nadia</td><td class="sheet__cell">Brandt</td><td class="sheet__cell">Heronwood Care</td><td class="sheet__cell">nadia.brandt@heronwood.example</td><td class="sheet__cell"></td><td class="sheet__cell">+44 7700 900418</td><td class="sheet__cell">ivy.crane@saltmere.example</td><td class="sheet__cell">Manual Handling, Fire Safety</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">Tomas</td><td class="sheet__cell">Vella</td><td class="sheet__cell">Vellamore Ltd</td><td class="sheet__cell">office@vellamore.example</td><td class="sheet__cell">t.vella@vellamore.example</td><td class="sheet__cell">07700 900731</td><td class="sheet__cell">ivy.crane@saltmere.example</td><td class="sheet__cell">Fire Safety;First Aid</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">Ines</td><td class="sheet__cell">Cardoso</td><td class="sheet__cell">Vellamore Ltd</td><td class="sheet__cell">office@vellamore.example</td><td class="sheet__cell"></td><td class="sheet__cell">07700 900731</td><td class="sheet__cell">ivy.crane@saltmere.example</td><td class="sheet__cell">First Aid</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">Amrit</td><td class="sheet__cell">Sandhu</td><td class="sheet__cell">Kelsby Works</td><td class="sheet__cell">a.sandhu@kelsbyworks.example</td><td class="sheet__cell"></td><td class="sheet__cell">00447700900265</td><td class="sheet__cell">dev.oyelaran@saltmere.example</td><td class="sheet__cell">Working at Height</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">Amrit</td><td class="sheet__cell">Sandhu</td><td class="sheet__cell">Kelsby Works</td><td class="sheet__cell">amrit.sandhu@kelsbyworks.example</td><td class="sheet__cell"></td><td class="sheet__cell">+44 7700 900318</td><td class="sheet__cell">dev.oyelaran@saltmere.example</td><td class="sheet__cell">Asbestos Awareness</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">Rowan</td><td class="sheet__cell">Ferrand</td><td class="sheet__cell">Ashlyn Group</td><td class="sheet__cell">R.Ferrand@ashlyn.example</td><td class="sheet__cell"></td><td class="sheet__cell">+447700900904</td><td class="sheet__cell">ivy.crane@saltmere.example</td><td class="sheet__cell">Fire safety, manual handling</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">Kofi Adjetey</td><td class="sheet__cell"></td><td class="sheet__cell">Marlowe Heath Estates</td><td class="sheet__cell">k.adjetey@marloweheath.example</td><td class="sheet__cell"></td><td class="sheet__cell">(0044) 7700 900612</td><td class="sheet__cell">roisin.tuohy@saltmere.example</td><td class="sheet__cell">MH; FS</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">Sofia</td><td class="sheet__cell">Nkemelu</td><td class="sheet__cell">Kelsby Works</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">07700 900947</td><td class="sheet__cell">dev.oyelaran@saltmere.example</td><td class="sheet__cell">First Aid</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">102 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">112</th><td class="sheet__cell">Clemency</td><td class="sheet__cell">Nettleship</td><td class="sheet__cell">Ovingham Print</td><td class="sheet__cell">c.nettleship@ovinghamprint.example</td><td class="sheet__cell"></td><td class="sheet__cell">07700 900355</td><td class="sheet__cell">roisin.tuohy@saltmere.example</td><td class="sheet__cell">Fire Safety</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">113</th><td class="sheet__cell">Casimir</td><td class="sheet__cell">Nettleship</td><td class="sheet__cell">Ovingham Print</td><td class="sheet__cell">c.nettleship@ovinghamprint.example</td><td class="sheet__cell"></td><td class="sheet__cell">+44 7700 900372</td><td class="sheet__cell">roisin.tuohy@saltmere.example</td><td class="sheet__cell">Manual Handling, First Aid</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">73 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">187</th><td class="sheet__cell">Yusuf</td><td class="sheet__cell">Adeyemi</td><td class="sheet__cell">Kelsby Works</td><td class="sheet__cell">y.adeyemi@kelsbyworks.example</td><td class="sheet__cell"></td><td class="sheet__cell">07700 900788</td><td class="sheet__cell">dev.oyelaran@saltmere.example</td><td class="sheet__cell">Working at Height</td></tr></tbody></table>
<p>Tomas Vella and Ines Cardoso sit behind one mailbox. Two people called Amrit
Sandhu work at Kelsby Works. Sofia Nkemelu has no address. Every number in the file
sits inside 07700 900000 to 900999, the mobile range
<a href="https://www.ofcom.org.uk/phones-and-broadband/phone-numbers/numbers-for-drama">Ofcom reserves for drama</a>,
so none of them reaches anybody.</p>
<h2 id="the-schema-it-becomes">The schema it becomes</h2>
<p>Seven fields, and two of them carry a transformer that runs before the value
enters the editor.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const COURSES = [
  "Manual Handling",
  "Fire Safety",
  "First Aid",
  "Working at Height",
  "Asbestos Awareness",
];

const UK_MOBILE = /^(?:\+?44|0044|0)(\d{10})$/;

const toE164 = (value: unknown): string => {
  const digits = String(value).replace(/[^\d+]/g, "");
  const match = UK_MOBILE.exec(digits);
  return match ? "+44" + match[1] : String(value).trim();
};

export const columns: DataEditorColumn[] = [
  { id: "firstName", title: "First name" },
  {
    id: "lastName",
    title: "Last name",
    validators: [{ type: "required" }],
  },
  {
    id: "email",
    title: "Email",
    transformer: (value) => String(value).trim().toLowerCase(),
    validators: [{ type: "email" }, { type: "unique" }],
  },
  {
    id: "phone",
    title: "Phone",
    transformer: toE164,
    validators: [
      {
        type: "regex",
        pattern: "^\\+[1-9]\\d{6,14}$",
        message: "Write the number as +447700900418",
      },
    ],
  },
  {
    id: "company",
    title: "Company",
    validators: [{ type: "required" }],
  },
  { id: "owner", title: "Account manager" },
  {
    id: "interests",
    title: "Interests",
    editor: { type: "multiselect", options: COURSES },
    validators: [{ type: "oneOf", values: COURSES }],
  },
];</code></pre>
<p><code>toE164</code> rewrites a UK mobile in any of the five shapes the file uses. The
<code>email</code> transformer trims the address and lowercases it. Both run on every value
arriving from outside the editor, so a file import, <code>loadData</code>, a remote source
and a paste of text from another app all call them, and the value the key
compares is the value the transformer produced. A value moving inside the grid
is left alone, so a manual edit, a fill, an undo and a redo never call them.</p>
<p>The value reaches the transformer in the shape the cell holds. A number and a
date reach it canonical, a <code>select</code> value reaches it as the option the person
confirmed, and a <code>multiselect</code> column hands it one token at a time.</p>
<h2 id="where-the-file-and-the-schema-disagree">Where the file and the schema disagree</h2>
<p>Eight values across the 186 rows each land somewhere different.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Value in the file</th>
<th>What it hits</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Work Email</code> beside <code>E-mail</code></td>
<td>two headers, one field, and one of them strands</td>
</tr>
<tr>
<td><code>office@vellamore.example</code></td>
<td>one mailbox on two people</td>
</tr>
<tr>
<td><code>R.Ferrand@ashlyn.example</code></td>
<td>a stored address that differs only in case</td>
</tr>
<tr>
<td><code>(0044) 7700 900612</code></td>
<td>the fifth written form in one column</td>
</tr>
<tr>
<td><code>Fire Safety;First Aid</code></td>
<td>a second delimiter inside one cell</td>
</tr>
<tr>
<td><code>MH; FS</code></td>
<td>initials that reach no option</td>
</tr>
<tr>
<td><code>Kofi Adjetey</code> in <code>First name</code></td>
<td>a surname that was never split out</td>
</tr>
<tr>
<td>an empty <code>E-mail</code></td>
<td>a row that can build no key</td>
</tr>
</tbody>
</table></div>
<p>The generic form of each one sits in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>.</p>
<h2 id="the-second-email-header">The second email header</h2>
<p><code>E-mail</code> and <code>Work Email</code> both mean the address field. Updog Importer pins exact
matches first, then solves the rest as one assignment where each field takes one
header. <code>E-mail</code> normalizes to <code>email</code>, so the exact pass takes the field and
reserves it. <code>Work Email</code> is then scored against the fields still free, and
reaches none of them.</p>
<pre><code class="language-text">First name       →  firstName      exact
Surname          →  lastName       synonym, 90
Organisation     →  company        synonym, 90
E-mail           →  email          exact, pinned
Work Email       →  nothing
Mobile           →  phone          synonym, 90
Account manager  →  owner          exact against the title
Interests        →  interests      exact</code></pre>
<p>One header per field is the rule that stops a second address column from
stealing the first one. <code>Work Email</code> still has three places to go. The person
points it at a field by hand, or takes the Create column option the dropdown
offers, or you add a <code>workEmail</code> field to the schema and the exact pass lands it
there on the next upload. The algorithm behind that screen is in
<a href="https://updog.tech/blog/csv-column-mapping-react/">how to build a CSV column mapping UI</a>.</p>
<h2 id="the-number-written-five-ways">The number written five ways</h2>
<p>The file writes UK mobiles in five shapes. <code>+44 7700 900418</code> on one row,
<code>07700 900731</code> on the next, then <code>00447700900265</code>, <code>+447700900904</code> and
<code>(0044) 7700 900612</code>. The mailing tool and the booking sheet each wrote numbers
their own way, so a key on this column compares habits before it compares people.</p>
<p><a href="https://www.itu.int/rec/T-REC-E.164-202602-I/en">E.164</a> is the numbering plan
that settles the shape. An international number carries fifteen digits at most,
and the first one, two or three of them are the country code. The prefix a caller
dials to leave their own country sits outside that count. One canonical form per
subscriber is what <code>toE164</code> produces.</p>
<pre><code class="language-text">+44 7700 900418      →  +447700900418
07700 900731         →  +447700900731
00447700900265       →  +447700900265
+447700900904        →  +447700900904
(0044) 7700 900612   →  +447700900612</code></pre>
<p>Nadia Brandt sits in your database on <code>+447700900418</code>, and her row in the file
writes the same subscriber as <code>+44 7700 900418</code>. Key on the phone column and the
transformer makes those one string, so her row merges.</p>
<p>That regular expression reads UK numbers and nothing else, mobile or not. A file
carrying numbers from more than one country needs a phone number library. The
transformer is where that library normalizes a number, and a
<code>{ type: "function", fn }</code> validator is where it judges one, so both halves stay
in code you own.</p>
<p><code>phone</code> holds text, so those five written forms are yours to settle. A <code>date</code>
column and a <code>number</code> column reach the store in one shape already. Updog
Importer scores every shape it knows against the values in the column, and the
shape that explains the most of them takes the whole column. Twenty three
writings of one day land on <code>2026-05-01</code>, among them <code>01/05/2026</code>, <code>1 May 2026</code>,
<code>2026年5月1日</code> and the Excel serial <code>46143</code>, with month names read in the editor's
own locale. Nine separator pairs do the same work for numbers, so <code>1 234,56</code>,
<code>1'234.56</code> and <code>12,34,567.89</code> all land as digits around one point. <code>1,234</code> reads
as <code>1234</code> in a column that carries <code>1,234.56</code> and as <code>1.234</code> in a column that
carries <code>1.234,56</code>, and the column's own values are what decide. A value the
winning shape cannot explain stays text for validation to flag, and a column two
shapes explain equally well reaches you through <code>onError</code>.</p>
<h2 id="the-courses-in-one-cell">The courses in one cell</h2>
<p><code>Interests</code> holds several courses per person, and the two exporters disagreed on
the separator. Updog Importer samples the column, scores <code>,</code> <code>;</code> <code>|</code>, newline and
tab by how many cells each one splits into recognizable options, and gives the
whole column one verdict. The column holds 83 distinct values, and over those the
comma splits 46 where the semicolon splits 31, so the comma wins.</p>
<p>A cell written with the other separator survives that verdict. When a token still
holds a candidate delimiter, the splitter tries it, and keeps the result only
when it recognizes every piece that comes out. Each token it hands over then goes
through the match-values screen, and that is where <code>Fire safety</code> picks up the
spelling of the option it matched.</p>
<pre><code class="language-text">Manual Handling, Fire Safety   →  ["Manual Handling", "Fire Safety"]
Fire Safety;First Aid          →  ["Fire Safety", "First Aid"]
Fire safety, manual handling   →  ["Fire Safety", "Manual Handling"]
MH; FS                         →  []</code></pre>
<p>Neither <code>MH</code> nor <code>FS</code> resembles a course name, so the splitter keeps the cell
whole, and that one token reaches no option. The row lands with an empty
<code>interests</code> array and passes every rule on it. It reaches your API as a contact
booked on no courses, and the result carries nothing to say the cell held text.</p>
<h2 id="choosing-the-key">Choosing the key</h2>
<p>This file can build a key three ways, out of the address, out of the number, or
out of the surname taken together with the company. Each one breaks on a
different row of it.</p>
<p>Say your database already holds four of these people.</p>
<pre><code class="language-text">Nadia Brandt    n.brandt@heronwood.example     +447700900418   Heronwood Care
Rowan Ferrand   r.ferrand@ashlyn.example       +447700900904   Ashlyn Group
Tomas Vella     office@vellamore.example       +447700900731   Vellamore Ltd
Amrit Sandhu    a.sandhu@kelsbyworks.example   +447700900265   Kelsby Works</code></pre>
<div class="blog-table blog-table--fixed blog-table--contact-keys"><table>
<thead>
<tr>
<th>The collision</th>
<th><code>email</code></th>
<th><code>phone</code></th>
<th><code>lastName + company</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>Two people behind <code>office@vellamore.example</code></td>
<td>merges two people into one row</td>
<td>merges, one handset between them</td>
<td>keeps both</td>
</tr>
<tr>
<td>One person whose address changed</td>
<td>adds a second row</td>
<td>merges</td>
<td>merges</td>
</tr>
<tr>
<td>Two people called Amrit Sandhu at Kelsby Works</td>
<td>keeps both</td>
<td>keeps both</td>
<td>merges two people into one row</td>
</tr>
<tr>
<td>Sofia Nkemelu, with no address</td>
<td>builds no key, so she is new on every upload</td>
<td>keys normally</td>
<td>keys normally</td>
</tr>
<tr>
<td>Kofi Adjetey, with the surname blank</td>
<td>keys normally</td>
<td>keys normally</td>
<td>builds no key, so he is new on every upload</td>
</tr>
</tbody>
</table></div>
<p>Every merge in that table happens against a stored row, because the match only
ever runs against rows that came from somewhere else. Two rows inside one upload
never merge with each other.</p>
<p>Run the eight rows above against those four stored contacts and the counts follow
the table. Keyed on the address, four of them arrive as new. Keyed on the number,
three. Keyed on surname and company together, three again, and a different three,
because that key tells the two behind the mailbox apart and merges the two who
share a name.</p>
<p>Load the whole file against those four contacts and the submit dialog reads
<code>182 new rows will be created</code> and <code>3 rows will be updated</code>. Four rows of the
file matched a stored contact, and three stored rows changed. Both Vellamore rows
carry <code>office@vellamore.example</code>, both matched the same stored row, and the later
one won. That row held <code>Tomas Vella</code> and now reads <code>Ines Cardoso</code>. Tomas is gone
from a list of 186 people, and the <code>unique</code> check has nothing left to flag,
because after the merge that address sits on one row.</p>
<h2 id="what-the-transformer-decides">What the transformer decides</h2>
<p>Values are compared after trimming, and the comparison keeps case. Take the
transformer off the email column and <code>R.Ferrand@ashlyn.example</code> in the file and
<code>r.ferrand@ashlyn.example</code> in your database become two different keys, so that
contact arrives as a duplicate.
<a href="https://www.rfc-editor.org/rfc/rfc5321#section-2.4">RFC 5321</a> is the reason
nobody folds it for you. The local-part of a mailbox "MUST BE treated as case
sensitive", and only the domain follows DNS rules. Folding the whole address is a
decision about your product.</p>
<p>Drop both transformers and the same run sends the values exactly as the file
wrote them.</p>
<pre><code class="language-text">                        normalized      as written
primaryKey: email       4 new rows      5 new rows
primaryKey: phone       3 new rows      7 new rows</code></pre>
<p>The address key loses one merge to a capital letter. The phone key loses four,
because <code>07700 900731</code> and <code>+447700900731</code> are the same subscriber written two
ways. The composite key moves by nothing, since no transformer touches a surname.
The column you key on and the normalization you put in front of it are one
decision.</p>
<h2 id="the-rows-the-person-fixes">The rows the person fixes</h2>
<p>The grid marks three cells across the 186 rows.</p>
<ul><li><strong>Clemency Nettleship</strong>, Email, <code>c.nettleship@ovinghamprint.example</code>: Value must be unique.</li><li><strong>Casimir Nettleship</strong>, Email, <code>c.nettleship@ovinghamprint.example</code>: Value must be unique.</li><li><strong>Kofi Adjetey</strong>, Last name, empty: This field is required.</li></ul>
<p>Clemency Nettleship and Casimir Nettleship both work at Ovingham Print, and the
tool that wrote this file built every address out of one initial and one surname.
Two people at one company can share those, so the scheme itself manufactures a
duplicate. Neither row merged into anything, so both are on the screen for
somebody to fix.</p>
<p><code>office@vellamore.example</code> draws no error at all. That address matched a stored
row, the two file rows collapsed into it, and <code>unique</code> sees one value. The
duplicate the person could have fixed is the one the merge already swallowed.</p>
<p>Sofia Nkemelu draws nothing either. Every built-in rule except <code>required</code> passes
an empty cell, so her blank address is neither an invalid email nor a duplicate.
Put <code>required</code> on the address when a contact without one has no place in your
product, and leave it off when the phone-only contacts are real customers.</p>
<h2 id="what-updog-importer-does-not-ship">What Updog Importer does not ship</h2>
<p>No phone number parsing. E.164 lives in your transformer, and so does every other
country's numbering plan. No case folding on the key or on the uniqueness check.
No survivorship rule, so when an imported row matches a stored one, the imported
values win the whole row. Nothing that looks at two rows and calls them the same
human on a resemblance.</p>
<p>Updog Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A contact list
that arrives as a PDF or a photograph of a business card goes to
<a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a>, and the rows it returns walk
the same path.</p>
<h2 id="reaching-your-backend">Reaching your backend</h2>
<p><code>loadData</code> hands the editor the contacts you already store, so the imported rows
have something to merge into. <code>onComplete</code> hands back one entry per source, each
row carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>.</p>
<pre><code class="language-tsx">import { DataEditor } from "@updog/data-editor";
import { columns } from "./columns";

type Contact = {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  company: string;
  owner: string;
  interests: string[];
};

type Props = { open: boolean; onClose: () => void };

export function ContactImport({ open, onClose }: Props) {
  return (
    &#x3C;DataEditor&#x3C;Contact>
      apiKey={import.meta.env.VITE_UPDOG_KEY}
      open={open}
      onClose={onClose}
      variant="uploader"
      columns={columns}
      primaryKey="email"
      loadData={async (onChunk) => {
        const response = await fetch("/api/contacts");
        onChunk(await response.json());
      }}
      onComplete={async (result) => {
        for (const source of result.sources) {
          const inserts = source.rows.filter(
            (r) => r.isNew &#x26;&#x26; !r.isDeleted &#x26;&#x26; r.isValid,
          );
          const updates = source.rows.filter(
            (r) => !r.isNew &#x26;&#x26; r.isChanged &#x26;&#x26; !r.isDeleted &#x26;&#x26; r.isValid,
          );
          const response = await fetch("/api/contacts", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ inserts, updates }),
          });
          if (!response.ok) throw new Error(await response.text());
        }
      }}
    />
  );
}</code></pre>
<p>A stored row nobody touched is left out of the result, so the second upload of
this list reaches your API as the handful that moved. Throw when your endpoint
fails. A handler that swallows its own error reads as success, and the editor
clears with the rows unsaved.</p>
<h2 id="what-you-built">What you built</h2>
<p>Seven fields, two transformers, six validators and one key. The key is the short
line, and it decided that Tomas Vella and Ines Cardoso are one person or two,
that the two Amrit Sandhus at Kelsby Works are one person or two, and that Sofia
Nkemelu arrives new every time somebody uploads this file. Pick it against the
collisions your own contact lists carry, then normalize the column you picked,
because that is the half that moves the count.</p>]]></content:encoded></item>
<item><title>How to Parse Dates Correctly During CSV Import</title><link>https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-parse-dates-correctly-during-csv-import/</guid><pubDate>Thu, 20 Aug 2026 00:00:00 GMT</pubDate><description>Dates come in different shapes. See how Updog Importer works out what each one means.</description><content:encoded><![CDATA[<p>A CSV cell holding <code>05/01/2026</code> names 5 January or 1 May, and the file carries
nothing that decides which.</p>
<pre><code class="language-text">05/01/2026   →   2026-01-05    read day first
05/01/2026   →   2026-05-01    read month first</code></pre>
<p>Both are days that exist, and both pass an unbounded date check. One of them
puts the record four months from where it belongs, and nothing downstream
complains.</p>
<p>This is a veterinary practice's patient list, exported on its way to new
software, sorted by last visit with the newest first.</p>
<p><code>brackenhill-clinic.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Patient ID</td><td class="sheet__cell">Patient Name</td><td class="sheet__cell">Species</td><td class="sheet__cell">Last Seen</td><td class="sheet__cell">Booster Due</td><td class="sheet__cell">Weight (kg)</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">BR-04100</td><td class="sheet__cell">Pippin</td><td class="sheet__cell">Cat</td><td class="sheet__cell">2026-08-14</td><td class="sheet__cell">2027-05-09</td><td class="sheet__cell">3.4</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">BR-04107</td><td class="sheet__cell">Nutmeg</td><td class="sheet__cell">Dog</td><td class="sheet__cell">2026-08-11</td><td class="sheet__cell">2027-05-01</td><td class="sheet__cell">54.1</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">BR-04114</td><td class="sheet__cell">Bramble</td><td class="sheet__cell">Cat</td><td class="sheet__cell">2026-08-06</td><td class="sheet__cell">2027-05-04</td><td class="sheet__cell">42.5</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">27 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">32</th><td class="sheet__cell">BR-04310</td><td class="sheet__cell">Juniper</td><td class="sheet__cell">Cat</td><td class="sheet__cell">2026-02-30</td><td class="sheet__cell">2026-12-06</td><td class="sheet__cell">41.4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">11 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">44</th><td class="sheet__cell">BR-04394</td><td class="sheet__cell">Frankie</td><td class="sheet__cell">Dog</td><td class="sheet__cell">2026-01-17</td><td class="sheet__cell">2026-10-08</td><td class="sheet__cell">26.8</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">45</th><td class="sheet__cell">BR-04401</td><td class="sheet__cell">Maud</td><td class="sheet__cell">Cat</td><td class="sheet__cell">12/01/2026</td><td class="sheet__cell">10/10/2026</td><td class="sheet__cell">18.8</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">46</th><td class="sheet__cell">BR-04408</td><td class="sheet__cell">Barnaby</td><td class="sheet__cell">Dog</td><td class="sheet__cell">08.01.2026</td><td class="sheet__cell">02/10/2026</td><td class="sheet__cell">19.2</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">47</th><td class="sheet__cell">BR-04415</td><td class="sheet__cell">Suki</td><td class="sheet__cell">Cat</td><td class="sheet__cell">05/01/2026</td><td class="sheet__cell">07/10/2026</td><td class="sheet__cell">23.2</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">48</th><td class="sheet__cell">BR-04422</td><td class="sheet__cell">Alfie II</td><td class="sheet__cell">Dog</td><td class="sheet__cell">02/01/2026</td><td class="sheet__cell"></td><td class="sheet__cell">27.9</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">49</th><td class="sheet__cell">BR-04429</td><td class="sheet__cell">Noor</td><td class="sheet__cell">Dog</td><td class="sheet__cell">11/12/2025</td><td class="sheet__cell">09/09/2026</td><td class="sheet__cell">31.3</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">50</th><td class="sheet__cell">BR-04436</td><td class="sheet__cell">Pippin</td><td class="sheet__cell">Dog</td><td class="sheet__cell">09/12/2025</td><td class="sheet__cell">04/09/2026</td><td class="sheet__cell">8.5</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">51</th><td class="sheet__cell">BR-04443</td><td class="sheet__cell">Nutmeg</td><td class="sheet__cell">Dog</td><td class="sheet__cell">28/11/2025</td><td class="sheet__cell">06/09/2026</td><td class="sheet__cell">42.3</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">3 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">55</th><td class="sheet__cell">BR-04471</td><td class="sheet__cell">Dexter</td><td class="sheet__cell">Cat</td><td class="sheet__cell">20251029</td><td class="sheet__cell">08/07/2026</td><td class="sheet__cell">36.7</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">3 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">59</th><td class="sheet__cell">BR-04499</td><td class="sheet__cell">Milo</td><td class="sheet__cell">Cat</td><td class="sheet__cell">11 Oct 2025</td><td class="sheet__cell">Jul 5, 2026</td><td class="sheet__cell">40.3</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">3 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">63</th><td class="sheet__cell">BR-04527</td><td class="sheet__cell">Poppy II</td><td class="sheet__cell">Dog</td><td class="sheet__cell">20/09/2025</td><td class="sheet__cell">03/04/26</td><td class="sheet__cell">6.2</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">65 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">129</th><td class="sheet__cell">BR-04989</td><td class="sheet__cell">Bruno</td><td class="sheet__cell">Cat</td><td class="sheet__cell">25/10/2024</td><td class="sheet__cell">03/07/2025</td><td class="sheet__cell">20.6</td></tr></tbody></table>
<p>Everything above line 45 was recorded by the system the practice bought at its
last migration, which writes ISO. Everything below was carried across from the
system before it, which writes the day first with slashes. Line 46 adds a third
shape with dots. Line 59 writes the month as a word in both columns, line 63
drops the century, and line 32 names a day February has never had.</p>
<h2 id="where-the-day-and-the-month-go-missing">Where the day and the month go missing</h2>
<p>A spreadsheet does not hold <code>05/01/2026</code>. It holds a number counting days from
its epoch, with a display format beside it, and the app renders one from the
other. Microsoft names both inputs to that rendering. The display format "varies
according to the date formats that have been applied to the cell, and the
current settings under Regional Settings in Control Panel" on Windows.</p>
<p>Saving as CSV keeps the rendering and drops the number and the format together.
The machine that produced the file knew the order. The file records the result
and never the rule.</p>
<p>That is why a list of accepted formats settles nothing on its own.
<code>05/01/2026</code> matches <code>DD/MM/YYYY</code> and <code>MM/DD/YYYY</code> equally well. Declaring both
accepts the value twice and leaves the question open.</p>
<h2 id="what-the-runtime-gives-you-for-free">What the runtime gives you for free</h2>
<p><code>new Date(value)</code> is the shortest path from a cell to a day. It answers a
different question than the one the file is asking. Measured in Node 24 on V8,
with the timezone set per line.</p>
<pre><code class="language-text">new Date("05/01/2026")      Fri May 01 2026    read month first
new Date("2026-01-05")      Sun Jan 04 2026    TZ=America/New_York
new Date("2026-01-05")      Mon Jan 05 2026    TZ=UTC
Date.parse("2026-02-30")    1772409600000      2 March 2026
new Date("20251029")        Invalid Date</code></pre>
<p>ECMAScript defines one interchange format for date-times, adapted from the ISO
8601 calendar date extended format. For a string that does not conform, the spec
says "the function may fall back to any implementation-specific heuristics or
implementation-specific date formats". Other formats are implementation-defined
and may not work across all browsers, MDN says, and it names the unreliability of
<code>Date.parse</code> as one of the motivations for the Temporal API.</p>
<p>Three of those lines matter for an import. V8 reads a slash date month first,
whatever locale the machine holds. A date-only ISO string lands on midnight UTC,
so <code>getDate()</code> in any zone behind UTC returns the day before. And a day February
never has rolls forward into March, which turns a broken cell into a plausible
one. TC39 keeps a table of parse cases where implementations disagree, and an
out-of-bounds day like that one is on it.</p>
<p>An import needs a parser whose failures stay visible.</p>
<h2 id="how-a-raw-cell-becomes-a-stored-day">How a raw cell becomes a stored day</h2>
<p>A column picks one shape and reads every cell with it. The shape comes out of a
count.</p>
<pre><code class="language-text">                       the column's values
                                │
                   every shape scores the sample
                                │
              ┌─────────────────┼─────────────────┐
        one shape read      two shapes tied     no shape read
          the most              on top             anything
              │                     │                  │
        it reads the          the machine       the column keeps
          column             picks one and         its text
                                 warns</code></pre>
<p>Then each cell goes through the winner.</p>
<pre><code class="language-text">                       a cell in that column
                                │
                 ┌──────────────┴──────────────┐
            already ISO              the column's shape
                 │                 ┌───────────┴──────────┐
            store as is        reads it             reads nothing
                                   │                      │
                              store ISO             keep the text,
                                                     flag the cell</code></pre>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>State</th>
<th>Example</th>
<th>What the cell holds afterwards</th>
</tr>
</thead>
<tbody>
<tr>
<td>Already ISO</td>
<td><code>2026-08-14</code></td>
<td>the same day, whatever shape won the column</td>
</tr>
<tr>
<td>The column's shape reads it</td>
<td><code>28/11/2025</code> where the slashes won</td>
<td>the ISO day</td>
</tr>
<tr>
<td>The column's shape reads nothing</td>
<td><code>08.01.2026</code> where the slashes won</td>
<td>the original text, and an error on the cell</td>
</tr>
<tr>
<td>Two shapes tied</td>
<td><code>10/10/2026</code> in a column of low days</td>
<td>the ISO day the machine's locale picks</td>
</tr>
</tbody>
</table></div>
<p>Updog Importer carries twenty-two shapes, and every one of them scores the
column on its own.</p>
<pre><code class="language-text">YYYY-MM-DD      2026-08-14      and 2026-8-4
YYYY/MM/DD      2026/03/05
YYYY.MM.DD      2026.03.05
YYYYMMDD        20260305
DD/MM/YYYY      12/01/2026      against MM/DD/YYYY
DD.MM.YYYY      08.01.2026      against MM.DD.YYYY
DD-MM-YYYY      08-01-2026      against MM-DD-YYYY
DD/MM/YY        12/01/26        against MM/DD/YY
DD.MM.YY        08.01.26        against MM.DD.YY
DD-MM-YY        08-01-26        against MM-DD-YY
D MMM YYYY      11 Oct 2025
MMM D, YYYY     Jul 5, 2026
DD-MMM-YYYY     11-Oct-2025
MMM-DD-YYYY     Oct-11-2025
YYYY年M月D日    2026年10月11日
serial          46143</code></pre>
<p>A time on the end of a value is cut before any shape sees it, so
<code>2026-01-05T14:30:00Z</code> and <code>2026-01-05 14:30</code> both reach the ISO shape and land
on 5 January. An era after a Russian date and a weekday in front of an English
one go the same way. The day survives and the time is gone.</p>
<p>A two-digit year widens on the POSIX window, <code>00</code> through <code>68</code> into the 2000s
and <code>69</code> through <code>99</code> into the 1900s.</p>
<p>The serial number is the one shape that has to explain every value in the sample
before it counts at all. A column of five-digit integers holds IDs as readily as
days.</p>
<p>Month names come from the language the importer runs in, full and short, and
English rides underneath whatever that language is. A German importer reads
<code>11 Okt 2025</code> and <code>11 Oct 2025</code> alike. A Finnish one reads <code>11 lokakuuta 2025</code>,
where the month carries an ending it never has standing alone. Set
<code>ui.calendar.months</code> to replace any of them.</p>
<p>A value with a part above 12 crosses a shape out by itself. <code>28/11/2025</code> hands
28 to the month under <code>MM/DD/YYYY</code>, which names no month, so that shape reads
nothing there and its score stops climbing. Every shape runs over the same
values, and the one that read the most of them takes the column.</p>
<pre><code class="language-ts">const DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

const exists = (y: number, m: number, d: number): boolean => {
  if (m &#x3C; 1 || m > 12 || d &#x3C; 1) return false;
  const leap = (y % 4 === 0 &#x26;&#x26; y % 100 !== 0) || y % 400 === 0;
  return d &#x3C;= (m === 2 &#x26;&#x26; leap ? 29 : DAYS[m - 1]);
};

const iso = (y: number, m: number, d: number): string | null => {
  if (!exists(y, m, d)) return null;
  const mm = String(m).padStart(2, "0");
  const dd = String(d).padStart(2, "0");
  return y + "-" + mm + "-" + dd;
};

export type Candidate = { id: string; read: (value: string) => string | null };

type Slot = "y" | "m" | "d";

// One shape, one regular expression, and the slot each captured group fills.
const shape = (
  id: string,
  re: RegExp,
  order: readonly [Slot, Slot, Slot],
): Candidate => ({
  id,
  read: (value) => {
    const match = re.exec(value.trim());
    if (!match) return null;
    const slot: Record&#x3C;string, number> = {};
    for (let i = 0; i &#x3C; 3; i++) slot[order[i]] = Number(match[i + 1]);
    return iso(slot.y, slot.m, slot.d);
  },
});

const SLASH = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;

export const shapes: Candidate[] = [
  shape("YYYY-MM-DD", /^(\d{4})-(\d{1,2})-(\d{1,2})$/, ["y", "m", "d"]),
  shape("DD/MM/YYYY", SLASH, ["d", "m", "y"]),
  shape("MM/DD/YYYY", SLASH, ["m", "d", "y"]),
];

// The shape that read the most values takes the column. A tie goes to the
// first in the list, which the caller orders by the machine's own locale.
export const detect = (
  values: string[],
  list: Candidate[],
): Candidate | null => {
  let winner: Candidate | null = null;
  let best = 0;
  for (const candidate of list) {
    let score = 0;
    for (const value of values) {
      if (candidate.read(value) !== null) score++;
    }
    if (score > best) {
      best = score;
      winner = candidate;
    }
  }
  return winner;
};</code></pre>
<p>Those lines carry three of the twenty-two shapes and the loop that scores them.
The rest are more regular expressions, a table of month names, and the same
loop.</p>
<h2 id="what-a-column-can-settle-on-its-own">What a column can settle on its own</h2>
<p>Reading a column before converting any of it is what makes the count possible.
Updog Importer takes the first 1000 rows of a file, scores every shape against
the values it finds in each column, and keeps the winner for that column of that
file.</p>
<p>The patient list has two date columns, and they come out differently.</p>
<pre><code class="language-text">Last Seen                        Booster Due
DD/MM/YYYY     82                MM/DD/YYYY     80
YYYY-MM-DD     42                DD/MM/YYYY     80
MM/DD/YYYY     34                YYYY-MM-DD     43
DD.MM.YYYY      1                MMM D, YYYY     1
MM.DD.YYYY      1                DD/MM/YY        1
D MMM YYYY      1                MM/DD/YY        1
YYYYMMDD        1</code></pre>
<p><code>Last Seen</code> holds 82 slash values, and 48 of them put a number above 12 first,
which no month can take. <code>MM/DD/YYYY</code> reads nothing in those 48, and the count
ends 82 to 34. The 42 readable ISO values score for a third shape and leave the
pair where it stands.</p>
<p><code>Booster Due</code> ties. The practice books its booster clinics in the first twelve
days of a month, so no value across its 128 rows holds a part above 12, and both
readings explain 80 values each. A column like that cannot answer the question
about itself, however many rows it holds, and the column beside it never speaks
for it.</p>
<p>A tie falls to the machine. The shapes are listed with the reader's own order
first, taken from <code>Intl.DateTimeFormat</code> asked to print a day and a month.</p>
<pre><code class="language-text">en-US    month 12 / day 31      month first
en-GB    day 31 / month 12      day first
de-DE    day 31 . month 12 .    day first
ja-JP    month 12 / day 31      month first</code></pre>
<p>The same column then imports one way on a laptop in Chicago and another way on a
laptop in Manchester. That is the floor of any detector. The machine that ran
this import reads <code>en-US</code>, so <code>MM/DD/YYYY</code> took <code>Booster Due</code>. The tie also
reaches your <code>onError</code>, which is the one place it is reported.</p>
<pre><code class="language-text">[updog] column "Booster Due" could be read as MM/DD/YYYY or DD/MM/YYYY;
applied MM/DD/YYYY. Samples: 2027-05-09, 2027-05-01, 2027-05-04,
2027-05-09, 2027-04-11</code></pre>
<p>The winner then converts the values it reads, and the rest keep their text.</p>
<pre><code class="language-text">Last Seen      line 45    12/01/2026     →   2026-01-12
Last Seen      line 51    28/11/2025     →   2025-11-28
Last Seen      line 46    08.01.2026     →   08.01.2026
Last Seen      line 59    11 Oct 2025    →   11 Oct 2025
Booster Due    line 46    02/10/2026     →   2026-02-10

cells that would hold a different day under the other reading
Last Seen                                               32
Booster Due                                             75</code></pre>
<p>The same punctuation reads two ways in one file. <code>12/01/2026</code> in <code>Last Seen</code>
becomes 12 January, and 32 cells of that column turn on a count of 82 against
34. <code>02/10/2026</code> in <code>Booster Due</code> becomes 10 February, and 75 cells of that one
turn on the machine that opened the file. A staff roster's start dates go
through the same count,
<a href="https://updog.tech/blog/how-to-import-employees-from-csv-and-excel/">column by column</a>.</p>
<h2 id="which-values-keep-their-text">Which values keep their text</h2>
<p>Six cells of 256 come out of the file unconverted. One of them names a day that
exists in no year. The other five match a shape that lost its column.</p>
<div class="blog-table blog-table--narrow blog-table--date-values"><table>
<thead>
<tr>
<th>Value</th>
<th>Line</th>
<th>Why it keeps its text</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>2026-02-30</code></td>
<td>32</td>
<td>ISO by shape, and 30 February exists in no year</td>
</tr>
<tr>
<td><code>08.01.2026</code></td>
<td>46</td>
<td>dots against a column of slashes, one score against 82</td>
</tr>
<tr>
<td><code>20251029</code></td>
<td>55</td>
<td><code>YYYYMMDD</code> reads it, and one score loses to 82</td>
</tr>
<tr>
<td><code>11 Oct 2025</code></td>
<td>59</td>
<td>one spelled-out month in a column of numbers</td>
</tr>
<tr>
<td><code>Jul 5, 2026</code></td>
<td>59</td>
<td>the same, in the column beside it</td>
</tr>
<tr>
<td><code>03/04/26</code></td>
<td>63</td>
<td><code>DD/MM/YY</code> reads it, and one score loses to 80</td>
</tr>
</tbody>
</table></div>
<p>A file that writes <code>20251029</code> in every row imports as days. One <code>20251029</code>
among 82 slash values keeps its text.</p>
<p>Excel reads <code>00</code> through <code>29</code> as 2000 to 2029, and <code>30</code> through <code>99</code> as 1930 to
1999, and Microsoft states that the cutoff a person can change in Control Panel
applies to typed dates only. Both windows carry <code>03/04/26</code> to 2026. They part
company at <code>30</code>, which Excel reads as 1930 and Updog Importer as 2030.</p>
<h2 id="what-the-person-sees">What the person sees</h2>
<p>A value that failed to convert stays exactly as the file wrote it, and the
column's date rule reports it.</p>
<pre><code class="language-text">line 32    Last seen      "2026-02-30"     Invalid date
line 46    Last seen      "08.01.2026"     Invalid date
line 55    Last seen      "20251029"       Invalid date
line 59    Last seen      "11 Oct 2025"    Invalid date
line 59    Booster due    "Jul 5, 2026"    Invalid date
line 63    Booster due    "03/04/26"       Invalid date</code></pre>
<p>The text survives. The cell shows the person the string they have to fix, and
the grid falls back to that text for anything that is not a valid ISO date.</p>
<p>A converted value is stored as <code>YYYY-MM-DD</code> and displayed through the viewer's
own locale. The same stored day reads as <code>12/01/2026</code> in London and <code>1/12/2026</code>
in Chicago. That formatter is pinned to Latin digits and the Gregorian calendar,
so <code>ar-EG</code> prints <code>19/8/2026</code> in Latin digits, <code>fa-IR</code> prints the Gregorian day,
and <code>th-TH</code> prints the year 2026. Typing a date back into the grid depends on
all three, and so does the search box, which reads what the screen shows.</p>
<p>Editing a cell opens a date picker, and the <code>min</code> and <code>max</code> of a
<code>{ type: "date" }</code> validator set the range it offers as well as the bounds the
check enforces. Those bounds compare ISO strings, so they only ever see values
that converted.</p>
<p>A converted value leaves through <code>onComplete</code> and through an export as ISO,
whatever shape it arrived in. A value that never converted leaves as the text
the file wrote, which is one more reason to fix the six flagged cells before
<a href="https://updog.tech/blog/import-csv-into-postgresql/">the rows reach a database</a>.</p>
<h2 id="where-the-shape-comes-from">Where the shape comes from</h2>
<p>Data reaches the grid three ways, and each one counts its own shapes.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>How the data arrives</th>
<th>Where the shape comes from</th>
</tr>
</thead>
<tbody>
<tr>
<td>A file the person uploads, or a remote source the wizard fetched</td>
<td>scored on that workbook's own columns, first 1000 rows</td>
</tr>
<tr>
<td><code>loadData</code> from your app</td>
<td>scored on the rows you pass, the same way</td>
</tr>
<tr>
<td>A paste into the grid</td>
<td>scored on the pasted block, first 1000 rows</td>
</tr>
</tbody>
</table></div>
<p>The winner is kept on the pair of the source and the column. A later chunk of
the same source reuses it, and a second file counts for itself. Two files
dropped in one upload get their own shape in every column, and neither borrows
anything from the other. Neither borrows from the punctuation of the number
columns either. A language can put the day first and still write <code>1,234.56</code>,
which is what British English does.</p>
<h2 id="what-this-does-not-solve">What this does not solve</h2>
<p>One shape covers one column. A column that mixes shapes converts the values its
winner reads and keeps the rest as text, which is what happens to <code>08.01.2026</code>
and <code>11 Oct 2025</code> here.</p>
<p>A column whose days never pass 12 ties, and the machine that opened the file
breaks the tie. Nothing inside <code>Booster Due</code> could have settled it, and no
number of extra rows would have helped.</p>
<p>Rows that disagree with each other inside one column, half day first and half
month first, get read one way. The rows on the other side of that split become
wrong days that pass validation.</p>
<p>A whole date is the unit. A cell holding <code>2026-01-05 14:30</code> arrives as
5 January 2026 with the 14:30 dropped, and an offset or a timezone on the end
goes with it.</p>
<p>As of August 2026 the importer never shows the winning shape on screen and never
asks anyone to confirm it. A person matching columns sees the file's own values,
and the converted ones appear later, in the grid. A tied column reaches your
<code>onError</code> and nobody else. The strongest guard against a wrong reading is
still a schema that asks the systems you control for ISO.</p>
<h2 id="what-you-write">What you write</h2>
<p>Two declarations turn a column into a date column. The editor puts every value
through the parser, and the rule that comes with it makes the failures visible.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  {
    id: "patientRef",
    title: "Patient ID",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  { id: "name", title: "Patient name", validators: [{ type: "required" }] },
  { id: "species", title: "Species" },
  {
    id: "lastVisit",
    title: "Last seen",
    editor: { type: "date" },
    validators: [{ type: "date", max: "2026-08-24" }],
  },
  {
    id: "boosterDue",
    title: "Booster due",
    editor: { type: "date" },
  },
  {
    id: "weightKg",
    title: "Weight (kg)",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 90, decimalPlaces: 1 }],
  },
];</code></pre>
<p><code>editor: { type: "date" }</code> is what triggers conversion. A column carrying only a
<code>{ type: "date" }</code> validator is checked and never converted, so its slash values
fail the check as written. A date editor with no validator of its own gets one
anyway, so <code>Booster due</code> reports its two cells without declaring a rule.
<code>Last seen</code> declares one, and that rule reports its four. Which of the file's
headers becomes that column is settled one step earlier, in
<a href="https://updog.tech/blog/csv-column-mapping-react/">column matching</a>.</p>
<p>The six flagged cells in this file are the safe ones. They stop, they name
themselves, and somebody fixes them in the grid before the import lands. The
hundred and seven that would hold a different day under the other reading are
why a date column earns this much attention, and why the work starts with
counting a column before touching a single value in it.</p>]]></content:encoded></item>
<item><title>How to Import Employees from CSV and Excel</title><link>https://updog.tech/blog/how-to-import-employees-from-csv-and-excel/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-employees-from-csv-and-excel/</guid><pubDate>Wed, 19 Aug 2026 00:00:00 GMT</pubDate><description>A staff export arrives from three payroll systems at once. See how Updog Importer turns it into one list of people.</description><content:encoded><![CDATA[<p>Updog Importer matches a file header to one of your fields, and a cell value to
one of your options. Both work on the strings in front of them. A staff export
carries one column those two tools cannot reach. The manager is written as a
person's name, your schema wants a staff number, and the person holding that
number is a row further down the same file.</p>
<p>That column is the whole job.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>Three properties export staff, three payroll systems produce the file, and the
group sends all of it as one roster.</p>
<p><code>harlow-court-roster.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Staff No</td><td class="sheet__cell">Given Name</td><td class="sheet__cell">Family Name</td><td class="sheet__cell">Email</td><td class="sheet__cell">Team</td><td class="sheet__cell">Reports To</td><td class="sheet__cell">First Day</td><td class="sheet__cell">Hrs/Week</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">A-0001</td><td class="sheet__cell">Marta</td><td class="sheet__cell">Okafor</td><td class="sheet__cell">marta.okafor@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">2019-07-03</td><td class="sheet__cell">23.8</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">A-0002</td><td class="sheet__cell">Priya</td><td class="sheet__cell">Raman</td><td class="sheet__cell">priya.raman@harlowcourt.example</td><td class="sheet__cell">Housekeeping</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">2022-04-22</td><td class="sheet__cell">34.2</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">A-0003</td><td class="sheet__cell">Tomasz</td><td class="sheet__cell">Wieczorek</td><td class="sheet__cell">tomasz.wieczorek@harlowcourt.example</td><td class="sheet__cell">Maintenance</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">2026-02-10</td><td class="sheet__cell">23.7</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">A-0004</td><td class="sheet__cell">Ines</td><td class="sheet__cell">Duarte</td><td class="sheet__cell">ines.duarte@harlowcourt.example</td><td class="sheet__cell">Reception</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">2023-09-27</td><td class="sheet__cell">28.8</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">A-0005</td><td class="sheet__cell">Fiona</td><td class="sheet__cell">Eriksen</td><td class="sheet__cell">fiona.eriksen@harlowcourt.example</td><td class="sheet__cell">Housekeeping</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">2019-11-23</td><td class="sheet__cell">27.7</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">A-0006</td><td class="sheet__cell">Grigor</td><td class="sheet__cell">Fahey</td><td class="sheet__cell">grigor.fahey@harlowcourt.example</td><td class="sheet__cell">House Keeping</td><td class="sheet__cell">Priya Raman</td><td class="sheet__cell">2023-03-11</td><td class="sheet__cell">18</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">A-0007</td><td class="sheet__cell">Hana</td><td class="sheet__cell">Gallardo</td><td class="sheet__cell">hana.gallardo@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">M. Okafor</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">28.1</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">13</th><td class="sheet__cell">A-0012</td><td class="sheet__cell">Mira</td><td class="sheet__cell">Lindqvist</td><td class="sheet__cell">mira.lindqvist@harlowcourt.example</td><td class="sheet__cell">Reception</td><td class="sheet__cell">Okafor, Marta</td><td class="sheet__cell">2025-03-31</td><td class="sheet__cell">16</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">19</th><td class="sheet__cell">A-0018</td><td class="sheet__cell">Tevita</td><td class="sheet__cell">Rasmussen</td><td class="sheet__cell">tevita.rasmussen@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">Dana Whitfield</td><td class="sheet__cell">2021-05-30</td><td class="sheet__cell">27.3</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">25</th><td class="sheet__cell">A-0024</td><td class="sheet__cell">Emeka</td><td class="sheet__cell">Eriksen</td><td class="sheet__cell">emeka.eriksen@harlowcourt.example</td><td class="sheet__cell">FOH</td><td class="sheet__cell">Priya Raman</td><td class="sheet__cell">2025-08-14</td><td class="sheet__cell">19.7</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">26</th><td class="sheet__cell">A-0025</td><td class="sheet__cell">Fiona</td><td class="sheet__cell">Fahey</td><td class="sheet__cell">fiona.fahey@harlowcourt.example</td><td class="sheet__cell">Front Desk</td><td class="sheet__cell">Priya Raman</td><td class="sheet__cell">2023-01-05</td><td class="sheet__cell">26.4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">31</th><td class="sheet__cell">A-0030</td><td class="sheet__cell">Kwame</td><td class="sheet__cell">Kovac</td><td class="sheet__cell">kwame.kovac@harlowcourt.example</td><td class="sheet__cell">Housekeping</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">2019-12-24</td><td class="sheet__cell">36.2</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">32</th><td class="sheet__cell">A-0031</td><td class="sheet__cell">Liesel</td><td class="sheet__cell">Lindqvist</td><td class="sheet__cell">liesel.lindqvist@harlowcourt.example</td><td class="sheet__cell">Maint.</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">2024-09-19</td><td class="sheet__cell">30.3</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">37</th><td class="sheet__cell">A-0036</td><td class="sheet__cell">Rafael</td><td class="sheet__cell">Quinlan</td><td class="sheet__cell">rafael.quinlan@harlowcourt.example</td><td class="sheet__cell">House Keeping</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">03/04/26</td><td class="sheet__cell">28.4</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">43</th><td class="sheet__cell">A-0042</td><td class="sheet__cell">Callum</td><td class="sheet__cell">Delaney</td><td class="sheet__cell">callum.delaney@harlowcourt.example</td><td class="sheet__cell">Housekeeping</td><td class="sheet__cell">Tomasz Wieczorek</td><td class="sheet__cell">46085</td><td class="sheet__cell">32.6</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">4 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">48</th><td class="sheet__cell">A-0047</td><td class="sheet__cell">Hana</td><td class="sheet__cell">Ivanova</td><td class="sheet__cell">hana.ivanova@harlowcourt.example</td><td class="sheet__cell">Housekeeping</td><td class="sheet__cell">Ines Duarte</td><td class="sheet__cell">2023-03-13</td><td class="sheet__cell">34.6</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">54</th><td class="sheet__cell">A-0053</td><td class="sheet__cell">Marta</td><td class="sheet__cell">Okafor</td><td class="sheet__cell">marta.okafor@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">Tomasz Wieczorek</td><td class="sheet__cell">2026-01-06</td><td class="sheet__cell">24.9</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">5 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">60</th><td class="sheet__cell">A-0059</td><td class="sheet__cell">Ulla</td><td class="sheet__cell">Abara</td><td class="sheet__cell">ulla.abara@harlowcourt.example</td><td class="sheet__cell">House Keeping</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">4 March 2026</td><td class="sheet__cell">18.1</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">1 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">62</th><td class="sheet__cell">A-47</td><td class="sheet__cell">Hana</td><td class="sheet__cell">Ivanova</td><td class="sheet__cell">hana.ivanova@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">Priya Raman</td><td class="sheet__cell">2020-09-05</td><td class="sheet__cell">35</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">10 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">73</th><td class="sheet__cell">A-0072</td><td class="sheet__cell">Mira</td><td class="sheet__cell">Ostrowski</td><td class="sheet__cell">mira.ostrowski@harlowcourt.example</td><td class="sheet__cell">Front of House</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">17/03/2026</td><td class="sheet__cell">26.9</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">23 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">97</th><td class="sheet__cell">A-0096</td><td class="sheet__cell">Rafael</td><td class="sheet__cell">Tanaka</td><td class="sheet__cell">rafael.tanaka@harlowcourt.example</td><td class="sheet__cell">Reception</td><td class="sheet__cell">Marta Okafor</td><td class="sheet__cell">2019-05-11</td><td class="sheet__cell">24.9</td></tr></tbody></table>
<p>Line 7 writes the housekeeping team as <code>House Keeping</code>. Line 8 writes the
manager as <code>M. Okafor</code> and the start date as <code>03/04/2026</code>. Neither line is
broken. Both disagree with the line above them.</p>
<h2 id="the-schema-it-becomes">The schema it becomes</h2>
<p>Eight fields, and every one of them holds a rule the file can break.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const TEAMS = [
  "Front of House",
  "Back of House",
  "Housekeeping",
  "Maintenance",
  "Reception",
];

export const columns: DataEditorColumn[] = [
  {
    id: "staffNumber",
    title: "Staff number",
    validators: [{ type: "required" }, { type: "unique" }],
    transformer: (v) => String(v ?? "").trim().toUpperCase(),
  },
  {
    id: "legalFirstName",
    title: "First name",
    validators: [{ type: "required" }],
  },
  {
    id: "legalLastName",
    title: "Last name",
    validators: [{ type: "required" }],
  },
  {
    id: "contactEmail",
    title: "Email",
    size: 240,
    validators: [{ type: "email" }, { type: "unique" }],
  },
  {
    id: "team",
    title: "Team",
    editor: { type: "select", options: TEAMS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: TEAMS }],
  },
  { id: "reportsTo", title: "Reports to", size: 200 },
  {
    id: "firstDay",
    title: "First day",
    editor: { type: "date" },
    validators: [{ type: "date", max: "2027-12-31" }],
  },
  {
    id: "weeklyHours",
    title: "Hours a week",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 48, decimalPlaces: 1 }],
  },
];</code></pre>
<p><code>primaryKey</code> is <code>staffNumber</code>, so a second upload of the same roster lands on
the rows these people already hold. <code>TEAMS</code> closes the team vocabulary,
and <code>enableCustomValue: false</code> stops the person inventing a sixth team while
they fix their rows.</p>
<h2 id="where-the-file-and-the-schema-disagree">Where the file and the schema disagree</h2>
<p>Seven kinds of disagreement run through the 96 rows, and each one lands in a
different part of the importer.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Value in the file</th>
<th>What it hits</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>House Keeping</code></td>
<td>the normalizing step, which drops the space</td>
</tr>
<tr>
<td><code>FOH</code></td>
<td>nothing, and the cell arrives empty</td>
</tr>
<tr>
<td><code>Maint.</code></td>
<td>the containment tier of the value matcher</td>
</tr>
<tr>
<td><code>M. Okafor</code></td>
<td>a manager reference that resolves to nobody</td>
</tr>
<tr>
<td><code>03/04/2026</code></td>
<td>a date the shape that won the column cannot read</td>
</tr>
<tr>
<td><code>46085</code></td>
<td>a workbook cell left on General format</td>
</tr>
<tr>
<td><code>A-47</code> against <code>A-0047</code></td>
<td>one person under two staff numbers</td>
</tr>
</tbody>
</table></div>
<h2 id="the-team-column">The team column</h2>
<p>Value matching scores every imported spelling against the five options and keeps
the best one at 60 or above. The score comes off a fixed ladder. Equal after
normalizing is 100, a synonym 90, one string held inside the other 80, half the
words shared 70, a spelling close enough to correct 65. A spelling that reaches
none of those rungs earns a fraction of the words it shares, which lands it far
under the threshold. This roster spells the five teams eleven ways, and six of
those miss the schema spelling.</p>
<div class="blog-table blog-table--narrow blog-table--roster-teams"><table>
<thead>
<tr>
<th>In the file</th>
<th>Lands on</th>
<th>Score</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Back-of-house</code></td>
<td>Back of House</td>
<td>100</td>
<td>normalizing drops the hyphens</td>
</tr>
<tr>
<td><code>House Keeping</code></td>
<td>Housekeeping</td>
<td>100</td>
<td>normalizing drops the space</td>
</tr>
<tr>
<td><code>Maint.</code></td>
<td>Maintenance</td>
<td>80</td>
<td>one string contains the other</td>
</tr>
<tr>
<td><code>Housekeping</code></td>
<td>Housekeeping</td>
<td>65</td>
<td>one edit away, inside the budget</td>
</tr>
<tr>
<td><code>Front Desk</code></td>
<td>nothing</td>
<td>20</td>
<td>one shared word out of three</td>
</tr>
<tr>
<td><code>FOH</code></td>
<td>nothing</td>
<td>0</td>
<td>containment needs four characters</td>
</tr>
</tbody>
</table></div>
<p>That budget comes off the longer of the two strings. Four characters allow one
edit, eight allow two, fifteen allow three, and anything longer allows four, so
<code>Housekeeping</code> at twelve letters carries three to spend.</p>
<p><code>Front Desk</code> and <code>FOH</code> fall under the threshold, so nothing is mapped, and the
cell reaches the grid empty. Every built-in rule except <code>required</code> passes an
empty value, which means <code>{ type: "oneOf" }</code> on its own says yes to a person
with no team. <code>{ type: "required" }</code> turns that silent gap into a row the
person has to fix. <code>{ type: "oneOf" }</code> earns its place on the rows you load
from your own backend, where a value can arrive off the list.</p>
<p>Three-letter abbreviations are the case you close by hand, because containment
refuses to match a string shorter than four characters. The
<code>synonyms</code> prop takes both halves of the vocabulary.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey="staffNumber"
  synonyms={{
    columns: {
      staffNumber: ["staff no", "staff #", "payroll ref"],
      reportsTo: ["reports to", "line manager", "supervisor"],
    },
    values: {
      "Front of House": ["foh", "front"],
      "Back of House": ["boh", "back"],
      Housekeeping: ["hk", "hskp"],
    },
  }}
/></code></pre>
<p><code>columns</code> feeds header matching and <code>values</code> feeds option matching, and the two
tables never cross. After that table lands, <code>FOH</code> reaches <code>Front of House</code> on
the synonym tier at 90. <code>Front Desk</code> shares one word out of three with
<code>Front of House</code> and nothing with the other four, so it stays unmatched and its
cell stays empty.</p>
<h2 id="the-first-day-column">The first day column</h2>
<p>The importer samples the first thousand rows of the column and offers them to
every date shape it knows. Each shape reads what it can, and the one that read
the most values takes the column. This roster writes 91 of its 96 dates as
<code>2019-07-03</code>, so <code>YYYY-MM-DD</code> wins ninety-one to two.</p>
<pre><code class="language-text">YYYY-MM-DD    91   ← reads the column
DD/MM/YYYY     2
MM/DD/YYYY     1
DD/MM/YY       1
MM/DD/YY       1
D MMM YYYY     1
serial         1</code></pre>
<p>The winner reads alone. A value it cannot parse keeps the text it arrived as,
and the date rule flags it.</p>
<pre><code class="language-text">2026-03-04    →  2026-03-04
03/04/2026    →  03/04/2026, flagged
17/03/2026    →  17/03/2026, flagged
4 March 2026  →  4 March 2026, flagged
03/04/26      →  03/04/26, flagged
46085         →  46085, flagged</code></pre>
<p>Line 8 holds <code>03/04/2026</code>, which is 3 April in one office and 4 March in
another. The column already reads <code>YYYY-MM-DD</code>, so that cell keeps its text and
reaches the person who knows which day it means. Ninety-one rows written the
same way carry the column, and five land in the grid to be read by hand.</p>
<p>A locale settles the column only when two shapes read the same number of
values. The browser's own order goes first, and the column reports the tie
through <code>onError</code>. An Excel serial takes a column only when every value in it
is a serial, so <code>46085</code> among 95 written dates stays a number.</p>
<p>The same roster saved as a workbook reads back as 91 cells typed as dates,
four typed as text, and one typed as a number.</p>
<pre><code class="language-text">Excel cell        stored   reaches the grid as
typed as a date   43649    2019-07-03
General format    46085    46085</code></pre>
<p>A cell Excel knows is a date arrives as ISO text before any importer logic runs,
whatever format the sheet shows it in, so the serial never appears. A cell
somebody left on General format is a plain number, the importer keeps the digits
it displayed, and the date rule flags them. Line 43 of this roster is that cell.</p>
<h2 id="the-manager-written-as-a-name">The manager written as a name</h2>
<p><code>Reports To</code> holds <code>Marta Okafor</code>, <code>Okafor, Marta</code>, and <code>M. Okafor</code>, and the
schema wants <code>A-0001</code>. Nothing in column mapping or value matching answers that,
because the answer lives in the other rows.</p>
<p><code>{ type: "asyncFunction" }</code> is the one rule handed whole rows. When a file
opens, the importer sweeps the column and calls your function once. The sweep
carries one entry per cell that holds a value and picked up no other error, and
each entry hands you the cell value and the full row it sits in. That is enough
to build the index out of the file itself, with no request to your backend.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const normalizeName = (value: string): string => {
  const trimmed = value.trim();
  const inverted = trimmed.match(/^([^,]+),\s*(.+)$/);
  const straight = inverted ? inverted[2] + " " + inverted[1] : trimmed;
  return straight.toLowerCase().replace(/\s+/g, " ");
};

export const reportsToColumn: DataEditorColumn = {
  id: "reportsTo",
  title: "Reports to",
  size: 200,
  validators: [
    {
      type: "asyncFunction",
      fn: async (cells) => {
        const byName = new Map&#x3C;string, string[]>();
        for (const { row } of cells) {
          const name = normalizeName(
            row.legalFirstName + " " + row.legalLastName,
          );
          const holders = byName.get(name) ?? [];
          holders.push(String(row.staffNumber));
          byName.set(name, holders);
        }

        return cells.map(({ value }) => {
          const holders = byName.get(normalizeName(String(value)));
          if (!holders) {
            return { level: "error", message: "No row carries that name" };
          }
          if (holders.length > 1) {
            return {
              level: "error",
              message: "Two rows carry that name, " + holders.join(" and "),
            };
          }
          return null;
        });
      },
    },
  ],
};</code></pre>
<p>Every <code>Reports To</code> in this roster holds a name, so the sweep carries all 96
cells and comes back with these verdicts.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Line</th>
<th>Reports To</th>
<th>Verdict</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td><code>Ines Duarte</code></td>
<td>resolved to A-0004</td>
</tr>
<tr>
<td>8</td>
<td><code>M. Okafor</code></td>
<td>No row carries that name</td>
</tr>
<tr>
<td>13</td>
<td><code>Okafor, Marta</code></td>
<td>Two rows carry that name, A-0001 and A-0053</td>
</tr>
<tr>
<td>19</td>
<td><code>Dana Whitfield</code></td>
<td>No row carries that name</td>
</tr>
</tbody>
</table></div>
<p>Normalizing turns <code>Okafor, Marta</code> into <code>marta okafor</code> on line 13, the lookup
succeeds, and the answer is still an error, because two people in this file
carry that name. A staff number is the thing that separates them, and the file
never wrote one.</p>
<p>Twenty-nine of the 96 rows carry an error on this column. One duplicated person
broke every plain reference to her. <code>M. Okafor</code> is the other shape, and it stays
unresolved on purpose. Matching works on strings, and deciding that an initial
means <code>Marta Okafor</code> guesses at a person.</p>
<p>A reference that points at a row pointing back is a loop, and a row naming
itself is the same bug written shorter. Walk the resolved pairs once the index
exists and both fall out.</p>
<h2 id="create-update-or-reject">Create, update, or reject</h2>
<p>The primary key decides what happens to each row.</p>
<pre><code class="language-text">staff number already in your data   →  update
staff number new                    →  create
staff number twice in one file      →  both rows land, unique flags them</code></pre>
<p>An import anchors against rows that came from somewhere else, so two rows inside
the same file never merge into each other. <code>unique</code> is the rule that catches an
in-file duplicate.</p>
<p>The importer compares keys as trimmed strings and nothing more, which is why
this roster carries <code>A-0047</code> on line 48 and <code>A-47</code> on line 62. Same person, two
spellings, two keys, two rows. The <code>transformer</code> on <code>staffNumber</code> is where you
normalize the padding before it becomes a key.</p>
<p>Email catches what the staff number missed. This file holds exactly two
duplicate addresses, and they mean opposite things.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Address</th>
<th>Rows</th>
<th>What it is</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>hana.ivanova@harlowcourt.example</code></td>
<td>A-0047, A-47</td>
<td>one person written twice</td>
</tr>
<tr>
<td><code>marta.okafor@harlowcourt.example</code></td>
<td>A-0001, A-0053</td>
<td>two people sharing a name</td>
</tr>
</tbody>
</table></div>
<p>The importer reports both as duplicates and stops there. Which one is a merge
and which one is a real collision is a question about your business, and the
person holding the file can answer it.</p>
<h2 id="the-rows-the-person-fixes">The rows the person fixes</h2>
<p>The empty team cell, the unreadable dates, and the unresolved managers all land
in the grid as cell errors before anything reaches your API. The person sees their
file with the problem cells marked, and works through a list that reads in their
own vocabulary.</p>
<ul><li><strong>Line 8</strong>, Reports to, <code>M. Okafor</code>: No row carries that name.</li><li><strong>Line 8</strong>, First day, <code>03/04/2026</code>: Invalid date.</li><li><strong>Line 13</strong>, Reports to, <code>Okafor, Marta</code>: Two rows carry that name, A-0001 and A-0053.</li><li><strong>Line 26</strong>, Team, empty: This field is required.</li><li><strong>Line 37</strong>, First day, <code>03/04/26</code>: Invalid date.</li><li><strong>Line 43</strong>, First day, <code>46085</code>: Invalid date.</li></ul>
<p>Fixing line 26 means picking a team from the five. Fixing line 13 means writing
a staff number the file already holds. Both are edits the person can make and
you cannot.</p>
<h2 id="what-updog-importer-does-not-ship">What Updog Importer does not ship</h2>
<p>The index your function builds covers the cells the sweep handed it. A person
who left their own <code>Reports To</code> empty stays out of that sweep, so nobody in the
file can resolve to them. Every row in this roster names a manager, so the
index stays whole.</p>
<p>One sweep covers every file up to 5,000 rows. Past that the importer sweeps once
per chunk, and a cell already carrying an error stays out of the next sweep. The
index shrinks with every pass, so a row that resolved against the first chunk
can come back an error once the second one lands. For a roster of a few thousand
people the mechanism is exact, and for a file larger than that the resolution
belongs after submit.</p>
<p>A value shorter than four characters cannot match by containment, so <code>FOH</code> needs
the <code>synonyms</code> prop. Normalizing keeps a <code>#</code>, which costs a header the exact and
containment tiers. <code>Emp #</code> shares no word with <code>Staff number</code> and reaches
nothing, while <code>Staff #</code> still lands on the column at 70, on the one word it
shares. One file column cannot fan out into two fields, so a
<code>Name (Last, First)</code> header scores 20 against both name columns and reaches
neither.</p>
<p>Updog Importer has no view of your database, it runs no lookups against it, and it never learns whether A-0047 already exists in
your system. Everything here happens in the browser against the file, and
reaching your data is your code.</p>
<h2 id="reaching-your-backend">Reaching your backend</h2>
<p><code>onComplete</code> fires once with every source the person imported, and every row
carries <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code>.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey="staffNumber"
  onComplete={async (result) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .filter((entry) => entry.isValid);

    const response = await fetch("/api/staff", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(rows.map((entry) => entry.row)),
    });

    if (!response.ok) {
      throw new Error("Staff import failed with " + response.status);
    }
  }}
/></code></pre>
<p>Throw when your request fails. The editor clears itself when the promise
resolves, so a handler that swallows its own error reads as success and takes
the person's work with it. Throwing keeps every row on screen and lets them
submit again.</p>
<h2 id="what-you-built">What you built</h2>
<p>A schema of eight fields, a closed team vocabulary with a synonym table behind
it, a date column that takes its order from the file, a duplicate rule that
tells a merge apart from a collision, and one column resolved against the other
rows of the same file.</p>
<p>The last one is the part the person with the file cannot fix by reading it. A
name is not an identity until something says which row it points at.</p>]]></content:encoded></item>
<item><title>CSV Import for Insurance Software</title><link>https://updog.tech/blog/csv-import-for-insurance-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-insurance-software/</guid><pubDate>Tue, 18 Aug 2026 00:00:00 GMT</pubDate><description>A policy register mixes new business, endorsements and cancellations in one file. How to write rules that read what kind of row they are judging.</description><content:encoded><![CDATA[<p>A policy register holds one row for every thing that happened to a policy. A
policy was written, changed, cancelled, reinstated or audited. All of those rows
carry the same thirteen columns.</p>
<p>The columns mean different things on different rows. An expiration date is
mandatory on a renewal and correctly empty on a cancellation. A premium is
positive on new business and negative on a cancellation. Which reading applies
is decided by one cell, and that cell holds the transaction code.</p>
<p>An insurance platform stores one row per policy transaction. Its customers
export those rows out of the agency management system they are leaving, as CSV.
Taking a customer's book of business into a schema of your own is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The file below holds 2,392 rows over thirteen columns, 306 KB of CSV. A schema
of required fields, option lists and number bounds imports it with 86 flagged
cells. None of the 86 is what is wrong with the file. Every number here came out
of that file or out of running it through the importer.</p>
<h2 id="the-column-that-decides-what-the-rest-of-the-row-means">The column that decides what the rest of the row means</h2>
<p>Vertafore publishes the policy transaction codes AMS360 writes, twenty-six of
them, each three letters. <code>NBS</code> is New Business. <code>RWL</code> is Renew Policy. <code>PCH</code> is
Policy Change. <code>XLC</code> is Cancellation Confirmation. <code>REI</code> is Reinstatement. <code>PAB</code>
is Premium Audit. <code>NRA</code> is Non-Renewal Notified Agency, and <code>REW</code> is Rewrite.</p>
<p>Nothing inside those three letters says any of that. <code>PCH</code> shares no word with
policy change and <code>PAB</code> shares none with premium audit. A matcher working on
string similarity reaches them only through a table somebody wrote down.</p>
<p>Your platform stores six kinds of transaction. New business, renewal,
endorsement, cancellation, reinstatement and audit. Every code in the file has
to land on one of the six, and the rest of the row waits on where it lands.</p>
<p>An expiration date is required on the three kinds that open a policy term. A
premium is positive on new business and on a renewal, and it is negative or zero
on a cancellation. A commission rate has to agree with the commission amount
beside it. Three rules, and all three read the same cell.</p>
<h2 id="one-transaction-as-your-platform-stores-it">One transaction as your platform stores it</h2>
<p>Salesforce publishes the <code>InsurancePolicy</code> object for Financial Services Cloud,
and its field list is the working vocabulary for this row. <code>Name</code> is "The
insurance policy number". <code>NameInsuredId</code> is "The name of the primary insured",
required, and a reference to another record. <code>WritingCarrierAccountId</code> is a
reference too. <code>LineOfBusiness</code> is a restricted picklist. <code>GrossWrittenPremium</code>
is "The total expected premium amount for the insurance policy over the policy
period". <code>CommissionPercent</code> is typed as a percent, <code>BillingType</code> publishes
Agency Billing and Direct Billing, and <code>EffectiveDate</code> and <code>ExpirationDate</code>
carry the term.</p>
<p>Two of those fields are references and the insured one is required. A policy row
stays unwritten until the named insured and the writing carrier both resolve to
a record you hold.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const TRANSACTION_TYPES = [
  "New Business",
  "Renewal",
  "Endorsement",
  "Cancellation",
  "Reinstatement",
  "Audit",
];

const LINES_OF_BUSINESS = [
  "Personal Auto",
  "Commercial Auto",
  "Homeowners",
  "Commercial Property",
  "General Liability",
  "Workers Compensation",
  "Umbrella",
];

const CARRIERS = [
  "Ardsley",
  "Kemwood",
  "Northgate",
  "Pelham",
  "Stanwick",
  "Valebrook",
];

const BILLING_TYPES = ["Agency Billing", "Direct Billing"];

export const columns: DataEditorColumn[] = [
  {
    id: "policyNumber",
    title: "Policy number",
    validators: [{ type: "required" }],
  },
  {
    id: "transactionType",
    title: "Transaction type",
    editor: {
      type: "select",
      options: TRANSACTION_TYPES,
      enableCustomValue: false,
    },
    validators: [
      { type: "required" },
      { type: "oneOf", values: TRANSACTION_TYPES },
    ],
  },
  {
    id: "transactionDate",
    title: "Transaction date",
    editor: { type: "date" },
  },
  {
    id: "effectiveDate",
    title: "Effective date",
    editor: { type: "date" },
    validators: [{ type: "required" }],
  },
  {
    id: "expirationDate",
    title: "Expiration date",
    editor: { type: "date" },
  },
  {
    id: "lineOfBusiness",
    title: "Line of business",
    editor: {
      type: "select",
      options: LINES_OF_BUSINESS,
      enableCustomValue: false,
    },
    validators: [{ type: "oneOf", values: LINES_OF_BUSINESS }],
  },
  {
    id: "insuredName",
    title: "Named insured",
    validators: [{ type: "required" }],
  },
  {
    id: "carrierCode",
    title: "Writing carrier",
    editor: { type: "select", options: CARRIERS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: CARRIERS }],
  },
  {
    id: "billingType",
    title: "Billing type",
    editor: {
      type: "select",
      options: BILLING_TYPES,
      enableCustomValue: false,
    },
    validators: [{ type: "oneOf", values: BILLING_TYPES }],
  },
  {
    id: "writtenPremium",
    title: "Written premium",
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", decimalPlaces: 2 }],
  },
  {
    id: "commissionRate",
    title: "Commission rate",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 100, decimalPlaces: 3 }],
  },
  {
    id: "commissionAmount",
    title: "Commission amount",
    editor: { type: "number" },
    validators: [{ type: "number", decimalPlaces: 2 }],
  },
  { id: "producerCode", title: "Producer code" },
];</code></pre>
<p>The policy number identifies a policy and it identifies no single row. 543
policy numbers cover the 2,392 rows in this file, one policy carries 15 of them,
and one number is written by two different carriers. <code>{ type: "unique" }</code> on
that column flags correct rows, and <code>primaryKey</code> on it merges transactions that
have nothing to do with each other. The key that holds is the policy number with
the transaction date and the transaction type, and it is distinct on all 2,392
rows here.</p>
<h2 id="the-register-an-agency-exports">The register an agency exports</h2>
<p>Wexbourne Insurance Group is an agency moving its book onto your platform. The
file is the transaction register printed by the management system they are
leaving, sorted by transaction date. A policy's rows are scattered down the
file.</p>
<p>EZLynx publishes the CSV template its commission statement import reads.
<code>Policy Number</code>, <code>Transaction Type Code</code>, <code>Premium</code>, <code>Comm Amount</code>, <code>LOB Code</code>,
<code>Policy Holder Name</code> and <code>Policy Eff Date</code> are the required headers.
<code>Agency ID</code>, <code>Producer Subcode</code>, <code>Transaction Date</code>, <code>Comm Percent</code>,
<code>LOB Subcode</code> and <code>Policy Exp Date</code> are the recommended ones. The same page
tells the person to enter a chargeback or a carrier fee as a negative amount.
The headers below are that template, shortened the way an export shortens.</p>
<p><code>agency-register.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Policy Number</td><td class="sheet__cell">Trans Code</td><td class="sheet__cell">Trans Date</td><td class="sheet__cell">Policy Eff Date</td><td class="sheet__cell">Policy Exp Date</td><td class="sheet__cell">LOB Code</td><td class="sheet__cell">Policy Holder Name</td><td class="sheet__cell">Carrier</td><td class="sheet__cell">Bill Type</td><td class="sheet__cell">Premium</td><td class="sheet__cell">Comm Percent</td><td class="sheet__cell">Comm Amount</td><td class="sheet__cell">Producer Code</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">VN551554629</td><td class="sheet__cell">NBS</td><td class="sheet__cell">2022-12-20</td><td class="sheet__cell">2023-01-07</td><td class="sheet__cell">2024-01-07</td><td class="sheet__cell">Commercial Property</td><td class="sheet__cell">Marchetti Foundry, Co</td><td class="sheet__cell">Valebrook National</td><td class="sheet__cell">A</td><td class="sheet__cell">57639.75</td><td class="sheet__cell">0.15</td><td class="sheet__cell">8645.96</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">NBS</td><td class="sheet__cell">2022-12-24</td><td class="sheet__cell">01/05/2023</td><td class="sheet__cell">2024-01-05</td><td class="sheet__cell">Commercial Property</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty Lines</td><td class="sheet__cell">Agency</td><td class="sheet__cell">17455.5</td><td class="sheet__cell">15</td><td class="sheet__cell">2,618.32</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">SFM54918094</td><td class="sheet__cell">New Business</td><td class="sheet__cell">2022-12-30</td><td class="sheet__cell">2023-01-14</td><td class="sheet__cell">01/14/2024</td><td class="sheet__cell">General Liability</td><td class="sheet__cell">Nyquist Contracting, Inc</td><td class="sheet__cell">Stanwick Fire &#x26; Marine</td><td class="sheet__cell">AB</td><td class="sheet__cell">23714.1</td><td class="sheet__cell">15</td><td class="sheet__cell">3557.12</td><td class="sheet__cell">HFN-04</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">NS-795288</td><td class="sheet__cell">N/B</td><td class="sheet__cell">2023-01-04</td><td class="sheet__cell">2023-01-15</td><td class="sheet__cell">2024-01-15</td><td class="sheet__cell">WORK</td><td class="sheet__cell">Dupree Excavating</td><td class="sheet__cell">NORTHGATE SPEC</td><td class="sheet__cell">DB</td><td class="sheet__cell">60,177.58</td><td class="sheet__cell">12</td><td class="sheet__cell">$7,221.31</td><td class="sheet__cell">HFN-04</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">KC9522547</td><td class="sheet__cell">N/B</td><td class="sheet__cell">2023-01-04</td><td class="sheet__cell">01/16/2023</td><td class="sheet__cell">01/16/2024</td><td class="sheet__cell">Personal Auto</td><td class="sheet__cell">Malachy Aldridge</td><td class="sheet__cell">Kemwood Casualty</td><td class="sheet__cell">D</td><td class="sheet__cell">$873.21</td><td class="sheet__cell">0.175</td><td class="sheet__cell">152.81</td><td class="sheet__cell">HFN-04</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">SFM21287702</td><td class="sheet__cell">NBS</td><td class="sheet__cell">2023-01-08</td><td class="sheet__cell">2023-01-23</td><td class="sheet__cell">2024-01-23</td><td class="sheet__cell">WORKERS COMPENSATION</td><td class="sheet__cell">Kessler Millwork, Inc</td><td class="sheet__cell">Stanwick F &#x26; M</td><td class="sheet__cell">Agency Bill</td><td class="sheet__cell">36501.35</td><td class="sheet__cell">17.5</td><td class="sheet__cell">6387.74</td><td class="sheet__cell">TRW-02</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">2385 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2393</th><td class="sheet__cell">KC9522547</td><td class="sheet__cell">RWL</td><td class="sheet__cell">2026-08-03</td><td class="sheet__cell">2026-01-16</td><td class="sheet__cell">2027-01-16</td><td class="sheet__cell">Personal Auto</td><td class="sheet__cell">Malachy Aldridge</td><td class="sheet__cell">Kemwood Casualty</td><td class="sheet__cell">D</td><td class="sheet__cell">901.55</td><td class="sheet__cell">17.5</td><td class="sheet__cell">157.77</td><td class="sheet__cell">HFN-04</td></tr></tbody></table>
<p>Seven rows, and most of the file's trouble is already on the screen. Three
spellings of new business. Effective dates written both ways round. A premium
carrying a dollar sign and a premium carrying a thousands comma. A commission
rate written <code>0.15</code> on one row and <code>15</code> on the next. <code>WORK</code> and
<code>WORKERS COMPENSATION</code> in one column, <code>Stanwick Fire &#x26; Marine</code> and
<code>Stanwick F &#x26; M</code> in another.</p>
<p>Counted over all 2,392 rows, the transaction code column holds 30 distinct
strings, the line of business column 29, the carrier column 24, the billing type
column 10 and the commission rate column 25. The expiration date is blank on 677
rows. The premium is negative on 561.</p>
<p>Header detection lands on row 1 at a confidence of 0.76 and asks the person to
confirm nothing. The parse reports no errors. 403 effective dates are written
<code>MM/DD/YYYY</code> against 1,989 written ISO, and the importer settles the ordering
once for the file, so all 2,392 reach the store as ISO.</p>
<h2 id="the-headers-that-end-in-code-and-date">The headers that end in Code and Date</h2>
<p>Seven of the thirteen headers reach a field with nothing configured.</p>
<div class="blog-table blog-table--fixed blog-table--policy-headers"><table>
<thead>
<tr>
<th>Header</th>
<th>Column it reaches</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Policy Number</code></td>
<td><code>policyNumber</code></td>
<td>100</td>
</tr>
<tr>
<td><code>Carrier</code></td>
<td><code>carrierCode</code></td>
<td>100</td>
</tr>
<tr>
<td><code>Producer Code</code></td>
<td><code>producerCode</code></td>
<td>100</td>
</tr>
<tr>
<td><code>Premium</code></td>
<td><code>writtenPremium</code></td>
<td>80</td>
</tr>
<tr>
<td><code>Trans Date</code></td>
<td><code>transactionDate</code></td>
<td>70</td>
</tr>
<tr>
<td><code>Bill Type</code></td>
<td><code>billingType</code></td>
<td>70</td>
</tr>
<tr>
<td><code>Comm Amount</code></td>
<td><code>commissionAmount</code></td>
<td>70</td>
</tr>
</tbody>
</table></div>
<p>Two of this schema's columns end in <code>Code</code> and three end in <code>Date</code>. A header
built from those words spreads its score over several columns and commits to
none of them.</p>
<p><code>Trans Code</code> and <code>LOB Code</code> reach nothing, and both of them score 70 against
<code>carrierCode</code> and 70 against <code>producerCode</code>. Those two columns go to the headers
that match them outright, <code>Carrier</code> and <code>Producer Code</code>, and the two <code>Code</code>
headers are left holding a tie they lost. <code>Policy Eff Date</code>, <code>Policy Exp Date</code>
and <code>Policy Holder Name</code> each share one word of three with four different
columns, which scores 20 and sits under the threshold. <code>Comm Percent</code> reaches
nothing at all.</p>
<p>Six headers stay unmapped, and five of them carry the columns every rule in this
article reads.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    transactionType: ["Trans Code", "Transaction Type Code", "Tran Type"],
    transactionDate: ["Trans Date"],
    effectiveDate: ["Policy Eff Date", "Eff Date"],
    expirationDate: ["Policy Exp Date", "Exp Date"],
    lineOfBusiness: ["LOB Code", "LOB", "Coverage Code"],
    insuredName: ["Policy Holder Name", "Insured", "Named Insured"],
    writtenPremium: ["Premium"],
    commissionRate: ["Comm Percent", "Comm Pct", "Commission Percent"],
    commissionAmount: ["Comm Amount"],
  },
  values: {
    "New Business": ["NBS", "NB", "New", "BNB"],
    Renewal: ["RWL", "REN", "RWR", "BRW"],
    Endorsement: ["PCH", "END", "Policy Change", "BPC"],
    Cancellation: ["XLC", "XLN", "CAN", "Cancel"],
    Reinstatement: ["REI", "Reinstate"],
    Audit: ["PAB", "AUD", "Premium Audit"],
    "Personal Auto": ["PAUTO", "PPA"],
    "Commercial Auto": ["CAUTO", "BAUTO", "Comm Auto"],
    Homeowners: ["HOME", "HO", "HO3"],
    "Commercial Property": ["PROP", "CPROP", "Comm Prop"],
    "General Liability": ["CGL", "GL", "Gen Liab"],
    "Workers Compensation": ["WORK", "WC", "Work Comp", "Workers Comp"],
    Umbrella: ["UMBR", "UMB", "Comm Umbrella"],
    "Agency Billing": ["A", "AB", "Agency", "Agency Bill"],
    "Direct Billing": ["D", "DB", "Direct", "Direct Bill"],
  },
};</code></pre>
<p>Every string on the left of the <code>values</code> list is published by somebody. The
three-letter codes are Vertafore's AMS360 list, <code>WORK</code> and <code>CGL</code> are the ACORD
line of business codes Vertafore names for Sagitta, and <code>Agency Bill</code> and
<code>Direct Bill</code> are the billing types EZLynx prints. The alias table is the
trade's own vocabulary written down once, so the next agency's export lands on
the same table.</p>
<p>With those rows in place all thirteen headers map.</p>
<h2 id="the-non-renewal-that-reads-as-a-renewal">The non-renewal that reads as a renewal</h2>
<p>Of the 30 distinct transaction codes, 25 reach one of the six options. Five
reach nothing and they cover 81 rows. <code>N/B</code> on 50, <code>NRA</code> on 13, <code>REW</code> on 8,
<code>Rewrite</code> on 5 and <code>NON RENEW</code> on 5.</p>
<p><code>N/B</code> is the one worth walking through. Value matching normalizes a value before
it compares, and normalizing strips whitespace, underscores, hyphens and full
stops. A slash stays where it is. <code>N/B</code> becomes <code>n/b</code>, which is three
characters, and the tier that matches on one string containing another refuses
anything shorter than four. The alias <code>"NB"</code> never sees it. An alias written
<code>"n/b"</code> settles all 50 rows.</p>
<p><code>NRA</code> and <code>REW</code> are published AMS360 codes and both are three characters, so
they fail the same way. <code>Rewrite</code> and <code>NON RENEW</code> name kinds of transaction this
schema does not store, and a person has to decide where they go.</p>
<p>Then there is the one that lands. <code>Non-Renewal</code> normalizes to <code>nonrenewal</code>,
which contains <code>renewal</code>, and that is a score of 80 without any alias behind it.
Seven rows enter the store as renewals. A non-renewal ends a policy and a
renewal opens a term, so the value landed on its own opposite.
<a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> walks the failures
any file can produce, and this is the shape that leaves no trace.</p>
<p><strong>A value that reaches no option arrives empty, and <code>oneOf</code> passes an empty
cell.</strong> With <code>oneOf</code> on four columns it flagged nothing at all across the whole
file. <code>{ type: "required" }</code> on the transaction type is what turns those 81 rows
into 81 flagged cells, and it is the only reason the person sees them.</p>
<h2 id="one-word-two-lines-of-business">One word, two lines of business</h2>
<p>The line of business column holds 29 distinct strings over seven options, and
with the alias table all 29 reach one. <code>CGL</code>, <code>GL</code> and <code>Gen Liab</code> land on
General Liability. <code>WORK</code>, <code>WC</code>, <code>Work Comp</code> and <code>WORKERS COMPENSATION</code> land on
Workers Compensation. Eight strings cover the two auto lines.</p>
<p><code>Auto</code> is written on 93 rows and it reaches Personal Auto. 25 of those 93 sit on
policies whose other rows write <code>BAUTO</code>, <code>CAUTO</code> or <code>Comm Auto</code>, and whose named
insured is a business.</p>
<p>Value matching settles one landing per column for the whole upload. The person
sees <code>Auto</code> once, picks one option, and the same choice reaches all 93 rows. A
string that means two things depending on the row cannot be settled on that
screen.</p>
<p>No rule recovers it either. <code>oneOf</code> passes Personal Auto because Personal Auto
is an option. The evidence sits in the policy's other rows, and a rule on a
cell never reaches them. The code that receives the finished import does reach
them, and the last section of this article is that code.</p>
<h2 id="a-required-rule-that-is-wrong-670-times">A required rule that is wrong 670 times</h2>
<p>The expiration date is blank on 677 of the 2,392 rows. It is blank on all 163
cancellations, on all 102 audits, on 387 of the 970 endorsements, and on 18 of
the 81 rows whose code reached no option. It is blank on none of the 490 new
business rows, none of the 53 reinstatements, and on 7 of the 533 renewals.</p>
<p>A term has an end date. A cancellation, a premium audit and a mid-term
endorsement have none, and the blank cell is the correct value.</p>
<div class="blog-table blog-table--fixed blog-table--policy-rules"><table>
<thead>
<tr>
<th>Rule on the expiration date</th>
<th>Cells flagged</th>
<th>Correct</th>
</tr>
</thead>
<tbody>
<tr>
<td>nothing</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td><code>{ type: "required" }</code></td>
<td>677</td>
<td>7</td>
</tr>
<tr>
<td><code>{ type: "function" }</code> reading the row</td>
<td>7</td>
<td>7</td>
</tr>
</tbody>
</table></div>
<pre><code class="language-ts">import type { CellValidator } from "@updog/data-editor";

const TERM_TYPES = ["New Business", "Renewal", "Reinstatement"];

const termNeedsAnEnd: CellValidator = (value, row) =>
  TERM_TYPES.includes(String(row.transactionType)) &#x26;&#x26; !value
    ? { level: "error", message: "A term needs an expiration date" }
    : null;

// on the transaction type column
dependentFields: ["expirationDate", "writtenPremium", "commissionRate"],

// on the expiration date column
validators: [{ type: "function", fn: termNeedsAnEnd }],</code></pre>
<p>The <code>fn</code> receives the cell value and the row it sits in, and it returns a
verdict or <code>null</code>. Reading <code>row.transactionType</code> is what makes the rule right on
all six kinds of row at once. <code>dependentFields</code> sits on the transaction type and
names the three columns to recheck, so a person correcting a code refreshes the
verdicts that read it.</p>
<p>The seven rows the conditional rule finds are the seven <code>Non-Renewal</code> rows.
Value matching sent them to Renewal, a renewal opens a term, and a term needs an
end date. A rule about one column caught a wrong value in another.</p>
<h2 id="when-a-negative-premium-is-the-correct-number">When a negative premium is the correct number</h2>
<p>561 of the 2,392 premiums are negative, and the sign follows the kind of row.</p>
<div class="blog-table blog-table--fixed blog-table--policy-signs"><table>
<thead>
<tr>
<th>Transaction type</th>
<th>Positive</th>
<th>Negative</th>
<th>Zero</th>
</tr>
</thead>
<tbody>
<tr>
<td>New Business</td>
<td>489</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>Renewal</td>
<td>526</td>
<td>0</td>
<td>7</td>
</tr>
<tr>
<td>Reinstatement</td>
<td>53</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>Endorsement</td>
<td>605</td>
<td>365</td>
<td>0</td>
</tr>
<tr>
<td>Audit</td>
<td>69</td>
<td>33</td>
<td>0</td>
</tr>
<tr>
<td>Cancellation</td>
<td>1</td>
<td>162</td>
<td>0</td>
</tr>
</tbody>
</table></div>
<p>An endorsement adds coverage on 605 rows and takes it away on 365, and a premium
audit corrects a payroll estimate in either direction. Both signs are legal on
both kinds of row. A cancellation returns unearned premium, so its number is
negative, and that is the chargeback rule EZLynx publishes.</p>
<p><code>{ type: "number", min: 0 }</code> on this column flags all 561 negative premiums and
560 of them are correct. No pair of bounds is right on six kinds of row at once,
so the rule reads the type.</p>
<pre><code class="language-ts">const premiumSignFollowsTheType: CellValidator = (value, row) => {
  const premium = Number(value);
  const type = String(row.transactionType);

  if (type === "Cancellation" &#x26;&#x26; premium > 0) {
    return { level: "error", message: "A cancellation returns premium" };
  }
  if (TERM_TYPES.includes(type) &#x26;&#x26; premium &#x3C;= 0) {
    return {
      level: "error",
      message: "This transaction cannot reduce premium",
    };
  }
  return null;
};

// on the written premium column
validators: [{ type: "function", fn: premiumSignFollowsTheType }],</code></pre>
<p>Nine cells come back. One is a new business row written <code>-4180.50</code>, one is a
cancellation written <code>2260.00</code>, and the other seven are the non-renewals that
arrived as renewals carrying a premium of zero. 531 premiums carry a dollar sign
and 720 carry a thousands comma, and every one of them reaches the store as a
number.</p>
<h2 id="the-rate-and-the-amount-disagree">The rate and the amount disagree</h2>
<p>The commission rate column holds 25 distinct strings. 1,700 rows write a whole
percent, <code>15</code> or <code>17.5</code>. 463 rows write the same rate as a fraction, <code>0.15</code> or
<code>.15</code>. 127 rows write it with a percent sign and 102 leave it blank.</p>
<p>The percent sign looks like the problem and is not. <code>15%</code> parses to <code>15</code> and
joins the whole percents, so those 127 rows are already correct. The fraction is
the problem, and <code>0.15</code> is a legal number between 0 and 100. <code>{ type: "number", min: 0, max: 100 }</code> passes it and passes <code>15</code> beside it.</p>
<p>The commission amount is the witness. Salesforce types <code>CommissionPercent</code> as a
percent, so the unit your schema stores is settled, and the amount divided by
the premium says which unit the file wrote.</p>
<pre><code class="language-ts">const rateAgreesWithAmount: CellValidator = (value, row) => {
  if (value === null || value === undefined || value === "") return null;

  const premium = Number(row.writtenPremium);
  const amount = Number(row.commissionAmount);
  if (!premium || !amount) return null;

  const implied = (amount / premium) * 100;

  return Math.abs(Number(value) - implied) > 0.5
    ? { level: "error", message: "Rate disagrees with the amount" }
    : null;
};

// on the commission rate column
validators: [{ type: "function", fn: rateAgreesWithAmount }],</code></pre>
<p>461 cells come back, which is the 463 fraction-written rates less the two whose
premium is zero.</p>
<p>The guard on the first line is load-bearing. <code>Number("")</code> is <code>0</code>, so a blank
rate implies a rate of zero and disagrees with every amount beside it. Without
the empty check the count came back 563, and 102 of those were blank cells doing
nothing wrong.</p>
<h2 id="nothing-here-knows-what-an-endorsement-is">Nothing here knows what an endorsement is</h2>
<p>Updog ships no insurance template, no transaction code table, no line of
business list and no carrier file. The thirteen columns, the six options, the
alias tables, the three conditional rules and the handler are all code you
write.</p>
<p>If the register is yours and the destination is yours, this is the wrong tool.
The agency management system you already run has an import screen built for its
own tables, and it knows what a reinstatement means. Updog Importer is for the
file that arrives from somebody else, in their vocabulary, on a day you did not
pick.</p>
<p>Updog Importer reads CSV, TSV, XLSX, XLS, XLSB, ODS, JSON and XML. A policy
schedule that survives only as a PDF goes through
<a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a> and arrives as ordinary
rows. One million rows is a practical ceiling rather than an unlimited claim,
and this register is 2,392.</p>
<h2 id="the-policies-with-no-beginning">The policies with no beginning</h2>
<p>The register is sorted by transaction date, so one policy is six rows in six
places. Gathered by policy number, <code>NS-742994</code> reads as a story.</p>
<p><code>agency-register.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Policy Number</td><td class="sheet__cell">Trans Code</td><td class="sheet__cell">Trans Date</td><td class="sheet__cell">Policy Eff Date</td><td class="sheet__cell">Policy Exp Date</td><td class="sheet__cell">LOB Code</td><td class="sheet__cell">Policy Holder Name</td><td class="sheet__cell">Carrier</td><td class="sheet__cell">Bill Type</td><td class="sheet__cell">Premium</td><td class="sheet__cell">Comm Percent</td><td class="sheet__cell">Comm Amount</td><td class="sheet__cell">Producer Code</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">1 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">NBS</td><td class="sheet__cell">2022-12-24</td><td class="sheet__cell">01/05/2023</td><td class="sheet__cell">2024-01-05</td><td class="sheet__cell">Commercial Property</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty Lines</td><td class="sheet__cell">Agency</td><td class="sheet__cell">17455.5</td><td class="sheet__cell">15</td><td class="sheet__cell">2,618.32</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">161 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">165</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">PCH</td><td class="sheet__cell">2023-03-28</td><td class="sheet__cell">2023-03-25</td><td class="sheet__cell"></td><td class="sheet__cell">CPROP</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty</td><td class="sheet__cell">AB</td><td class="sheet__cell">-840.81</td><td class="sheet__cell">15</td><td class="sheet__cell">-126.12</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">494 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">660</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">RWL</td><td class="sheet__cell">2023-12-31</td><td class="sheet__cell">2024-01-05</td><td class="sheet__cell">2025-01-04</td><td class="sheet__cell">Comm Prop</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty</td><td class="sheet__cell">Agency</td><td class="sheet__cell">$18,865.94</td><td class="sheet__cell">15</td><td class="sheet__cell">2829.89</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">51 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">712</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">endorsement</td><td class="sheet__cell">2024-01-31</td><td class="sheet__cell">2024-01-24</td><td class="sheet__cell">2025-01-04</td><td class="sheet__cell">Commercial Property</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty</td><td class="sheet__cell">Agency Bill</td><td class="sheet__cell">1,234.38</td><td class="sheet__cell">15</td><td class="sheet__cell">185.16</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">221 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">934</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">END</td><td class="sheet__cell">2024-05-28</td><td class="sheet__cell">2024-05-23</td><td class="sheet__cell">2025-01-04</td><td class="sheet__cell">Commercial Property</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">NORTHGATE SPEC</td><td class="sheet__cell">A</td><td class="sheet__cell">$1,648.81</td><td class="sheet__cell">0.15</td><td class="sheet__cell">247.32</td><td class="sheet__cell">GBY-06</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">111 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1046</th><td class="sheet__cell">NS-742994</td><td class="sheet__cell">Cancellation</td><td class="sheet__cell">2024-07-29</td><td class="sheet__cell">2024-07-24</td><td class="sheet__cell"></td><td class="sheet__cell">Comm Prop</td><td class="sheet__cell">Ostrander Bakery, LLC</td><td class="sheet__cell">Northgate Specialty Lines</td><td class="sheet__cell">AGENCY BILL</td><td class="sheet__cell">-8476.75</td><td class="sheet__cell">.15</td><td class="sheet__cell">-1271.51</td><td class="sheet__cell">GBY-06</td></tr></tbody></table>
<p>New business, a policy change that gives premium back, a renewal, two more
endorsements and a cancellation. The two rows with no expiration date are the
mid-term change and the cancellation, and neither one opens a term. Both
negative premiums sit on rows that take coverage away.</p>
<p>Your handler groups the rows this way because a policy is what your platform
stores. Once they are grouped, the handler can look for the row that opened the
policy. No rule on a cell reaches that far.</p>
<pre><code class="language-ts">type Transaction = Record&#x3C;string, unknown>;

const CREATING = ["New Business", "Renewal"];

export const policiesWithNoBeginning = (rows: Transaction[]) => {
  const byPolicy = new Map&#x3C;string, Transaction[]>();

  for (const row of rows) {
    const key = String(row.policyNumber);
    const held = byPolicy.get(key) ?? [];
    held.push(row);
    byPolicy.set(key, held);
  }

  return [...byPolicy.entries()]
    .filter(([, held]) =>
      held.every((row) => !CREATING.includes(String(row.transactionType))),
    )
    .map(([policyNumber, held]) => ({ policyNumber, transactions: held }));
};</code></pre>
<p>543 policies cover the 2,392 transactions, and 28 of them carry no new business
row and no renewal row. That is 60 transactions describing policies that never
began.</p>
<p>Three of the 28 have no creating row anywhere in the file, so an endorsement
arrived for a policy the export left behind. The other 25 have one, and it wrote
<code>N/B</code>. One alias missing from the table makes 25 policies look as though they
appeared out of nothing, and no cell in the grid says so.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey={["policyNumber", "transactionDate", "transactionType"]}
  onComplete={async (result) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row);

    const orphans = policiesWithNoBeginning(rows);

    await postRegister({ transactions: rows, orphans });
  }}
/></code></pre>
<p>All of that runs where the person dropped the file, and the rows travel from
their browser to your endpoint under your own agreement.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
follows a file down each of the two routes.</p>
<h2 id="what-the-handler-refuses-to-write">What the handler refuses to write</h2>
<p>2,392 rows and thirteen columns make 31,096 cells. A schema of required fields,
option lists and number bounds flags 86 of them, and the register still lands
wrong. The schema whose rules read the row flags 563.</p>
<p>461 are commission rates written in the wrong unit. 81 are transaction codes
that reached no option. 8 are premiums a term row cannot carry, 7 are terms with
no end date, 5 are rows with no named insured, and 1 is a cancellation that adds
premium.</p>
<p>Every one of them is legible to the person who knows the book. The policy
number, the insured name and the transaction code sit in the same row as the
flagged cell, and the code says what the row was meant to be.</p>
<p>Then 28 policies reach your handler in a list of their own rather than in the
table, because an endorsement needs a policy underneath it. A register printed
for a person to read becomes rows your platform can bill.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Neo4j</title><link>https://updog.tech/blog/import-csv-into-neo4j/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-neo4j/</guid><pubDate>Mon, 17 Aug 2026 00:00:00 GMT</pubDate><description>Match a shareholder register in the browser, post the clean rows to your own route, and write nodes and relationships into Neo4j with one UNWIND and MERGE.</description><content:encoded><![CDATA[<p>Neo4j documents several ways to move a CSV into a graph. <code>LOAD CSV</code> reads a file out of the server's import directory or off an HTTPS URL, and the local form carries the marker "Not available on Aura". <code>neo4j-admin database import</code> writes CSV straight into the store, and its own page asks for an offline server, an empty database, and data that is "clean/fault-free". Neo4j Data Importer takes CSV and TSV through a graphical tool and draws the model beside them. Every one of those starts from a seat that already holds database credentials. Your customer sits outside that seat, holding the shareholder register their company secretary exported this morning.</p>
<h2 id="the-row-is-an-edge">The row is an edge</h2>
<p>Every one of those paths wants the graph pre-split. A file of nodes, then a file of relationships whose start and end nodes already exist. A register from a customer arrives as one flat export, and each row names two parties and the holding between them.</p>
<p>So one row becomes three things. A node for the holder, a node for the company, and an <code>OWNS</code> relationship carrying the percentage and the date. The same reference turns up as a holder on one line and as a company on another. That is what makes this a graph.</p>
<p>The person drags both registers into the importer inside your app. Updog Importer reads them in the browser, matches each file's headers to your schema, and puts every row in front of them. Your <code>onComplete</code> handler receives the rows grouped by file. The handler posts them to a route you own, and that route writes them a thousand at a time.</p>
<p>No Updog server stands between the browser and Neo4j.</p>
<h2 id="the-graph-the-rows-land-in">The graph the rows land in</h2>
<p>One label holds every party. A person, a company, a trust and a fund are all a <code>Party</code> with a <code>ref</code>, a <code>name</code> and a <code>kind</code>, so a chain of ownership is a path through one label. Two Cypher statements set that up before the first import.</p>
<pre><code class="language-cypher">CREATE CONSTRAINT party_ref_unique IF NOT EXISTS
FOR (p:Party) REQUIRE p.ref IS UNIQUE;

CREATE INDEX party_name IF NOT EXISTS
FOR (p:Party) ON (p.name);</code></pre>
<p>The constraint earns its place twice. Neo4j's own manual asks for it directly, since constraints "provide index-backed performance improvements" and prevent "the creation of data that differ in unintended ways from pre-existing data". It also protects "against duplicate creation under concurrent loads, where MERGE alone only guarantees the existence of the pattern, not its uniqueness".</p>
<p>Property uniqueness stops short of one thing. Neo4j states that such constraints "do not require all nodes or relationships to have values for the properties listed in the constraint", so a <code>Party</code> with no <code>ref</code> slips past it. Requiring the property as well takes a key constraint, which is Enterprise Edition. On any edition, a missing reference gets caught in the browser.</p>
<p>A property holds a primitive or a homogeneous list of primitives, and a <code>MAP</code> is absent from Neo4j's list of property types. The structure a document store buries inside a field lives here as the relationship.</p>
<h2 id="the-registers-that-arrive">The registers that arrive</h2>
<p>Two groups send their disclosures in the same week. Each one exports from a different system.</p>
<p><code>helvetia-holding-register.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Holder Ref</td><td class="sheet__cell">Registered Holder</td><td class="sheet__cell">Holder Type</td><td class="sheet__cell">Investee Ref</td><td class="sheet__cell">Investee</td><td class="sheet__cell">Stake</td><td class="sheet__cell">Since</td><td class="sheet__cell">Class</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">CORP</td><td class="sheet__cell">CHE-241-663-004</td><td class="sheet__cell">Alpina Logistik AG</td><td class="sheet__cell">62,5</td><td class="sheet__cell">31.12.2024</td><td class="sheet__cell">ORD</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">CORP</td><td class="sheet__cell">CHE-241-663-004</td><td class="sheet__cell">Alpina Logistik AG</td><td class="sheet__cell">66,0</td><td class="sheet__cell">01.03.2026</td><td class="sheet__cell">ORD</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">CORP</td><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">100,0</td><td class="sheet__cell">31.12.2024</td><td class="sheet__cell">ORD</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">CHE-380-441-902</td><td class="sheet__cell">Marta Reinhardt</td><td class="sheet__cell">IND</td><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">18,0</td><td class="sheet__cell">14.06.2019</td><td class="sheet__cell">A</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell"></td><td class="sheet__cell">Bernhard Kueng</td><td class="sheet__cell">IND</td><td class="sheet__cell">CHE-114-208-717</td><td class="sheet__cell">Helvetia Beteiligungen AG</td><td class="sheet__cell">9,5</td><td class="sheet__cell">14.06.2019</td><td class="sheet__cell">A</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">68 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">75</th><td class="sheet__cell">CHE-902-118-336</td><td class="sheet__cell">Kaspar Zwygart</td><td class="sheet__cell">IND</td><td class="sheet__cell">CHE-241-663-004</td><td class="sheet__cell">Alpina Logistik AG</td><td class="sheet__cell">4,0</td><td class="sheet__cell">22.09.2021</td><td class="sheet__cell">A</td></tr></tbody></table>
<p><code>nordwind-psc-export.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Shareholder Reference</td><td class="sheet__cell">Shareholder Name</td><td class="sheet__cell">Nature</td><td class="sheet__cell">Company Number</td><td class="sheet__cell">Company Name</td><td class="sheet__cell">Percentage Held</td><td class="sheet__cell">Acquisition Date</td><td class="sheet__cell">Security Class</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">GB-OC-388211</td><td class="sheet__cell">Nordwind Capital LLP</td><td class="sheet__cell">corporate entity</td><td class="sheet__cell">GB-12994017</td><td class="sheet__cell">Nordwind Renewables Ltd</td><td class="sheet__cell">74.9%</td><td class="sheet__cell">2019-07-01</td><td class="sheet__cell">Ordinary Shares</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">GB-PSC-771034</td><td class="sheet__cell">Ingrid Sorensen</td><td class="sheet__cell">individual person</td><td class="sheet__cell">GB-12994017</td><td class="sheet__cell">Nordwind Renewables Ltd</td><td class="sheet__cell">15.1%</td><td class="sheet__cell">2019-07-01</td><td class="sheet__cell">Class A Ordinary</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">GB-TR-449120</td><td class="sheet__cell">The Sorensen Family Trust</td><td class="sheet__cell">trust or foundation</td><td class="sheet__cell">GB-12994017</td><td class="sheet__cell">Nordwind Renewables Ltd</td><td class="sheet__cell">10.0%</td><td class="sheet__cell">2021-11-30</td><td class="sheet__cell">Preference Shares</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">84 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">89</th><td class="sheet__cell">GB-12994017</td><td class="sheet__cell">Nordwind Renewables Ltd</td><td class="sheet__cell">corporate entity</td><td class="sheet__cell">GB-13880554</td><td class="sheet__cell">Nordwind Solar Park Two Ltd</td><td class="sheet__cell">100%</td><td class="sheet__cell">2022-04-05</td><td class="sheet__cell">Ordinary Shares</td></tr></tbody></table>
<p>The two files disagree on almost every convention. The Swiss export separates its fields with a semicolon and writes <code>62,5</code> with a comma, and Updog reads the delimiter out of the file itself. The dotted date <code>31.12.2024</code> puts 31 in the first position, above 12, so that file settles day first and <code>01.03.2026</code> lands as <code>2026-03-01</code>. The British export uses commas, ISO dates and a percent sign, and the number reader strips the sign before it looks at the digits. Each file gets its own verdict.</p>
<p>Four rows carry real trouble. Rows 2 and 3 of the Swiss file declare the same holder and the same company at a different percentage, because somebody restated the holding and left both lines in. Row 4 lists <code>CHE-114-208-717</code> as its own shareholder. Row 6 has no holder reference at all. The last row of the British file makes <code>GB-12994017</code> a holder, far below the rows where it was the company.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array describes the register as the person sees it.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const KINDS = ["Individual", "Company", "Trust", "Fund"];
const CLASSES = ["Ordinary", "Preference", "Class A", "Class B"];
const REF = "^[A-Z]{2,3}-[A-Z0-9-]{3,}$";

export const columns: DataEditorColumn[] = [
  {
    id: "holderRef",
    title: "Holder reference",
    size: 170,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [{ type: "required" }, { type: "regex", pattern: REF }],
    dependentFields: ["companyRef"],
  },
  {
    id: "holderName",
    title: "Holder name",
    size: 210,
    transformer: (value) => String(value).trim(),
    validators: [{ type: "required" }],
  },
  {
    id: "holderType",
    title: "Holder type",
    size: 140,
    editor: { type: "select", options: KINDS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: KINDS }],
  },
  {
    id: "companyRef",
    title: "Company number",
    size: 170,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: REF },
      {
        type: "function",
        fn: (value, row) =>
          String(value) === String(row.holderRef)
            ? { level: "error", message: "A party cannot hold itself" }
            : null,
      },
    ],
  },
  {
    id: "companyName",
    title: "Company name",
    size: 210,
    validators: [{ type: "required" }],
  },
  {
    id: "stakePercent",
    title: "Stake percent",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, max: 100, decimalPlaces: 2 },
    ],
  },
  {
    id: "sinceDate",
    title: "Since date",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "shareClass",
    title: "Share class",
    size: 150,
    editor: { type: "select", options: CLASSES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: CLASSES }],
  },
];</code></pre>
<p>Each rule answers something Neo4j will do without complaining. <code>{ type: "required" }</code> on the two reference columns catches the blank cell while somebody can still type into it. The <code>regex</code> rule holds both references to the shape your graph already uses, so a stray value cannot open a second node beside a real one. The <code>function</code> rule on the company number reads <code>holderRef</code> off the same row and refuses a party that holds itself. <code>dependentFields</code> names the columns to revalidate when its own column changes, so the entry sits on the holder reference and points at the company number, and editing the holder reruns the check that reads it. Nothing in Cypher refuses that self-relationship, so the refusal has to happen here.</p>
<p>The <code>select</code> editors hold the holder type and the share class to fixed lists. With <code>enableCustomValue: false</code> the person picks from the list you shipped, and a value nobody maps is dropped from the row.</p>
<h2 id="the-headers-each-group-sends">The headers each group sends</h2>
<p>An edge file carries mirrored columns. Two names, two references, one pair for each end of the relationship, and half the headers therefore look like the other half. <code>Registered Holder</code> scores 70 against <code>holderRef</code>, <code>holderName</code> and <code>holderType</code> at the same time.</p>
<p>Matching settles that in two passes. Headers that normalize onto a column id or title claim their column outright. So <code>Holder Ref</code> takes <code>holderRef</code> at 100 and <code>Holder Type</code> takes <code>holderType</code> at 100. Everything left goes into one maximum-weight assignment over the remaining headers and the remaining columns. Each column can be claimed once, and pairs below the threshold are zeroed before the solve, so a weak pairing never blocks a strong one. <code>Registered Holder</code> reaches <code>holderName</code> because the assignment has one column left for it. <code>Investee Ref</code> reaches <code>companyRef</code> the same way.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>File</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Holder Ref</code></td>
<td>Swiss</td>
<td><code>holderRef</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Holder Type</code></td>
<td>Swiss</td>
<td><code>holderType</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Registered Holder</code></td>
<td>Swiss</td>
<td><code>holderName</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Investee Ref</code></td>
<td>Swiss</td>
<td><code>companyRef</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Investee</code></td>
<td>Swiss</td>
<td><code>companyName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Stake</code></td>
<td>Swiss</td>
<td><code>stakePercent</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Since</code></td>
<td>Swiss</td>
<td><code>sinceDate</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Class</code></td>
<td>Swiss</td>
<td><code>shareClass</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Company Number</code></td>
<td>British</td>
<td><code>companyRef</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Company Name</code></td>
<td>British</td>
<td><code>companyName</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Shareholder Reference</code></td>
<td>British</td>
<td><code>holderRef</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Shareholder Name</code></td>
<td>British</td>
<td><code>holderName</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Acquisition Date</code></td>
<td>British</td>
<td><code>sinceDate</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Security Class</code></td>
<td>British</td>
<td><code>shareClass</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Nature</code></td>
<td>British</td>
<td><code>holderType</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Percentage Held</code></td>
<td>British</td>
<td><code>stakePercent</code></td>
<td>synonym, 90</td>
</tr>
</tbody>
</table></div>
<p>Three headers reach nothing on their own. <code>Investee</code> and <code>Nature</code> share no whole word with any column, and both run too far from every id for the edit-distance tier. <code>Percentage Held</code> looks close to <code>Stake percent</code> and lands at zero, since <code>percentage</code> and <code>percent</code> are different words and the strings sit four edits apart where three are allowed. One <code>synonyms</code> entry each carries all three.</p>
<p>Value matching runs once for the whole import and collects values per column across both files. <code>individual person</code> and <code>trust or foundation</code> contain their options and land at eighty. <code>IND</code>, <code>CORP</code>, <code>TR</code> and <code>ORD</code> are trade shorthand of three or four characters and reach nothing, so one synonym entry each does it. <code>Class A Ordinary</code> contains both <code>Ordinary</code> and <code>Class A</code> at eighty, and the first option in the list wins that tie. The synonym entry lifts <code>Class A</code> to ninety and settles it.</p>
<p>Whatever the person fixes by hand comes back as <code>learnedSynonyms</code>, ready to feed back through <code>synonyms</code> for the next register. <a href="https://updog.tech/blog/remember-csv-import-mappings/">Remembering CSV import mappings between uploads</a> covers that loop.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the two registers, the schema and the graph together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Holding>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey={["holderRef", "companyRef"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      companyName: ["investee"],
      holderType: ["nature"],
      stakePercent: ["percentage held"],
    },
    values: {
      Individual: ["ind"],
      Company: ["corp", "corporate entity"],
      Trust: ["tr"],
      Ordinary: ["ord"],
      "Class A": ["a", "class a ordinary"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> takes two columns, because an ownership line is identified by a holder and a company together. Values are compared after trimming, and a row missing either half merges with nothing and arrives as new. Updog's own uniqueness rule reads one column at a time, so the pair does its work as the key. The two restated lines both land where the person can see them.</p>
<p><code>enableDeleteRow="all"</code> lets them drop the superseded line by hand. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, the blank reference and the self-holding included.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source. Each register lands as its own entry, carrying the file name, so a holding declared by the Nordwind group still says so on the way out.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 1000;

const toRow = (entry: ResultRow&#x3C;Holding>) => {
  if (entry.isDeleted) return [];
  return [{
    holderRef: entry.row.holderRef,
    holderName: entry.row.holderName,
    holderType: entry.row.holderType,
    companyRef: entry.row.companyRef,
    companyName: entry.row.companyName,
    stakePercent: Number(entry.row.stakePercent),
    sinceDate: entry.row.sinceDate,
    shareClass: entry.row.shareClass || null,
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Holding>) => {
  for (const source of result.sources) {
    const rows = source.rows.flatMap(toRow);

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const written = await fetch("/api/ownership/write", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          register: source.sourceName,
          rows: rows.slice(start, start + CHUNK_SIZE),
        }),
      });
      if (!written.ok) throw new Error((await written.json()).message);
    }
  }
}, []);</code></pre>
<p>A new holding and a restated one are the same payload, since <code>MERGE</code> matches or creates either way. A deleted row goes nowhere, since withdrawing a disclosure deserves its own route. The percentage becomes a JavaScript number here, which the driver maps to a Cypher <code>FLOAT</code>. An empty share class becomes <code>null</code>, and Neo4j does not store a null property.</p>
<p>The chunk size belongs to you. Neo4j publishes 1,000 rows as the default batch for its own <code>CALL { } IN TRANSACTIONS</code> clause, and names 10,000 as a larger batch for larger data sets. The driver manual's good-practice example passes 10,000 objects into one <code>UNWIND</code>. Neither number describes a POST body. So a thousand rows is a number chosen against what your own endpoint accepts, and it matches the batch the route writes.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and both registers clear the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-statement-that-writes">The statement that writes</h2>
<p>One statement writes both nodes and the relationship for every row in the chunk.</p>
<pre><code class="language-cypher">UNWIND $rows AS row

MERGE (holder:Party {ref: row.holderRef})
  ON CREATE SET holder.firstDeclaredIn = $register
SET holder.name = row.holderName,
    holder.kind = row.holderType

MERGE (company:Party {ref: row.companyRef})
  ON CREATE SET company.firstDeclaredIn = $register
SET company.name = row.companyName

MERGE (holder)-[stake:OWNS]->(company)
  ON CREATE SET stake.firstDeclaredIn = $register
SET stake.percent = row.stakePercent,
    stake.since = date(row.sinceDate),
    stake.shareClass = row.shareClass,
    stake.declaredIn = $register,
    stake.declaredBy = $group</code></pre>
<p>The identity is the reference, and the name is a property set afterwards. That order is the whole trick. Neo4j's manual shows the alternative, where merging a Charlie Sheen who differs in one property creates a second Charlie Sheen. Put <code>name</code> in the pattern and <code>Nordwind Renewables Ltd</code> and <code>Nordwind Renewables Limited</code> become two companies.</p>
<p>The relationship follows the same rule for a sharper reason. <code>MERGE (holder)-[stake:OWNS]->(company)</code> names the type alone, and the percentage, the date and the share class are set after it. Cypher "has no constraint that limits the number of relationships of a given type between two nodes", so a percentage inside the pattern would open a second <code>OWNS</code> every time a group restates a holding. <code>ON CREATE SET</code> records which register first declared a party. The plain <code>SET</code> clauses overwrite on every pass, so the last row in the list is the one that stands. Order the payload by date, or let the person delete the superseded line in the grid.</p>
<h2 id="the-write-that-may-run-twice">The write that may run twice</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import neo4j from "neo4j-driver";

const driver = neo4j.driver(
  process.env.NEO4J_URI,
  neo4j.auth.basic(process.env.NEO4J_USER, process.env.NEO4J_PASSWORD),
);

const BATCH = 1000;

app.post("/api/ownership/write", async (request, response) => {
  const account = await getVerifiedAccount(request);
  if (!account) return response.status(401).json({ message: "Not signed in" });

  const { register, rows } = request.body;
  const group = await groupFilingRegister(account.id, register);
  if (!group) {
    return response.status(403).json({ message: "That register is not yours" });
  }

  const graph = driver.session({ database: "neo4j" });
  try {
    for (let start = 0; start &#x3C; rows.length; start += BATCH) {
      const slice = rows.slice(start, start + BATCH);
      await graph.executeWrite((tx) =>
        tx.run(WRITE_OWNERSHIP, { rows: slice, register, group: group.id }),
      );
    }
  } catch (error) {
    request.log.error({ err: error, code: error.code });
    return response.status(502).json({ message: "The write did not finish" });
  } finally {
    await graph.close();
  }

  response.json({ written: rows.length });
});</code></pre>
<p><code>getVerifiedAccount()</code> stands in for your own server-side authentication check. The register name arrives in the body, so the route resolves which group is allowed to file it and refuses a name belonging to somebody else. Every relationship it writes carries that group's id, so one customer's disclosure stays separable from another's inside one graph. The driver is built once at module scope, since driver objects are "immutable, thread-safe, and expensive to create".</p>
<p><code>executeWrite</code> is the reason the statement looks the way it does. The driver "automatically retries to run a failed query if the failure is deemed to be transient". The manual asks for the consequence in the next breath. "Transaction functions should produce the same effect when run several times (idempotent), because you do not know upfront how many times they are going to be executed." <code>MERGE</code> satisfies that on every attempt. <code>CREATE</code> would add a node per attempt.</p>
<p>One transient failure is waiting for exactly this import. When <code>MERGE</code> finds no relationship, Neo4j acquires "exclusive locks on both end nodes", which is how two concurrent writes are kept from creating the same edge twice. Two registers naming the same company at the same moment is that case, and <code>Neo.TransientError.Transaction.DeadlockDetected</code> says of it that "Retrying this transaction will most likely be successful". The driver retries it for thirty seconds by default, backing off from a one-second delay, before your <code>catch</code> ever sees it.</p>
<h2 id="the-row-that-writes-anyway">The row that writes anyway</h2>
<p>A blank reference does not stop its row. Updog hands an empty cell to your handler as an empty string, and <code>MERGE (holder:Party {ref: ''})</code> is a legal pattern, so the row goes in. It opens a <code>Party</code> whose reference is empty, every later blank reference matches that same node, and <code>SET holder.name = row.holderName</code> renames it on each pass. One node collects every holder the registers failed to identify and wears the last name in the chunk. Bernhard Kueng's 9.5% of Helvetia hangs off it. <code>MERGE</code> refuses a property value that is genuinely null and names the clause directly with <code>22N31</code>. A key absent from the payload arrives that way. An empty cell arrives as a string.</p>
<p>That makes <code>{ type: "required" }</code> on the two reference columns the cheapest line in the schema. The person sees the flagged cell beside the name it belongs to, types the reference their register left out, and every node the chunk opens carries a reference somebody can look up. The errors that do arrive take the whole thousand with them, since one transaction covers the chunk and a transaction "is either committed in its entirety or rolled back on failure". A constraint violation arrives as <code>Neo.ClientError.Schema.ConstraintValidationFailed</code> and a bad type as <code>Neo.ClientError.Statement.TypeError</code>. Both carry a <code>code</code>, and both reach the <code>catch</code>, which answers 502 and lets the handler throw.</p>
<p>All of this happens with the confirm dialog open and a spinner on the button. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Neo4j connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route in the middle is work you do. Our uniqueness rule reads one column, so the pair that identifies a holding is checked by <code>primaryKey</code> and by the person looking at the grid.</p>
<p>Neo4j already ships its own way in for the other case. <code>neo4j-admin database import</code> moves millions of entities at store-file speed. Its own page states the conditions plainly, an offline server, direct access to the machine, an empty database, and CSV that is already fault-free. A customer's register meets none of those. <code>LOAD CSV</code> covers the middle ground from a <code>file:///</code> path in the server's import directory, and the local form is marked unavailable on Aura. The remote form reads an HTTPS URL, which would mean publishing somebody's shareholder list at a public address. For a first load your own team assembled, the admin tool is the shorter way in. Everything above exists for the registers your customers send, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-register">The pieces you wrote and the next register</h2>
<p>You wrote one label, one relationship type, a uniqueness constraint, a schema with eight columns, three column synonyms and five value synonyms, one handler that chunks by a thousand, and one route that runs a single <code>UNWIND</code> inside a transaction the driver may run twice. The files stay on the machine that opened them. The rows travel from your own front end to your own route and into Neo4j, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The next filing brings the same two groups and a third one with a fourth spelling of <code>Percentage Held</code>. The mappings from this import are already stored, the constraint has been protecting the graph since before the first row, and the new group costs one more line in <code>synonyms</code>.</p>]]></content:encoded></item>
<item><title>CSV Import for Manufacturing and ERP Software</title><link>https://updog.tech/blog/csv-import-for-manufacturing-erp-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-manufacturing-erp-software/</guid><pubDate>Sun, 16 Aug 2026 00:00:00 GMT</pubDate><description>A bill of materials keeps its structure in a Level column and the order of its rows. How to take that file into a schema of parent and child parts.</description><content:encoded><![CDATA[<p>A bill of materials is a tree. A finished product is built from assemblies, an
assembly from sub-assemblies, and the bottom of the tree is a part somebody
buys. Manufacturers keep that tree in an ERP or a PLM system, and they hand it
out as a spreadsheet.</p>
<p>A spreadsheet has rows. Flattening a tree into rows means the shape has to be
recorded some other way, and every system picks its own convention for that.
Part numbers add their own trouble, because a spreadsheet reads one as a
number and drops the leading zeros.</p>
<p>Your BOM line table holds a parent part number and a child part number. The
file a customer sends holds eleven columns, and not one of them is a parent.</p>
<p>The parent is the row above. Which row above is settled by a <code>Level</code> integer and
by the order the rows were printed in. Nothing else in the file says it.</p>
<p>A manufacturing platform stores one row per BOM line. Its customers export those
lines out of the system they are leaving, and that export prints a tree as a
list. Taking a customer's bill of materials into a schema of your own is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The file below holds 829 rows over eleven columns, 54 KB of CSV. Every number
here came out of that file or out of running it through the importer.</p>
<h2 id="the-column-that-holds-the-tree">The column that holds the tree</h2>
<p>SAP Ariba publishes the template its BOM import reads, and the first mandatory
field on it is <code>Level</code>. The page describes it as an integer value indicating
"the hierarchical position of an entry in BOM". Beside it sit <code>MaterialNumber</code>,
<code>BOMNumber</code>, a two-character <code>BOMCategory</code>, and a <code>PlantID</code>. Two more carry the
effectivity, <code>ValidFromDate</code> and <code>ValidToDate</code>, both in <code>YYYY-MM-DD</code>. An
<code>ItemCategory</code> closes the row over the values D, I, K, L, M, N, R and T.</p>
<p>One integer per row carries the whole shape of the assembly. That integer is
written two ways, and First Resonance publishes both of them by name. Level
notation numbers the tree, so 1 is the top assembly, 1.1 and 1.2 are its
children, and 1.1.1 is a child of 1.1. Depth notation writes the indentation
level instead, 1, then 2, then 3. OpenBOM builds the structure from either form
on a spreadsheet import.</p>
<p>First Resonance also publishes the warning that goes with the second form.
<strong>"The order matters"</strong>, and the file must not have "been rearranged since
exporting". A depth number says how far down a row sits. The row it sits under
is whichever row above it holds the number one smaller, and that fact lives in
the row order alone.</p>
<h2 id="a-bom-line-on-your-side">A BOM line on your side</h2>
<p>Microsoft Learn describes the destination shape for Dynamics 365 Supply Chain
Management. "A single BOM describes a single level that is identified by a
unique ID. Components might have their own BOMs that are referenced by BOM
versions." One assembly, its immediate children, and nothing deeper.</p>
<p>NetSuite publishes the same model as a file. Its BOM member replacement takes
three columns in a fixed order, the internal ID of the assembly item, the
internal ID of the BOM member, and a quantity. One assembly item gets as many
rows as it has members. ERPNext stores it the same way,
where "each item (sub-assembly) could have its own BOM hence forming a tree of
Items with multiple levels". BuyPLM's own import file describes a "single-level
BOM", the relationship "between an assembly and its immediate child parts".</p>
<p>Four published references, one storage model. A parent, a child, a quantity, and
no level column anywhere. Your schema is a table of pairs, and the file is a
picture of a tree.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const LINE_TYPES = ["Item", "Phantom", "Pegged supply", "Vendor"];

const UNITS = ["EA", "SET", "G", "KG", "L", "ML", "M", "MM", "SQM"];

export const columns: DataEditorColumn[] = [
  {
    id: "level",
    title: "Level",
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", min: 1 }],
  },
  {
    id: "findNumber",
    title: "Find number",
    editor: { type: "number" },
  },
  {
    id: "childPartNumber",
    title: "Part number",
    validators: [{ type: "required" }],
  },
  { id: "revision", title: "Revision" },
  {
    id: "description",
    title: "Description",
    validators: [{ type: "required" }],
  },
  {
    id: "quantityPer",
    title: "Quantity per",
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, decimalPlaces: 3 },
    ],
  },
  {
    id: "unitOfMeasure",
    title: "Unit of measure",
    editor: { type: "select", options: UNITS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: UNITS }],
  },
  {
    id: "lineType",
    title: "Line type",
    editor: { type: "select", options: LINE_TYPES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: LINE_TYPES }],
  },
  { id: "referenceDesignators", title: "Reference designators" },
  { id: "effectiveFrom", title: "Effective from", editor: { type: "date" } },
  { id: "effectiveTo", title: "Effective to", editor: { type: "date" } },
];</code></pre>
<p>Eleven fields, and <code>level</code> is one of them. It arrives, it is checked, and it is
gone before the rows reach your database. There is no <code>parentPartNumber</code> column
in this schema, because no header in any file can fill it.</p>
<h2 id="the-file-a-plm-system-prints">The file a PLM system prints</h2>
<p>Wrenfield Instruments makes flow instruments and is moving onto your platform.
The file is the indented explosion of three products, printed by the system they
are leaving.</p>
<p><code>wrenfield-bom.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Level</td><td class="sheet__cell">Find</td><td class="sheet__cell">Part Number</td><td class="sheet__cell">Rev</td><td class="sheet__cell">Description</td><td class="sheet__cell">Qty</td><td class="sheet__cell">UOM</td><td class="sheet__cell">Type</td><td class="sheet__cell">Ref Des</td><td class="sheet__cell">Eff From</td><td class="sheet__cell">Eff To</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">1</td><td class="sheet__cell"></td><td class="sheet__cell">WF-1000</td><td class="sheet__cell">B</td><td class="sheet__cell">Kestrel 400 Flow Meter</td><td class="sheet__cell">1</td><td class="sheet__cell">EA</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">07/17/2024</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">2</td><td class="sheet__cell">10</td><td class="sheet__cell">  2101-790</td><td class="sheet__cell">02</td><td class="sheet__cell">Bushing Bronze 10mm</td><td class="sheet__cell">2</td><td class="sheet__cell">ea</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">2023-11-15</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">2</td><td class="sheet__cell">20</td><td class="sheet__cell">  SA-1044</td><td class="sheet__cell">02</td><td class="sheet__cell">Rotor Assembly</td><td class="sheet__cell">1</td><td class="sheet__cell"></td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">2026-02-06</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">3</td><td class="sheet__cell">10</td><td class="sheet__cell">    0712-330</td><td class="sheet__cell">B</td><td class="sheet__cell">O-Ring 24mm Viton</td><td class="sheet__cell">1</td><td class="sheet__cell">PC</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">3</td><td class="sheet__cell">20</td><td class="sheet__cell">    SA-1046</td><td class="sheet__cell">C</td><td class="sheet__cell">Valve Block</td><td class="sheet__cell">1</td><td class="sheet__cell">ea</td><td class="sheet__cell">item</td><td class="sheet__cell"></td><td class="sheet__cell">2025-06-25</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">4</td><td class="sheet__cell">10</td><td class="sheet__cell">      2108-880</td><td class="sheet__cell">D</td><td class="sheet__cell">Foam Tape 12mm</td><td class="sheet__cell">4.296</td><td class="sheet__cell">MM</td><td class="sheet__cell">Pegged</td><td class="sheet__cell"></td><td class="sheet__cell">2026-02-20</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">4</td><td class="sheet__cell">20</td><td class="sheet__cell">      SA-1047</td><td class="sheet__cell">02</td><td class="sheet__cell">Filter Cartridge</td><td class="sheet__cell">4</td><td class="sheet__cell">PCS</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">08/06/2026</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">5</td><td class="sheet__cell">10</td><td class="sheet__cell">        2115-917</td><td class="sheet__cell">01</td><td class="sheet__cell">Grommet 8mm</td><td class="sheet__cell">12</td><td class="sheet__cell">EA</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">2023-06-13</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">5</td><td class="sheet__cell">20</td><td class="sheet__cell">        2117-335</td><td class="sheet__cell">-</td><td class="sheet__cell">Epoxy Adhesive 2-Part</td><td class="sheet__cell">0</td><td class="sheet__cell"></td><td class="sheet__cell">Pegged supply</td><td class="sheet__cell"></td><td class="sheet__cell">2026-02-25</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">5</td><td class="sheet__cell">30</td><td class="sheet__cell">        EC-51008</td><td class="sheet__cell"></td><td class="sheet__cell">Capacitor 100nF 50V</td><td class="sheet__cell">4</td><td class="sheet__cell">Ea</td><td class="sheet__cell">Item</td><td class="sheet__cell">R1, R2, R3, R4</td><td class="sheet__cell">2024-07-21</td><td class="sheet__cell">2025-07-21</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="11"><span class="sheet__break-text">262 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">274</th><td class="sheet__cell">1</td><td class="sheet__cell"></td><td class="sheet__cell">WF-2200</td><td class="sheet__cell">A</td><td class="sheet__cell">Kestrel 250 Flow Meter</td><td class="sheet__cell">1</td><td class="sheet__cell">EA</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">03/04/2025</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="11"><span class="sheet__break-text">286 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">561</th><td class="sheet__cell">1</td><td class="sheet__cell"></td><td class="sheet__cell">WF-3100</td><td class="sheet__cell">C</td><td class="sheet__cell">Kestrel 600 Flow Meter</td><td class="sheet__cell">1</td><td class="sheet__cell">EA</td><td class="sheet__cell">Item</td><td class="sheet__cell"></td><td class="sheet__cell">2025-09-08</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="11"><span class="sheet__break-text">268 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">830</th><td class="sheet__cell">5</td><td class="sheet__cell">40</td><td class="sheet__cell">        2119-402</td><td class="sheet__cell">01</td><td class="sheet__cell">Washer M6 Nylon</td><td class="sheet__cell">8</td><td class="sheet__cell">EA</td><td class="sheet__cell">Purchased</td><td class="sheet__cell"></td><td class="sheet__cell">2024-10-02</td><td class="sheet__cell"></td></tr></tbody></table>
<p>Depth notation, two spaces of indentation per level, carried inside the
<code>Part Number</code> cell. That is what a printed indented BOM looks like on paper, and
the export writes the paper.</p>
<p>The <code>Level</code> column runs 1 on 3 rows, 2 on 38, 3 on 150, 4 on 391 and 5 on 247.
Part numbers come in four house styles, <code>WF-</code> for products, <code>SA-</code> for
sub-assemblies, <code>EC-</code> for electronics, and four digits, a dash and three digits
for purchased parts.</p>
<h2 id="the-indentation-that-is-not-data">The indentation that is not data</h2>
<p>Every parser in the SDK trims the cell before anything else sees it.
<code>cleanCell</code> strips zero-width characters, turns a non-breaking space and a
narrow non-breaking space into an ordinary space, normalises to NFC, and trims
both ends. It runs on every cell of a CSV, an XLSX, a JSON file and an XML file,
and on text pasted into the grid.</p>
<p>826 of the 829 <code>Part Number</code> cells in this file begin with a space. After the
parse, <strong>none of them do</strong>.</p>
<p>That is the right answer for a part number. <code>SA-1046</code> is the same part whether
it is printed at the second level or the fourth, and a leading space is a
property of the printout. The picture of the tree was never in that cell in a
form your database could keep.</p>
<p>So <code>Level</code> is the only carrier left, and the row order underneath it.</p>
<h2 id="the-headers-this-export-abbreviates">The headers this export abbreviates</h2>
<p>Seven of the eleven headers reach a field with nothing configured.</p>
<div class="blog-table blog-table--fixed blog-table--bom-headers"><table>
<thead>
<tr>
<th>Header</th>
<th>Column it reaches</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Level</code></td>
<td><code>level</code></td>
<td>100</td>
</tr>
<tr>
<td><code>Description</code></td>
<td><code>description</code></td>
<td>100</td>
</tr>
<tr>
<td><code>Find</code></td>
<td><code>findNumber</code></td>
<td>80</td>
</tr>
<tr>
<td><code>Part Number</code></td>
<td><code>childPartNumber</code></td>
<td>80</td>
</tr>
<tr>
<td><code>Type</code></td>
<td><code>lineType</code></td>
<td>80</td>
</tr>
<tr>
<td><code>Eff From</code></td>
<td><code>effectiveFrom</code></td>
<td>70</td>
</tr>
<tr>
<td><code>Eff To</code></td>
<td><code>effectiveTo</code></td>
<td>70</td>
</tr>
</tbody>
</table></div>
<p><code>Rev</code>, <code>Qty</code>, <code>UOM</code> and <code>Ref Des</code> reach nothing at all. Each of them is a
shortening a manufacturing engineer reads without pausing, and a shortening
shares no word with the field it stands for. <code>Part Number</code> also draws
<code>findNumber</code> as a runner-up at 70, settled by the assignment that gives
<code>findNumber</code> to <code>Find</code>.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    childPartNumber: ["Part Number", "Part No.", "ChildNumber", "Component"],
    findNumber: ["Find", "Find No.", "Item No."],
    revision: ["Rev", "Revision"],
    quantityPer: ["Qty", "Qty Per", "Per", "Quantity Per Assembly"],
    unitOfMeasure: ["UOM", "Unit", "U/M"],
    referenceDesignators: ["Ref Des", "RefDes", "Reference Designator"],
  },
  values: {
    Item: ["Purchased", "Buy", "Standard", "Make", "Normal"],
    Phantom: ["Ph", "Phantom Item", "Phantom Assembly"],
    Vendor: ["Subcontract", "Subcontractor", "Outsourced"],
    "Pegged supply": ["Pegged", "Subproduction"],
    EA: ["Each", "PC", "PCS", "Piece", "Pieces"],
  },
};</code></pre>
<p>Every string on the left of that list is published by somebody. BuyPLM prints
<code>Find</code> and <code>RefDes</code> as header names in its own BOM import file, MRPeasy prints
<code>Part No.</code>, <code>Quantity</code> and <code>Revision</code>, and BuyPLM prints <code>Per</code> for a quantity
per assembly. The alias table is the industry's vocabulary written down once, so
the next customer's export lands on the same table.</p>
<p>With those six rows in place all eleven headers map.</p>
<h2 id="item-phantom-pegged-supply-vendor">Item, Phantom, Pegged supply, Vendor</h2>
<p>Microsoft publishes four line types for a BOM line, and each one changes what
the manufacturing run does. <strong>Item</strong> is an ordinary component. <strong>Phantom</strong>
explodes "any lower-level BOM items that are contained on the BOM line".
<strong>Pegged supply</strong> raises a subproduction, an event kanban or a direct purchase
order for that line. <strong>Vendor</strong> is the subcontracted case.</p>
<p>Those four are the option list your schema declares. The <code>Type</code> column in this
file holds 17 different strings and a blank.</p>
<p><code>Item</code> on 261 rows, <code>Purchased</code> on 74, <code>Buy</code> on 69, <code>item</code> on 65 and blank on
58. Then <code>Subcontract</code> on 51, <code>Pegged supply</code> on 44, <code>Vendor</code> on 41, <code>Standard</code>
on 38, <code>Make</code> on 36, <code>vendor</code> on 29 and <code>Pegged</code> on 22. The tail is <code>ITEM</code> on
14, <code>Phantom</code> on 12, <code>phantom</code> on 7, <code>Ph</code> on 4, <code>Phantom Item</code> on 2 and
<code>PHANTOM</code> on 2.</p>
<p>Ten of the seventeen reach the right option unaided, because they are an option
written in another case or with a word dropped. <code>Purchased</code>, <code>Buy</code>, <code>Standard</code>,
<code>Make</code>, <code>Subcontract</code> and <code>Ph</code> reach nothing, and they cover 272 rows. Somebody
has to say that a subcontracted line and a <code>Vendor</code> line are one thing, and no
matcher can say it for them.</p>
<p><strong>A value that reaches no option arrives empty, and the <code>oneOf</code> rule passes it.</strong>
An empty cell is not a wrong value, so the rule has nothing to report. Left
alone, 330 rows carry no line type at all, which is the 58 blanks in the file
plus the 272 that matched nothing. <code>{ type: "required" }</code> on the column is what
turns that silence into a flag.</p>
<p>The seventeenth lands on the wrong option. <code>Phantom Item</code> matches <code>Item</code> before
it matches <code>Phantom</code>, and it is written on 2 rows. The <code>values</code> half of
the alias list settles all seventeen and puts those two where they belong. After
it, 58 line-type cells stay empty, and 58 is exactly the number of blanks the
file was written with.</p>
<p>The unit column behaves the same way. <code>Each</code>, <code>PC</code>, <code>PCS</code>, <code>pcs</code> and <code>Ea</code> are
five spellings of one unit, and one alias row folds them onto <code>EA</code>.</p>
<h2 id="the-quantity-that-is-not-a-number">The quantity that is not a number</h2>
<p>The <code>Qty</code> column holds 650 plain integers and 49 zeros. 109 decimals are
written with a dot and 10 with a comma. Three cells are blank, and 8 read
<code>AR</code>.</p>
<p><code>AR</code> means as required. First Resonance publishes a quantity "including zero for
consumables/as-required materials", so both the word and the zero are legal in
this trade. A number column cannot hold the word, and the 8 cells come through
flagged <code>Invalid number</code>. The 49 zeros come through clean, which is why the rule
on this column reads <code>min: 0</code>. A <code>min: 1</code> would flag 49 correct lines.</p>
<p>Ten cells carry a comma. Updog settles a number format per
file, and this file's quantity column votes United States on the strength of its
109 dot decimals. Each comma cell then landed somewhere.</p>
<div class="blog-table blog-table--fixed blog-table--bom-quantities"><table>
<thead>
<tr>
<th>Row</th>
<th>In the file</th>
<th>In the store</th>
<th>Flagged</th>
</tr>
</thead>
<tbody>
<tr>
<td>22</td>
<td><code>1,095</code></td>
<td><code>1095</code></td>
<td>no</td>
</tr>
<tr>
<td>75</td>
<td><code>1,312</code></td>
<td><code>1312</code></td>
<td>no</td>
</tr>
<tr>
<td>148</td>
<td><code>3,556</code></td>
<td><code>3556</code></td>
<td>no</td>
</tr>
<tr>
<td>180</td>
<td><code>4,082</code></td>
<td><code>4082</code></td>
<td>no</td>
</tr>
<tr>
<td>473</td>
<td><code>2,323</code></td>
<td><code>2323</code></td>
<td>no</td>
</tr>
<tr>
<td>685</td>
<td><code>2,135</code></td>
<td><code>2135</code></td>
<td>no</td>
</tr>
<tr>
<td>188</td>
<td><code>0,503</code></td>
<td><code>0,503</code></td>
<td>yes</td>
</tr>
<tr>
<td>305</td>
<td><code>0,92</code></td>
<td><code>0,92</code></td>
<td>yes</td>
</tr>
<tr>
<td>353</td>
<td><code>3,27</code></td>
<td><code>3,27</code></td>
<td>yes</td>
</tr>
<tr>
<td>807</td>
<td><code>2,15</code></td>
<td><code>2,15</code></td>
<td>yes</td>
</tr>
</tbody>
</table></div>
<p>A comma followed by three digits is legal grouping in a United States file, so
six quantities became whole numbers a thousand times larger and nothing was
flagged. A group of one or two digits cannot be grouping, and neither can a
group that starts from a zero. The other four stayed exactly as they were
written, and the person sees them.</p>
<p>That is the honest ceiling on a per-file decision. Four cells announce
themselves and six do not.
<a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> walks the failures
any file can produce. A quantity that reads as a number and holds the wrong
number is the one nobody goes looking for.</p>
<h2 id="the-row-that-lost-its-parent">The row that lost its parent</h2>
<p>One row in 829 claims a level with no row above it to hang on. Row 251,
<code>SA-1117</code>, is written as level 5, and the row before it is written as level 3. A
hand edit somewhere between the export and the email took the level 4 line out.</p>
<p><strong>No rule you can put on a cell will notice it.</strong> A <code>function</code> validator is
called with the value and the row it sits in, and nothing else.
<code>dependentFields</code> widens that to another column of the same row. One line here
needs it, row 125, <code>EC-51164</code>, valid from <code>2026-05-14</code> until <code>2024-03-01</code>. The
schema above declares no rule that reads two columns, so that row comes through
clean. A rule reaches across a row. It never reaches up a row.</p>
<p>Position in the file is not a property of a cell. The check for it belongs to
the code that receives the finished import.</p>
<h2 id="a-part-number-written-thirty-five-times">A part number written thirty-five times</h2>
<p>702 distinct part numbers cover 829 rows, so 127 rows carry a part number that
already appeared. Four fasteners account for all 127. <code>0461-018</code> is written 36
times, <code>0453-204</code> 35 times, <code>0712-330</code> 34 times, and <code>0453-119</code> 26 times. Every
other part in this file is written once.</p>
<p>A <code>{ type: "unique" }</code> rule on the part number would flag all 127, and every one
of those rows is correct. The same bronze bushing goes into thirty-five
different assemblies, and saying so is what a bill of materials is for.
<code>primaryKey</code> on that column is wrong here for the same reason.</p>
<p>The pair is closer. Rebuilt from the file, 825 child rows produce 803 distinct
parent-child pairs, so 22 rows repeat a pair that is already there. Two lines on
one assembly for the same part is ordinary, and the find number is what tells
them apart. Parent, child and find number together are distinct on all 825 rows
in this file.</p>
<h2 id="nothing-here-knows-what-a-sub-assembly-is">Nothing here knows what a sub-assembly is</h2>
<p>Updog ships no BOM template, no part number format, no line type list, and no
connector to any manufacturing system. The eleven columns, the four options, the
alias tables, the rules and the walk below are all code you write.</p>
<p>If the parts list is yours and the destination is yours, this is the wrong tool.
The system you already run has an import screen built for its own tables, and it
knows what a revision means. Updog Importer is for the file
that arrives from somebody else, in their vocabulary, on a day you did not pick.</p>
<p>Updog Importer reads CSV, TSV, XLSX, XLS, XLSB, ODS, JSON and XML. A BOM that
survives only as a PDF goes through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a>
and arrives as ordinary rows. One million rows is a practical ceiling rather
than an unlimited claim, and this file is 829.</p>
<h2 id="from-levels-to-parents">From levels to parents</h2>
<p>The walk is one pass over the rows in the order they arrived, keeping the last
part number seen at each level.</p>
<pre><code class="language-ts">type BomLine = Record&#x3C;string, unknown>;

export const withParents = (rows: BomLine[]) => {
  const partAtLevel: string[] = [];

  return rows.map((row) => {
    const level = Number(row.level);
    partAtLevel[level] = String(row.childPartNumber);
    partAtLevel.length = level + 1;

    return {
      parentPartNumber: level === 1 ? null : (partAtLevel[level - 1] ?? null),
      childPartNumber: String(row.childPartNumber),
      findNumber: row.findNumber,
      revision: row.revision,
      quantityPer: Number(row.quantityPer),
      unitOfMeasure: row.unitOfMeasure,
      lineType: row.lineType,
    };
  });
};</code></pre>
<p>Setting <code>partAtLevel.length</code> after the assignment is the whole trick. A row at
level 3 drops everything the array held at level 4 and below, so a part number
from a branch that closed cannot become a parent in the next branch. A row whose
level jumps by more than one finds nothing at the level above it and reports
<code>null</code>. Row 251 reaches your handler with an empty parent, which is the one
answer a person can act on.</p>
<pre><code class="language-csv"># the eight rows as the file writes them
Level,Find,Part Number,Rev,Qty,UOM,Type
1,,WF-1000,B,1,EA,Item
2,10,  2101-790,02,2,ea,Item
2,20,  SA-1044,02,1,,Item
3,10,    0712-330,B,1,PC,
3,20,    SA-1046,C,1,ea,item
4,10,      2108-880,D,4.296,MM,Pegged
4,20,      SA-1047,02,4,PCS,Item
5,10,        2115-917,01,12,EA,Item

# the same eight rows as the handler posts them
parentPartNumber,childPartNumber,findNumber,revision,quantityPer,unitOfMeasure,lineType
,WF-1000,,B,1,EA,Item
WF-1000,2101-790,10,02,2,EA,Item
WF-1000,SA-1044,20,02,1,,Item
SA-1044,0712-330,10,B,1,EA,
SA-1044,SA-1046,20,C,1,EA,Item
SA-1046,2108-880,10,D,4.296,MM,Pegged supply
SA-1046,SA-1047,20,02,4,EA,Item
SA-1047,2115-917,10,01,12,EA,Item</code></pre>
<p><code>Level</code> is gone, <code>parentPartNumber</code> is filled, the indentation never made it
past the parser, and the spellings settled on the value step. Eight rows of a
printed tree became eight rows of a table.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  onComplete={async (result) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row);

    const lines = withParents(rows);
    const orphans = lines.filter(
      (line, n) => !line.parentPartNumber &#x26;&#x26; Number(rows[n].level) > 1,
    );

    await postBomLines({ product: "WF-1000", lines, orphans });
  }}
/></code></pre>
<p>All of that runs where the person dropped the file, and the rows travel from
their browser to your endpoint under your own agreement.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
follows a file down each of the two routes.</p>
<h2 id="the-list-the-engineer-works-down">The list the engineer works down</h2>
<p>829 rows and eleven columns make 9,119 cells, and 15 of them come through
flagged. Twelve are quantities the importer could not reduce to a number, 8 of
them written <code>AR</code> and 4 written with a decimal comma. Three are quantities the
file left blank. One row has no parent, and it reaches your handler in the
<code>orphans</code> list rather than in the table.</p>
<p>Sixteen items go to the person who knows the product, and every one of them is
legible. The description sits beside every flagged quantity. The level 3 line
above <code>SA-1117</code> names the assembly the missing line belonged to.</p>
<p>Then 803 parent-child pairs land in a table your platform can explode, and a
tree printed for a person to read becomes rows.</p>]]></content:encoded></item>
<item><title>CSV Import for Procurement and Vendor Management Software</title><link>https://updog.tech/blog/csv-import-for-procurement-vendor-management-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-procurement-vendor-management-software/</guid><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><description>Every customer configures its own supplier fields, so the column list is not knowable in advance. How to build the schema at runtime and still match the file.</description><content:encoded><![CDATA[<p>A supplier list grows one buyer at a time. Somebody adds a vendor for a single
purchase order, somebody else adds payment terms, and finance adds a tax ID a
year later. By the time that list leaves the old system it holds every field
anyone there ever needed.</p>
<p>Payment terms and tax IDs are the fields your platform expects. The rest is
whatever that one company decided to track, and it reaches you as a column
header you have never seen.</p>
<p>Six of the eighteen headers in the file below name fields this platform never
shipped. Three of those, <code>Risk Tier</code>, <code>Insurance Expiry</code> and <code>Plants Served</code>,
exist nowhere outside this one customer.</p>
<p>A procurement platform lets its customers decide what a supplier is. Coupa
writes the consequence into its own integration documentation. "For CSV Import,
Prompt field value is used as column header." A Prompt is a string a buyer typed
into an admin screen, and it becomes a column header in the export. Your code
cannot carry that string, because your code shipped before the customer existed.</p>
<p>So the field list arrives over the wire and the schema is built at mount.
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">Customer data onboarding</a> is the work
of turning a customer's supplier list into your own records. On a procurement
platform the target of that work moves with the tenant.</p>
<p>The file below runs 3,120 rows over 18 columns, 545 KB of <code>.csv</code>. Every figure
in this article was read off imports of that one file.</p>
<h2 id="the-supplier-list-an-erp-hands-over">The supplier list an ERP hands over</h2>
<p>A customer moving onto your platform exports the suppliers they already hold.
The column names come out of the system they are leaving, so a Coupa supplier
information export carries <code>Supplier Number</code>, <code>Preferred Currency</code>,
<code>Invoice Matching Level</code>, <code>Minority Indicator</code> and <code>Minority Type</code>. A NetSuite
vendor list carries different ones. Seven rows out of this file, in the spelling
the export used.</p>
<p><code>supplier-export.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th><th class="sheet__column" scope="col">N</th><th class="sheet__column" scope="col">O</th><th class="sheet__column" scope="col">P</th><th class="sheet__column" scope="col">Q</th><th class="sheet__column" scope="col">R</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Supplier Number</td><td class="sheet__cell">Company Name</td><td class="sheet__cell">Display Name</td><td class="sheet__cell">SIM Status</td><td class="sheet__cell">Organization Type</td><td class="sheet__cell">Federal Tax ID</td><td class="sheet__cell">DUNS</td><td class="sheet__cell">Country of Operation</td><td class="sheet__cell">Preferred Currency</td><td class="sheet__cell">Payment Term</td><td class="sheet__cell">Invoice Matching Level</td><td class="sheet__cell">Minority Indicator</td><td class="sheet__cell">Minority Type</td><td class="sheet__cell">Primary Contact Email</td><td class="sheet__cell">Pay Group</td><td class="sheet__cell">Risk Tier</td><td class="sheet__cell">Insurance Expiry</td><td class="sheet__cell">Plants Served</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">V-100424</td><td class="sheet__cell">Quarrington Springs PLC</td><td class="sheet__cell">Quarrington Springs</td><td class="sheet__cell">Pending</td><td class="sheet__cell">Corporation</td><td class="sheet__cell">355869704</td><td class="sheet__cell">97825272</td><td class="sheet__cell">GB</td><td class="sheet__cell">usd</td><td class="sheet__cell">2/10 Net 30</td><td class="sheet__cell">3-way</td><td class="sheet__cell">TRUE</td><td class="sheet__cell">SDVOSB</td><td class="sheet__cell">ap@quarringtonspr.com; quarrington.springs@quarringtonspr.com</td><td class="sheet__cell"></td><td class="sheet__cell">2</td><td class="sheet__cell">03/26/2026</td><td class="sheet__cell">PLT-08;PLT-04;PLT-02</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">V-100862</td><td class="sheet__cell">Lansdowne Forgings Ltd</td><td class="sheet__cell"></td><td class="sheet__cell">Draft</td><td class="sheet__cell">LLC</td><td class="sheet__cell">66-4988758</td><td class="sheet__cell">902636648</td><td class="sheet__cell">USA</td><td class="sheet__cell">USD</td><td class="sheet__cell">Net 30</td><td class="sheet__cell">3-way</td><td class="sheet__cell">False</td><td class="sheet__cell"></td><td class="sheet__cell">ap@lansdownefor.com; lansdowne.forgings@lansdownefor.com</td><td class="sheet__cell"></td><td class="sheet__cell">High</td><td class="sheet__cell">2026-11-25</td><td class="sheet__cell">PLT-05 / PLT-12</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">V-100031</td><td class="sheet__cell">Ashworth Foundry Corp</td><td class="sheet__cell">Ashworth Foundry</td><td class="sheet__cell">Active</td><td class="sheet__cell">S-Corp</td><td class="sheet__cell">38-3386951</td><td class="sheet__cell">703093457</td><td class="sheet__cell">DE</td><td class="sheet__cell">USD</td><td class="sheet__cell">Net 30</td><td class="sheet__cell">3-way</td><td class="sheet__cell">1</td><td class="sheet__cell">WBE</td><td class="sheet__cell">ashworth.foundry@ashworthfou.com</td><td class="sheet__cell">CA-AP</td><td class="sheet__cell">1</td><td class="sheet__cell">2026-12-10</td><td class="sheet__cell">PLT-11</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell"></td><td class="sheet__cell">Draycott Seals Inc.</td><td class="sheet__cell">Draycott Seals</td><td class="sheet__cell">A</td><td class="sheet__cell">Limited Liability Company</td><td class="sheet__cell">99-6577700</td><td class="sheet__cell">908805639</td><td class="sheet__cell">DE</td><td class="sheet__cell">USD</td><td class="sheet__cell">Net 90</td><td class="sheet__cell">3-way-direct</td><td class="sheet__cell">YES</td><td class="sheet__cell">DBE</td><td class="sheet__cell">draycott.seals@draycottsea.com</td><td class="sheet__cell">EU-AP</td><td class="sheet__cell">Low</td><td class="sheet__cell"></td><td class="sheet__cell">PLT-12;PLT-05</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">V-100022</td><td class="sheet__cell">Saltburn Gasket GmbH</td><td class="sheet__cell"></td><td class="sheet__cell">A</td><td class="sheet__cell"></td><td class="sheet__cell">698433731</td><td class="sheet__cell">258080784</td><td class="sheet__cell">US</td><td class="sheet__cell">USD</td><td class="sheet__cell">Net 30</td><td class="sheet__cell">3-way</td><td class="sheet__cell">False</td><td class="sheet__cell"></td><td class="sheet__cell">saltburn.gasket.saltburngas.com</td><td class="sheet__cell">MX-AP</td><td class="sheet__cell">3</td><td class="sheet__cell">09/27/2028</td><td class="sheet__cell">PLT-02</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">V-100023</td><td class="sheet__cell">Ingleby Forgings Inc</td><td class="sheet__cell"></td><td class="sheet__cell">Active</td><td class="sheet__cell">Limited Liability Company</td><td class="sheet__cell">242799638</td><td class="sheet__cell">15-184-8574</td><td class="sheet__cell">CA</td><td class="sheet__cell"></td><td class="sheet__cell">Net 45</td><td class="sheet__cell">2 way</td><td class="sheet__cell">F</td><td class="sheet__cell"></td><td class="sheet__cell">ingleby.forgings.inglebyfor.com</td><td class="sheet__cell">US-AP</td><td class="sheet__cell">Low</td><td class="sheet__cell">2026-06-05</td><td class="sheet__cell">PLT-05, PLT-02</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="18"><span class="sheet__break-text">3113 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3121</th><td class="sheet__cell">V-103118</td><td class="sheet__cell">Wendover Bearings Ltd</td><td class="sheet__cell">Wendover Bearings</td><td class="sheet__cell">Active</td><td class="sheet__cell">Corporation</td><td class="sheet__cell">84-2210567</td><td class="sheet__cell">551908364</td><td class="sheet__cell">GB</td><td class="sheet__cell">USD</td><td class="sheet__cell">Net 30</td><td class="sheet__cell">3-way</td><td class="sheet__cell">False</td><td class="sheet__cell"></td><td class="sheet__cell">ap@wendoverbea.com</td><td class="sheet__cell">EU-AP</td><td class="sheet__cell">Low</td><td class="sheet__cell">2027-02-19</td><td class="sheet__cell">PLT-08</td></tr></tbody></table>
<p><code>V-100424</code> has a <code>DUNS</code> of eight digits. <code>V-100862</code> writes two plant codes with
a slash between them. The row for Draycott Seals arrives with no supplier number
at all. And two addresses share the <code>Primary Contact Email</code> cell, which is how
accounts payable keeps a mailbox and a person in one field.</p>
<p>The file names 3,120 suppliers and 2,857 tax numbers. Updog reads it, matches it
and checks it in the tab the person opened, so your endpoint is the first
machine to receive a row. Where that work runs is a design decision, and
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">client-side and server-side import</a>
walks both.</p>
<h2 id="the-fields-your-customer-added-themselves">The fields your customer added themselves</h2>
<p>Twelve fields are yours and ship with the product. Supplier number, legal name,
display name, status, organization type, tax id, D-U-N-S, country, currency,
payment terms, invoice matching level and contact email. Every customer gets
those.</p>
<p>The rest comes back from your own configuration endpoint.</p>
<pre><code class="language-ts">export type SupplierField =
  | { kind: "text"; id: string; label: string; headerAliases?: string[] }
  | { kind: "date"; id: string; label: string; headerAliases?: string[] }
  | {
      kind: "choice";
      id: string;
      label: string;
      options: string[];
      headerAliases?: string[];
      valueAliases?: Record&#x3C;string, string[]>;
    }
  | {
      kind: "multi";
      id: string;
      label: string;
      options: string[];
      separator?: string;
      headerAliases?: string[];
    }
  | {
      kind: "boolean";
      id: string;
      label: string;
      headerAliases?: string[];
      valueAliases?: Record&#x3C;string, string[]>;
    };

// What GET /tenants/:id/supplier-fields answers for one customer.
export const fields: SupplierField[] = [
  {
    kind: "boolean",
    id: "diverseOwned",
    label: "Diverse Owned",
    headerAliases: ["minority indicator", "diverse supplier"],
    valueAliases: { Yes: ["t", "1"], No: ["f", "0"] },
  },
  {
    kind: "choice",
    id: "diversityCategory",
    label: "Diversity Category",
    options: ["MBE", "WBE", "WOSB", "VOSB", "SDVOSB", "HUBZone", "DBE"],
    headerAliases: ["minority type", "certification"],
  },
  {
    kind: "choice",
    id: "payGroup",
    label: "Pay Group",
    options: ["US-AP", "EU-AP", "CA-AP", "MX-AP", "UK-AP"],
  },
  {
    kind: "choice",
    id: "riskTier",
    label: "Risk Tier",
    options: ["1", "2", "3"],
    valueAliases: { "1": ["low"], "2": ["medium"], "3": ["high"] },
  },
  { kind: "date", id: "insuranceExpiry", label: "Insurance Expiry" },
  {
    kind: "multi",
    id: "plantsServed",
    label: "Plants Served",
    options: ["PLT-01", "PLT-02", "PLT-03", "PLT-04", "PLT-05", "PLT-06",
      "PLT-07", "PLT-08", "PLT-09", "PLT-10", "PLT-11", "PLT-12"],
    separator: " / ",
  },
];</code></pre>
<p>That array is data your admin screen already writes. It holds the label the
customer chose, the options they set, and two things worth adding while you are
there. <code>headerAliases</code> records what the field is called in the systems this
customer exports from. <code>separator</code> records how their files write a list in one
cell. Both answers exist inside the customer and nowhere in your repository.</p>
<h2 id="a-schema-assembled-at-mount">A schema assembled at mount</h2>
<p><code>columns</code> takes an array of plain objects, so a schema is data and data can be
built. One function turns a configured field into a column.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { core } from "./core";
import type { SupplierField } from "./fields";

const toColumn = (field: SupplierField): DataEditorColumn => {
  switch (field.kind) {
    case "date":
      return { id: field.id, title: field.label, editor: { type: "date" } };
    case "boolean":
      return {
        id: field.id,
        title: field.label,
        editor: { type: "select", options: ["Yes", "No"], enableCustomValue: false },
      };
    case "choice":
      return {
        id: field.id,
        title: field.label,
        editor: { type: "select", options: field.options, enableCustomValue: false },
        validators: [{ type: "oneOf", values: field.options }],
      };
    case "multi":
      return {
        id: field.id,
        title: field.label,
        editor: {
          type: "multiselect",
          options: field.options,
          delimiter: field.separator,
          enableCustomValue: false,
        },
      };
    default:
      return { id: field.id, title: field.label };
  }
};

export const buildColumns = (fields: SupplierField[]): DataEditorColumn[] => {
  return [...core, ...fields.map(toColumn)];
};</code></pre>
<p>A <code>choice</code> field becomes a select with <code>enableCustomValue: false</code>, which closes
the list so nobody invents an eighth diversity certification during an import. A
<code>multi</code> field becomes a multiselect over the same options. A <code>boolean</code> becomes a
two-option select, because seventeen written forms of yes and no have to land on
one of two strings, and the value-matching step is where they land.</p>
<p>Nothing in that function is procurement. It is a switch over your own field
kinds, and it runs before the importer opens.</p>
<h2 id="diverse-owned-against-minority-indicator">Diverse Owned against Minority Indicator</h2>
<p>Sixteen of the eighteen headers reach a column before an alias is applied. The
two that miss are <code>Minority Indicator</code> and <code>Minority Type</code>, against columns titled
<code>Diverse Owned</code> and <code>Diversity Category</code>.</p>
<p>Neither name is wrong. The file speaks the vocabulary of the system that wrote
it, and the schema speaks the vocabulary the buyer typed into your admin screen.
No matcher bridges those on its own, because the two strings share no word.</p>
<p>The bridge is the same array that produced the columns.</p>
<pre><code class="language-ts">export const buildSynonyms = (fields: SupplierField[]) => {
  const columns: Record&#x3C;string, string[]> = { ...coreColumnAliases };
  const values: Record&#x3C;string, string[]> = { ...coreValueAliases };

  for (const field of fields) {
    if (field.headerAliases) {
      columns[field.id] = field.headerAliases;
    }
    if ("valueAliases" in field &#x26;&#x26; field.valueAliases) {
      for (const [option, aliases] of Object.entries(field.valueAliases)) {
        values[option] = aliases;
      }
    }
  }

  return { columns, values };
};</code></pre>
<p>With that table in place all eighteen headers reach a column. The gain is not
limited to the configured fields. <code>Canada</code>, <code>Germany</code>, <code>Deutschland</code>, <code>Mexico</code>,
<code>United Kingdom</code> and <code>United States</code> reach nothing against a five-code country
list on their own, and the core alias table lands all six. <code>U.S.</code> and <code>usd</code>
already land without help, because an abbreviation sits closer to a code than a
spelled-out name does.</p>
<p>An unmatched value does not arrive as itself. A select value survives the
value-matching step only when it is mapped, so the cell lands empty. Without the
alias table 913 country cells empty out that way, and 683 risk tiers, 571
statuses, 395 organization types and 119 currencies go with them. No rule fires
on any of them. With the table in place, country, risk tier, organization type
and currency all come back to the count of cells the file itself left blank.</p>
<h2 id="every-way-a-system-writes-yes">Every way a system writes yes</h2>
<p><code>Minority Indicator</code> arrives as seventeen distinct strings, and 215 rows leave
it empty. NetSuite publishes
what its own vendor import accepts for a boolean, and the list is
"True, true, TRUE, T, yes, Yes, YES". A file written to that spec carries every
one of them.</p>
<p>Updog holds a built-in value table covering common categorical vocabularies,
and it lands 13 of the 17 on <code>Yes</code> or <code>No</code> with no configuration. Everything
spelled out arrives. <code>true</code>, <code>True</code>, <code>TRUE</code>, <code>Y</code>, <code>yes</code>, <code>Yes</code>, <code>YES</code>, <code>false</code>,
<code>False</code>, <code>FALSE</code>, <code>N</code>, <code>no</code> and <code>No</code> all reach an option.</p>
<p>The four it leaves are <code>T</code>, <code>F</code>, <code>0</code> and <code>1</code>, and 705 rows of this file sit on
those four strings. They go in the <code>valueAliases</code> of the configured field, next
to the label, where the customer's own answer already lives.</p>
<p><code>Pending</code> and <code>On Hold</code> in the status column reach nothing either, and that
result is correct. Neither is a spelling of <code>active</code>, <code>inactive</code> or <code>draft</code>.
Only the buyer can say which one they meant, and the value-matching step is
where they say it.</p>
<h2 id="the-identifier-that-lost-a-digit">The identifier that lost a digit</h2>
<p>A D-U-N-S Number is nine digits. The digits carry no meaning, so about one
identifier in ten opens with a zero, and Excel drops that zero on the way in.
Dun &#x26; Bradstreet publishes the problem in its own help centre. "Leading zeros in
number fields such as zip code and D-U-N-S Number are not visible in Excel
unless you apply custom formatting."</p>
<p>In this file 219 rows carry eight digits where nine were written. Another 161
carry the number with dashes in it. A regex rule reports all 380.</p>
<div class="blog-table blog-table--fixed"><table>
<thead>
<tr>
<th>What arrives</th>
<th>Rows</th>
<th>What the rule does</th>
</tr>
</thead>
<tbody>
<tr>
<td>nine digits</td>
<td>2,431</td>
<td>passes</td>
</tr>
<tr>
<td>eight digits</td>
<td>219</td>
<td>flagged</td>
</tr>
<tr>
<td><code>15-184-8574</code></td>
<td>161</td>
<td>flagged</td>
</tr>
<tr>
<td>empty</td>
<td>309</td>
<td>passes</td>
</tr>
</tbody>
</table></div>
<p>The 309 empty cells are the part worth reading twice. A regex has nothing to
test against an empty string, so a supplier with no D-U-N-S at all travels
through in silence. Whether an
empty D-U-N-S blocks a supplier is a platform decision, and
<code>{ type: "required" }</code> beside the regex is where you write it down.</p>
<h2 id="a-term-your-option-list-does-not-hold">A term your option list does not hold</h2>
<p>Payment terms have to land on a list your system already holds. Coupa states it
as a rule for its supplier import, "Must match existing payment terms", and
NetSuite states the same thing the other way round. "You must create payment
terms prior to referencing them."</p>
<p>Thirteen distinct terms arrive against six options. Eleven of them land on their
own. <code>NET30</code>, <code>Net30</code>, <code>N30</code> and <code>30 days</code> all reach <code>Net 30</code>, which is right.
<code>COD</code> and <code>Immediate</code> reach nothing, and those are decisions for the buyer. 213
rows carry one of the two, and every one of them reaches the grid with an empty
payment term.</p>
<p>One auto-match lands and is wrong. <code>2/10 Net 30</code> reaches <code>Net 30</code> on 151 rows.
The term means two percent off for paying inside ten days, and the option list
holds no term that carries a discount. The value arrives looking settled, and
nothing in the wizard flags it.</p>
<p>The fix is the option list. A closed select and a <code>oneOf</code> rule keep a value
inside the set, and they cannot invent a set member that finance never created.
When a term matters to a customer, that customer configures it, which is the
same loop the rest of this schema runs on.</p>
<h2 id="the-separator-this-export-uses">The separator this export uses</h2>
<p><code>Plants Served</code> holds a list in one cell, and this file writes that list three
ways. 1,157 rows separate with a semicolon, 556 with a comma and a space, and
155 with a slash.</p>
<p>Updog detects the separator among comma, semicolon, pipe, newline and tab by
checking which one splits cells into tokens that resemble your options. It picks
the semicolon here, and it recovers the comma rows too, because every piece of
those splits into a known plant.</p>
<p>The slash rows are the ones to watch. A slash is no candidate, so
<code>PLT-05 / PLT-12</code> stays whole, fuzzy-matches to <code>PLT-05</code> and looks settled. 252
plant references disappear that way, and 146 strings reach the value-matching
step where twelve belong.</p>
<p>Declaring the separator takes the column to twelve exact values with nothing
lost, because the recovery rule still splits the semicolon and comma cells
underneath. That is what <code>separator: " / "</code> is doing in the configuration
object. The customer knows which system writes their files, and your code
does not.</p>
<h2 id="the-rows-that-stop-at-a-rule">The rows that stop at a rule</h2>
<p>Out of 3,120 rows, 840 carry something a rule caught.</p>
<div class="blog-table blog-table--fixed"><table>
<thead>
<tr>
<th>Message</th>
<th>Rows</th>
<th>What is in the cell</th>
</tr>
</thead>
<tbody>
<tr>
<td>Invalid email address</td>
<td>443</td>
<td>284 cells holding two addresses, 159 with no <code>@</code></td>
</tr>
<tr>
<td>DUNS must be 9 digits</td>
<td>380</td>
<td>219 short, 161 with dashes</td>
</tr>
<tr>
<td>Value must be unique</td>
<td>48</td>
<td>24 supplier numbers written on two rows each</td>
</tr>
<tr>
<td>This field is required</td>
<td>40</td>
<td>an empty supplier number</td>
</tr>
</tbody>
</table></div>
<p>The 24 repeated supplier numbers are the reason <code>primaryKey</code> names that column
and the schema puts <code>{ type: "unique" }</code> on it. Company names repeat as well,
486 of them, and a repeated legal name is ordinary. Two branches of one group
trade under one name and settle their invoices apart.</p>
<p>One column raised nothing. <code>Insurance Expiry</code> arrives with 1,876 dates in ISO
and 790 written <code>03/26/2026</code>, and every one of them parsed.</p>
<p>A rule fires on what arrived. The cells that never arrived are the other half of
the list. 484 rows reach the grid with no status, where the file left 133 blank.
The 351 in between held <code>Pending</code> or <code>On Hold</code>, and the value-matching step
dropped both because neither maps to an option. Payment terms behave the same
way, 434 empty against 221 blank in the file.</p>
<p>An empty cell carries no error beside it. <code>{ type: "required" }</code> on the columns
a supplier record cannot go without is what turns that silence into one of the
messages above, and which columns those are is a decision your platform
makes.</p>
<h2 id="what-your-handler-receives">What your handler receives</h2>
<pre><code class="language-tsx">const fields = await loadSupplierFields(tenantId);
const columns = buildColumns(fields);
const synonyms = buildSynonyms(fields);

&#x3C;DataEditor&#x3C;Supplier>
  apiKey={apiKey}
  open={open}
  onClose={close}
  columns={columns}
  synonyms={synonyms}
  primaryKey="supplierNumber"
  onComplete={async (result) => {
    for (const source of result.sources) {
      const rows = source.rows.filter((r) => r.isValid &#x26;&#x26; !r.isDeleted);
      await upsertSuppliers(tenantId, rows.map((r) => r.row));
    }
  }}
/></code></pre>
<p><code>onComplete</code> hands back flat rows grouped by source, each carrying <code>isNew</code>,
<code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. The row shape follows the schema you
built, so a configured field arrives under the id the customer's configuration
gave it and your upsert writes it as a custom attribute.</p>
<p><code>primaryKey</code> is a single column here, since a supplier number identifies a
supplier inside one tenant. A file whose numbers repeat across branches takes a
list instead, and a row merges only when every part matches.</p>
<h2 id="no-supplier-schema-ships-in-the-box">No supplier schema ships in the box</h2>
<p>Updog ships no supplier template, no diversity certification list and no
connector to any procurement suite. Updog Importer reads CSV, TSV, JSON, XML,
XLSX, XLS, XLSB and ODS. A signed supplier questionnaire that arrives as a PDF
or a scan needs <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a>, and its
rows land in the grid beside the spreadsheet rows. The twelve core columns, the
field mapper, the alias builder and every option list are yours to write and
yours to keep.</p>
<p>The catalog side of procurement stays out too. A price file keyed on a supplier
part number against your own item number is a different import with a different
key, and a published catalog format like CIF reaches the drop zone the same way
a PDF does, through a parser you write.</p>
<p>One thing in this file is worth a decision before you map it. A supplier export
can carry a social security number, because a sole proprietor's tax number is
their social security number. Leaving that column out of the schema is enough to
drop it, since an unmapped header lands nowhere.</p>
<h2 id="the-same-code-at-the-second-customer">The same code at the second customer</h2>
<p>Mount the same build against a second customer and the field array comes back
different. Broker code, contract end, service line. Twelve of the eighteen
headers in this same file reach a column, and the six that miss are <code>Pay Group</code>,
<code>Risk Tier</code>, <code>Insurance Expiry</code>, <code>Plants Served</code>, <code>Minority Indicator</code> and
<code>Minority Type</code>.</p>
<p>All six are fields this customer does not keep. Nothing is broken. A header with
nowhere to land is the correct answer when the customer never asked for the
field, and the person sees it sitting unmapped and moves on.</p>
<p>That is the whole shape of a procurement import. The file comes from a system
you do not control, the schema comes from a customer you have not met, and the
code you write is the function between them.</p>]]></content:encoded></item>
<item><title>Excel Import for Construction Management Software</title><link>https://updog.tech/blog/excel-import-for-construction-management-software/</link><guid isPermaLink="true">https://updog.tech/blog/excel-import-for-construction-management-software/</guid><pubDate>Sat, 15 Aug 2026 00:00:00 GMT</pubDate><description>A contractor sends the budget detail their accounting system prints. How to take that file into your cost code schema, merged header cells and all.</description><content:encoded><![CDATA[<p>Construction budgets live in Excel. The accounting system prints a schedule of
values, the project manager opens it in a spreadsheet, adds a column for this
month's billing, and sends it on. The workbook is a document before it is
data, and it is laid out to be printed and signed.</p>
<p>Those documents reach your importer intact. A title block sits above the
table, cost codes carry leading zeros a spreadsheet is happy to drop, and
subtotal rows sit between the line items your schema wants.</p>
<p>A contractor's budget export writes its column headings across two rows. The
importer reads the upper one, and eight of the nine headings reach a field. The
row underneath reaches all nine.</p>
<p>Both rows are header rows. Row 5 and row 6 each say <code>PHASE</code>, <code>ITEM NO.</code> and
<code>DESCRIPTION OF WORK</code>, because a spreadsheet merge covers both. They differ in
one place, and that place is a money column your schema keeps.</p>
<p>A construction management platform stores one row per budget line. Its customers
export those lines out of the accounting system they are leaving, or out of the
workbook the project accountant keeps beside it. Taking a contractor's budget
into a schema of your own is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The file below holds 656 rows over nine columns and 18 merged ranges, 41 KB of
<code>.xlsx</code>. Every count in this article came out of running that file through the
importer.</p>
<h2 id="the-budget-an-accounting-system-prints">The budget an accounting system prints</h2>
<p>A schedule of values lists what a contract is worth line by line, and how much
of each line is finished. The AIA G703 continuation sheet is the form the
industry prints it on, and the AIA instructions name the money columns. One
holds work completed by the previous application, one holds work completed this
period, one holds materials presently stored, and one holds the total of the
three.</p>
<p>Hartwell Construction Group is a general contractor moving onto your platform.
The file is their budget detail for the Riverside Transit Center, printed by the
system they are leaving. Procore, Autodesk Build and Sage 300 CRE all hold
budgets in this shape, and so does the workbook a project accountant keeps by
hand.</p>
<p><code>riverside-transit-budget.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row"><th class="sheet__number" scope="row">1</th><td class="sheet__cell" colspan="9">HARTWELL CONSTRUCTION GROUP</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell" colspan="9">Riverside Transit Center, Project 24-118</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell" colspan="9">Budget Detail, Period Ending 07/31/2026</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">5</th><td class="sheet__cell" rowspan="2">PHASE</td><td class="sheet__cell" rowspan="2">ITEM NO.</td><td class="sheet__cell" rowspan="2">DESCRIPTION OF WORK</td><td class="sheet__cell" rowspan="2">COST TYPE</td><td class="sheet__cell" rowspan="2">SCHEDULED VALUE</td><td class="sheet__cell" colspan="2">WORK COMPLETED</td><td class="sheet__cell" rowspan="2">MATERIALS PRESENTLY STORED</td><td class="sheet__cell" rowspan="2">BALANCE TO FINISH</td></tr><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">FROM PREVIOUS APPLICATION</td><td class="sheet__cell">THIS PERIOD</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">Enabling Works</td><td class="sheet__cell">2026-02-20</td><td class="sheet__cell">Hazardous Material Survey</td><td class="sheet__cell">O</td><td class="sheet__cell">$248,478.66</td><td class="sheet__cell">$122,957.44</td><td class="sheet__cell">$27,172.23</td><td class="sheet__cell"></td><td class="sheet__cell">$98,348.99</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell"></td><td class="sheet__cell">02-220</td><td class="sheet__cell">Site Demolition</td><td class="sheet__cell">Prof Services</td><td class="sheet__cell">$30,250.00</td><td class="sheet__cell">$16,740.55</td><td class="sheet__cell">$4,493.96</td><td class="sheet__cell"></td><td class="sheet__cell">$9,015.49</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell"></td><td class="sheet__cell">02-220</td><td class="sheet__cell">Site Demolition</td><td class="sheet__cell">M</td><td class="sheet__cell">$105,241.85</td><td class="sheet__cell">$21,581.12</td><td class="sheet__cell">$23,871.00</td><td class="sheet__cell"></td><td class="sheet__cell">$59,789.73</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell"></td><td class="sheet__cell">02-230</td><td class="sheet__cell">Site Clearing</td><td class="sheet__cell">L</td><td class="sheet__cell">$107,031.81</td><td class="sheet__cell">$31,778.76</td><td class="sheet__cell">$4,537.25</td><td class="sheet__cell"></td><td class="sheet__cell">$70,715.80</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell"></td><td class="sheet__cell">2026-02-20</td><td class="sheet__cell">Hazardous Material Survey</td><td class="sheet__cell">LAB</td><td class="sheet__cell">$89,209.76</td><td class="sheet__cell">$2,151.61</td><td class="sheet__cell">$23,104.98</td><td class="sheet__cell"></td><td class="sheet__cell">$63,953.17</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell"></td><td class="sheet__cell">01-500</td><td class="sheet__cell">Temporary Facilities and Controls</td><td class="sheet__cell">Labor</td><td class="sheet__cell">$349,912.69</td><td class="sheet__cell">$124,913.75</td><td class="sheet__cell">$49,872.58</td><td class="sheet__cell">$8,451.69</td><td class="sheet__cell">$166,674.67</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">34 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">47</th><td class="sheet__cell"></td><td class="sheet__cell">31 23 00</td><td class="sheet__cell">Excavation and Backfill</td><td class="sheet__cell"></td><td class="sheet__cell">$72,242.65</td><td class="sheet__cell">$3,915.41</td><td class="sheet__cell">$15,862.63</td><td class="sheet__cell">$22,658.15</td><td class="sheet__cell">$29,806.46</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">8 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">56</th><td class="sheet__cell"></td><td class="sheet__cell">02.230</td><td class="sheet__cell">Site Clearing</td><td class="sheet__cell">MAT</td><td class="sheet__cell">$466,024.72</td><td class="sheet__cell">$237,826.15</td><td class="sheet__cell">$41,763.04</td><td class="sheet__cell"></td><td class="sheet__cell">$186,435.53</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">14 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">71</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Enabling Works Total</td><td class="sheet__cell"></td><td class="sheet__cell">$15,205,849.02</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">1 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">73</th><td class="sheet__cell">Substructure</td><td class="sheet__cell">03-210</td><td class="sheet__cell">Cast-In-Place Concrete</td><td class="sheet__cell">L</td><td class="sheet__cell">$472,468.91</td><td class="sheet__cell">$174,544.27</td><td class="sheet__cell">$20,253.81</td><td class="sheet__cell"></td><td class="sheet__cell">$277,670.83</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">582 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">656</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Values shown are current contract amounts including approved change orders.</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr></tbody></table>
<p>Rows 1 to 3 are the title block, each one a single cell stretched across all
nine columns. Rows 5 and 6 are the header. Row 7 is where the lines start, and
row 71 is where the first phase closes with a subtotal.</p>
<h2 id="what-a-budget-line-is-on-your-side">What a budget line is on your side</h2>
<p>Procore calls the model a work breakdown structure. A budget code is built from
segments, and the three defaults are cost code, cost type and an optional sub
job. Cost code is a tiered segment, so it carries a parent and a child with a
dash between them. Cost type is a flat segment with a list of items and no
hierarchy under it.</p>
<p>Procore publishes seven cost types, and prints a letter beside each one. (E)
Equipment, (L) Labor, (M) Materials, (O) Other, (OC) Owner Cost, (S)
Commitments, and (SVC) Professional Services. Those seven are the option list
your schema declares.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const PHASES = [
  "Enabling Works",
  "Substructure",
  "Superstructure",
  "Envelope",
  "Interiors",
  "Mechanical and Electrical",
  "Sitework",
];

const COST_TYPES = [
  "Equipment",
  "Labor",
  "Materials",
  "Other",
  "Owner Cost",
  "Commitment",
  "Professional Services",
];

export const columns: DataEditorColumn[] = [
  {
    id: "phase",
    title: "Phase",
    editor: { type: "select", options: PHASES },
  },
  {
    id: "budgetCode",
    title: "Budget code",
    validators: [
      { type: "required" },
      {
        type: "regex",
        pattern: "^\\d{2}-\\d{2,3}$",
        message: "Not a cost code",
      },
    ],
  },
  {
    id: "costCodeName",
    title: "Cost code name",
    validators: [{ type: "required" }],
  },
  {
    id: "costType",
    title: "Cost type",
    editor: { type: "select", options: COST_TYPES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: COST_TYPES }],
  },
  {
    id: "originalBudget",
    title: "Original budget",
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", min: 0 }],
  },
  {
    id: "completedPrevious",
    title: "Completed previous",
    editor: { type: "number" },
    validators: [{ type: "number" }],
  },
  {
    id: "completedThisPeriod",
    title: "Completed this period",
    editor: { type: "number" },
    validators: [{ type: "number" }],
  },
  {
    id: "storedMaterials",
    title: "Stored materials",
    editor: { type: "number" },
    validators: [{ type: "number" }],
  },
  {
    id: "balanceToFinish",
    title: "Balance to finish",
    editor: { type: "number" },
    validators: [{ type: "number" }],
  },
];</code></pre>
<p>Nine fields. The budget code carries a pattern the contractor's own house style
has to clear, and every money column is a number.</p>
<h2 id="the-headings-the-file-spells-its-own-way">The headings the file spells its own way</h2>
<p>Five of the nine headings reach a field with nothing configured. <code>PHASE</code>, <code>COST TYPE</code>, <code>MATERIALS PRESENTLY STORED</code> and <code>BALANCE TO FINISH</code> share a word with
the field beside them, and <code>WORK COMPLETED</code> reaches <code>completedPrevious</code> on the
word the two of them share.</p>
<p>Three of the four that miss are places where the file's word and your word are
different words for one thing. <code>ITEM NO.</code> against <code>budgetCode</code>. <code>DESCRIPTION OF WORK</code> against <code>costCodeName</code>. <code>SCHEDULED VALUE</code> against <code>originalBudget</code>.
Nothing is wrong with either name.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    budgetCode: ["ITEM NO.", "Cost Code", "Code"],
    costCodeName: [
      "DESCRIPTION OF WORK",
      "Description",
      "Cost Code Description",
    ],
    originalBudget: ["SCHEDULED VALUE", "Budget", "Original Contract"],
    completedPrevious: ["FROM PREVIOUS APPLICATION", "Previous"],
    completedThisPeriod: ["THIS PERIOD"],
    storedMaterials: ["MATERIALS PRESENTLY STORED"],
    balanceToFinish: ["BALANCE TO FINISH"],
  },
};</code></pre>
<p>Seven rows finish the mapping and eight of the nine headings reach a field.
Every string on the left of that list is the vocabulary the AIA form prints, so
the next contractor's budget lands on the same table. The ninth heading is the
file's own doing.</p>
<h2 id="a-heading-that-spans-two-columns">A heading that spans two columns</h2>
<p><code>WORK COMPLETED</code> is one heading over two columns on the printed form, and the
workbook writes it as a merge across F5 and G5. The seven headings beside it are
merged the other way, each one down two rows.</p>
<p>Updog fills a merged range across its whole area, so every cell the range covers
carries the anchor's value. A merge shows its value over its whole area in the
spreadsheet, and the import mirrors that.</p>
<p>Row 5 comes out of the fill with nine cells, and two of them read <code>WORK COMPLETED</code>. Two columns cannot share one header, so the importer suffixes the
second and the row ends <code>WORK COMPLETED</code>, <code>WORK COMPLETED (2)</code>. Your alias table
has no entry for a name the importer wrote.</p>
<p><strong>Row 6 comes out of the fill with nine cells too.</strong> In the file it holds two,
<code>FROM PREVIOUS APPLICATION</code> and <code>THIS PERIOD</code>. The seven label merges above it
reach down one row, so after the fill it holds nine and every one of them is
distinct. The better header row exists because of the fill.</p>
<h2 id="the-row-the-importer-was-sure-about">The row the importer was sure about</h2>
<p>Updog inspects the first rows of a file to decide which row holds the headers,
looking at where each column's values switch from text labels to a consistent
type. A row that reads as a banner loses its claim to the next row below it that
scores higher, so the three title rows are stepped over.</p>
<p>On this file the detector lands on row 5, at a confidence of 0.79 against a
threshold of 0.55. That verdict is confident and it is defensible. Row 5 is a
header row.</p>
<p>A confident verdict means no header-selection step. The person reaches column
matching, reads <strong>8/9 matched</strong> at the top of the screen, and finds <code>WORK COMPLETED (2)</code> sitting on <strong>Select column</strong> with nothing to put in it.</p>
<h2 id="the-row-underneath-it">The row underneath it</h2>
<p><strong>Change header row</strong> sits in the footer of the matching step, beside Back and
Next. It reopens header selection for the file being matched, including a file
whose header was detected confidently and whose screen was skipped.</p>
<p>The screen opens with row 5 already chosen and the title block above it. Choose
row 6, press Next, and the columns match again. Nine of nine, with
<code>FROM PREVIOUS APPLICATION</code> and <code>THIS PERIOD</code> where a duplicate heading used to
be.</p>
<p>Leaving it on row 5 costs two things and both are quiet. The second header row
arrives as data, so the grid holds 643 rows where row 6 gives 642. And
<code>completedThisPeriod</code> lands empty on all 643, because one heading spanning two
columns cannot be aliased twice.</p>
<p><strong>A column you mapped by hand keeps your choice when its header reads the same
on the new row.</strong> A match you cleared stays cleared as well, so the alias list
above does not put <code>MATERIALS PRESENTLY STORED</code> back after a header change.
Pressing the button costs nothing already done.</p>
<h2 id="the-phase-written-once">The phase written once</h2>
<p>The same fill that duplicates a heading fills a column nobody wants to type.</p>
<p><code>PHASE</code> is written seven times in this file, once at the top of each block, and
every one of those cells is merged down its own rows. The blocks run 64, 88, 96,
82, 118, 126 and 58 lines. After the fill, seven cells reach 632 rows, and every
line row carries the phase it belongs to.</p>
<p>Unmerging that column by hand means typing seven words 632 times.</p>
<h2 id="the-cost-code-written-more-than-one-way">The cost code written more than one way</h2>
<p>Procore's default cost code list holds 17 divisions aligned with the CSI
MasterFormat, and its tiers are delimited by a dash, so <code>03-210</code> is division 03
and cost code 210. MasterFormat itself holds 50 divisions and writes a section
as six digits in three pairs, so <code>03 30 00</code> is division 03, section 30. Two
published vocabularies for one catalogue.</p>
<p>This contractor's estimating system and their accounting system disagree about
which one they emit, and both land in the same column. 475 rows are written
<code>03-210</code>, 73 are written <code>03 30 00</code>, and 34 are written <code>03.210</code>, which is the
contractor's own third house style.</p>
<p>The pattern on <code>budgetCode</code> accepts one of the three. 157 rows come through
flagged <code>Not a cost code</code>, and 157 is 73 plus 50 plus 34. The 50 in the middle
have a different story behind them.</p>
<h2 id="the-code-that-became-a-date">The code that became a date</h2>
<p>Procore publishes a help article on preserving cost code formatting in Excel.
Number-to-date reformatting happens when someone opens a file with Excel, and
the program looks at the encoded cell values and decides on its own whether a
cell should read as a date, a fraction, currency or text.</p>
<p>Four codes in this catalogue carry a two-digit second tier. <code>02-20</code> Hazardous
Material Survey, <code>05-12</code> Steel Erection, <code>06-24</code> Interior Architectural
Woodwork, and <code>09-30</code> Tiling. A General-formatted column reads each of them as a
day and a month, and 50 rows reach the store as <code>2026-02-20</code>, <code>2026-05-12</code>,
<code>2026-06-24</code> and <code>2026-09-30</code>.</p>
<p>The description column beside them survives, so the code is recoverable. A
person reading <code>2026-05-12</code> against <code>Steel Erection</code> knows what the contractor
meant.</p>
<h2 id="every-letter-procore-prints">Every letter Procore prints</h2>
<p>The cost type column holds sixteen strings and one of them is blank. <code>L</code> on 91
rows, <code>M</code> on 82, <code>S</code> on 79, <code>Labor</code> on 54, <code>Material</code> on 50, <code>Subcontract</code> on
50, <code>E</code> on 49, <code>Equipment</code> on 30, <code>Subcontractor</code> on 25, <code>LAB</code> on 24, <code>Sub</code> on
23, <code>O</code> on 20, <code>MAT</code> on 19, <code>Prof Services</code> on 14, <code>Owner</code> on 11, and blank on
29.</p>
<p>Six of the fifteen reach an option on their own. <code>Labor</code> and <code>LAB</code> land on
Labor, <code>Material</code> on Materials, <code>Equipment</code> on Equipment, <code>Owner</code> on Owner Cost,
and <code>Prof Services</code> on Professional Services.</p>
<p><strong>The letters Procore itself prints reach nothing.</strong> <code>L</code>, <code>M</code>, <code>E</code>, <code>O</code> and <code>S</code>
are the abbreviations published beside the seven options, and a one-letter
string shares no word with a word. <code>MAT</code> misses where <code>LAB</code> lands, because <code>lab</code>
sits inside <code>labor</code> and <code>mat</code> sits inside <code>materials</code> below the tier that would
take it.</p>
<p><code>Subcontractor</code>, <code>Subcontract</code> and <code>Sub</code> are a decision about the domain.
Procore publishes <code>(S) Commitment</code>, and the word this file writes is absent from
the list. Somebody has to say the two are one thing, and no matcher can say it
for them.</p>
<p>Nine values left unmapped leave 459 of 642 cost type cells empty, against 29
blanks in the file. An unmatched value on a closed select lands as nothing, and
it lands there without an error. The person maps them on the value step, or a
<code>values</code> alias arrives with the next export.</p>
<h2 id="the-subtotal-that-arrives-as-a-line">The subtotal that arrives as a line</h2>
<p>Ten rows in this file are not budget lines. Seven are phase subtotals reading
<code>Enabling Works Total</code> and the six like it, one is <code>PROJECT TOTAL</code>, and two are
notes at the bottom. The last of them is a sentence.</p>
<p>Every one of them carries a description and no item number, so <code>required</code> on the
budget code flags all ten and the person deletes them.
<a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> covers the failures
any file can produce, and a total row is the failure a printed form produces.</p>
<h2 id="when-a-sheet-is-not-a-table">When a sheet is not a table</h2>
<p>Some files read fine and hold no single table. Updog scores every sheet it reads
for how safely it reads as one rectangular table, and a sheet that scores badly
hands the whole file to a reader you supply.</p>
<p>The score notices a value painted across a whole row, a value merged down its
rows, a sheet that changes shape partway down, and a near-empty tail. This file
carries all four and still reads as a table, at 0.9635 where 0.65 is the line
below which a file goes to your handler.
Seven phase blocks under one header is one shape repeated, and one shape
repeated is a table.</p>
<p>The scoring runs only when <code>onUnstructuredFile</code> is set. The measure is internal
and it moves as it meets more real files, so build against what your handler
receives.</p>
<h2 id="nothing-here-knows-what-a-cost-code-is">Nothing here knows what a cost code is</h2>
<p>Updog ships no division list, no MasterFormat table, no schedule of values
template, and no connector to any construction system. Updog Importer reads CSV,
TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A budget that survives only as a PDF
goes through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a> and arrives as
ordinary rows. The nine columns, the alias list, the pattern and the seven
options are yours.</p>
<p>The merge story needs a single-sheet file. Merge information survives on the
rows a parse returns, and a multi-sheet workbook previews its sheets through
another path that carries no merge list. Header detection reads the flattened
row either way and reaches the same verdict, so a tab in a workbook behaves the
same as the file above. The structure score loses one of its signals.</p>
<h2 id="what-your-own-reader-gives-back">What your own reader gives back</h2>
<pre><code class="language-ts">export const readBudget = async (
  file: File,
  { signal }: { signal: AbortSignal },
) => {
  const body = new FormData();
  body.append("file", file);
  const res = await fetch("/api/read-budget", { method: "POST", body, signal });
  return res.json(); // CustomImportTable[]
};</code></pre>
<p>Your route reads the sheet, takes row 6 as the header, and keeps a row only when
it carries both an item number and a description. It answers with one named
table of 632 rows, and that table stages as an ordinary card with its own
matching screen.</p>
<p>Nine of nine headings reach a field. The ten rows that are not lines never
arrive, every <code>required</code> error goes with them, and 157 rows come through
flagged. All 157 are the cost code column.</p>
<p>This is the one place in the import where the file leaves the browser. It
travels from the person's browser to wherever your handler sends it, under your
own processing agreement, and nothing about it passes through Updog.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
follows a file down each of the two routes.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey="budgetCode"
  onUnstructuredFile={readBudget}
  onComplete={async (result) => {
    const lines = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row)
      .map((row) => ({
        phase: row.phase,
        budgetCode: row.budgetCode,
        costCodeName: row.costCodeName,
        costType: row.costType,
        originalBudget: Number(row.originalBudget),
        completedPrevious: Number(row.completedPrevious || 0),
        completedThisPeriod: Number(row.completedThisPeriod || 0),
        storedMaterials: Number(row.storedMaterials || 0),
        balanceToFinish: Number(row.balanceToFinish || 0),
      }));

    await postBudget({ project: "24-118", lines });
  }}
/></code></pre>
<h2 id="the-one-problem-left-in-the-file">The one problem left in the file</h2>
<p>157 lines out of 632 carry a cost code the pattern refuses. 73 are written the
MasterFormat way, 34 are written with a dot, and 50 are dates that used to be
codes.</p>
<p>All 157 are legible. The description sits beside every one of them, so the
project accountant works down the list against the code list their own company
publishes, which is the only place that answer lives.</p>
<p>Then 632 lines of a contract become budget codes your platform can add up, and a
file printed for a person to read becomes rows.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Databricks</title><link>https://updog.tech/blog/import-csv-into-databricks/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-databricks/</guid><pubDate>Fri, 14 Aug 2026 00:00:00 GMT</pubDate><description>Match several partner files in the browser, post the clean rows to your own route, and merge them into a Delta table with one SQL statement.</description><content:encoded><![CDATA[<p>Databricks documents several ways to move a CSV into a table. A workspace page takes up to ten files at a time, under two gigabytes in total, and turns them into a managed Delta table. A notebook reads one out of a Unity Catalog volume with <code>spark.read</code>. <code>COPY INTO</code> and Auto Loader pull files that already sit in cloud object storage. Every one of those starts from a seat that already holds the workspace. Your customer sits outside that seat, holding a claims file their service desk exported this morning.</p>
<h2 id="the-door-a-web-backend-has">The door a web backend has</h2>
<p>Rows reach a Databricks table through SQL. The Statement Execution API takes a statement over HTTPS, runs it on a SQL warehouse, and answers with a statement id and a state. That is the whole surface a web backend gets, and everything below is built on it.</p>
<p>Two things are checked before the statement touches anything. Unity Catalog wants <code>MODIFY</code> on the table, and the documentation adds that the caller "must also have <code>SELECT</code> on the table, <code>USE SCHEMA</code> on the parent schema, and <code>USE CATALOG</code> on the parent catalog". The warehouse wants <code>CAN USE</code>. So the grants your data team already manages decide what your import route can write.</p>
<p>One thing is not checked. Databricks states that primary key, foreign key and unique constraints "are informational only and aren't enforced". A second row carrying a key the table already holds lands beside the first and nothing complains. <code>NOT NULL</code> and <code>CHECK</code> do hold, and a violated one fails the transaction. In <a href="https://updog.tech/blog/import-csv-into-snowflake/">how to import CSV into Snowflake</a> the same job runs through a staging table. Here the identity work moves earlier, into the browser.</p>
<h2 id="the-files-that-arrive">The files that arrive</h2>
<p>Four repair partners send their April claims in the same week. Two of them look like this.</p>
<p><code>northgate-service-april.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Claim Ref</td><td class="sheet__cell">Dealer ID</td><td class="sheet__cell">Serial</td><td class="sheet__cell">Model</td><td class="sheet__cell">Fault</td><td class="sheet__cell">Repair Date</td><td class="sheet__cell">Labour Hrs</td><td class="sheet__cell">Parts</td><td class="sheet__cell">Currency</td><td class="sheet__cell">Status</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">WC-00811</td><td class="sheet__cell">NG-14</td><td class="sheet__cell">SN0041872</td><td class="sheet__cell">X200</td><td class="sheet__cell">No power</td><td class="sheet__cell">12/04/2026</td><td class="sheet__cell">1.5</td><td class="sheet__cell">48.20</td><td class="sheet__cell">EUR</td><td class="sheet__cell">approved</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">WC-00812</td><td class="sheet__cell">NG-14</td><td class="sheet__cell">SN0041905</td><td class="sheet__cell">X200 Pro</td><td class="sheet__cell">flickering screen</td><td class="sheet__cell">3/4/2026</td><td class="sheet__cell">0.75</td><td class="sheet__cell">0.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">pending</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">WC-00813</td><td class="sheet__cell">NG-14</td><td class="sheet__cell">SN0042110</td><td class="sheet__cell">X200</td><td class="sheet__cell">NP</td><td class="sheet__cell">22/04/2026</td><td class="sheet__cell">2</td><td class="sheet__cell">115.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">APPROVED</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">138 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">143</th><td class="sheet__cell">WC-00952</td><td class="sheet__cell">NG-14</td><td class="sheet__cell">SN0043918</td><td class="sheet__cell">X100</td><td class="sheet__cell">Battery fault</td><td class="sheet__cell">29/04/2026</td><td class="sheet__cell">1.25</td><td class="sheet__cell">62.40</td><td class="sheet__cell">EUR</td><td class="sheet__cell">approved</td></tr></tbody></table>
<p><code>vantage-claims-2026-04.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Claim Ref</td><td class="sheet__cell">Servicer</td><td class="sheet__cell">Serial No.</td><td class="sheet__cell">Model</td><td class="sheet__cell">Fault Code</td><td class="sheet__cell">Date of repair</td><td class="sheet__cell">Labour hours</td><td class="sheet__cell">Parts cost</td><td class="sheet__cell">Curr</td><td class="sheet__cell">Status</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">WC-00811</td><td class="sheet__cell">VG-07</td><td class="sheet__cell">SN0067341</td><td class="sheet__cell">X200 Pro</td><td class="sheet__cell">H2O damage</td><td class="sheet__cell">2026-04-08</td><td class="sheet__cell">3.25</td><td class="sheet__cell">240.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Rejected - no fault found</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">WC-00812</td><td class="sheet__cell">VG-07</td><td class="sheet__cell">SN0067402</td><td class="sheet__cell">X100</td><td class="sheet__cell">Battery fault</td><td class="sheet__cell">2026-04-19</td><td class="sheet__cell">0.5</td><td class="sheet__cell">31.90</td><td class="sheet__cell">EUR</td><td class="sheet__cell">approved</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">85 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">89</th><td class="sheet__cell">WC-00898</td><td class="sheet__cell">VG-07</td><td class="sheet__cell">SN0068890</td><td class="sheet__cell">X200</td><td class="sheet__cell">No power</td><td class="sheet__cell">2026-04-30</td><td class="sheet__cell">2</td><td class="sheet__cell">88.50</td><td class="sheet__cell">EUR</td><td class="sheet__cell">approved</td></tr></tbody></table>
<p>Every partner names the same things differently. One says <code>Dealer ID</code> and the other says <code>Servicer</code>. One writes dates day first and the other writes them ISO. <code>Curr</code>, <code>Labour Hrs</code> and <code>NP</code> are somebody's local shorthand. <code>H2O damage</code> and <code>flickering screen</code> mean two of the four faults your catalogue holds. Both files carry a claim <code>WC-00811</code>, because each partner runs its own numbering.</p>
<p>The person drags all four files into the importer inside your app. Updog Importer reads them in the browser, matches each file's headers to your schema, holds the fault codes to your list, and puts every row in front of them. Your <code>onComplete</code> handler receives the rows grouped by file. The handler posts them to a route you own, and that route runs one <code>MERGE</code>.</p>
<p>No Updog server stands between the browser and Databricks.</p>
<h2 id="the-table-the-rows-land-in">The table the rows land in</h2>
<p>One Delta table holds the claims, and the key is two columns wide.</p>
<pre><code class="language-sql">create table main.service.warranty_claims
(
  partner_code  string not null,
  claim_ref     string not null,
  serial_number string,
  model         string,
  fault_code    string,
  repair_date   date,
  labour_hours  decimal(5, 2),
  parts_cost    decimal(10, 2),
  status        string,
  source_file   string,
  updated_at    timestamp,
  constraint warranty_claims_pk primary key (partner_code, claim_ref) rely
)
cluster by (partner_code, repair_date);

alter table main.service.warranty_claims
  add constraint labour_hours_sane check (labour_hours >= 0 and labour_hours &#x3C;= 24);</code></pre>
<p>The key constraint is declared for the optimizer and for the next person reading the schema. Databricks will not enforce it. The check constraint arrives in a second statement, because the <code>CREATE TABLE</code> grammar carries key constraints alone and points at <code>ALTER TABLE</code> for a check.</p>
<p><code>CLUSTER BY</code> is liquid clustering, generally available for Delta tables from Databricks Runtime 15.4 LTS, and it refuses to combine with <code>PARTITIONED BY</code>. Clustering on the partner and the repair date matches how the table gets read, one partner at a time over a month.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array is the same table written for the person looking at the file.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const FAULTS = ["No power", "Screen flicker", "Battery fault", "Water damage"];
const STATUSES = ["Approved", "Rejected", "Pending"];
const CURRENCIES = ["EUR", "GBP", "USD"];

export const columns: DataEditorColumn[] = [
  {
    id: "partnerCode",
    title: "Partner code",
    size: 140,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^[A-Z]{2}-\\d{2}$" },
    ],
  },
  {
    id: "claimRef",
    title: "Claim ref",
    size: 140,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^WC-\\d{5}$" },
    ],
  },
  {
    id: "serialNumber",
    title: "Serial number",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
  },
  { id: "model", title: "Model", size: 120 },
  {
    id: "faultCode",
    title: "Fault code",
    size: 170,
    editor: { type: "select", options: FAULTS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: FAULTS }],
  },
  {
    id: "repairDate",
    title: "Repair date",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "labourHours",
    title: "Labour hours",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, max: 24, decimalPlaces: 2 },
    ],
  },
  {
    id: "partsCost",
    title: "Parts cost",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "currency",
    title: "Currency",
    size: 120,
    editor: { type: "select", options: CURRENCIES, enableCustomValue: false },
  },
  {
    id: "status",
    title: "Status",
    size: 150,
    editor: { type: "select", options: STATUSES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: STATUSES }],
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>date</code> editor turns <code>22/04/2026</code> into <code>2026-04-22</code>, and since 22 is above 12 that file settles day first, so <code>12/04/2026</code> and <code>3/4/2026</code> land as <code>2026-04-12</code> and <code>2026-04-03</code>. The <code>select</code> editors hold the fault code and the status to a fixed list, and a value nobody maps is dropped from the row. Uniqueness stays off <code>claimRef</code>, because <code>{ type: "unique" }</code> scores one column against the whole grid and both partners number their claims from the same series. Identity here is two columns wide, and <code>primaryKey</code> is where that lives.</p>
<h2 id="the-same-column-under-a-different-header">The same column under a different header</h2>
<p>Column matching repeats per file. Each file gets its own screen and its own mapping, so the same schema column is fed by a different header in each one.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>File</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Claim Ref</code></td>
<td>both</td>
<td><code>claimRef</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Dealer ID</code></td>
<td>Northgate</td>
<td><code>partnerCode</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Servicer</code></td>
<td>Vantage</td>
<td><code>partnerCode</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Serial</code></td>
<td>Northgate</td>
<td><code>serialNumber</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Serial No.</code></td>
<td>Vantage</td>
<td><code>serialNumber</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Fault</code></td>
<td>Northgate</td>
<td><code>faultCode</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Fault Code</code></td>
<td>Vantage</td>
<td><code>faultCode</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Repair Date</code></td>
<td>Northgate</td>
<td><code>repairDate</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Date of repair</code></td>
<td>Vantage</td>
<td><code>repairDate</code></td>
<td>shared words, 70</td>
</tr>
<tr>
<td><code>Labour Hrs</code></td>
<td>Northgate</td>
<td><code>labourHours</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Curr</code></td>
<td>Vantage</td>
<td><code>currency</code></td>
<td>contains, 80</td>
</tr>
</tbody>
</table></div>
<p><code>Serial</code> reaches <code>serialNumber</code> because the contains tier fires once the shorter string runs to four characters or more. <code>Curr</code> sits exactly on that floor and gets in. <code>Dealer ID</code> and <code>Servicer</code> get nothing from fuzzy matching at all, since neither shares a whole word with <code>partnerCode</code> and both sit too far away in edits, so one <code>synonyms</code> entry carries every partner's word for the same thing.</p>
<p>Value matching runs once for the whole import and collects values per schema column across all four files. <code>flickering screen</code> reaches <code>Screen flicker</code> on the word they share. <code>H2O damage</code> reaches <code>Water damage</code> the same way. <code>NP</code> is two characters, so it reaches nothing on its own and needs the synonym table. <code>Rejected - no fault found</code> contains <code>rejected</code> and lands at eighty.</p>
<p>Each file also settles its own dates. The verdict comes from a sample of that file alone, so a day-first export and an ISO export in the same import never borrow each other's reading.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the four files, the schema and the warehouse together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Claim>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey={["partnerCode", "claimRef"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      partnerCode: ["dealer id", "servicer", "asc code", "workshop"],
      claimRef: ["claim no", "job number"],
    },
    values: {
      "No power": ["np", "dead unit"],
      "Water damage": ["liquid ingress"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> takes two columns, because a claim reference identifies a claim only inside one partner. Both files carry <code>WC-00811</code>, and with the partner beside it those stay two claims. Values are compared after trimming, and a row missing either part merges with nothing and arrives as new.</p>
<p><code>enableDeleteRow="all"</code> lets the person drop a claim a partner sent twice by hand. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, source-and-target pairs split into <code>columns</code> and <code>values</code>, which you store and fold into the <code>synonyms</code> tables next month.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source. Each file lands as its own entry, carrying the file name, so the row that came from Vantage still says so on the way out.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 5_000;

const toRow = (entry: ResultRow&#x3C;Claim>, sourceFile: string) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  return [{
    partner_code: entry.row.partnerCode,
    claim_ref: entry.row.claimRef,
    serial_number: entry.row.serialNumber,
    model: entry.row.model,
    fault_code: entry.row.faultCode,
    repair_date: entry.row.repairDate,
    labour_hours: entry.row.labourHours,
    parts_cost: entry.row.partsCost,
    status: entry.row.status,
    source_file: sourceFile,
    op: entry.isDeleted ? "delete" : "upsert",
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Claim>) => {
  for (const source of result.sources) {
    const rows = [
      ...new Map(
        source.rows
          .flatMap((entry) => toRow(entry, source.sourceName))
          .map((row) => [row.partner_code + "\u0000" + row.claim_ref, row] as const),
      ).values(),
    ];

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const written = await fetch("/api/claims/merge", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
      });
      if (!written.ok) throw new Error((await written.json()).message);
    }
  }
}, []);</code></pre>
<p>Three flags become one column. An insert and an update are the same payload, since the merge settles which one it is, and a delete is the same payload with <code>op</code> set, which happens for rows the editor loaded from your own table. A row the person added and then deleted goes nowhere. The <code>Map</code> keeps one row per partner-and-claim pair, so a chunk never carries the same key twice.</p>
<p>The chunk size belongs to you. Databricks publishes two ceilings here, sixteen mebibytes of query text and twenty-five mebibytes of inline result. Neither one binds this route, because the statement is a constant and the rows travel beside it as a parameter value, which carries no published ceiling. So five thousand rows is a number chosen against what your own endpoint accepts.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and four partners' claims clear the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-merges">The route that merges</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">const CLAIM_SCHEMA =
  "array&#x3C;struct&#x3C;partner_code: string, claim_ref: string, " +
  "serial_number: string, model: string, fault_code: string, " +
  "repair_date: date, labour_hours: decimal(5,2), " +
  "parts_cost: decimal(10,2), status: string, " +
  "source_file: string, op: string>>";

const MERGE_CLAIMS =
  "merge into main.service.warranty_claims as t " +
  "using (select r.* from (select explode(from_json(:payload, '" +
  CLAIM_SCHEMA + "', map('mode', 'FAILFAST'))) as r)) as s " +
  "on t.partner_code = s.partner_code and t.claim_ref = s.claim_ref " +
  "when matched and s.op = 'delete' then delete " +
  "when matched then update set " +
  "  serial_number = s.serial_number, model = s.model, " +
  "  fault_code = s.fault_code, repair_date = s.repair_date, " +
  "  labour_hours = s.labour_hours, parts_cost = s.parts_cost, " +
  "  status = s.status, source_file = s.source_file, " +
  "  updated_at = current_timestamp() " +
  "when not matched and s.op = 'upsert' then insert " +
  "  (partner_code, claim_ref, serial_number, model, fault_code, " +
  "   repair_date, labour_hours, parts_cost, status, source_file, updated_at) " +
  "  values (s.partner_code, s.claim_ref, s.serial_number, s.model, " +
  "   s.fault_code, s.repair_date, s.labour_hours, s.parts_cost, " +
  "   s.status, s.source_file, current_timestamp())";

app.post("/api/claims/merge", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const rows = request.body.rows;
  const allowed = await partnersFor(session.accountId);
  if (rows.some((row) => !allowed.has(row.partner_code))) {
    return response.status(403).json({ message: "A partner code is not yours" });
  }

  try {
    await runStatement(MERGE_CLAIMS, [
      { name: "payload", value: JSON.stringify(rows), type: "STRING" },
    ]);
  } catch (error) {
    request.log.error({ err: error });
    return response.status(502).json({ message: "The merge did not run" });
  }

  response.json({ merged: rows.length });
});</code></pre>
<p>The rows never become SQL text. Databricks warns that generating SQL dynamically "can result in SQL injection attacks", and answers it with parameter markers, which handle input arguments "separately from the rest of your SQL code". This API takes named markers alone, each carrying one value cast to the type you name, so the whole chunk rides as one <code>STRING</code> and <code>from_json</code> rebuilds it inside the warehouse. The schema beside it is a constant your code owns, written the way <code>CREATE TABLE</code> writes types. <code>FAILFAST</code> makes a malformed payload raise <code>MALFORMED_RECORD_IN_PARSING</code> rather than quietly nulling the fields it could not read.</p>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. The partner codes arrive in the body, so the route checks each one against the partners that session is allowed to load. A guessed code reaches no other manufacturer's rows.</p>
<h2 id="waiting-for-the-statement">Waiting for the statement</h2>
<p><code>wait_timeout</code> accepts <code>0s</code> or five to fifty seconds, and defaults to ten. The route asks for fifty and takes what comes back. A merge that finishes inside the window arrives <code>SUCCEEDED</code> in the first response, and everything slower comes back <code>PENDING</code> with a statement id to poll. A serverless warehouse that auto-stopped after its default ten idle minutes is starting up inside that same wait.</p>
<p>The poll is where the trap sits. A warehouse that fails to run your statement answers HTTP 200 with <code>status.state</code> set to <code>FAILED</code>, and the error waits at <code>status.error</code>. A rejected request is a non-200, and a failed merge is not. So a route that reads <code>response.ok</code> alone reports a clean import over a table nothing was written to, and the grid clears.</p>
<p>All of this happens with the confirm dialog open and a spinner on the button. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="when-the-merge-refuses">When the merge refuses</h2>
<p>A merge fails as a statement. <code>DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE</code> is the one this import can produce, and Databricks raises it when more than one source row matches the same target row under the <code>ON</code> and <code>WHEN MATCHED</code> conditions. Two lines carrying the same partner and claim reference are exactly that input. The documentation asks the caller to preprocess the source, and the handler does it by keeping one row per partner-and-claim pair before the chunk leaves the browser.</p>
<p>There is no per-row failure list. The statement carries one error code and one message at <code>status.error</code>, populated only when the state is <code>FAILED</code>. The bad row is named by the message rather than by an index, which is why the checking sits in the browser where a row has a screen position and somebody to fix it.</p>
<h2 id="the-routes-nobody-ships-for-you">The routes nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Databricks connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the routes in the middle are work you do.</p>
<p>Databricks already ships its own ways in for the other case. The upload page turns up to ten files into a table and states plainly that "Joining or merging records during file upload is not supported", which is the line between the two jobs. A volume takes a file up to five gigabytes through the UI, and larger ones through the Databricks SDK, up to what the underlying cloud storage holds. <code>COPY INTO</code> and Auto Loader keep object storage flowing in, and a notebook reads a CSV where it sits. For an export your own team downloaded, those tools are the shorter way in. Everything above exists for the four exports your partners sent, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-next-month">The pieces you wrote and next month</h2>
<p>You wrote one Delta table, a schema with ten columns, one synonym entry covering four partners' vocabularies, a token cache, a statement runner that polls, and one merge route. The files stay on the machine that opened them. The rows travel from your own front end to your own route and into Unity Catalog, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>May will bring the same four partners and a fifth one with a fifth spelling of <code>Partner code</code>. The mappings from April are already stored, the two-column key keeps the numbering apart, and the new partner costs one more line in <code>synonyms</code>.</p>]]></content:encoded></item>
<item><title>CSV Import for Sports Statistics Software</title><link>https://updog.tech/blog/csv-import-for-sports-statistics-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-sports-statistics-software/</guid><pubDate>Thu, 13 Aug 2026 00:00:00 GMT</pubDate><description>A basketball program sends the box score archive it keeps as a spreadsheet. How to take that file into your player and game schema, minutes symbols and all.</description><content:encoded><![CDATA[<p>A box score is written once, during the game, by a scorer sitting at the
table. It goes into the statistics software the school runs, and it gets
copied into a spreadsheet the moment anybody wants to look at a season instead
of a night. A program holds one of those for every game it has played.</p>
<p>Box scores are printed for people to read. Shooting is written as makes and
attempts inside one cell, minutes are written the way a clock reads, and the
sheet carries rows for team totals that belong to no player.</p>
<p>A basketball program's box score archive arrives with seventeen columns. Your
schema has a field for sixteen. Three of those columns carry two numbers in one
cell, and one of them writes how long a player was on the court in five ways.</p>
<p>A sports statistics platform stores one row per player per game. Its customers
export those rows out of the software their scorer runs during a game, or out of
the spreadsheet an assistant keeps beside it. Taking a program's archive into a
schema of your own is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The sports information director at the program is the one who uploads the
archive, when that program goes live on your product. The schema it reaches is
yours.</p>
<p>The archive below holds 2,443 rows over seventeen columns, 164 KB of <code>.csv</code>.
Every count in this article came out of running that file through the importer.</p>
<h2 id="how-long-a-player-was-on-the-court">How long a player was on the court</h2>
<p>The NCAA publishes a statisticians' manual every season. Section 9 says that
minutes played "may be kept and reported either to the second or to the nearest
minute", and then names four symbols.</p>
<p>A player who was on the court for exactly zero seconds gets <code>0</code>. A player who was
on for less than half a minute gets <code>0+</code>. A player who was on for at least 39
minutes and 30 seconds, without playing the whole 40, gets <code>40-</code>. A player who
never entered gets <code>DNP</code>.</p>
<p>FIBA's own manual, published for the 2024 season, uses <code>DNP</code> for the same case
and writes minutes with seconds everywhere else. Two governing bodies, one
symbol.</p>
<p><strong>Two of those symbols name a range.</strong> <code>0+</code> covers everything between zero and 30
seconds, and <code>40-</code> covers everything from 39 minutes 30 seconds up to the final
horn. Neither one is a value your database can add up. Which number your platform
stores in their place is a decision you make once, in code.</p>
<h2 id="the-archive-a-statistician-keeps">The archive a statistician keeps</h2>
<p>The file is one row per player per game, over 174 games and six seasons. Its
column names come from the box score the program's stats software printed, with
a date and an opponent added so a season stays in one sheet.</p>
<p><code>box-scores-2020-2026.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th><th class="sheet__column" scope="col">N</th><th class="sheet__column" scope="col">O</th><th class="sheet__column" scope="col">P</th><th class="sheet__column" scope="col">Q</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Date</td><td class="sheet__cell">Opponent</td><td class="sheet__cell">##</td><td class="sheet__cell">Player Name</td><td class="sheet__cell">TOT-FG</td><td class="sheet__cell">3-PT</td><td class="sheet__cell">FT</td><td class="sheet__cell">OF</td><td class="sheet__cell">DE</td><td class="sheet__cell">TOT</td><td class="sheet__cell">PF</td><td class="sheet__cell">TP</td><td class="sheet__cell">A</td><td class="sheet__cell">TO</td><td class="sheet__cell">BLK</td><td class="sheet__cell">S</td><td class="sheet__cell">MIN</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="17"><span class="sheet__break-text">1022 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1024</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">00</td><td class="sheet__cell">Zeke Gillick</td><td class="sheet__cell">7-13</td><td class="sheet__cell">7-8</td><td class="sheet__cell">0-1</td><td class="sheet__cell">4</td><td class="sheet__cell">4</td><td class="sheet__cell">8</td><td class="sheet__cell">5</td><td class="sheet__cell">21</td><td class="sheet__cell">7</td><td class="sheet__cell">0</td><td class="sheet__cell">3</td><td class="sheet__cell">3</td><td class="sheet__cell">31</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1025</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">23</td><td class="sheet__cell">Priit Vantrease</td><td class="sheet__cell">2-3</td><td class="sheet__cell">2-3</td><td class="sheet__cell">0-3</td><td class="sheet__cell">1</td><td class="sheet__cell">7</td><td class="sheet__cell">8</td><td class="sheet__cell">4</td><td class="sheet__cell">6</td><td class="sheet__cell">6</td><td class="sheet__cell">3</td><td class="sheet__cell">3</td><td class="sheet__cell">2</td><td class="sheet__cell">31</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1026</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">20</td><td class="sheet__cell">Dedrick Gillick</td><td class="sheet__cell">5-7</td><td class="sheet__cell">0-2</td><td class="sheet__cell">1-6</td><td class="sheet__cell">0</td><td class="sheet__cell">2</td><td class="sheet__cell">2</td><td class="sheet__cell">4</td><td class="sheet__cell">11</td><td class="sheet__cell">2</td><td class="sheet__cell">4</td><td class="sheet__cell">2</td><td class="sheet__cell">2</td><td class="sheet__cell">28</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1027</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">40</td><td class="sheet__cell">Amare Quiroz</td><td class="sheet__cell">1-10</td><td class="sheet__cell">1-7</td><td class="sheet__cell">2-3</td><td class="sheet__cell">3</td><td class="sheet__cell">8</td><td class="sheet__cell">11</td><td class="sheet__cell">3</td><td class="sheet__cell">5</td><td class="sheet__cell">3</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">3</td><td class="sheet__cell">33</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1028</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">52</td><td class="sheet__cell">Oisin Vantrease</td><td class="sheet__cell">2-4</td><td class="sheet__cell">2-4</td><td class="sheet__cell">4-7</td><td class="sheet__cell">2</td><td class="sheet__cell">8</td><td class="sheet__cell">10</td><td class="sheet__cell">1</td><td class="sheet__cell">10</td><td class="sheet__cell">4</td><td class="sheet__cell">2</td><td class="sheet__cell">1</td><td class="sheet__cell">0</td><td class="sheet__cell">33</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1029</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">31</td><td class="sheet__cell">Solomon Janowski</td><td class="sheet__cell">5-10</td><td class="sheet__cell">0-2</td><td class="sheet__cell">5-5</td><td class="sheet__cell">3</td><td class="sheet__cell">5</td><td class="sheet__cell">8</td><td class="sheet__cell">2</td><td class="sheet__cell">15</td><td class="sheet__cell">2</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">25</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1030</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">25</td><td class="sheet__cell">Rasheed Redfern</td><td class="sheet__cell">2-2</td><td class="sheet__cell">1-1</td><td class="sheet__cell">0-2</td><td class="sheet__cell">0</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">5</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">11</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1031</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">33</td><td class="sheet__cell">Yannick Ulmer</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1032</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">10</td><td class="sheet__cell">Malachi Quiroz</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">DNP</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1033</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">05</td><td class="sheet__cell">Dedrick Doran</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">DNP</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1034</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">45</td><td class="sheet__cell">Lachlan Ostrander</td><td class="sheet__cell">0-2</td><td class="sheet__cell">0-2</td><td class="sheet__cell">1-1</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">2</td><td class="sheet__cell">0</td><td class="sheet__cell">1</td><td class="sheet__cell">2</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">9</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1035</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell">24</td><td class="sheet__cell">Emeka Eklund</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0-0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">0+</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1036</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell"></td><td class="sheet__cell">TEAM</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">4</td><td class="sheet__cell">4</td><td class="sheet__cell">8</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">2</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1037</th><td class="sheet__cell">01/22/2023</td><td class="sheet__cell">Underhill</td><td class="sheet__cell"></td><td class="sheet__cell">Totals</td><td class="sheet__cell">24-51</td><td class="sheet__cell">13-29</td><td class="sheet__cell">13-28</td><td class="sheet__cell">18</td><td class="sheet__cell">40</td><td class="sheet__cell">58</td><td class="sheet__cell">20</td><td class="sheet__cell">74</td><td class="sheet__cell">26</td><td class="sheet__cell">13</td><td class="sheet__cell">11</td><td class="sheet__cell">11</td><td class="sheet__cell">200</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="17"><span class="sheet__break-text">855 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1893</th><td class="sheet__cell">02/07/2025</td><td class="sheet__cell">Calderwood</td><td class="sheet__cell">11</td><td class="sheet__cell">Ferran Bosque</td><td class="sheet__cell">6-11</td><td class="sheet__cell">2-5</td><td class="sheet__cell">3-4</td><td class="sheet__cell">1</td><td class="sheet__cell">6</td><td class="sheet__cell">7</td><td class="sheet__cell">2</td><td class="sheet__cell">17</td><td class="sheet__cell">4</td><td class="sheet__cell">2</td><td class="sheet__cell">0</td><td class="sheet__cell">1</td><td class="sheet__cell">40-</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="17"><span class="sheet__break-text">550 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2444</th><td class="sheet__cell">03/07/2026</td><td class="sheet__cell">Ravensmoor</td><td class="sheet__cell"></td><td class="sheet__cell">Totals</td><td class="sheet__cell">26-55</td><td class="sheet__cell">9-24</td><td class="sheet__cell">15-19</td><td class="sheet__cell">11</td><td class="sheet__cell">29</td><td class="sheet__cell">40</td><td class="sheet__cell">17</td><td class="sheet__cell">76</td><td class="sheet__cell">15</td><td class="sheet__cell">10</td><td class="sheet__cell">4</td><td class="sheet__cell">7</td><td class="sheet__cell">200</td></tr></tbody></table>
<p>Fourteen rows of one game, a line from two seasons later, and the row the archive
ends on. The player wearing <code>00</code> played 31 minutes. One player played <code>0+</code>, one
played <code>0</code>, and two never left the bench. The row reading <code>TEAM</code> carries four
rebounds each way and two turnovers with no jersey against it. The row reading
<code>Totals</code> closes that game at 200 minutes, row 1893 is the <code>40-</code> case, and row
2444 closes the last game the archive holds.</p>
<p>Updog opens that file in the tab the statistician is already sitting in. The
reading, the matching and the checking run on their machine. Nothing about this
game travels to your API until they press submit.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
follows a file down each of the two routes.</p>
<h2 id="the-fields-your-platform-stores">The fields your platform stores</h2>
<p>Sportradar publishes the field names its NBA box score endpoint answers with.
Made and attempted are two fields each, being <code>field_goals_made</code> and
<code>field_goals_att</code>. Minutes arrive as a string in <code>"MM:SS"</code>, as in <code>"30:44"</code>.</p>
<p>Minutes are stored in seconds, because seconds is the only unit that holds every
shape the file writes. The date column writes <code>01/22/2023</code>, and the first value with a
part above 12 settles the whole file as month-first, so all 2,443 dates land as
ISO.</p>
<pre><code class="language-ts">import type {
  DataEditorColumn,
  DataEditorRow,
  ValidationError,
} from "@updog/data-editor";
import { pointsAgree } from "./pointsAgree";
import { readSeconds } from "./readSeconds";

const printedPair = (value: unknown): ValidationError | null => {
  const written = String(value ?? "").trim();
  if (written === "") return null;
  const pair = /^(\d+)-(\d+)$/.exec(written);
  if (!pair) {
    return { level: "error", message: "Write this as made-attempted" };
  }
  return Number(pair[1]) > Number(pair[2])
    ? { level: "error", message: "More made than attempted" }
    : null;
};

const playerOrTeam = (
  value: unknown,
  row: DataEditorRow,
): ValidationError | null => {
  if (String(value ?? "").trim() !== "") return null;
  return row.playerName === "TEAM"
    ? null
    : { level: "error", message: "Every line carries a jersey number" };
};

const shooting = (id: string, title: string): DataEditorColumn => {
  return {
    id,
    title,
    dependentFields: ["points"],
    validators: [{ type: "function", fn: printedPair }],
  };
};

const tally = (id: string, title: string): DataEditorColumn => {
  return {
    id,
    title,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  };
};

export const columns: DataEditorColumn[] = [
  {
    id: "gameDate",
    title: "Game date",
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  { id: "opponent", title: "Opponent" },
  {
    id: "jerseyNumber",
    title: "Jersey number",
    validators: [{ type: "function", fn: playerOrTeam }],
  },
  {
    id: "playerName",
    title: "Player name",
    dependentFields: ["jerseyNumber"],
  },
  {
    id: "secondsPlayed",
    title: "Seconds played",
    editor: { type: "number" },
    transformer: readSeconds,
    validators: [{ type: "number", min: 0, max: 3600, decimalPlaces: 0 }],
  },
  shooting("fieldGoals", "Field goals"),
  shooting("threePointers", "Three pointers"),
  shooting("freeThrows", "Free throws"),
  tally("offensiveRebounds", "Offensive rebounds"),
  tally("defensiveRebounds", "Defensive rebounds"),
  tally("personalFouls", "Personal fouls"),
  {
    id: "points",
    title: "Points",
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 0 },
      { type: "function", fn: pointsAgree },
    ],
  },
  tally("assists", "Assists"),
  tally("turnovers", "Turnovers"),
  tally("blocks", "Blocks"),
  tally("steals", "Steals"),
];</code></pre>
<p>The three shooting columns keep the pair the file printed, and a rule checks its
shape. Splitting them into six numbers is the last thing that happens, and it has
a section below.</p>
<h2 id="the-headers-that-reach-nothing">The headers that reach nothing</h2>
<p>Three of the seventeen headers land with no configuration. <code>Opponent</code> is the
field name. <code>Player Name</code> is the field name with a space in it. <code>Date</code> sits
inside <code>gamedate</code>.</p>
<p>The other fourteen are abbreviations, and an abbreviation shares no word with a
field name. Thirteen of them shrink to three characters or fewer once the
punctuation comes off, and the matcher refuses to look inside a string that
short. <code>A</code>, <code>S</code>, <code>TO</code> and <code>PF</code> reach nothing, and so do <code>MIN</code> and <code>TOT-FG</code>.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    jerseyNumber: ["##", "no", "uni"],
    secondsPlayed: ["min", "mp"],
    fieldGoals: ["tot-fg", "fg-fga", "fg"],
    threePointers: ["3-pt", "3pt", "3fg"],
    freeThrows: ["ft", "ft-fta"],
    offensiveRebounds: ["of", "oreb"],
    defensiveRebounds: ["de", "dreb"],
    personalFouls: ["pf"],
    points: ["tp", "pts"],
    assists: ["a", "ast"],
    turnovers: ["to", "tov"],
    blocks: ["blk"],
    steals: ["s", "stl"],
  },
};</code></pre>
<p>Thirteen rows finish the mapping, and sixteen of the seventeen headers reach a
field. <code>TOT</code> stays unmapped on purpose, because the total rebound column is the
sum of the two beside it and your platform can add. Every string here is the
vocabulary this whole sport writes in, so the next program's export lands on the
same table.
<a href="https://updog.tech/blog/remember-csv-import-mappings/">Remembering an import mapping</a> covers
carrying what one person fixed by hand into the next upload.</p>
<h2 id="one-unit-for-every-shape">One unit for every shape</h2>
<p>The minutes column arrives at a number field, so Updog reduces what it can. A
currency symbol, a percent sign, accounting parentheses and the file's own
grouping all come off. A clock does not, because no pattern in the numeric
grammar reads one.</p>
<p>So <code>31:24</code> stays as written, and so do <code>0+</code>, <code>40-</code> and <code>DNP</code>. Against a schema
with no transformer, 1,241 of the 2,269 filled cells in that column carry
<code>Invalid number</code>.</p>
<pre><code class="language-ts">export const readSeconds = (value: unknown): unknown => {
  const written = String(value ?? "").trim();
  if (written === "" || written === "DNP") return "";

  const clock = /^(\d+):([0-5]\d)$/.exec(written);
  if (clock) return String(Number(clock[1]) * 60 + Number(clock[2]));

  if (written === "0+") return "0";

  const nearly = /^(\d+)-$/.exec(written);
  if (nearly) return String((Number(nearly[1]) - 1) * 60 + 30);

  if (/^\d+$/.test(written)) return String(Number(written) * 60);

  return value;
};</code></pre>
<p>Every shape in the column reaches one unit, and every one of the 1,241 flags goes
to zero.</p>
<div class="blog-table blog-table--fixed blog-table--boxscore-minutes"><table>
<thead>
<tr>
<th>Written</th>
<th>Rows</th>
<th>Becomes</th>
</tr>
</thead>
<tbody>
<tr>
<td>a clock, as <code>31:24</code></td>
<td>896</td>
<td>1884</td>
</tr>
<tr>
<td>whole minutes, as <code>28</code></td>
<td>854</td>
<td>1680</td>
</tr>
<tr>
<td><code>DNP</code></td>
<td>289</td>
<td>an empty cell</td>
</tr>
<tr>
<td><code>200</code>, on the totals line</td>
<td>174</td>
<td>12000, and out of range</td>
</tr>
<tr>
<td>empty, on the team line</td>
<td>174</td>
<td>stays empty</td>
</tr>
<tr>
<td><code>40-</code></td>
<td>31</td>
<td>2370</td>
</tr>
<tr>
<td><code>0+</code></td>
<td>25</td>
<td>0</td>
</tr>
</tbody>
</table></div>
<p>Two of those conversions are a judgement, and it is worth writing down what they
cost. <code>0+</code> becomes zero seconds and <code>40-</code> becomes 2370 seconds, so each one is
short by at most 29 seconds. This archive holds 25 cells reading <code>0+</code> and 31
reading <code>40-</code>, which keeps the whole rounding under half an hour across six
seasons.</p>
<p><strong>An empty cell and a zero mean different things here.</strong> Both manuals say so. The
NCAA writes that a game played "would not be ruled out by the use of a '0' under
minutes played". FIBA writes that a game with <code>DNP</code> does not count as a game
played at all. A player given <code>0</code> was in the book for that game, and a player
given <code>DNP</code> was never in it.</p>
<p>Folding <code>DNP</code> into zero seconds erases that line, and a games-played count goes
up by one for every player who sat. The transformer above returns an empty string
for <code>DNP</code> and the string <code>"0"</code> for a zero. The handler at the end of this article
reads that empty cell as a <code>played</code> flag.</p>
<h2 id="the-cell-that-holds-two-numbers">The cell that holds two numbers</h2>
<p><code>7-13</code> is seven field goals made out of thirteen attempted. A published Stat Crew
box score prints <code>FG-FGA</code>, <code>FG-FGA</code> and <code>FT-FTA</code> as its three shooting columns,
and the NCAA points its own statisticians at that software.</p>
<p>One header reaches one field. Your schema holds <code>fieldGoalsMade</code> and
<code>fieldGoalsAtt</code> apart, and the file offers <code>TOT-FG</code> as one column. The mapping
step has nowhere to put the second number.</p>
<p><strong>Keep the pair as the file wrote it and check its shape.</strong> <code>printedPair</code> lets an
empty cell through and asks every other one for digits, a hyphen and digits. It
also reports a cell whose first number is larger than its second, because nobody
makes more shots than they take. Fourteen lines in this archive are written
attempted-made, and all fourteen land in the person's list.</p>
<h2 id="where-the-second-number-goes">Where the second number goes</h2>
<p>The grid ships a <strong>Split column</strong> move, and the person reaches it from the column
header. It takes one source column, a separator, and two or more target columns,
and it previews three rows before anything is written.</p>
<p>Point it at the field goals column, give it <code>-</code> as the separator, and choose
<code>fieldGoalsMade</code> and <code>fieldGoalsAtt</code> as the targets. 2,443 rows fill in one step
that undo reverses. An empty cell hands both targets an empty cell, so the 289
rows reading <code>DNP</code> stay empty.</p>
<p>The form also offers to delete the source column afterwards. That offer reaches
only a column the person created themselves in the matching step. A column your
schema declares survives the split and keeps what it had.</p>
<p>For an import that runs the same way every time, do the split in the handler. The
four-line <code>pair</code> helper below reaches the same six numbers, and nobody has to
remember a step.</p>
<h2 id="the-points-column-that-disagrees">The points column that disagrees</h2>
<p>The points a line carries are decided by the three columns above it. Two points
for every field goal, one more for every one of those that came from behind the
arc, and one for every free throw.</p>
<pre><code class="language-ts">import type { DataEditorRow, ValidationError } from "@updog/data-editor";

const made = (written: unknown): number | null => {
  const pair = /^(\d+)-(\d+)$/.exec(String(written ?? "").trim());
  return pair ? Number(pair[1]) : null;
};

export const pointsAgree = (
  value: unknown,
  row: DataEditorRow,
): ValidationError | null => {
  const field = made(row.fieldGoals);
  const three = made(row.threePointers);
  const free = made(row.freeThrows);
  if (field === null || three === null || free === null) return null;

  const total = (field - three) * 2 + three * 3 + free;
  return Number(value) === total
    ? null
    : { level: "error", message: "The shooting columns add up to " + total };
};</code></pre>
<p>The rule reads the whole row, so <code>dependentFields: ["points"]</code> sits on each
shooting column and fires the check again when a person edits one. 82 rows in
this archive report that the shooting columns add up to something else. Four more
carry points below zero, which the <code>min</code> bound catches first, because a cell
reports the first rule it fails.</p>
<p>34 of those 82 are <code>Totals</code> rows, and that is the rule working. A game total
stops adding up the moment one line inside it is wrong, so a flagged totals row
points at the game around it.</p>
<h2 id="the-jersey-number-that-is-not-a-number">The jersey number that is not a number</h2>
<p><code>0</code> and <code>00</code> are both legal. The NCAA approved uniform numbers "0 or 00 through
99" for the 2023-24 season, and before that the legal set already held both. Two
players, two numbers, one character apart.</p>
<p>The canonical number form Updog stores rejects a leading zero, in the same way it
rejects <code>007</code>. Declare the jersey column as a number and 377 cells in this
archive are flagged, being every <code>00</code>, <code>01</code>, <code>02</code>, <code>04</code> and <code>05</code>. The 58 rows
reading <code>0</code> pass, so the one value that had to stay apart is the one that gets
edited.</p>
<p>Declare it as text and nothing touches it. <code>00</code> arrives as <code>00</code> and <code>05</code> keeps
its padding, and the only rule left on that column is that a line carries one at
all.</p>
<h2 id="the-row-with-no-player-behind-it">The row with no player behind it</h2>
<p>A rebound that no player earned still belongs to a team. The NCAA's manual
defines the team rebound and the dead-ball rebound, and says that national
rankings count team rebounds and leave dead-ball rebounds out. That is why every
box score carries a <code>TEAM</code> line.</p>
<p>348 rows in this archive carry no jersey number, being 174 <code>TEAM</code> lines and 174
<code>Totals</code> lines. A plain <code>required</code> rule would flag both, and it would also stop
the team lines from ever reaching your handler.</p>
<p><strong>The <code>TEAM</code> line is the one row whose numbers sit nowhere else.</strong> A totals line
can be rebuilt from the lines above it. Four team rebounds cannot, so
<code>playerOrTeam</code> lets an empty jersey through when the name beside it reads <code>TEAM</code>,
and the handler routes that line to your game record. The 174 totals lines have
no such excuse, and every one of them lands in the person's list to be deleted.</p>
<p><code>dependentFields: ["jerseyNumber"]</code> sits on the player name column, so correcting
a name rechecks the jersey beside it.
<a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> covers the failures
any file can produce, and the ones above are the failures a box score produces.</p>
<h2 id="nothing-here-knows-what-a-rebound-is">Nothing here knows what a rebound is</h2>
<p>Updog ships no sport, no stat vocabulary, no roster template and no connector to
any scoring system. Updog Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and
ODS. An old workbook therefore opens beside this year's export, with no step in
between. A box score that survives only as a PDF goes
through <a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a> and arrives as
ordinary rows. Everything above that layer is yours, being the sixteen columns,
the alias table, the transformer and the three rules.</p>
<p>The transformer carries one limit worth knowing. Its argument is a single cell,
so anything that has to read a second column belongs in a validator or in your
handler.</p>
<p>This archive arrives once, on the day a program moves in. No schedule, no queue
and no server of ours sits between the statistician and your API.</p>
<h2 id="what-the-handler-writes">What the handler writes</h2>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey={["gameDate", "opponent", "jerseyNumber"]}
  blockSubmitOnError
  onComplete={async (result) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row);

    const pair = (written: unknown) => {
      const [made, attempted] = String(written ?? "").split("-");
      return [Number(made || 0), Number(attempted || 0)];
    };

    const lines = [];
    const teamLines = [];

    for (const row of rows) {
      if (row.playerName === "Totals") continue;

      if (row.playerName === "TEAM") {
        teamLines.push({
          gameDate: row.gameDate,
          opponent: row.opponent,
          teamRebounds:
            Number(row.offensiveRebounds || 0) +
            Number(row.defensiveRebounds || 0),
          teamTurnovers: Number(row.turnovers || 0),
        });
        continue;
      }

      const [fgm, fga] = pair(row.fieldGoals);
      const [tpm, tpa] = pair(row.threePointers);
      const [ftm, fta] = pair(row.freeThrows);

      lines.push({
        gameDate: row.gameDate,
        opponent: row.opponent,
        jerseyNumber: row.jerseyNumber,
        playerName: row.playerName,
        played: row.secondsPlayed !== "",
        seconds: row.secondsPlayed === "" ? null : Number(row.secondsPlayed),
        fieldGoalsMade: fgm,
        fieldGoalsAtt: fga,
        threePointsMade: tpm,
        threePointsAtt: tpa,
        freeThrowsMade: ftm,
        freeThrowsAtt: fta,
        offensiveRebounds: Number(row.offensiveRebounds || 0),
        defensiveRebounds: Number(row.defensiveRebounds || 0),
        points: Number(row.points || 0),
      });
    }

    await postArchive({ lines, teamLines });
  }}
/></code></pre>
<p><code>onComplete</code> hands back every row under the source it arrived in, each one tagged
<code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. The handler drops the totals
lines, routes the team lines to your game record, and splits each printed pair on
the way out. An empty seconds cell becomes <code>played: false</code>, which is the <code>DNP</code>
line arriving as what it is.</p>
<p><code>primaryKey</code> is required, and a box score line carries no identity of its own.
The date, the opponent and the jersey together identify one, so all three go into
the key. A team line carries an empty jersey, and a key with an empty part inside
it matches no existing row, so that line arrives as new.</p>
<h2 id="the-list-the-statistician-works-down">The list the statistician works down</h2>
<p>Out of 2,443 rows, 226 carry something a rule caught. 174 of them are the
<code>Totals</code> lines, which leaves <strong>52 player lines out of 2,095</strong>. Fourteen are
written attempted-made, and each of those fails the points check as well. The
other 38 carry points that disagree with three columns written correctly.</p>
<p>The statistician works down that list against the book the game was scored in,
which is the only place those answers live. Then 2,095 lines become six seasons
of minutes in one unit, and a platform that could not add <code>0+</code> to <code>31:24</code> can add
up a career.</p>]]></content:encoded></item>
<item><title>How to Import CSV Records Into Salesforce</title><link>https://updog.tech/blog/import-csv-into-salesforce/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-salesforce/</guid><pubDate>Wed, 12 Aug 2026 00:00:00 GMT</pubDate><description>Map and validate a messy CSV in the browser, post the rows to your own route in chunks of 200, and upsert them into Salesforce on an External ID.</description><content:encoded><![CDATA[<p>An External ID is a custom field Salesforce indexes so a record can be found by a key another system already owns. Four custom field types carry the attribute, AutoNumber, Email, Number and Text. Point an upsert at that field and Salesforce decides for itself whether to create a record or update one. A broker platform importing an agency's book of business needs exactly that. The agency knows its policies by carrier and policy number, and it knows nothing about a Salesforce id.</p>
<p>The agency's export arrives looking like this.</p>
<p><code>agency-book.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Cxr Cd</td><td class="sheet__cell">Policy No</td><td class="sheet__cell">Insured</td><td class="sheet__cell">Eff Date</td><td class="sheet__cell">Exp Date</td><td class="sheet__cell">Premium</td><td class="sheet__cell">Line</td><td class="sheet__cell">Status</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">AXA-UK</td><td class="sheet__cell">PL-4417</td><td class="sheet__cell">Redwood Joinery Ltd</td><td class="sheet__cell">01/02/2026</td><td class="sheet__cell">31/01/2027</td><td class="sheet__cell">1.250,00</td><td class="sheet__cell">General Liability</td><td class="sheet__cell">Active</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">HISCOX</td><td class="sheet__cell">PL-4417</td><td class="sheet__cell">Marden Freight Ltd</td><td class="sheet__cell">15/03/2026</td><td class="sheet__cell">14/03/2027</td><td class="sheet__cell">1950,00</td><td class="sheet__cell">GL</td><td class="sheet__cell">Current</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">axa-uk</td><td class="sheet__cell">PL-5108 </td><td class="sheet__cell">Ollerton Care Homes</td><td class="sheet__cell">01-Feb-26</td><td class="sheet__cell">31-Jan-27</td><td class="sheet__cell">4380</td><td class="sheet__cell">WORKERS COMP</td><td class="sheet__cell">Active</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">636 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">641</th><td class="sheet__cell">HISCOX</td><td class="sheet__cell">PL-6042</td><td class="sheet__cell">Thornbury Plant Hire Ltd</td><td class="sheet__cell">01/06/2026</td><td class="sheet__cell">31/05/2027</td><td class="sheet__cell">2760</td><td class="sheet__cell">GL</td><td class="sheet__cell">Active</td></tr></tbody></table>
<p>Eight headers, and none of them carry the names the object uses. Two rows hold the same policy number under different carriers. The third carrier code arrives lowercase and its policy number trails a space. Two premiums use a comma for the decimal point. Four dates use slashes, and the Ollerton Care Homes row writes its two as <code>01-Feb-26</code> and <code>31-Jan-27</code>. The line column says <code>General Liability</code>, <code>GL</code> and <code>WORKERS COMP</code>.</p>
<p>The person hands that book of business to the importer inside your app. Updog Importer opens it in the browser, maps those eight headers onto your columns, and shows the person every value. Your <code>onComplete</code> handler receives the rows. The handler posts them two hundred at a time to a route you own. The route holds the Salesforce credentials and calls the sObject Collections upsert. Salesforce writes the custom object.</p>
<p>Updog runs no server anywhere between that browser and Salesforce.</p>
<h2 id="step-1-give-the-object-an-external-id-field">Step 1. Give the object an External ID field</h2>
<p>Start with the field the whole import turns on.</p>
<pre><code class="language-plaintext">Policy__c                 custom object
  Broker_Key__c           Text(80)        External ID, Unique
  Carrier_Code__c         Text(16)
  Policy_Number__c        Text(32)
  Insured_Name__c         Text(120)
  Effective_Date__c       Date
  Expiry_Date__c          Date
  Premium__c              Number(16, 2)
  Line_Of_Business__c     Picklist
  Status__c               Picklist</code></pre>
<p><code>Broker_Key__c</code> carries the External ID attribute and holds one string built from the agency, the carrier and the policy number. An upsert URL names one field, so a natural key of several parts arrives in it concatenated.</p>
<p>External ID with the Unique attribute gives a unique index and needs no special permission. External ID on its own gives a non-unique index, and the calling application needs View All Data. Marking the field Unique is what keeps one key on one record.</p>
<p>Matching is case-sensitive by default. Salesforce puts it plainly, that matching by external ID is case-insensitive only when the field has the Unique attribute with the option treating ABC and abc as duplicate values. So <code>axa-uk</code> and <code>AXA-UK</code> reach two records unless something upstream settles the case.</p>
<h2 id="step-2-describe-the-object-as-columns">Step 2. Describe the object as columns</h2>
<p>The <code>columns</code> array is the object written for the person looking at the file. Each entry sets a <code>title</code> they read, an editor deciding how a cell is typed, and validators marking what fails.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const LINES = ["General Liability", "Commercial Auto", "Workers Compensation"];
const STATUSES = ["Active", "Lapsed", "Cancelled"];

export const columns: DataEditorColumn[] = [
  {
    id: "carrierCode",
    title: "Carrier code",
    size: 130,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [{ type: "required" }],
  },
  {
    id: "policyNo",
    title: "Policy number",
    size: 140,
    transformer: (value) => String(value).trim(),
    validators: [{ type: "required" }],
  },
  {
    id: "insuredName",
    title: "Insured name",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "effectiveDate",
    title: "Effective date",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "expiryDate",
    title: "Expiry date",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "premium",
    title: "Premium",
    size: 120,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "lineOfBusiness",
    title: "Line of business",
    size: 190,
    editor: { type: "select", options: LINES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: LINES }],
  },
  {
    id: "status",
    title: "Status",
    size: 120,
    editor: { type: "select", options: STATUSES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: STATUSES }],
  },
];</code></pre>
<p>Each editor answers a value the agency's export writes in its own way. The <code>number</code> editor sees <code>1.250,00</code>, reads the comma as the decimal point because it sits after the dot, and lands <code>1250.00</code>. <code>1950,00</code> follows the same reading and lands <code>1950.00</code>. The <code>date</code> editor turns <code>01/02/2026</code> into <code>2026-02-01</code>, which is the <code>yyyy-MM-dd</code> a Salesforce date field takes as it stands. The file settles that reading on its own, because <code>31/01/2027</code> carries a day past 12 and no month-first reading survives it.</p>
<p><code>01-Feb-26</code> matches none of the patterns the parser holds, so it reaches the grid as typed and the <code>date</code> validator flags the cell. The person fixes two cells and moves on.</p>
<p>The <code>transformer</code> on <code>carrierCode</code> uppercases and trims. That is what keeps <code>axa-uk</code> and <code>AXA-UK</code> on one External ID value at the far end of the chain.</p>
<p>The <code>synonyms</code> prop teaches matching the words the agency already uses, and the mount ties the whole thing together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Policy>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey={["carrierCode", "policyNo"]}
  synonyms={{
    columns: { carrierCode: ["cxr cd", "carrier", "carrier cd"] },
    values: { "General Liability": ["gl", "gen liab"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p>Column synonyms map <code>Cxr Cd</code> onto <code>carrierCode</code>, a pair no score reaches on its own, since the two strings share no word and neither one contains the other. <code>Policy No</code> lands exactly, <code>Insured</code> and <code>Line</code> land because the schema name contains them, and <code>Eff Date</code> lands on the word it shares with <code>Effective date</code>. Value synonyms map <code>GL</code> onto <code>General Liability</code>. <code>WORKERS COMP</code> needs no help, because <code>Workers Compensation</code> contains it once matching lowercases the value and drops the spaces. <code>Current</code> reaches <code>Active</code> through the built-in table, which already covers status vocabularies.</p>
<p>Every match the person corrects by hand returns as <code>learnedSynonyms</code>, ready to store and replay on the agency's next export. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> follows those matches from one export to the next. The package install and the modal state behind <code>open</code> and <code>onClose</code> sit in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<p>Every snippet here is React. The web component build takes the same props, so a Vue, Angular or Svelte app writes this columns array and this handler unchanged.</p>
<h2 id="step-3-point-the-primary-key-at-both-halves-of-the-identity">Step 3. Point the primary key at both halves of the identity</h2>
<p><code>primaryKey</code> decides how an imported row meets a row already in the grid. It accepts one column or a list of them, and identity here takes two. An imported row merges into an existing one only when every listed column matches. Rows inside one file are appended beside each other, so both <code>PL-4417</code> policies reach the grid whatever the key says.</p>
<p>The key earns its keep on the second file and on every repeat import. Set it to <code>policyNo</code> alone and the agency's next export lands one carrier's <code>PL-4417</code> on the other carrier's row. Pass <code>["carrierCode", "policyNo"]</code> and each policy keeps its own row through every pass.</p>
<p>A row with an empty value in any part of the key merges with nothing and arrives as new. Values are compared after surrounding whitespace is trimmed, so the space trailing <code>PL-5108 </code> costs nothing.</p>
<p>Leave the <code>unique</code> validator off both columns. Uniqueness in Updog is relational per column, checked against every other row in the same column, and a carrier code repeats across a whole book by design.</p>
<p>The primary key step in the wizard appears when there is something to merge into and a key to offer. A multi-column <code>primaryKey</code> counts as a key once every part of it is mapped, and it shows up as one choice named after its columns.</p>
<p>The same two columns decide the External ID at the far end. A key built from the policy number alone gives two policies one <code>Broker_Key__c</code>, and both of them travel inside one chunk.</p>
<h2 id="step-4-post-the-result-in-chunks-of-200">Step 4. Post the result in chunks of 200</h2>
<p>Pressing submit hands your handler every policy grouped by source, each row carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. A book of business can arrive as three files in one import, each file its own source entry. The handler flattens them before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 200;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Policy>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/policies/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>Salesforce publishes the two hundred. The sObject Collections resource takes a list that can contain up to 200 objects, all of them the same object type, and the whole request counts as one call toward the org's API allocation. That allocation is published too. A Developer Edition org holds 15,000 calls per 24 hours, and an Enterprise org holds 100,000 plus 1,000 for each Salesforce license plus whatever add-ons it bought. Forty thousand policies at 200 a request is 200 calls.</p>
<p><strong>Throw when a chunk of policies fails.</strong> Updog Importer waits on that promise and clears the editor the moment it resolves. Catch that error inside the handler and return, and Updog reads a success. The grid empties with those rows unwritten. Throwing holds the policies, the mappings and the fixes in place, so the person submits again on a book they can still see.</p>
<p>A spinner in the confirm dialog covers the whole loop, which is the other reason chunks hold 200. Copy anything you want off the result inside the handler, because the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<p>That <code>isValid</code> filter decides which policies never reach Salesforce. A failed validator marks the cell and lets the person submit anyway, so flagged rows reach your handler and the filter drops them on the floor. Pass <code>blockSubmitOnError</code> to the editor and submit stays disabled until every policy validates.</p>
<h2 id="step-5-upsert-the-chunk-from-your-own-route">Step 5. Upsert the chunk from your own route</h2>
<p>The browser reaches this route and stops there, and the Salesforce token sits behind it.</p>
<pre><code class="language-ts">import express from "express";

const app = express();
app.use(express.json({ limit: "2mb" }));

const API_VERSION = "v67.0";

app.post("/api/policies/import", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) {
    return response.status(401).json({ message: "Not signed in" });
  }

  const { instanceUrl, accessToken } = await getSalesforceToken();
  const records = request.body.rows.map((row) => ({
    attributes: { type: "Policy__c" },
    Broker_Key__c: session.agencyCode + "_" + row.carrierCode + "_" + row.policyNo,
    Carrier_Code__c: row.carrierCode,
    Policy_Number__c: row.policyNo,
    Insured_Name__c: row.insuredName,
    Effective_Date__c: row.effectiveDate,
    Expiry_Date__c: row.expiryDate,
    Premium__c: row.premium === "" ? null : Number(row.premium),
    Line_Of_Business__c: row.lineOfBusiness,
    Status__c: row.status,
  }));

  const salesforce = await fetch(
    instanceUrl + "/services/data/" + API_VERSION +
      "/composite/sobjects/Policy__c/Broker_Key__c",
    {
      method: "PATCH",
      headers: {
        Authorization: "Bearer " + accessToken,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ allOrNone: false, records }),
    },
  );

  const results = await salesforce.json();

  if (!salesforce.ok) {
    return response.status(502).json({ message: results[0].message });
  }

  const failures = results.filter((entry) => !entry.success);

  if (failures.length > 0) {
    return response.status(400).json({
      message: failures[0].errors[0].message,
      statusCode: failures[0].errors[0].statusCode,
      failed: failures.length,
    });
  }

  return response.json({ written: results.length });
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check, and <code>getSalesforceToken()</code> for the token exchange. Salesforce documents an OAuth 2.0 client credentials flow for server-to-server integration. It runs as an integration user with no person in the loop.</p>
<p>That token carries the integration user's access to every agency in the org, so the route decides tenancy itself. <code>session.agencyCode</code> comes off the verified session and never off the request body. It goes into the External ID value, so an agency's rows land on keys carrying that agency's code alone.</p>
<p>The rest of the mapping is small. <code>premium</code> arrives as the string <code>1250.00</code>, and converting it before it enters the record keeps the payload matching a number field. <code>effectiveDate</code> arrives as <code>2026-02-01</code> and needs nothing. A dateTime field would want the offset form as well.</p>
<p><code>allOrNone</code> decides what one bad policy costs. It defaults to false, and the documented behaviour is to continue with the independent creation of the other objects in the request. Set it to true and Salesforce rolls the whole request back, marking the records that would have landed with <code>ALL_OR_NONE_OPERATION_ROLLED_BACK</code>. A book of business is a pile of independent policies, so false keeps the other 199.</p>
<p>The <code>jsforce</code> library wraps the same call and carries one caveat worth reading first. Its documentation says an upsert with the <code>allOrNone</code> option will not revert successful upserts when one or more fail.</p>
<h2 id="step-6-read-the-per-record-result">Step 6. Read the per-record result</h2>
<p>Salesforce answers a collections upsert with <code>200 OK</code> and an array holding one entry per record. The status line says nothing about the records. A request Salesforce turns down outright answers with its own status and an array of error objects, so the route reads <code>salesforce.ok</code> before it counts per-record failures.</p>
<pre><code class="language-json">[
  {
    "id": "a03xx000003DHP0AAO",
    "success": true,
    "errors": [],
    "created": true
  },
  {
    "success": false,
    "errors": [
      {
        "statusCode": "DUPLICATE_VALUE",
        "message": "duplicate value found: Broker_Key__c duplicates value on record with id: a03xx000003DHP1AAO",
        "fields": ["Broker_Key__c"]
      }
    ]
  }
]</code></pre>
<p><code>created</code> separates an insert from an update, and it is the closest thing to a report of what the External ID matched. Salesforce documents three outcomes. An External ID matching nothing creates a record. An External ID matching one record updates it. An External ID matching several records creates and updates nothing. The single-record upsert URL reports that third outcome as a 300 over the whole response. A collections call keeps its <code>200 OK</code> and carries the outcome on the one record that hit it.</p>
<p><code>DUPLICATE_EXTERNAL_ID</code> covers a user-specified external ID matching more than one record during an upsert. <code>DUPLICATE_VALUE</code> covers a duplicate value supplied for a field that must be unique. Two rows carrying the same External ID inside one call get their own rule, and Salesforce says those records are marked as errors in the upsert result. <code>DUPLICATES_DETECTED</code> belongs to duplicate rules, so only an org running them ever sees it.</p>
<p>Chunks that already landed stay landed. An upsert on the same External ID writes the same values a second time, so a retry after a failed chunk costs a rewrite of what already exists. That is what makes pressing submit again safe.</p>
<h2 id="step-7-move-to-bulk-api-20-when-the-file-grows">Step 7. Move to Bulk API 2.0 when the file grows</h2>
<p>A loop of 200-row requests stops paying at some size, and Salesforce draws the line at 2,000 records. Any data operation above that is a good candidate for Bulk API 2.0, and jobs below it belong in bulkified synchronous calls in REST or SOAP. Bulk API 2.0 takes a whole CSV as one job and works through it in the background.</p>
<pre><code class="language-ts">const base = instanceUrl + "/services/data/v67.0/jobs/ingest";
const auth = { Authorization: "Bearer " + accessToken };

const job = await fetch(base, {
  method: "POST",
  headers: { ...auth, "Content-Type": "application/json" },
  body: JSON.stringify({
    object: "Policy__c",
    operation: "upsert",
    externalIdFieldName: "Broker_Key__c",
    contentType: "CSV",
  }),
}).then((res) => res.json());

await fetch(base + "/" + job.id + "/batches", {
  method: "PUT",
  headers: { ...auth, "Content-Type": "text/csv" },
  body: csv,
});

await fetch(base + "/" + job.id, {
  method: "PATCH",
  headers: { ...auth, "Content-Type": "application/json" },
  body: JSON.stringify({ state: "UploadComplete" }),
});

const failed = await fetch(base + "/" + job.id + "/failedResults/", {
  headers: auth,
}).then((res) => res.text());</code></pre>
<p>Four calls replace the loop. Create the job with <code>externalIdFieldName</code> naming the same External ID field. Upload the CSV, and one request carries up to 150 MB of base64 encoded content, so Salesforce advises keeping the file itself under 100 MB. Close the job and Salesforce starts work. Read <code>failedResults</code> afterwards for a CSV carrying <code>sf__Error</code> and <code>sf__Id</code> beside the original fields.</p>
<p>The ceilings sit far out. Bulk API 2.0 uploads 150,000,000 records per rolling 24 hours, a field holds 131,072 characters, a record holds 400,000, and a finished job keeps its status and results for seven days before Salesforce deletes them. The CSV goes up in UTF-8, its headers are the field API names, and <code>#N/A</code> is how a value is set to null.</p>
<p>The person is still waiting behind the confirm dialog while your handler runs. A job Salesforce works through in the background outlives that wait, so the route accepts the rows, starts the job, and answers straight away. The editor clears on that answer, and whatever the job reports later reaches the person through a screen you own.</p>
<h2 id="the-seats-salesforces-own-tools-need">The seats Salesforce's own tools need</h2>
<p>Updog Importer integrates with nobody. There is no Salesforce connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code a result object, and the route between your app and Salesforce is yours to write.</p>
<p>Salesforce already ships its own import for the other case. The Data Import Wizard sits in the Setup menu and takes up to 50,000 records at a time, across common standard objects and custom ones. Data Loader is a client application installed on a desktop, and it carries up to 150 million records when it runs on Bulk API 2.0. Both start from the seat of somebody who holds the org. A file already sitting on the org holder's desk travels faster through those two. The seven steps above exist for a book of business belonging to an agency, arriving in a browser session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> weighs the two models against each other.</p>
<h2 id="the-identity-the-agency-already-uses">The identity the agency already uses</h2>
<p>You wrote an External ID field, a schema of eight columns, a key made of two of them, a handler that chunks at 200, and a route that holds one token. The agency's export never leaves the machine that opened it. The rows travel from your own front end to your own route, and from there into Salesforce, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or a plain web component and the middle stays the same.</p>
<p>If the agency knows a policy by its carrier and its number, Salesforce can find that policy by the same two things.</p>]]></content:encoded></item>
<item><title>Import PDFs and Scans With Your Own Parser</title><link>https://updog.tech/blog/import-pdf-with-updog/</link><guid isPermaLink="true">https://updog.tech/blog/import-pdf-with-updog/</guid><pubDate>Tue, 11 Aug 2026 00:00:00 GMT</pubDate><description>Updog Importer reads CSV, Excel, JSON and XML. A PDF or a scan goes to a handler you write, and the rows it returns walk the same import path.</description><content:encoded><![CDATA[<p>Updog Importer reads CSV, TSV, XLSX, XLS, XLSB, ODS, JSON and XML, and it reads every one of them in the browser, on the machine that opened the page.</p>
<p>A PDF, a scanned document, a photograph of a table, or an export in a format one vendor invented reaches the same drop zone and finds no parser there. What reads a document today is a model or an OCR service, and either one takes a server, an API key, and a contract with whoever runs it.</p>
<p>Updog Importer lets you plug in your own parser. You declare the format and give it a function, every file that matches goes to that function, and the rows that come back walk the path a CSV walks.</p>
<h2 id="what-it-takes-to-read-a-pdf">What it takes to read a PDF</h2>
<p>A PDF describes a page. It holds letters and numbers with a position for each of them, so a table inside it is an arrangement on that page, and the file carries no rows and no columns unless somebody tagged it with them. A reader has to put the table back together from those positions, decide where one column ends and the next begins, join a cell that wrapped onto a second line, and drop the header that repeats at the top of every page. Words arrive without spaces in them, because a gap between two words on a PDF page can be a jump to the next position with no character behind it.</p>
<p>A scan or a photograph carries no letters at all. It carries pixels, so something has to recognise the characters first, on a page that can be rotated, shadowed, or shot at an angle by a phone. The rows and columns are then inferred from that same picture.</p>
<p>Document parsers, OCR engines and vision models do that work, and it is why data extraction is bought as a service.</p>
<h2 id="where-the-document-reader-lives">Where the document reader lives</h2>
<p>Updog Importer runs no server. So the SDK gives you an API for doing that reading on your side.</p>
<p>The person drops the file into the importer. The SDK hands it to your function. Your function posts it to your endpoint. Your endpoint sends it to your parser. The parser answers with rows. Your endpoint returns those rows to your function. Your function returns them to the SDK. The SDK stages them as a preview card, and the import continues from there.</p>
<p>We are not in that chain. You already hold that data and answer for it, and the contract for reading it is one you can sign.</p>
<h2 id="what-a-custom-format-claims">What a custom format claims</h2>
<p>One <code>customFormats</code> entry holds a label, the extensions it claims, an optional list of MIME types, and the function that reads the file.</p>
<pre><code class="language-tsx">customFormats={[
  {
    label: "PDF",
    extensions: [".pdf"],
    handle: async (file, { signal }) => {
      const body = new FormData();
      body.append("file", file);
      const res = await fetch("/api/extract", { method: "POST", body, signal });
      return res.json();
    },
  },
]}</code></pre>
<p>That entry puts <code>.pdf</code> into the accept list for the drop zone, the browse button and the grid's own drop zone. A PDF dropped there gets a card right away with a skeleton where the preview will go, and <strong>Next</strong> stays disabled while that card is pending.</p>
<p><code>extensions</code> matches the end of the file name whatever the case, and the leading dot is required, so <code>[".pdf"]</code> claims a document whatever the case of its name and <code>["pdf"]</code> claims nothing. A photograph is easier to claim by MIME, and one entry with <code>mimeTypes: ["image/*"]</code> covers a PNG, a JPEG and a HEIC from a phone whatever the file is called. A file goes to the first format that claims it, and a file no format claims takes the built-in path unchanged.</p>
<h2 id="what-your-service-receives-and-returns">What your service receives and returns</h2>
<p>The handler runs in the person's browser, so the request to your service is yours to shape. The entry above posts the file as multipart form data and passes the abort signal straight to <code>fetch</code>.</p>
<p>Your endpoint receives that file and sends it to whatever reads documents for you, a hosted model, a self-hosted one, or a document parser with no AI in it. Name the keys you want back in the prompt, because those keys become the headers Updog scores against your schema.</p>
<pre><code class="language-ts">// your server
export async function POST(request: Request) {
  const form = await request.formData();
  const file = form.get("file") as File;

  const answer = await yourModel.extract({
    document: await file.arrayBuffer(),
    instruction:
      "Read the table in this document. Return JSON, one object per row, " +
      "with the keys sku, description, quantity, unit and unitPrice.",
  });

  return Response.json(answer.rows);
}</code></pre>
<p>What travels back to the browser is an array of plain objects.</p>
<pre><code class="language-json">[
  { "sku": "A-1042", "description": "Steel bracket", "quantity": 12, "unit": "pcs", "unitPrice": 4.5 },
  { "sku": "A-1043", "description": "Steel bracket, wide", "quantity": 4, "unit": "pcs", "unitPrice": 6 }
]</code></pre>
<p>The keys become the column headers, in the order they first appear across the array, and a key missing from one object reads as an empty cell in that row. A handler has three shapes to answer in.</p>
<p><strong>Plain rows.</strong> A <code>Record&#x3C;string, unknown>[]</code> stages one card under the file's name, which is the shape a single-table document returns. Name the keys the way your schema names its columns and the matcher does the rest.</p>
<p><strong>Named tables.</strong> A <code>{ name, rows }[]</code> stages one card per table. One document can hold several tables.</p>
<pre><code class="language-json">[
  { "name": "Line items", "rows": [{ "sku": "A-1042", "quantity": 12 }] },
  { "name": "Totals", "rows": [{ "label": "VAT", "amount": 61.2 }] }
]</code></pre>
<p><strong>A file.</strong> A <code>File</code> in a format the SDK reads goes through the built-in parser, and its card takes that file's name. Hand one back when your service emits clean CSV or XLSX.</p>
<h2 id="what-runs-while-an-extraction-waits">What runs while an extraction waits</h2>
<p>Built-in reads run one file at a time, in drop order, through a single worker, which keeps a million-row XLSX from competing with three other files for memory. Custom handlers run outside that queue and beside each other. Reading a file is bounded by the machine. Extracting a document is bounded by somebody else's service.</p>
<p>Drop three spreadsheets and a scan together and the spreadsheets read while the scan is still out. The scan's card sits pending with a cancel button in its corner. The person clicking that button aborts the signal your handler received, and a result that arrives after the cancellation is discarded. Pass that signal to your <code>fetch</code> so the request to your server stops with it.</p>
<p>Updog Importer puts no timeout on <code>handle</code>. An extraction takes as long as your service takes, and any number we picked would be invented, so the person cancels by hand. A handler that ignores the signal keeps running.</p>
<h2 id="what-the-person-sees-when-a-document-fails">What the person sees when a document fails</h2>
<p>Throwing fails the file, and the message you throw reaches the screen word for word. "This scan is too blurry to read. Try a clearer copy." arrives exactly like that, the card leaves the list, and the rest of the batch keeps going. Catch the low-level error and throw a sentence a person can act on, which keeps a stack trace and your endpoint name off the screen. A throw with no message falls back to "Could not process the file".</p>
<p>An empty array is a different outcome. The document was read and held no table, and the person is told that no tables were found.</p>
<p>Underneath both, your <code>onError</code> receives a <code>PARSE_ERROR</code> with the source set to <code>custom-handler</code> and the original thrown value in <code>originalError</code>. The person reads a plain sentence and your monitoring gets the real error. The prop reference sits in <a href="https://docs.updog.tech/api-reference/import/#customformats">the import docs</a>.</p>
<h2 id="conclusion">Conclusion</h2>
<p>PDFs and images are one use of this. A custom format takes any file type your product has to support, and the path through the importer is the same one. If you have a way to parse that format, Updog Importer can import files in it.</p>]]></content:encoded></item>
<item><title>Client-Side vs Server-Side CSV Import: How to Choose</title><link>https://updog.tech/blog/client-side-vs-server-side-importer/</link><guid isPermaLink="true">https://updog.tech/blog/client-side-vs-server-side-importer/</guid><pubDate>Mon, 10 Aug 2026 00:00:00 GMT</pubDate><description>What a server-side import meters, what a client-side import limits, and how to tell which of the two models a job needs.</description><content:encoded><![CDATA[<p>When someone uploads a CSV or Excel file, it either stays on the machine that already holds it, or it travels over a network to a server that does the work there.</p>
<p>This post covers what a server-side import does and what its meter counts, what a client-side import does and what limits it, and how to tell which one a given job needs.</p>
<h2 id="what-happens-in-a-server-side-import">What happens in a server-side import</h2>
<p>After upload, the file travels across the network. The vendor's infrastructure receives it, holds it while the job runs, parses and validates it, and returns the result to the page or to your backend.</p>
<p>Moving a large file takes machinery of its own. Amazon calls multipart upload a best practice for objects of 100 MB or larger, so the parts can travel in parallel and a failed part can be sent again without restarting the whole file.</p>
<p>The file sits on the vendor's side while the work happens. Every row costs the vendor processor time, memory and storage. Server-side products meter that cost by the rows in a single import, the size of the file, and the number of imports in a billing period.</p>
<p>Holding the file brings duties with it. The vendor encrypts the data on the way and while it sits there. It chooses the region the data lives in, the employees who can open it, the number of days it stays, and the process that deletes it. It writes all of that down, has it audited, and puts it in the contract your procurement team signs. Pay attention to how long your users' data stays there and how much you pay for it.</p>
<h2 id="what-a-server-does-well">What a server does well</h2>
<p>A machine in a data centre parses a file faster than a laptop does.</p>
<p>The larger advantage is that a server runs unattended. Products built for this pull files from SFTP, S3, cloud drives and shared spreadsheets on hourly, daily or custom cron schedules, run transformations and validation, retry transient failures on their own, and deliver rows to a destination. An API call can start a run, and a webhook reports back when it finishes.</p>
<p>Those jobs need a machine that is always on. The work has to begin on its own, keep going after a failure, and leave a record of what happened.</p>
<h2 id="what-happens-in-a-client-side-import">What happens in a client-side import</h2>
<p>After upload, the file is still on the machine that opened the page, and the browser can read it there. Nothing travels before the work starts. Updog Importer reads the file where it sits, the editing happens in the browser, and your code receives clean rows.</p>
<p>That reading does not have to happen on the thread that draws the interface. MDN describes Web Workers as background threads that let code run processor-intensive calculations without blocking the user interface thread. Updog Importer runs parsing, validation, filtering and export in those workers. The grid draws on a canvas, so the browser keeps track of one element instead of a million, and a frame costs whatever the visible part of the screen costs, however many rows sit behind it.</p>
<p>We wrote up how we made Updog Importer fast in <a href="https://updog.tech/blog/canvas-grid-performance/">the canvas engine</a> and <a href="https://updog.tech/blog/filter-panel-performance/">the filter pipeline</a>.</p>
<h2 id="what-a-browser-does-well">What a browser does well</h2>
<p>The row data stays on the machine that opened the page. It is read there, edited there, and handed to your code from there. As of August 2026 Updog Importer makes a single call to us to check the license, and loading a file, editing, validating and exporting send nothing. We wrote up what vendors receive, and what to check before adding one, in <a href="https://updog.tech/blog/data-compliance-for-saas/">data compliance for SaaS</a>.</p>
<p>For the team adding the importer, that removes a step. A vendor that holds customer files gets reviewed as one, and the review asks where the data sits, who can open it, how long it stays and what deletes it. Those questions have no subject when no file arrives.</p>
<p>It also changes what a person can put through the importer. A file with salaries or customer records in it takes the same path as any other file, since it travels from their disk to your code and nowhere else.</p>
<h2 id="what-limits-a-client-side-import">What limits a client-side import</h2>
<p>Memory and processing speed set the limit. The memory is whatever the browser tab can hold. The speed is whatever a single core can get through, because parsing, sorting, filtering and validating all touch every row, and each of those runs in a worker on one thread. Small files finish fast, and large ones slow down as the row count climbs.</p>
<p>We built Updog Importer to take everything the browser and the machine will give. The limit that remains is theirs, and it is the same on every plan.</p>
<p>However, a million rows is a practical ceiling. On narrower files, fewer columns and no column filters, we have watched five million rows run fast. That is closer to curiosity than to a working number, and a million is the one we will stand behind for the files people import.</p>
<p>When an importer slows down in the tens of thousands of rows, the cost is in how it draws them. A DOM element carries layout and paint cost that a canvas pixel does not, so an importer built on an HTML table meets that ceiling wherever the parsing happens. The rows behind the table can still fit in memory and still be cheap to scan.</p>
<h2 id="which-mode-your-job-needs">Which mode your job needs</h2>
<p>Client-side and server-side are modes, and one product can sell both, so the choice belongs to the job. The numbers and modes, product by product, are in the <a href="https://updog.tech/blog/best-csv-importer-for-react/">roundup of CSV importers</a>.</p>
<p><strong>File size.</strong> How many rows do your files carry, and how many columns? A browser handles up to about a million rows. Past that the work moves to a server.</p>
<p><strong>Who starts the import.</strong> Does a person click Import, or does a system deliver a file on a schedule? A person in the loop works in both models, since a server-side importer shows a UI and does the processing behind it. Running with nobody there is the part only a server can do.</p>
<p><strong>Metered imports.</strong> Are you willing to pay by rows, file size and import count as your volume grows? That is how server-side products bill, and the bill follows your users' activity.</p>
<p>If none of those answers call for server processing, the choice comes down to price and to whether your users' data leaves their machine. Updog Importer is built for that case.</p>]]></content:encoded></item>
<item><title>How to Remember CSV Import Mappings Between Uploads</title><link>https://updog.tech/blog/remember-csv-import-mappings/</link><guid isPermaLink="true">https://updog.tech/blog/remember-csv-import-mappings/</guid><pubDate>Sun, 09 Aug 2026 00:00:00 GMT</pubDate><description>Updog hands back the header and value pairs a person fixed by hand. Store them, feed them back as synonyms, and the next import matches itself.</description><content:encoded><![CDATA[<p>A partner keeps sending the same employee export. Their header says <code>Work</code> where your field says <code>Company</code>, and their status column says <code>LOA</code> where your app says <code>On leave</code>. Someone on the customer side opens the importer, picks the right field from two dropdowns, and finishes. Later the same file arrives and the same two dropdowns are waiting for them.</p>
<p>A pair someone fixed once can come back the next time and land before anyone looks at the screen. Somebody has to keep those pairs from one import to the next.</p>
<h2 id="what-the-matching-engine-does-on-its-own">What the matching engine does on its own</h2>
<p>Updog scores every file header against every field in your schema. Both strings are normalized first, lowercased with spaces, underscores, hyphens and dots removed, so <code>First Name</code>, <code>first_name</code> and <code>firstname</code> are one string and score 100.</p>
<p>A pair listed in the synonym table scores 90. One string containing the other scores 80, provided the shorter one runs at least four characters. Half the words shared scores 70. A typo scores 65, where a typo means one edit for strings up to four characters and up to four edits past fifteen. Below 60 the header stays unmatched.</p>
<p>Columns match in two passes. Exact matches go first and reserve their field, then Updog sorts the remaining headers by their best score and lets each take what is left. A weaker guess never takes a field a confident header already claimed. Values run the same scoring against the options you allow in a select field.</p>
<p>Updog ships with a built-in table of common words. <code>fname</code> and <code>given name</code> reach <code>First name</code>, <code>dept</code> and <code>division</code> reach <code>Department</code>, <code>hire date</code> and <code>joining date</code> reach <code>Start date</code>. It carries value aliases too, <code>M</code> and <code>F</code>, <code>Jr</code> and <code>Sr</code>, <code>FT</code> and <code>PT</code>, <code>yes</code> and <code>no</code>.</p>
<p>A group scores 90 only when both strings fall into it. <code>fname</code> against <code>Department</code> stays at zero, and so does <code>dept</code> against <code>First name</code>.</p>
<p>That table stops where your industry invented a word. <code>Work</code> against <code>Company</code> scores zero on every tier. Neither string contains the other, they share no whole word, and their lengths differ by more than the typo allowance for strings that size. Somebody has to say what it means, once.</p>
<h2 id="where-the-memory-can-live">Where the memory can live</h2>
<p><strong>Nobody remembers.</strong> The importer scores each file from scratch and the person answers the same dropdown every time. Nothing to store, nothing to secure, and the work repeats for as long as that partner keeps sending files. Watch how many of your imports are the same file shape coming back.</p>
<p><strong>The vendor remembers.</strong> The importer keeps confirmed pairs on its own servers and applies them next time. Your users get memory and you write no code for it. Those pairs are headers out of their spreadsheets and words out of their cells, and from that day they live with a third party. Check that vendor the way you check any processor, with a data processing agreement, a named storage region, and a retention period you can point at.</p>
<p><strong>You remember.</strong> The importer hands those pairs back and accepts them as input on the next run. They go into your own database, beside the customer data you already hold, under the policy you already wrote. No new processor enters the picture, and the scope and the deletion rules stay yours. Decide where in your schema the table belongs before the first import ships.</p>
<p>Updog hands the pairs back and keeps none of them. As of August 2026 we run no server in the path of a file and hold no copy of anything a person imports, so a table on our side would contradict the whole design.</p>
<h2 id="what-updog-hands-back-after-an-import">What Updog hands back after an import</h2>
<p>Every <code>onComplete</code> result carries <code>learnedSynonyms</code>, split into <code>columns</code> and <code>values</code>. An entry is a source and a target. Source is the word the file used. Target is your column title, or the option value the person picked inside a select field.</p>
<pre><code class="language-ts">{
  columns: [
    { source: "Work", target: "Company" }
  ],
  values: [
    { source: "LOA", target: "On leave" },
    { source: "New hire", target: "Onboarding" }
  ]
}</code></pre>
<p>Updog keeps its own guess beside the finished mapping and hands back the difference. A pair the matcher filled in and the person left alone stays out, because next time the matcher fills it in again. A pair your <code>onColumnMatch</code> or <code>onValueMatch</code> returned stays out too, since that answer already lives in your code, in a rule you wrote or in <a href="https://updog.tech/blog/bring-your-own-ai/">your own model</a>.</p>
<p>Updog also drops a pair the built-in table or your own <code>synonyms</code> prop already covers, and a pair whose two strings normalize to the same thing, so <code>E-mail</code> against <code>Email</code> never becomes a row. What comes back is the pair someone picked by hand.</p>
<p>Updog takes the difference when the rows land in the grid, and the list reaches you on submit. An import someone cancels halfway teaches nothing.</p>
<p>The two lists go back in as two tables. A word learned inside a dropdown scores only against dropdown options, and a header alias scores only against your columns.</p>
<h2 id="the-round-trip-in-a-react-app">The round trip in a React app</h2>
<p>Take an employee schema with a <code>Company</code> field and a <code>Status</code> field with four options. The <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">React import guide</a> covers installing the package and wiring the first import.</p>
<pre><code class="language-ts">const columns = [
  { id: "firstName", title: "First name" },
  { id: "lastName", title: "Last name" },
  { id: "email", title: "Email" },
  { id: "company", title: "Company" },
  {
    id: "status",
    title: "Status",
    editor: {
      type: "select",
      options: ["Active", "Onboarding", "On leave", "Terminated"],
    },
  },
];</code></pre>
<p>A file lands with a <code>Work</code> header and the statuses <code>Active</code>, <code>LOA</code> and <code>New hire</code>. <code>Active</code> matches on its own. The other three score zero and wait for a person, who picks <code>Company</code>, <code>On leave</code> and <code>Onboarding</code>. Those three answers are what comes back in <code>learnedSynonyms</code>.</p>
<p>Post the object as it arrives and let your endpoint take it apart. It stores each pair with the table it came from, and it answers with the two tables keyed by target, which is the shape the <code>synonyms</code> prop takes.</p>
<pre><code class="language-tsx">import { useCallback, useEffect, useState } from "react";
import { DataEditor } from "@updog/data-editor";

export function ImportEmployees() {
  const [open, setOpen] = useState(false);
  const [synonyms, setSynonyms] = useState({ columns: {}, values: {} });

  useEffect(() => {
    fetch("/api/import-synonyms")
      .then((response) => response.json())
      .then(setSynonyms);
  }, []);

  const openImporter = useCallback(() => {
    setOpen(true);
  }, []);

  const closeImporter = useCallback(() => {
    setOpen(false);
  }, []);

  const onComplete = useCallback(async (result) => {
    const response = await fetch("/api/import-synonyms", {
      method: "POST",
      body: JSON.stringify(result.learnedSynonyms),
    });

    setSynonyms(await response.json());
    setOpen(false);
  }, []);

  return (
    &#x3C;>
      &#x3C;button onClick={openImporter}>Import employees&#x3C;/button>
      &#x3C;DataEditor
        apiKey="your-license-key"
        variant="uploader"
        open={open}
        onClose={closeImporter}
        columns={columns}
        primaryKey="email"
        synonyms={synonyms}
        onComplete={onComplete}
      />
    &#x3C;/>
  );
}</code></pre>
<p>The next file of that shape reaches the Match columns step with <code>Work</code> already on <code>Company</code>, and the Match values step with both statuses already picked, all three at the synonym tier. Updog reads <code>synonyms</code> when the importer mounts, so the new tables have to be in place before the next open. Closing the modal and opening it again is enough.</p>
<h2 id="what-lands-in-your-database">What lands in your database</h2>
<p>Those rows are user data. A source is a header someone typed into their spreadsheet, and on the value side it is a word out of their cells. Updog never sees the table, which leaves every decision about it with you.</p>
<p>Pick a scope. Per person keeps one user's answers to that one user. Per organization lets a team share what any of them fixed. Per partner feed fits a recurring file from the same sender.</p>
<p>Deduplicate on table, source and target as you write. A pair stops coming back once it reaches Updog through <code>synonyms</code>, and until then a second import of the same file teaches it again.</p>
<p>Decide what happens when someone maps one source to two different targets over time. Both pairs stay live, both score 90, and the field that wins is the one that comes first in your schema. Keeping the most recent answer per source is the simplest rule that stays predictable.</p>
<p>Value aliases carry no field of their own. The <code>values</code> table is keyed by the option value, so an alias learned inside one select field applies to every field offering the same option. Look at your schema for two fields that share option vocabulary and decide whether that suits you.</p>
<h2 id="when-you-do-not-need-this">When you do not need this</h2>
<p>A one-off migration has nothing to remember. A schema whose field names match the words the world already uses gets there on the built-in table alone, and adding storage buys nothing. A file that arrives once, from one person, is not worth a table either.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The partner will send <code>Work</code> again, and the matcher will put it on <code>Company</code> without asking. The engine handles the headers the world already shares, and a person answers the rest once. Those answers come back in <code>learnedSynonyms</code> on submit, go into your own table, and return through <code>synonyms</code> on the next open. The words your customers use stay yours, beside the customer data you already hold.</p>]]></content:encoded></item>
<item><title>How to Import a CSV File Into an Angular App With the Updog Importer</title><link>https://updog.tech/blog/how-to-import-csv-into-angular-app/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-csv-into-angular-app/</guid><pubDate>Sat, 08 Aug 2026 00:00:00 GMT</pubDate><description>Add CSV and Excel import to an Angular app. Register the custom element, define your schema, set up matching, and get clean rows back.</description><content:encoded><![CDATA[<p>An Angular app takes CSV and Excel files from its users with one custom element and a column schema. Import takes more than a parser. Read <a href="https://updog.tech/blog/csv-import-is-more-than-parsing/">CSV import is more than parsing a file</a> for the reasons.</p>
<p>You install the package, tell Angular about the element, describe your data, match the file to your schema, and read the result. The data is a product catalog with eight columns.</p>
<p><strong>Upload</strong> is when someone puts a file into the data editor. The file is read in the browser, and nothing has reached you yet. <strong>Import</strong> is the last step, when the cleaned rows land in your system. Everything between the two happens inside the editor, and that is where the messy data gets fixed.</p>
<p>Updog comes to Angular as a Web Component. You register the custom element once, then use it in templates like any other tag. The same package works in Vue, Svelte, and plain JavaScript. React has its own package. We measured every build number and reproduced every compiler message on Angular 21.2 with the <code>@angular/build</code> application builder, in August 2026.</p>
<h2 id="step-1-install-the-web-component">Step 1. Install the web component</h2>
<pre><code class="language-bash">npm install @updog/data-editor-wc</code></pre>
<p>The package is on npm as <a href="https://www.npmjs.com/package/@updog/data-editor-wc">@updog/data-editor-wc</a>. The module defines <code>&#x3C;updog-editor></code> globally. The stylesheet adds the styles. You need both.</p>
<h2 id="step-2-tell-angular-it-is-a-custom-element">Step 2. Tell Angular it is a custom element</h2>
<p>Angular resolves every tag in a template against the components you imported. It finds nothing named <code>updog-editor</code> and stops the build.</p>
<pre><code class="language-plaintext">NG8001: 'updog-editor' is not a known element:
1. If 'updog-editor' is an Angular component, then verify that it is
   included in the '@Component.imports' of this component.
2. If 'updog-editor' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA'
   to the '@Component.schemas' of this component to suppress this message.</code></pre>
<p>Add <code>CUSTOM_ELEMENTS_SCHEMA</code> to the <code>schemas</code> array of the component that renders the element, and Angular passes unknown tags through to the browser, where the custom element is waiting.</p>
<p>The stylesheet goes in the <code>styles</code> array in <code>angular.json</code>, ahead of your own global sheet, so your rules win where they overlap.</p>
<pre><code class="language-json">{
  "projects": {
    "catalog": {
      "architect": {
        "build": {
          "options": {
            "styles": [
              "@updog/data-editor-wc/styles.css",
              "src/styles.css"
            ]
          }
        }
      }
    }
  }
}</code></pre>
<p>The stylesheet is registered once for the app. The schema goes on every component that renders the element.</p>
<h2 id="step-3-mount-the-editor">Step 3. Mount the editor</h2>
<p>Put the element in your template, grab it with <code>viewChild</code>, and pass your configuration to <code>configure()</code>. The editor sits behind a button. Modal is the default mode, so <code>show()</code> opens the editor.</p>
<pre><code class="language-ts">import {
  ChangeDetectionStrategy,
  Component,
  CUSTOM_ELEMENTS_SCHEMA,
  ElementRef,
  effect,
  viewChild,
} from "@angular/core";
import "@updog/data-editor-wc";
import type {
  DataEditorResult,
  UpdogEditorElement,
} from "@updog/data-editor-wc";
import { columns } from "./columns";

@Component({
  selector: "app-importer",
  changeDetection: ChangeDetectionStrategy.OnPush,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `
    &#x3C;button type="button" (click)="open()">Import products&#x3C;/button>

    &#x3C;updog-editor
      #editor
      variant="uploader"
      (close)="editor.hide()"
    >&#x3C;/updog-editor>
  `,
})
export class ImporterComponent {
  private readonly editorRef =
    viewChild.required&#x3C;ElementRef&#x3C;UpdogEditorElement>>("editor");

  constructor() {
    effect(() => {
      this.editorRef().nativeElement.configure({
        apiKey: "your-license-key",
        columns,
        primaryKey: "sku",
        onComplete: (result: DataEditorResult) => {
          console.log(result);
          this.editorRef().nativeElement.hide();
        },
      });
    });
  }

  protected open(): void {
    this.editorRef().nativeElement.show();
  }
}</code></pre>
<p>The element exists once the view has rendered, and an <code>effect</code> runs after that, then again whenever a signal it reads changes. Configuration that comes from a signal input stays in sync on its own.</p>
<p>Set <code>variant</code> to <code>uploader</code> to open the upload wizard first, so the person starts by picking a file. The default <code>editor</code> variant opens the grid first, for data you already have. Sign up at <a href="https://console.updog.tech/">console.updog.tech</a> to get the <code>apiKey</code>. Updog is free on localhost and on the preview domains from hosts like Vercel and Netlify.</p>
<h2 id="step-4-pass-props-the-right-way">Step 4. Pass props the right way</h2>
<p>An HTML attribute carries a string. Everything the editor needs beyond strings and booleans travels as a JavaScript property.</p>
<h3 id="simple-values-can-be-attributes">Simple values can be attributes</h3>
<p>Eight props are primitives, so they work as plain HTML attributes. Five take a string value, <code>api-key</code>, <code>primary-key</code>, <code>variant</code>, <code>mode</code>, and <code>locale</code>. Three are boolean, <code>open</code>, <code>rtl</code>, and <code>readonly</code>, where the presence of the attribute means true.</p>
<pre><code class="language-html">&#x3C;updog-editor
  #editor
  api-key="your-license-key"
  primary-key="sku"
  variant="uploader"
>&#x3C;/updog-editor></code></pre>
<p>Angular property binding reaches the same values under their camelCase names. <code>open</code> controls the modal, and setting it does the same work as <code>show()</code> and <code>hide()</code>. Bind it to a signal and the modal state lives with the rest of your component state.</p>
<pre><code class="language-html">&#x3C;updog-editor #editor variant="uploader" [open]="isOpen()">&#x3C;/updog-editor></code></pre>
<h3 id="inline-mode-replaces-the-modal">Inline mode replaces the modal</h3>
<p><code>mode</code> picks where the editor renders. The default is <code>modal</code>. Use <code>mode="inline"</code> to render the editor in place, as part of your page.</p>
<pre><code class="language-html">&#x3C;updog-editor #editor variant="uploader" mode="inline">&#x3C;/updog-editor></code></pre>
<p>Inline mode has no modal, so the modal API does nothing. <code>show()</code> and <code>hide()</code> return without an effect, and the element sends no <code>close</code> event. Remove the button and the listener from step 3, then give the element the space it should fill.</p>
<h3 id="everything-else-goes-through-configure">Everything else goes through configure</h3>
<p>Columns, callbacks, translations, remote sources, and every other object or function go through <code>configure()</code>. It takes any number of props at once and applies them in one render.</p>
<p>Callbacks have no template form. Angular reserves property names that start with <code>on</code> for DOM event handlers, and it refuses to bind one.</p>
<pre><code class="language-html">&#x3C;!-- wrong: the build stops here -->
&#x3C;updog-editor [onComplete]="save">&#x3C;/updog-editor></code></pre>
<pre><code class="language-plaintext">NG8002: Binding to event property 'onComplete' is disallowed for
security reasons, please use (Complete)=...</code></pre>
<p>The suggested <code>(Complete)</code> event does not exist, so ignore that half of the message and move the callback into <code>configure()</code>, along with <code>onError</code>, <code>onColumnMatch</code>, and <code>onValueMatch</code>.</p>
<h3 id="closing-is-an-event">Closing is an event</h3>
<p>There is no <code>onClose</code> prop. The element sends a real <code>close</code> event, which Angular binds like any other. A template reference variable on the element points at the element itself, so <code>(close)="editor.hide()"</code> in step 3 closes the modal without a listener to register or remove.</p>
<h2 id="step-5-describe-your-data">Step 5. Describe your data</h2>
<p>The <code>columns</code> array describes the shape your app expects. Updog changes every uploaded file to match it. More detail here means less manual fixing later.</p>
<h3 id="start-with-the-columns">Start with the columns</h3>
<p>Each column needs an <code>id</code> and a <code>title</code>. The <code>id</code> matches the key in your row data. The <code>title</code> is the text people see. <code>size</code> is optional. Add it in pixels to make a column wider or narrower.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor-wc";

export const columns: DataEditorColumn[] = [
  {
    id: "sku",
    title: "SKU",
    size: 140,
  },
  {
    id: "name",
    title: "Product name",
    size: 240,
  },
  {
    id: "category",
    title: "Category",
    size: 160,
  },
  {
    id: "price",
    title: "Price",
    size: 120,
  },
  {
    id: "stock",
    title: "In stock",
    size: 120,
  },
  {
    id: "releasedOn",
    title: "Released on",
    size: 140,
  },
  {
    id: "tags",
    title: "Tags",
    size: 220,
  },
  {
    id: "status",
    title: "Status",
    size: 140,
  },
];</code></pre>
<h3 id="choose-an-editor-for-each-column">Choose an editor for each column</h3>
<p>Text is the default, so the SKU and name columns need nothing. Use <code>select</code> for the category, <code>number</code> for price and stock, <code>date</code> for the release date, and <code>multiselect</code> for tags. An editor sets what people can type. For <code>select</code> and <code>multiselect</code> it also gives the matching step a list of values to match against.</p>
<pre><code class="language-ts">{
  id: "category",
  title: "Category",
  size: 160,
  editor: {
    type: "select",
    options: ["Laptops", "Monitors", "Keyboards", "Cables"],
  },
},
{
  id: "price",
  title: "Price",
  size: 120,
  editor: {
    type: "number",
  },
},
{
  id: "releasedOn",
  title: "Released on",
  size: 140,
  editor: {
    type: "date",
  },
},
{
  id: "tags",
  title: "Tags",
  size: 220,
  editor: {
    type: "multiselect",
    options: ["Sale", "New", "Refurbished", "Bundle"],
  },
},</code></pre>
<h3 id="add-the-rules">Add the rules</h3>
<p>Validators run on every edit. The grid highlights a value that fails. The full schema puts editors and validators on the same columns.</p>
<pre><code class="language-ts">const STATUSES = ["Draft", "Active", "Discontinued"];

export const columns: DataEditorColumn[] = [
  {
    id: "sku",
    title: "SKU",
    size: 140,
    validators: [
      { type: "required", message: "SKU is required" },
      { type: "unique" },
    ],
  },
  {
    id: "name",
    title: "Product name",
    size: 240,
    validators: [{ type: "required", message: "Product name is required" }],
  },
  {
    id: "category",
    title: "Category",
    size: 160,
    editor: {
      type: "select",
      options: ["Laptops", "Monitors", "Keyboards", "Cables"],
    },
  },
  {
    id: "price",
    title: "Price",
    size: 120,
    editor: { type: "number" },
    validators: [
      {
        type: "number",
        min: 0,
        decimalPlaces: 2,
        message: "Price must be zero or greater",
      },
    ],
  },
  {
    id: "stock",
    title: "In stock",
    size: 120,
    editor: { type: "number" },
    validators: [{ type: "number", decimalPlaces: 0 }],
  },
  {
    id: "releasedOn",
    title: "Released on",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "date", message: "Enter a valid date" }],
  },
  {
    id: "tags",
    title: "Tags",
    size: 220,
    editor: {
      type: "multiselect",
      options: ["Sale", "New", "Refurbished", "Bundle"],
    },
  },
  {
    id: "status",
    title: "Status",
    size: 140,
    editor: { type: "select", options: STATUSES },
    validators: [
      {
        type: "oneOf",
        values: STATUSES,
        message: "Select a status from the list",
      },
    ],
  },
];</code></pre>
<p>SKU uses <code>required</code> and <code>unique</code>, which flags the second row that repeats a code. Price uses a <code>number</code> check that rejects anything below zero. Status uses <code>oneOf</code> against the same list its dropdown offers, which catches a value that slips past matching. A failed rule marks the cell. It does not block submission by default. Invalid rows still reach you with the <code>isValid</code> flag. Set <a href="https://docs.updog.tech/api-reference/core-props/#blocksubmitonerror"><code>blockSubmitOnError</code></a> to hold submission until every error is fixed.</p>
<p>Those are all built-in rules, declarative objects that Updog ships with. There are seven, <code>required</code>, <code>regex</code>, <code>oneOf</code>, <code>number</code>, <code>email</code>, <code>date</code>, and <code>unique</code>.</p>
<p>For logic no built-in covers, a <code>function</code> rule takes your own function. It receives the cell value and the whole row, and returns an error or <code>null</code>. Pair it with <code>dependentFields</code> to revalidate a column when another column changes. A discount price that has to stay under the list price needs one.</p>
<p>For a check against your own backend, an <code>asyncFunction</code> rule receives every affected cell in one batch and reports failures as they arrive. Async rules run after all the sync ones, so a value reaches your server only after it passes the format checks. The <a href="https://docs.updog.tech/api-reference/columns/#validators">columns reference</a> covers all three.</p>
<h3 id="fix-common-errors-before-anyone-sees-them">Fix common errors before anyone sees them</h3>
<p>A validator flags a bad value. A <code>transformer</code> fixes it first. Add one to a column, and Updog runs it on each cell as the uploaded file is turned into rows, before anyone sees the grid. Use it to trim spaces, upper-case a product code, or drop a currency symbol.</p>
<pre><code class="language-ts">{
  id: "sku",
  title: "SKU",
  size: 140,
  transformer: (value) => {
    return String(value).trim().toUpperCase();
  },
},</code></pre>
<h3 id="shape-how-columns-show-and-filter">Shape how columns show and filter</h3>
<p>A <code>formatter</code> changes how a value looks on the grid, and the stored value stays the same. Price can show a <code>$</code> while the number underneath stays clean. A <code>filter</code> adds a control to the sidebar.</p>
<pre><code class="language-ts">{
  id: "price",
  title: "Price",
  size: 120,
  formatter: (value) => {
    return value ? "$" + value : "";
  },
  filter: {
    type: "number-range",
    label: "Price",
  },
},</code></pre>
<h2 id="step-6-help-updog-match-the-file">Step 6. Help Updog match the file</h2>
<p>A file rarely matches your schema word for word. Updog runs fuzzy matching first and catches small differences on its own, like extra spaces, different capitalization, or a common alternate spelling. Your data may also use terms it cannot guess, such as an internal code or a word from your industry. For those you add your own dictionary.</p>
<h3 id="match-the-columns">Match the columns</h3>
<p>A warehouse export of this catalog arrived with the headers <code>Item Code</code>, <code>Title</code>, <code>Group</code>, <code>Cost</code>, <code>Qty</code>, <code>Launch</code>, <code>Labels</code>, and <code>State</code>. Built-in matching paired one of the eight. List the headers your users send in the <code>columns</code> table of <code>synonyms</code>, and the same file arrives fully mapped.</p>
<pre><code class="language-ts">this.editorRef().nativeElement.configure({
  synonyms: {
    columns: {
      sku: ["item code", "article number", "part no"],
      name: ["title", "product title", "item name"],
      category: ["group", "product group", "product line"],
      price: ["cost", "unit price", "list price"],
      stock: ["qty", "quantity", "on hand"],
      releasedOn: ["launch", "launch date", "release date"],
      tags: ["labels"],
      status: ["state", "product status"],
    },
  },
});</code></pre>
<p>For a header no list catches, pass the decision to your own model through <code>onColumnMatch</code>. Updog gives it the file headers and your columns. You return a map of which goes where.</p>
<pre><code class="language-ts">this.editorRef().nativeElement.configure({
  onColumnMatch: async (headers, columns) => {
    // headers = ["Item Code", "Group", ...] from the file
    // columns = your sku, name, category, ... schema
    const map = await askYourModel(headers, columns);
    return map; // { "Item Code": "sku", Group: "category" }
  },
});</code></pre>
<p>See <a href="https://updog.tech/blog/bring-your-own-ai/">bring your own AI to CSV and Excel import</a> for that path and how the data stays private.</p>
<h3 id="match-the-values">Match the values</h3>
<p>The same works inside the status column. A file can send <code>eol</code> and <code>retired</code> for the status <code>Discontinued</code>. Value aliases go in the <code>values</code> table, keyed by the option, with the array listing what maps to it. The two tables stay apart, so a word learned inside a dropdown never competes for a column.</p>
<p>One object holds both tables, so write it once. A second <code>configure()</code> call with a new <code>synonyms</code> object replaces the first one, and your column aliases disappear without a warning.</p>
<pre><code class="language-ts">this.editorRef().nativeElement.configure({
  synonyms: {
    columns: {
      sku: ["item code", "article number", "part no"],
      status: ["state", "product status"],
    },
    values: {
      Discontinued: ["eol", "end of life", "retired"],
      Refurbished: ["refurb", "renewed"],
    },
  },
});</code></pre>
<p>For values no list covers, <code>onValueMatch</code> works the same way one level down. Updog gives you the values found in each select column and the options you allow. You return the mapping.</p>
<pre><code class="language-ts">this.editorRef().nativeElement.configure({
  onValueMatch: async (valuesToMatch) => {
    // { status: { importedValues: ["eol"], options: [...] } }
    const map = await askYourModel(valuesToMatch);
    return map; // { status: { eol: "Discontinued" } }
  },
});</code></pre>
<h2 id="step-7-import-the-result-into-your-system">Step 7. Import the result into your system</h2>
<p>Everything before this step happened in the browser, and nothing has left the page yet.</p>
<p>When the person is done cleaning the data, Updog passes it to <code>onComplete</code>, grouped by source. Each row carries four flags, <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code>. Routing depends on your backend, so Updog leaves it to you. Filter on the flags and send each row where it belongs.</p>
<pre><code class="language-ts">import type { DataEditorResult } from "@updog/data-editor-wc";

export class ImporterComponent {
  protected readonly imported = signal(0);

  constructor() {
    effect(() => {
      this.editorRef().nativeElement.configure({
        onComplete: async (result: DataEditorResult) => {
          for (const source of result.sources) {
            const inserts = source.rows.filter((row) => {
              return row.isNew &#x26;&#x26; !row.isDeleted &#x26;&#x26; row.isValid;
            });

            const updates = source.rows.filter((row) => {
              return (
                !row.isNew &#x26;&#x26;
                row.isChanged &#x26;&#x26;
                !row.isDeleted &#x26;&#x26;
                row.isValid
              );
            });

            await saveProducts(inserts, updates);
            this.imported.update((count) => count + inserts.length);
          }

          this.editorRef().nativeElement.hide();
        },
      });
    });
  }
}</code></pre>
<p>A modern Angular app renders when something notifies it, and a signal write, a template event binding, and an async pipe all do. The editor calls <code>onComplete</code> from its own render tree, outside every one of them. Assign the imported count to a plain field there and the field holds the new number while the screen keeps showing the old one. Write it into a signal and the view catches up. An <code>output()</code> that a parent template listens to works too, since Angular runs change detection around its own listeners.</p>
<p>Rows arrive keyed by your column IDs, typed as <code>Record&#x3C;string, unknown></code>. The custom element takes no generic parameter. Cast to your own row type here if you want one.</p>
<h2 id="step-8-localize-it">Step 8. Localize it</h2>
<p>Three props control language and layout, and each does one job.</p>
<pre><code class="language-ts">this.editorRef().nativeElement.configure({
  translations: arabicTranslations, // changes the language
  locale: "ar",                     // picks Arabic plural forms
  rtl: true,                        // flips the layout
});</code></pre>
<p><code>translations</code> is the prop that changes the language. Pass an object with the strings you override. Only the keys you provide are replaced.</p>
<p><code>locale</code> takes a BCP 47 tag and selects the plural form for keys that end in <code>_one</code>, <code>_few</code>, <code>_many</code>, or <code>_other</code>. That is its only job. It loads no translations, and on its own it leaves the UI in English. Set it when your language pluralizes differently from English. Arabic has six forms, Russian has three.</p>
<p><code>rtl</code> flips the layout for Arabic, Hebrew, and other right-to-left languages. It changes grid direction, text alignment, and scrollbar position, and it reverses the column order in exported files.</p>
<p>Copy the defaults object from the <a href="https://docs.updog.tech/localization/#defaults">localization docs</a>, paste it into your AI, and ask it to translate the values.</p>
<h2 id="style-it-to-match-your-app">Style it to match your app</h2>
<p>The editor renders in the light DOM, so your CSS can reach it. Angular rewrites <code>.updog-button</code> in a component stylesheet into <code>.updog-button[_ngcontent-ng-c123456]</code>, and it stamps that attribute on the elements it renders itself. The editor builds its own DOM without one, so the rule matches nothing. The modal sits further out still, at the end of <code>document.body</code>, where even <code>:host ::ng-deep</code> stops at the component boundary and misses it.</p>
<p>Global styles reach everything. Put your editor rules in <code>src/styles.css</code>, next to the editor stylesheet you registered in step 2.</p>
<pre><code class="language-css">/* importer.component.css: never reaches the editor. */
.updog-button {
  border-radius: 0;
}

/* src/styles.css: does. */
.updog-button {
  border-radius: 0;
}</code></pre>
<p>A selector that starts with <code>::ng-deep</code> compiles down to that same global rule and works too, with the catch that it applies everywhere in the app from the moment the component loads.</p>
<p>Colors come from CSS variables. Fonts come from your page. If your app sets no font, the editor uses the browser default, so set one on the element or on your app.</p>
<pre><code class="language-css">updog-editor {
  font-family: "Inter", system-ui, sans-serif;
  --updog-grid-cell-bg-idle: #ffffff;
  --updog-grid-header-bg-idle: #f8f9fa;
}</code></pre>
<p>For the full variable list, see the <a href="https://docs.updog.tech/styling/">styling reference</a>. There is a longer walkthrough in <a href="https://updog.tech/blog/style-updog-to-match-your-product/">style Updog to match your product</a>.</p>
<h2 id="what-it-costs-and-how-to-pay-less">What it costs, and how to pay less</h2>
<p>The web component carries its own copy of React and the engine that reads Excel files. The same Angular app weighs three different amounts, depending on where that import sits. Every number is after Brotli compression.</p>
<div class="blog-table blog-table--narrow"><table><thead><tr><th>Build</th><th>First load</th></tr></thead><tbody><tr><td>Angular on its own</td><td>28 KB</td></tr><tr><td>Updog imported in the component</td><td>500 KB</td></tr><tr><td>Updog behind <code>@defer</code></td><td>52 KB</td></tr></tbody></table></div>
<p>A new Angular workspace sets a bundle budget of 500 kB for a warning and 1 MB for an error, counted before compression. The eager build weighs 2.11 MB there, so <code>ng build</code> reports a failure and writes nothing. Raising the budget clears the message and leaves every visitor downloading the importer.</p>
<p>React accounts for about a tenth of that weight. The spreadsheet engine takes most of the rest, and the single-file build cannot split it out.</p>
<p>The editor runs inside your page as a single custom element, and that is what the weight buys. The usual alternative is an iframe, where the code lives somewhere else and the cost moves instead of going away. Your CSS and your fonts stop at the frame boundary. The frame clips dropdowns and modals instead of letting them float over your layout. Focus and scrolling need their own handling. Every row of data crosses a <code>postMessage</code> protocol, and you maintain that protocol.</p>
<p>An importer opens when someone clicks a button, so it does not belong in your first bundle. Wrap the component in <code>@defer</code>, and Angular moves it and its imports into a chunk that downloads on the first click.</p>
<pre><code class="language-ts">import { ChangeDetectionStrategy, Component, signal } from "@angular/core";
import { ImporterComponent } from "./importer/importer.component";

@Component({
  selector: "app-catalog",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ImporterComponent],
  template: `
    &#x3C;button type="button" (click)="wanted.set(true)">
      Import products
    &#x3C;/button>

    @defer (when wanted()) {
      &#x3C;app-importer />
    }
  `,
})
export class CatalogComponent {
  protected readonly wanted = signal(false);
}</code></pre>
<p>The importer component from step 3 stays as it is. The parent decides when it loads, the initial bundle drops to 52 KB, and the 453 KB chunk goes out to the people who ask for it. The development server hides this while you work, because hot module replacement loads every <code>@defer</code> dependency eagerly and logs <code>NG0751</code> to say so. Run <code>ng build</code> to see the real split.</p>
<h2 id="angular-on-the-server">Angular on the server</h2>
<p>The editor's module calls <code>customElements.define</code> the moment it loads, and an app with <code>@angular/ssr</code> loads your components in Node first, to walk the routes. A plain import brings the whole build down there.</p>
<pre><code class="language-plaintext">An error occurred while extracting routes.

ReferenceError: customElements is not defined
    at file:///.angular/prerender-root/main.server.mjs</code></pre>
<p><code>@defer</code> solves this too. Angular puts the deferred block behind a dynamic import that the server never reaches, route extraction finishes, and the page prerenders. The button ships in the HTML, and the editor arrives in the browser when someone clicks it.</p>
<p>A schema, a custom element, and a <code>@defer</code> block are the whole integration. The file the person picks stays in their browser the entire time, and what reaches you at the end is clean rows.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Amazon S3</title><link>https://updog.tech/blog/import-csv-into-s3/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-s3/</guid><pubDate>Fri, 07 Aug 2026 00:00:00 GMT</pubDate><description>Match a field trial export in the browser, then write the clean rows into S3 from your own route with PutObject and a conditional write that lands once.</description><content:encoded><![CDATA[<p>Amazon S3 documents several ways to move a CSV into a bucket. The console takes a file by drag and drop, and its own page caps that at 160 GB. The AWS CLI and the SDKs send "a single object up to 5 GB in size" in one <code>PUT</code>, and multipart carries one object to 50 TB. AWS Transfer Family answers SFTP, FTPS and FTP straight into the same bucket. Each one starts from a seat that already holds AWS credentials. Your customer sits outside that seat, holding the harvest export a research station emailed over last night.</p>
<h2 id="what-s3-checks">What S3 checks</h2>
<p>Nothing about the bytes. There is no schema on a bucket, no column type, no constraint and no unique index. A CSV with a missing field, a stray line break or a date in the wrong century arrives with a <code>200 OK</code> and stays.</p>
<p>Two things are checked, and both are worth building on.</p>
<p><strong>The key.</strong> An object key is "the unique identifier for an object within a bucket", up to 1,024 bytes of UTF-8. AWS lists the characters that are safe in one, and lists the ones it recommends against.</p>
<p><strong>The precondition.</strong> Send <code>If-None-Match</code> with the <code>*</code> value and S3 refuses to write over an object that already exists, answering <code>412 Precondition Failed</code>.</p>
<p>What S3 declines to offer matters as much. "Updates are key-based. There is no way to make atomic updates across keys." An import spread over several objects has no transaction behind it, so the batch needs a shape of its own.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>A seed company runs variety trials through contract research stations. Each station sends one export at the end of the season.</p>
<p><code>wgn-2026-harvest.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Plot</td><td class="sheet__cell">Site</td><td class="sheet__cell">Cultivar</td><td class="sheet__cell">Harvest Date</td><td class="sheet__cell">Yield (t/ha)</td><td class="sheet__cell">Moisture %</td><td class="sheet__cell">Fungicide</td><td class="sheet__cell">Notes</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">TR-2026-0148</td><td class="sheet__cell">Wageningen (NL) #2</td><td class="sheet__cell">Belmonte</td><td class="sheet__cell">14/05/2026</td><td class="sheet__cell">9,84</td><td class="sheet__cell">14,2 %</td><td class="sheet__cell">Untreated</td><td class="sheet__cell">Lodging on the north edge</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">TR-2026-0149</td><td class="sheet__cell">Wageningen (NL) #2</td><td class="sheet__cell">KWS Extase</td><td class="sheet__cell">21/10/2026</td><td class="sheet__cell">10,20</td><td class="sheet__cell">13,9 %</td><td class="sheet__cell">standard</td><td class="sheet__cell">Sprayed late,
weather delay</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">TR-2026-0150</td><td class="sheet__cell">Wageningen NL 2</td><td class="sheet__cell">Belmonte</td><td class="sheet__cell">03/09/2026</td><td class="sheet__cell"></td><td class="sheet__cell">15,1 %</td><td class="sheet__cell">Enhanced Fungicide</td><td class="sheet__cell">Yield sheet missing</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">TR-2026-0151</td><td class="sheet__cell">Rothamsted (UK) #1</td><td class="sheet__cell">Champion</td><td class="sheet__cell">21/10/2026</td><td class="sheet__cell">8,70</td><td class="sheet__cell">12,8 %</td><td class="sheet__cell">none</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">91 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">97</th><td class="sheet__cell">TR-2026-0243</td><td class="sheet__cell">Rothamsted (UK) #1</td><td class="sheet__cell">KWS Extase</td><td class="sheet__cell">29/10/2026</td><td class="sheet__cell">9,15</td><td class="sheet__cell">13,4 %</td><td class="sheet__cell">standard</td><td class="sheet__cell"></td></tr></tbody></table>
<p>The header row says <code>Cultivar</code> where the company says variety, and <code>Fungicide</code> where it says treatment. One station appears as <code>Wageningen (NL) #2</code> on three rows and <code>Wageningen NL 2</code> on the fourth. Dates run day first. One yield cell is empty, and one notes cell carries a line break inside its quotes.</p>
<p>The person drags the file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, holds the sites and treatments to your lists, and puts every row in front of them. Your <code>onComplete</code> handler posts the clean rows to a route you own. That route writes them into the bucket as objects.</p>
<p>No Updog server stands between the browser and S3.</p>
<h2 id="the-layout-in-the-bucket">The layout in the bucket</h2>
<p>S3 stores no folders. "The Amazon S3 data model is a flat structure", and the tree the console draws comes from prefixes and the <code>/</code> delimiter inside key names. So the layout is a naming decision, and it is the closest thing this destination has to a schema.</p>
<pre><code class="language-plaintext">s3://acme-trials/
  harvest/
    season=2026/
      site=NL-WGN-02/
        batch=9f2c1e84-7d3a-4c11-b0a6-2e5f7c9d1b40/
          part-0001.csv
          part-0002.csv
      site=UK-RTH-01/
        batch=9f2c1e84-7d3a-4c11-b0a6-2e5f7c9d1b40/
          part-0001.csv
  _batches/
    season=2026/
      9f2c1e84-7d3a-4c11-b0a6-2e5f7c9d1b40.json</code></pre>
<p>One import becomes one batch id, and every object it writes carries that id in its key. The parts sit under the season and the site, which is what lets a query engine read one station's 2026 harvest without touching anything else. The manifest sits outside the prefix the table reads, so nothing has to explain a JSON file to a CSV table.</p>
<p>Splitting one import across several keys costs nothing here. S3 handles "at least 3,500 PUT/COPY/POST/DELETE or 5,500 GET/HEAD requests per second per partitioned Amazon S3 prefix", and there are no limits on the number of prefixes in a bucket. Rows destined for a warehouse take a different road, and <a href="https://updog.tech/blog/import-csv-into-redshift/">importing a CSV into Amazon Redshift</a> shows that one.</p>
<h2 id="the-value-that-becomes-part-of-the-key">The value that becomes part of the key</h2>
<p><code>Wageningen (NL) #2</code> is a site name in a spreadsheet. It is also, one step later, a piece of a path. It carries a space, which AWS lists among the characters that "might require additional code handling", and a pound sign, which sits in the list AWS recommends against "because of significant special character handling, which isn't consistent across all applications".</p>
<p>S3 would take it. Every tool that reads the bucket afterwards is the thing at risk.</p>
<p>So the site column is a closed list of station codes, and the messy spellings reach those codes through value matching. <code>NL-WGN-02</code> holds only characters from the safe set, and both spellings in the file arrive at it. The route checks the code against a pattern a second time before it builds a key, since a value from a browser is a value from a browser.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array carries the shape the bucket will hold.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const SITES = ["NL-WGN-02", "UK-RTH-01", "FR-CLF-03"];
const TREATMENTS = ["Untreated", "Standard fungicide", "Enhanced fungicide"];

export const columns: DataEditorColumn[] = [
  {
    id: "plotRef",
    title: "Plot reference",
    size: 160,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^TR-\\d{4}-\\d{4}$" },
      { type: "unique" },
    ],
  },
  {
    id: "site",
    title: "Trial site",
    size: 150,
    editor: { type: "select", options: SITES, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: SITES }],
  },
  {
    id: "variety",
    title: "Variety",
    size: 160,
    validators: [{ type: "required" }],
  },
  {
    id: "harvestedOn",
    title: "Harvest date",
    size: 150,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "yieldTHa",
    title: "Yield",
    size: 120,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, max: 30, decimalPlaces: 2 },
    ],
  },
  {
    id: "moisturePct",
    title: "Moisture at harvest",
    size: 180,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, max: 100, decimalPlaces: 1 },
    ],
  },
  {
    id: "treatment",
    title: "Treatment",
    size: 190,
    editor: { type: "select", options: TREATMENTS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: TREATMENTS }],
  },
  {
    id: "notes",
    title: "Notes",
    size: 260,
    transformer: (value) =>
      String(value ?? "").replace(/[\r\n]+/g, " ").trim(),
  },
];</code></pre>
<p>Two rules exist because of what reads the object later, and the section below names the pages they come from. <code>required</code> on both numeric columns keeps an empty cell out of a numeric column in the table. The <code>transformer</code> on <code>notes</code> collapses any line break the station left inside a quoted field.</p>
<p>The rest guard the key and the lists. The <code>regex</code> holds the plot reference to one shape, <code>unique</code> catches the same plot twice in one file, and the two <code>select</code> editors with <code>enableCustomValue: false</code> refuse anything outside the station codes and the treatment names.</p>
<h2 id="the-headers-the-station-sends">The headers the station sends</h2>
<p>Updog scores each header against the column id and the column title, and the higher score wins.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Plot</code></td>
<td><code>plotRef</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Site</code></td>
<td><code>site</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Cultivar</code></td>
<td><code>variety</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Harvest Date</code></td>
<td><code>harvestedOn</code></td>
<td>exact against the title, 100</td>
</tr>
<tr>
<td><code>Yield (t/ha)</code></td>
<td><code>yieldTHa</code></td>
<td>contains against the title, 80</td>
</tr>
<tr>
<td><code>Moisture %</code></td>
<td><code>moisturePct</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Fungicide</code></td>
<td><code>treatment</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Notes</code></td>
<td><code>notes</code></td>
<td>exact, 100</td>
</tr>
</tbody>
</table></div>
<p><code>Harvest Date</code> is the one to watch. Against the column id <code>harvestedOn</code> it scores nothing, since the two share no whole word and sit too far apart for the edit-distance tier. Against the column title "Harvest date" it normalizes to the same string and lands at a hundred.</p>
<p><code>Cultivar</code> and <code>Fungicide</code> reach nothing on their own. Neither shares a word with the column it belongs to, and no built-in group carries either. Both are one line each in the <code>synonyms</code> block below.</p>
<p>Values follow the same ladder. <code>Enhanced Fungicide</code> normalizes onto the option. <code>standard</code> is contained by <code>Standard fungicide</code>. <code>none</code> and the two site spellings are spelled out in the mount.</p>
<p>The file settles its own dates. <code>14/05/2026</code> on the first row carries a value above twelve in the first position, so the scan stops there and reads the whole file day first, and <code>21/10/2026</code> and <code>03/09/2026</code> follow. The numbers work the other way. Each of <code>9,84</code> and <code>14,2 %</code> carries one separator, so each one is a vote, and the majority settles the file as European.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the file, the schema and the bucket together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;TrialRow>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="plotRef"
  blockSubmitOnError
  remoteSources={lastSeason}
  synonyms={{
    columns: {
      variety: ["cultivar", "line"],
      treatment: ["fungicide", "spray programme"],
    },
    values: {
      "NL-WGN-02": ["wageningen (nl) #2", "wageningen nl 2", "wgn2"],
      "UK-RTH-01": ["rothamsted (uk) #1", "rothamsted 1"],
      Untreated: ["none", "nil", "control"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> is the plot reference. Its work here is identity inside the import, because the destination answers no question about what it already holds. S3 lists keys and returns objects. Asking whether plot <code>TR-2026-0148</code> is in the lake means reading objects back through a query engine, so this import loads nothing and every row arrives new.</p>
<p><code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, which is what keeps the empty yield on row three out of the bucket. Whatever the person fixes by hand comes back as <code>learnedSynonyms</code>, ready to store and feed through <code>synonyms</code> next season.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="last-seasons-object-back-in-the-grid">Last season's object, back in the grid</h2>
<p>The bucket is where last season's export already sits, so the upload step can offer it as a starting point. <code>remoteSources</code> renders a button and hands you the fetch.</p>
<pre><code class="language-tsx">const lastSeason = useMemo(() => [
  {
    id: "last-season",
    label: "Last season",
    icon: "&#x3C;svg>...&#x3C;/svg>",
    description: "Open the 2025 harvest file for this site",
    fetch: async () => {
      const answer = await fetch("/api/trials/last-season");
      if (!answer.ok) throw new Error("That season is not in the bucket yet");
      const body = await answer.blob();
      return new File([body], "wgn-2025-harvest.csv", { type: "text/csv" });
    },
  },
], []);</code></pre>
<p>Return a <code>File</code> and it walks the ordinary parse path, header matching and all. Return an array of records and the SDK stages them without parsing. A throw becomes an error message on the upload step, and the person picks a file instead.</p>
<p>The bytes come through your own route, which reads the object and streams it back inside the session your app already issued. Nothing about AWS reaches the browser.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying four independent flags.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 2000;

const toRow = (entry: ResultRow&#x3C;TrialRow>) => ({
  plotRef: entry.row.plotRef,
  site: entry.row.site,
  variety: entry.row.variety,
  harvestedOn: entry.row.harvestedOn,
  yieldTHa: Number(entry.row.yieldTHa),
  moisturePct: Number(entry.row.moisturePct),
  treatment: entry.row.treatment,
  notes: entry.row.notes ?? "",
});

const onComplete = useCallback(async (result: DataEditorResult&#x3C;TrialRow>) => {
  const batchId = crypto.randomUUID();
  const rows = result.sources.flatMap((source) =>
    source.rows.filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted).map(toRow),
  );

  let part = 0;
  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    part += 1;
    const answer = await fetch("/api/trials/parts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        batchId,
        part,
        rows: rows.slice(start, start + CHUNK_SIZE),
      }),
    });
    if (!answer.ok) throw new Error((await answer.json()).message);
  }

  const closed = await fetch("/api/trials/complete", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ batchId, parts: part, rows: rows.length }),
  });
  if (!closed.ok) throw new Error((await closed.json()).message);

  await storeSynonyms(result.learnedSynonyms);
}, []);</code></pre>
<p>Only valid rows travel, since a row S3 accepts is a row somebody has to find again later. The handler mints one batch id, posts the rows in chunks, then calls a second endpoint that closes the batch.</p>
<p>The chunk size is yours. S3 publishes no row count, and the numbers that bound it sit at the two ends. A single <code>PUT</code> carries up to 5 GB, AWS suggests multipart "when your object size reaches 100 MB", and your own endpoint accepts whatever body it accepts. Two thousand rows is a number chosen against that endpoint.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the whole season clears the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it.</p>
<h2 id="the-route-that-writes-the-object">The route that writes the object</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";

const s3 = new S3Client({});
const BUCKET = process.env.TRIALS_BUCKET;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const SITE = /^[A-Z]{2}-[A-Z]{3}-\d{2}$/;

const FIELDS = ["plotRef", "variety", "harvestedOn", "yieldTHa",
  "moisturePct", "treatment", "notes"];
const HEADER = "plot_ref,variety,harvested_on,yield_t_ha," +
  "moisture_pct,treatment,notes";

const cell = (value) => '"' + String(value ?? "").replaceAll('"', '""') + '"';
const toCsv = (rows) => [HEADER]
  .concat(rows.map((row) => FIELDS.map((f) => cell(row[f])).join(",")))
  .join("\n") + "\n";

app.post("/api/trials/parts", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const { batchId, part, rows } = request.body;
  if (!UUID.test(batchId)) {
    return response.status(400).json({ message: "Bad batch id" });
  }
  if (!Number.isInteger(part) || part &#x3C; 1 || part > 9999) {
    return response.status(400).json({ message: "Bad part number" });
  }

  const bySite = new Map();
  for (const row of rows) {
    if (!SITE.test(row.site) || !session.sites.includes(row.site)) {
      return response.status(403).json({ message: "Unknown trial site" });
    }
    bySite.set(row.site, (bySite.get(row.site) ?? []).concat(row));
  }

  for (const [site, siteRows] of bySite) {
    const key = "harvest/season=" + session.season + "/site=" + site +
      "/batch=" + batchId + "/part-" + String(part).padStart(4, "0") + ".csv";
    try {
      await s3.send(new PutObjectCommand({
        Bucket: BUCKET,
        Key: key,
        Body: toCsv(siteRows),
        ContentType: "text/csv",
        ChecksumAlgorithm: "CRC32",
        IfNoneMatch: "*",
      }));
    } catch (error) {
      if (error.name !== "PreconditionFailed") {
        request.log.error({ key, name: error.name });
        return response.status(502).json({ message: describe(error) });
      }
    }
  }

  response.json({ part });
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. The season comes off the session, and the site is checked against the codes that session is allowed to write. Every value that reaches the key is validated in the route, whatever the browser did first.</p>
<p><code>IfNoneMatch: "*"</code> is what makes a repeat harmless. "If there's no existing object with the same key name in the bucket, the write operation succeeds, resulting in a <code>200 OK</code> response. If there's an existing object, the write operation fails, resulting in a <code>412 Precondition Failed</code> response." A part posted twice lands once. AWS also settles the race between two callers. "If multiple conditional writes or copies occur for the same object name, the first write operation to finish succeeds." There is no extra charge for any of it.</p>
<p><code>ChecksumAlgorithm</code> asks S3 to verify what arrived against what the SDK says it sent, and <code>CRC64NVME</code> is the default when you name nothing. Objects are encrypted at rest with SSE-S3 unless you ask for something else.</p>
<p>A batch is readable once the manifest lands. That endpoint writes one small JSON object under <code>_batches/</code>, with the same <code>If-None-Match</code>, carrying the part count and the row count. Parts with no manifest behind them are an abandoned attempt, which is what a resubmitted import leaves, and a lifecycle rule can expire them.</p>
<h2 id="the-door-the-browser-could-open-itself">The door the browser could open itself</h2>
<p>S3 is the one destination in this cluster the browser could write to directly. A route can sign a <code>PUT</code> for one key and hand the URL over, and the upload skips your server entirely.</p>
<p>AWS describes what comes with that. "In essence, presigned URLs are bearer tokens that grant access to those who possess them." The URL works "multiple times, up to the expiration date and time", set as high as seven days through the SDKs. And a <code>PUT</code> to a key that exists replaces the object, since "Amazon S3 replaces the existing object with the uploaded object".</p>
<p>Keeping the write on the server buys one place where the rows are checked, one place where the key is built, and one place where the conditional header is set. For an import whose whole point is what lands, that is where it belongs.</p>
<h2 id="when-the-write-fails">When the write fails</h2>
<p>A rejected write arrives as an error carrying <code>name</code>, and <code>PreconditionFailed</code> is the one to catch by hand, since it means the object is already there. <code>$metadata.httpStatusCode</code> holds the status behind it.</p>
<p>Throttling is handled for you. S3 answers <code>503 (Slow Down)</code> while it scales a prefix to a higher rate, and the SDK classifies <code>SlowDown</code> as a throttling error and retries it with a longer base delay. The default is three attempts, one request and two retries, tuned through <code>AWS_MAX_ATTEMPTS</code>. The 2026 backoff timings need <code>AWS_NEW_RETRIES_2026=true</code> in the environment until they become the default.</p>
<p>Log the key and the error name, answer the browser with a sentence an agronomist can act on, and let the handler throw. All of it happens with the confirm dialog open and a spinner on the button, so anything on the result worth keeping gets copied inside the handler.</p>
<h2 id="what-reads-it-back">What reads it back</h2>
<p>S3 stores the object. Amazon Athena reads it, and Athena has the rules S3 declined to have.</p>
<pre><code class="language-sql">CREATE EXTERNAL TABLE trials.harvest (
  plot_ref     string,
  variety      string,
  harvested_on string,
  yield_t_ha   double,
  moisture_pct double,
  treatment    string,
  notes        string
)
PARTITIONED BY (season string, site string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
  'separatorChar' = ',',
  'quoteChar'     = '"',
  'escapeChar'    = '\\'
)
STORED AS TEXTFILE
LOCATION 's3://acme-trials/harvest/'
TBLPROPERTIES ('skip.header.line.count' = '1');</code></pre>
<p>Three of those rules were settled in the browser hours earlier. The Open CSV SerDe needs to be told about a header row, which is what <code>skip.header.line.count</code> does. It "does not support embedded line breaks in CSV files", which is why the <code>notes</code> transformer collapses them. And it "Does not recognize empty or null values in columns defined as a numeric data type, leaving them as <code>string</code>", which is why yield and moisture are both required.</p>
<p>Dates keep their own rule. The SerDe reads a <code>DATE</code> column as days elapsed since 1 January 1970, so <code>harvested_on</code> is declared as a string. AWS names the way out. "To further convert columns to the desired type in a table, you can create a view over the table and use <code>CAST</code> to convert to the desired type." A column that can genuinely arrive empty takes the same road.</p>
<p>The site never appears in the file. It is a partition column, read out of the key the route built, which is the last thing that value does before it becomes a path.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no S3 connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route, the key layout and the manifest in the middle are work you do.</p>
<p>S3 already ships its own ways in for the other case. The console takes a file up to 160 GB by drag and drop. <code>aws s3api put-object</code> sends one up to 5 GB in a single <code>PUT</code>, and <code>aws s3 cp</code> switches to multipart above 8 MB, which carries a single object to 50 TB across as many as 10,000 parts. AWS Transfer Family answers SFTP straight into the bucket. For a file your own team assembled, those are the shorter way in. Everything above exists for the export a research station sends, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-season">The pieces you wrote and the next season</h2>
<p>You wrote a schema with eight columns, one <code>synonyms</code> block, a key layout, a route that turns a chunk into objects under a conditional header, and a second endpoint that closes the batch. The file stays on the machine that opened it. The rows travel from your own front end to your own route and into your own bucket. The only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>Next season the same station sends the same spelling of its own name, and a fourth one nobody has seen. The mappings are already stored, the new spelling costs one more line in <code>synonyms</code>, and the value that would have become a pound sign in an object key sits in a grid cell instead, in front of the person who typed it.</p>]]></content:encoded></item>
<item><title>How Updog Makes Its Importer Accessible</title><link>https://updog.tech/blog/how-updog-makes-its-importer-accessible/</link><guid isPermaLink="true">https://updog.tech/blog/how-updog-makes-its-importer-accessible/</guid><pubDate>Thu, 06 Aug 2026 00:00:00 GMT</pubDate><description>Screen reader support, keyboard navigation and WCAG 2.2 A and AA testing across the upload steps, the data grid and the cell editors.</description><content:encoded><![CDATA[<p>Some people use an app with the keyboard alone. Others hear it through a screen reader, software that turns page elements into speech. Everything a web app does has to be within reach of both.</p>
<p>The Web Content Accessibility Guidelines, usually shortened to WCAG, describe what that takes. Version 2.2 sorts its requirements into three levels. Level A covers the basics, level AA covers the set that buyers, procurement teams, and public bodies normally ask for, and level AAA goes further than most products can meet across a whole interface. Level AA is the target Updog builds toward.</p>
<p>The work starts below the interface. Updog is made of components we own, most of the importer is ordinary HTML built from those components, and one part is a data grid painted on a canvas. Each layer carries its own share of the job.</p>
<h2 id="what-level-aa-asks-for">What level AA asks for</h2>
<p>The requirements come down to a handful of things a person can check.</p>
<p><strong>Everything has a name and a role.</strong> A screen reader announces what a control is and what it is called. A button says it is a button and says what it does. A field says what it holds.</p>
<p><strong>Everything works from the keyboard.</strong> Any action available to a mouse is available to Tab, the arrow keys, Enter, and Escape, and focus never gets stuck anywhere it cannot leave.</p>
<p><strong>Focus is visible.</strong> The element that will receive the next keypress is marked clearly enough to find on screen.</p>
<p><strong>Contrast is high enough to read.</strong> Normal text holds a ratio of 4.5 to 1 against its background. Large text, icons, and the borders that show where a field is hold 3 to 1.</p>
<p><strong>The layout survives being resized.</strong> Text scales to 200 percent and content reflows into a column about 320 pixels wide without losing anything.</p>
<p><strong>Errors are explained in words.</strong> A red border alone leaves out anyone who cannot see the red.</p>
<p>An automated rule checker can measure most of these. Whether a name means anything to the person hearing it is a separate question, and answering it takes someone listening. Updog does both.</p>
<h2 id="a-ui-kit-of-our-own">A UI kit of our own</h2>
<p>Updog ships its own components, and the importer and the editor are built from them. Buttons, inputs, selects, combo boxes, date pickers, dropdowns, menus, modals, drawers, tooltips, and tables all come from that kit.</p>
<p>Building a component library is more work than installing one. Adopting somebody else's kit means adopting their role model, their focus behavior, and their release schedule, and a naming decision buried inside it becomes something to work around. Owning the kit puts every accessible name, every keyboard interaction, and every color token in one place under our control, and a change reaches the whole product at once.</p>
<p>That control shows up in ordinary details. A label is wired to its control by id, so clicking the label moves focus and a screen reader reads the two together. A control takes its name from the label wired to it rather than from the placeholder inside it, so a filter announces the field it belongs to. A field holding a pair of controls, such as the minimum and maximum of a range filter, becomes a labelled group where each control keeps a name of its own, so one announces "Age, minimum" and the other "Age, maximum".</p>
<p>Every component has a story in Storybook, and every story is scanned for accessibility rule violations as part of the normal test run. Unit tests pin the roles and names of the dropdown and everything built on top of it, so later refactoring cannot change what a screen reader hears without a test failing.</p>
<h2 id="everything-outside-the-grid">Everything outside the grid</h2>
<p>The importer has two halves. The upload wizard, the filter panel, the modals, the menus, and the cell editors are regular DOM elements. The data grid is a canvas. The DOM half inherits its accessibility from the kit, which is the point of owning the kit.</p>
<p>Every control on those screens carries a name a screen reader can read, and every step of the wizard announces which step is active. Anything reachable with a mouse is reachable with Tab and the arrow keys, and panels that close drop out of the tab order, so a screen reader reads only what is open.</p>
<h2 id="the-grid-on-a-canvas">The grid on a canvas</h2>
<p>A browser cannot hold a million rows as elements and still scroll inside a frame budget, so the grid paints pixels instead, which is the <a href="https://updog.tech/blog/canvas-grid-performance/">rendering side of the decision</a>. A canvas is one element with an image inside it. The roles, the names, and the position information an HTML table gives assistive technology for free are absent, so the grid supplies all of them itself.</p>
<p>The way it does that is a second copy of the grid built from real elements. Beside the canvas sits a table holding only the rows currently in view, roughly twenty of them at a normal window size, and scrolling rebuilds it to match what the canvas has painted. A screen reader reads that table and never touches the canvas.</p>
<p>This table has to be invisible on screen and still available to a screen reader, which rules out the usual ways of hiding something. Setting an element to display none takes it out of the page, and marking it hidden to assistive technology takes it out of the accessibility tree, the structure a browser builds for a screen reader to read. So the table stays in the layout inside a box one pixel across with its contents clipped away. Nobody sees it, and a screen reader finds it in the normal place.</p>
<p>Twenty rows would describe the file wrongly if the numbers stopped there. The grid states how many rows and columns the dataset holds, and every row and cell in the table states where it sits inside that dataset. A screen reader can then say row 4,318 of 40,000 while only twenty rows exist on the page. ARIA has attributes for this, and a virtualized grid is what they were written for.</p>
<p>Those numbers track what the user is looking at rather than what the file contains. Filter the grid down to one row and the count becomes one. Open the bin and the count covers the deleted rows. Pin a column to the left and the header order in the table moves with it.</p>
<p>Rebuilding that table on every scroll frame would compete with the canvas for the main thread and cost frames, so it waits until 150 milliseconds after scrolling stops. Keyboard movement is different. An arrow press past the bottom edge scrolls the grid, and waiting there would leave the new row missing for a moment, so a keypress rebuilds the table straight away.</p>
<p>Moving around the grid also has to be heard. A small area of the page holds a line of text that a screen reader reads whenever it changes, and the grid writes into it. Moving to a cell writes the row number, the column name, and the value. Selecting rows or columns writes how many. Counts go through the plural rules of the language being read, so English gets "1 row selected" and "3 rows selected", and Arabic gets all six of its plural forms.</p>
<p>A cell that fails a validation rule shows a red border on the canvas, which says nothing to a screen reader. The same cell in the table is marked as invalid and carries the message with it, and that message is spoken when focus lands on the cell.</p>
<h2 id="what-the-keyboard-reaches">What the keyboard reaches</h2>
<p>A grid holding a million cells cannot give each one a tab stop, because crossing it would take a million presses. So the whole grid is a single tab stop. <kbd>Tab</kbd> moves focus onto it, and from there the arrow keys move a cursor from cell to cell, which is how a spreadsheet already works.</p>
<p>Arrows move the cell cursor and <span class="blog__shortcut"><kbd>Shift</kbd> + <kbd>↑</kbd></span> extends the selection, while <span class="blog__shortcut"><kbd>Cmd</kbd> + <kbd>↑</kbd></span> jumps to the edge of the data, with <kbd>Ctrl</kbd> standing in for <kbd>Cmd</kbd> away from a Mac. <span class="blog__shortcut"><kbd>Shift</kbd> + <kbd>Space</kbd></span> takes the whole row the cursor sits on, and <span class="blog__shortcut"><kbd>Cmd</kbd> + <kbd>Space</kbd></span> takes the column, bound the way Excel and Google Sheets bind them. Through all of it the cursor keeps its place, so <kbd>Enter</kbd> still opens the editor on the cell you were on. In a right-to-left layout, left and right swap.</p>
<p><kbd>Enter</kbd> or <kbd>F2</kbd> opens the editor on the focused cell, and typing a character opens it and starts with that character. <kbd>Esc</kbd> closes it again. Copy, cut, paste, undo, redo, select all, and clearing a cell all sit on the shortcuts a spreadsheet uses.</p>
<p>The context menu opens with <span class="blog__shortcut"><kbd>Shift</kbd> + <kbd>F10</kbd></span>, or with the dedicated <kbd>Menu</kbd> key. Mac keyboards carry neither, so <span class="blog__shortcut"><kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>\</kbd></span> opens it instead, which is the binding Google Sheets uses. What opens follows the selection, so a row selection opens the row menu with Clear row, Duplicate row, and Delete row on it.</p>
<p>Closing a menu, an editor, or a popup sends focus back to the grid while the closing animation is still running. Someone who picks "Insert row above" and starts typing straight away keeps the first characters.</p>
<p>An editor opens on top of the canvas with no label beside it and no cell element behind it, so it builds a name out of the column and the row and announces "Edit First Name, row 1". The list inside a select editor takes its name from the field it belongs to.</p>
<p>The rest of the keys, and the places the grid parts from Excel, sit in the <a href="https://docs.updog.tech/keyboard-shortcuts/">keyboard shortcuts reference</a>.</p>
<h2 id="color-contrast-and-motion">Color, contrast, and motion</h2>
<p>Text has to stand out from what sits behind it, and level AA puts that at 4.5 to 1 for normal text. Every text token is measured against the surface it lands on. For example, the gray used for placeholder text measures 4.98 to 1 on the base surface and 4.68 to 1 on the raised one, and that single token covers the placeholders of the text field, the select, the combo box, and the date picker.</p>
<p>A keyboard user needs to see where focus has gone, and a mouse user already knows. So controls draw an outline when focus arrives from the keyboard and stay quiet under a click.</p>
<p>Animation makes some people ill, and the operating system already knows who they are. With reduced motion switched on, the animated controls stop animating, and the dropdown and the context menu drop their transitions.</p>
<p>The colors are the one part we cannot measure for you. Updog is themed with CSS custom properties and your palette replaces ours, so your own tokens need checking against the same 4.5 to 1 threshold.</p>
<h2 id="how-we-test">How we test</h2>
<p>Every component has a story, and every story is scanned with axe, an accessibility rule checker, inside a headless Chromium browser as part of the normal test command. A violation fails the run. Content rendered into a portal is scanned along with the rest, which is where popups usually slip past a scanner.</p>
<p>The importer is scanned the same way. Playwright opens a state and checks the page against WCAG 2.2 level A and AA rules, working through every wizard step, all five cell editors, each menu, modal, and panel the editor can open, and the editor itself in readonly and right-to-left form.</p>
<p>A scanner reads the colors a browser has computed, and a color halfway through a fade belongs to neither end of it. So every scan waits for the animations on the page to finish before it measures anything.</p>
<p>People listen to it as well. Every state of the importer gets a manual pass with VoiceOver on macOS.</p>
<h2 id="where-we-aim">Where we aim</h2>
<p>Level AA is the standard we write against and measure by, on every change to the code. Formal conformance has its own paperwork, an independent audit or a Voluntary Product Accessibility Template, and as of August 2026 Updog holds neither. Accessibility is part of how we build and test the product, and the work of getting closer to that level continues.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into DynamoDB</title><link>https://updog.tech/blog/import-csv-into-dynamodb/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-dynamodb/</guid><pubDate>Wed, 05 Aug 2026 00:00:00 GMT</pubDate><description>Match a hotel rate sheet in the browser, post the clean rows to your own route, and write them into DynamoDB 25 items a call with the leftovers retried.</description><content:encoded><![CDATA[<p>DynamoDB documents several ways to move a CSV into a table. Import from Amazon S3 reads CSV, DynamoDB JSON or Amazon Ion out of a bucket, up to 50,000 objects a job, and consumes no write capacity. NoSQL Workbench loads up to 150 rows into a model on a desktop. The CLI has <code>batch-write-item</code>, and AWS publishes a Lambda pattern that fires when an object lands in S3. Every one of those starts from a seat that already holds an AWS account. Your customer sits outside that seat, holding the rate sheet their revenue manager exported this morning.</p>
<h2 id="the-door-a-web-backend-has">The door a web backend has</h2>
<p>Rows reach a DynamoDB table item by item. <code>BatchWriteItem</code> is the bulk form of that, and AWS states its shape plainly. "A single call to <code>BatchWriteItem</code> can transmit up to 16MB of data over the network, consisting of up to 25 item put or delete operations." Individual items can be up to 400 KB once stored. Every batched write a web backend sends is cut to those two numbers.</p>
<p>Four things it refuses, and each one moves work earlier.</p>
<p>It cannot update. "If you perform a <code>BatchWriteItem</code> operation on an existing item, that item's values will be overwritten by the operation and it will appear like it was updated." It takes no conditions, since "you cannot specify conditions on individual put and delete requests". It is not atomic as a whole, though each put and delete inside it is. And it rejects the entire batch when your request "contains at least two items with identical hash and range keys".</p>
<p>So nothing on the server side can tell a new rate from a changed one, refuse an overwrite, or single out one bad line. <code>TransactWriteItems</code> takes conditions and runs all or nothing, and it caps at 100 actions and 4 MB with no partial success to retry, so a season of rates gains nothing from it. Every decision goes in front of the write.</p>
<h2 id="the-files-that-arrive">The files that arrive</h2>
<p>Two properties send their October rates in the same week. Each one exports from a different system.</p>
<p><code>alfama-october.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Property</td><td class="sheet__cell">Plan</td><td class="sheet__cell">Room</td><td class="sheet__cell">Stay Date</td><td class="sheet__cell">Rate</td><td class="sheet__cell">Currency Code</td><td class="sheet__cell">Min Stay</td><td class="sheet__cell">CTA</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">LIS-ALFAMA</td><td class="sheet__cell">BAR</td><td class="sheet__cell">DBL</td><td class="sheet__cell">01/10/2026</td><td class="sheet__cell">145.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">2</td><td class="sheet__cell">N</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">LIS-ALFAMA</td><td class="sheet__cell">BAR</td><td class="sheet__cell">DBL</td><td class="sheet__cell">01/10/2026</td><td class="sheet__cell">152.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">2</td><td class="sheet__cell">N</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">LIS-ALFAMA</td><td class="sheet__cell">NRF</td><td class="sheet__cell">TWN</td><td class="sheet__cell">19/10/2026</td><td class="sheet__cell">129.50</td><td class="sheet__cell">EUR</td><td class="sheet__cell">1</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">LIS-ALFAMA</td><td class="sheet__cell">BAR</td><td class="sheet__cell">DBL</td><td class="sheet__cell">2/10/2026</td><td class="sheet__cell">145.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">2</td><td class="sheet__cell">N</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">181 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">187</th><td class="sheet__cell">LIS-ALFAMA</td><td class="sheet__cell">NRF</td><td class="sheet__cell">TWN</td><td class="sheet__cell">31/10/2026</td><td class="sheet__cell">138.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">1</td><td class="sheet__cell">N</td></tr></tbody></table>
<p><code>porto-ribeira-channel.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Property ID</td><td class="sheet__cell">Rate Plan Code</td><td class="sheet__cell">Room Type</td><td class="sheet__cell">Arrival Date</td><td class="sheet__cell">Amount</td><td class="sheet__cell">Currency</td><td class="sheet__cell">Minimum Nights</td><td class="sheet__cell">Closed To Arrival</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">OPO-RIBEIRA</td><td class="sheet__cell">Non Refundable</td><td class="sheet__cell">Double Room</td><td class="sheet__cell">2026-10-01</td><td class="sheet__cell">118.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">2</td><td class="sheet__cell">No</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">OPO-RIBEIRA</td><td class="sheet__cell">Advance Purchase 21</td><td class="sheet__cell">Twin room</td><td class="sheet__cell">2026-10-02</td><td class="sheet__cell">99.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">3</td><td class="sheet__cell">Yes</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">121 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">125</th><td class="sheet__cell"></td><td class="sheet__cell">Advance Purchase 21</td><td class="sheet__cell">Double Room</td><td class="sheet__cell">2026-10-03</td><td class="sheet__cell">104.00</td><td class="sheet__cell">EUR</td><td class="sheet__cell">3</td><td class="sheet__cell">No</td></tr></tbody></table>
<p>The Alfama property calls the column <code>Plan</code> and the Ribeira property calls it <code>Rate Plan Code</code>. One writes dates day first and the other writes them ISO. <code>BAR</code>, <code>NRF</code>, <code>DBL</code>, <code>TWN</code> and <code>CTA</code> are the trade's shorthand. The first file prices <code>01/10/2026</code> twice, because somebody repriced and left both lines in. The last row of the second file has no property code at all.</p>
<p>The person drags both files into the importer inside your app. Updog Importer reads them in the browser, matches each file's headers to your schema, holds the plans and room types to your lists, and puts every row in front of them. Your <code>onComplete</code> handler receives the rows grouped by file. The handler posts them to a route you own, and that route writes them 25 at a time.</p>
<p>No Updog server stands between the browser and DynamoDB.</p>
<h2 id="the-table-the-rows-land-in">The table the rows land in</h2>
<p>One table holds the calendar, and only two of its attributes are declared.</p>
<pre><code class="language-bash">aws dynamodb create-table \
  --table-name rate_calendar \
  --attribute-definitions \
      AttributeName=property_code,AttributeType=S \
      AttributeName=rate_key,AttributeType=S \
  --key-schema \
      AttributeName=property_code,KeyType=HASH \
      AttributeName=rate_key,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST</code></pre>
<p>DynamoDB is schemaless past the key. AWS states that "other than the primary key attributes, you don't have to define any attributes or data types when you create tables". So <code>rate_amount</code>, <code>currency</code> and the rest exist only on the items that carry them, with whatever type the write gave them.</p>
<p><code>property_code</code> is the partition key and <code>rate_key</code> is the sort key, built as <code>PLAN#&#x3C;plan>#&#x3C;date></code> so one query returns a plan's whole month in date order. A partition key value runs to 2048 bytes and a sort key value to 1024, both far above anything here. Names are case-sensitive, so <code>rate_key</code> and <code>Rate_Key</code> are two different attributes.</p>
<p>One number sets the pace. "Every partition in a DynamoDB table is designed to deliver a maximum capacity of 3,000 read units per second and 1,000 write units per second", and one write unit is one write a second for an item up to 1 KB. Every row in one property's file carries the same partition key, so one property's whole import lands on one partition and 1,000 rate rows a second is its ceiling.</p>
<h2 id="the-template-the-property-downloads">The template the property downloads</h2>
<p>The key columns are the one thing DynamoDB will not accept broken. An attribute value can be an empty string when the attribute is not part of a table or index key, and a key attribute holding one is refused. The blank property code in the second file is that row.</p>
<p>The cheapest fix arrives before the export does. <code>sampleData</code> fills the "Download Example" file the import wizard offers, so the property starts from your headers instead of guessing them.</p>
<pre><code class="language-ts">const sampleData = [
  {
    propertyCode: "LIS-ALFAMA",
    planCode: "Flexible",
    roomType: "Double",
    stayDate: "2026-10-01",
    rateAmount: "145.00",
    currency: "EUR",
    minStay: "2",
    closedToArrival: "No",
  },
  {
    propertyCode: "LIS-ALFAMA",
    planCode: "Non-refundable",
    roomType: "Twin",
    stayDate: "2026-10-02",
    rateAmount: "129.50",
    currency: "EUR",
    minStay: "1",
    closedToArrival: "Yes",
  },
];</code></pre>
<p>The generated file carries your column headers and these rows. Leave <code>sampleData</code> out and the SDK still writes a template, carrying one generic example row generated from your column definitions. Real values do more work here, since a revenue manager reading <code>2026-10-01</code> and <code>Non-refundable</code> learns the date format and the plan vocabulary in one look.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array describes the table as the person sees it.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const PLANS = ["Flexible", "Non-refundable", "Advance purchase", "Corporate"];
const ROOMS = ["Double", "Twin", "Single", "Suite"];
const CURRENCIES = ["EUR", "GBP", "USD"];
const YES_NO = ["Yes", "No"];

export const columns: DataEditorColumn[] = [
  {
    id: "propertyCode",
    title: "Property code",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^[A-Z]{3}-[A-Z]+$" },
    ],
  },
  {
    id: "planCode",
    title: "Plan code",
    size: 170,
    editor: { type: "select", options: PLANS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: PLANS }],
  },
  {
    id: "roomType",
    title: "Room type",
    size: 130,
    editor: { type: "select", options: ROOMS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: ROOMS }],
  },
  {
    id: "stayDate",
    title: "Stay date",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "rateAmount",
    title: "Rate amount",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, max: 100_000, decimalPlaces: 2 },
    ],
  },
  {
    id: "currency",
    title: "Currency",
    size: 120,
    editor: { type: "select", options: CURRENCIES, enableCustomValue: false },
  },
  {
    id: "minStay",
    title: "Min stay",
    size: 120,
    editor: { type: "number" },
    validators: [{ type: "number", min: 1, max: 30, decimalPlaces: 0 }],
  },
  {
    id: "closedToArrival",
    title: "Closed to arrival",
    size: 160,
    editor: { type: "select", options: YES_NO, enableCustomValue: false },
    validators: [{ type: "oneOf", values: YES_NO }],
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>date</code> editor turns <code>19/10/2026</code> into <code>2026-10-19</code>, and since 19 is above 12 that file settles day first, so <code>01/10/2026</code> and <code>2/10/2026</code> land as <code>2026-10-01</code> and <code>2026-10-02</code>. The <code>select</code> editors hold the plan, the room type and the arrival flag to fixed lists, and a value nobody maps is dropped from the row. <code>{ type: "required" }</code> on the property code catches the blank cell while somebody can still type into it.</p>
<h2 id="the-headers-each-property-sends">The headers each property sends</h2>
<p>Column matching repeats per file. Each file gets its own screen and its own mapping, so the same schema column is fed by a different header in each one.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>File</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Property</code></td>
<td>Alfama</td>
<td><code>propertyCode</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Property ID</code></td>
<td>Ribeira</td>
<td><code>propertyCode</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Plan</code></td>
<td>Alfama</td>
<td><code>planCode</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Rate Plan Code</code></td>
<td>Ribeira</td>
<td><code>planCode</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Room</code></td>
<td>Alfama</td>
<td><code>roomType</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Stay Date</code></td>
<td>Alfama</td>
<td><code>stayDate</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Arrival Date</code></td>
<td>Ribeira</td>
<td><code>stayDate</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Rate</code></td>
<td>Alfama</td>
<td><code>rateAmount</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Amount</code></td>
<td>Ribeira</td>
<td><code>rateAmount</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Currency Code</code></td>
<td>Alfama</td>
<td><code>currency</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Minimum Nights</code></td>
<td>Ribeira</td>
<td><code>minStay</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>CTA</code></td>
<td>Alfama</td>
<td><code>closedToArrival</code></td>
<td>synonym, 90</td>
</tr>
</tbody>
</table></div>
<p><code>Plan</code> and <code>Room</code> sit exactly on the contains floor, which fires once the shorter string runs to four characters. <code>Currency Code</code> needs no configuration, since the built-in synonym table already carries it. <code>CTA</code> is three characters and reaches nothing on its own, and <code>Minimum Nights</code> shares no whole word with <code>Min stay</code>, while normalized it runs six characters longer than <code>minstay</code>, twice what the edit-distance tier allows at that length. Both come in through one <code>synonyms</code> entry each.</p>
<p>Value matching runs once for the whole import and collects values per schema column across both files. <code>Double Room</code> and <code>Twin room</code> contain their options and land at eighty. <code>Y</code> and <code>N</code> reach <code>Yes</code> and <code>No</code> at ninety, since the built-in table already carries them, and <code>TWN</code> lands on <code>Twin</code> at sixty-five through the edit-distance tier. <code>BAR</code>, <code>NRF</code> and <code>DBL</code> reach nothing, so one <code>synonyms</code> entry per option carries the trade's shorthand.</p>
<p>Each file also settles its own dates. The verdict comes from a sample of that file alone, so a day-first export and an ISO export in the same import never borrow each other's reading.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the two files, the schema and the table together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Rate>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  sampleData={sampleData}
  primaryKey={["propertyCode", "planCode", "stayDate"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      minStay: ["minimum nights", "min nights", "los", "length of stay"],
      closedToArrival: ["cta", "no arrival", "arrival closed"],
    },
    values: {
      Flexible: ["bar", "best available rate", "rack"],
      "Non-refundable": ["nrf", "nr"],
      Double: ["dbl", "db"],
      Twin: ["twn", "tw"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> takes three columns, because a rate is identified by a property, a plan and a night together. Values are compared after trimming, and a row missing any part merges with nothing and arrives as new.</p>
<p><code>enableDeleteRow="all"</code> lets the person drop the second <code>01/10/2026</code> line by hand once the grid shows both. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, the blank property code included. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back through <code>synonyms</code> next season.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source. Each file lands as its own entry, carrying the file name, so the row that came from Ribeira still says so on the way out.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 500;

const toRow = (entry: ResultRow&#x3C;Rate>, sourceFile: string) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  return [{
    property_code: entry.row.propertyCode,
    plan_code: entry.row.planCode,
    room_type: entry.row.roomType,
    stay_date: entry.row.stayDate,
    rate_amount: Number(entry.row.rateAmount),
    currency: entry.row.currency,
    min_stay: entry.row.minStay ? Number(entry.row.minStay) : undefined,
    closed_to_arrival: entry.row.closedToArrival === "Yes",
    source_file: sourceFile,
    op: entry.isDeleted ? "delete" : "put",
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Rate>) => {
  for (const source of result.sources) {
    const rows = source.rows.flatMap((entry) => toRow(entry, source.sourceName));

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const written = await fetch("/api/rates/write", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
      });
      if (!written.ok) throw new Error((await written.json()).message);
    }
  }
}, []);</code></pre>
<p>Three flags become one field. A new rate and a changed rate are the same payload, since <code>BatchWriteItem</code> overwrites either way. A row the person added and then deleted goes nowhere. Nothing here loads from your backend, so every row arrives new and <code>op</code> reads <code>put</code> on all of them. The <code>delete</code> branch waits on the season you feed the existing rates in through <code>loadData</code>.</p>
<p><strong>DynamoDB stores the type you send.</strong> Numbers travel to the API as strings and are treated as numbers once they land, and a value the browser hands over as text stays text on the item forever. <code>Number()</code> around the rate and the minimum stay is what keeps them comparable later. The boolean is built here for the same reason, since <code>"Yes"</code> is what the person reads and <code>true</code> is what a filter can use.</p>
<p>The chunk size belongs to you. AWS publishes 25 items a <code>BatchWriteItem</code> call and 1,000 write units a second per partition, and neither number describes a POST body. So five hundred rows is a number chosen against what your own endpoint accepts, and it fills half a second of one partition's budget. The route splits it into the published 25.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and both properties' rates clear the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-writes">The route that writes</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, BatchWriteCommand } from "@aws-sdk/lib-dynamodb";

const TABLE = "rate_calendar";
const BATCH = 25;
const ATTEMPTS = 6;

const client = DynamoDBDocumentClient.from(new DynamoDBClient({}), {
  marshallOptions: { removeUndefinedValues: true },
});

const rateKey = (row) => "PLAN#" + row.plan_code + "#" + row.stay_date;

const dedupe = (rows) => {
  const latest = new Map();
  for (const row of rows) latest.set(row.property_code + "|" + rateKey(row), row);
  return [...latest.values()];
};

const toRequest = (row) => {
  const key = { property_code: row.property_code, rate_key: rateKey(row) };
  if (row.op === "delete") return { DeleteRequest: { Key: key } };
  return {
    PutRequest: {
      Item: {
        ...key,
        plan_code: row.plan_code,
        room_type: row.room_type,
        stay_date: row.stay_date,
        rate_amount: row.rate_amount,
        currency: row.currency,
        min_stay: row.min_stay,
        closed_to_arrival: row.closed_to_arrival,
        source_file: row.source_file,
        updated_at: new Date().toISOString(),
      },
    },
  };
};</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. The property codes arrive in the body, so the route checks each one against the properties that session is allowed to load. A guessed code reaches no other hotel's calendar.</p>
<p><code>dedupe</code> is there because DynamoDB rejects the whole batch when two items carry identical keys, and Updog cannot catch that one for you. <code>{ type: "unique" }</code> is a single-column rule, checked against every other row in the same column, and this key spans three. So the person sees both <code>01/10/2026</code> lines and can delete one, and the map keeps the last of any pair that survives.</p>
<p>The sort key is composed here, from the plan and the date the person already settled. One place in your code builds that string, so the write and any later query agree on it.</p>
<h2 id="the-200-that-wrote-nothing">The 200 that wrote nothing</h2>
<p>A <code>BatchWriteItem</code> call answers HTTP 200 and can still leave items unwritten.</p>
<pre><code class="language-ts">const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const writeBatch = async (requests) => {
  let pending = requests;

  for (let attempt = 0; attempt &#x3C; ATTEMPTS &#x26;&#x26; pending.length > 0; attempt++) {
    if (attempt > 0) await wait(2 ** attempt * 50 + Math.random() * 50);

    const answer = await client.send(
      new BatchWriteCommand({ RequestItems: { [TABLE]: pending } }),
    );
    pending = answer.UnprocessedItems?.[TABLE] ?? [];
  }

  if (pending.length > 0) {
    throw new Error(pending.length + " items were handed back unwritten");
  }
};

app.post("/api/rates/write", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const rows = dedupe(request.body.rows);
  const allowed = await propertiesFor(session.accountId);
  if (rows.some((row) => !allowed.has(row.property_code))) {
    return response.status(403).json({ message: "A property code is not yours" });
  }

  try {
    for (let start = 0; start &#x3C; rows.length; start += BATCH) {
      await writeBatch(rows.slice(start, start + BATCH).map(toRequest));
    }
  } catch (error) {
    request.log.error({ err: error });
    return response.status(502).json({ message: "The write did not finish" });
  }

  response.json({ written: rows.length });
});</code></pre>
<p>AWS names the mechanism directly. Failed operations "are returned in the <code>UnprocessedItems</code> response parameter", the value "is in the same form as <code>RequestItems</code>, so you can provide this value directly to a subsequent <code>BatchWriteItem</code> operation", and a clean call "contains an empty <code>UnprocessedItems</code> map". So the loop reads what came back and sends it again.</p>
<p>AWS asks for one thing on that retry. "we strongly recommend that you use an exponential backoff algorithm", because an immediate retry meets the same throttling that produced the leftovers. Throttling that stops the whole call raises <code>ProvisionedThroughputExceededException</code> or <code>ThrottlingException</code> instead, and both come back as errors your <code>try</code> already catches. <a href="https://updog.tech/blog/import-csv-into-mongodb/">Importing a CSV into MongoDB</a> shows the other document store's answer to the same problem, where a failed bulk write names each rejected row by index.</p>
<p>All of this happens with the confirm dialog open and a spinner on the button. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no DynamoDB connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route in the middle is work you do. Our uniqueness rule reads one column, so a multi-column key is checked by your own code.</p>
<p>DynamoDB already ships its own way in for the other case. Import from Amazon S3 reads CSV, DynamoDB JSON or Amazon Ion, runs 50,000 objects a job, and consumes no write capacity on the table it fills. It also states that "Import into existing tables is not currently supported by this feature", and a repeat customer import is exactly a write into a table that already exists. For a one-off load your own team assembled, that import is the shorter way in. Everything above exists for the rate sheets your properties send, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-next-season">The pieces you wrote and next season</h2>
<p>You wrote one table with two declared attributes, a schema with eight columns, a downloadable template, one <code>synonyms</code> block covering the trade's shorthand, a dedupe map, and one route that writes 25 items at a time and retries what comes back. The files stay on the machine that opened them. The rows travel from your own front end to your own route and into DynamoDB, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>Next season brings the same two properties and a third one with a third spelling of <code>Closed to arrival</code>. The mappings from October are already stored, the template goes out with the request for rates, and the new property costs one more line in <code>synonyms</code>.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into SQL Server</title><link>https://updog.tech/blog/import-csv-into-sql-server/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-sql-server/</guid><pubDate>Tue, 04 Aug 2026 00:00:00 GMT</pubDate><description>Match a heritage survey export in the browser, stream the clean rows into SQL Server with bulk copy, and settle the batch with one MERGE from your own route.</description><content:encoded><![CDATA[<p>SQL Server documents several ways to move a CSV into a table. The Import Flat File Wizard copies a file "to a new table in your database" from inside SQL Server Management Studio. <code>BULK INSERT</code> reads a path "from the server on which SQL Server is running", or a UNC share, and asks for the <code>ADMINISTER BULK OPERATIONS</code> permission. The <code>bcp</code> utility runs on a machine somebody signs into. Each one starts from a seat that already holds a server connection. Your customer sits outside that seat, holding the survey export a consultancy sent them this morning.</p>
<h2 id="the-door-above-a-thousand-rows">The door above a thousand rows</h2>
<p>Microsoft publishes a ladder for writing many rows at once, and it has three rungs. "For &#x3C; 100 rows, use a single parameterized <code>INSERT</code> command." "For &#x3C; 1,000 rows, use table-valued parameters." "For >= 1000 rows, use <code>SqlBulkCopy</code>."</p>
<p>The bottom rung runs out on its own. An <code>INSERT ... VALUES</code> list stops at a thousand rows, and Microsoft numbers the failure, since "Error 10738 is returned if the number of rows exceeds the maximum". A city register with several thousand buildings in it starts on the top rung.</p>
<p>Bulk copy carries a set of rows straight over the connection. There is no statement to parse, no parameter to count, and no row limit to work around. In Node that door is <code>request.bulk()</code>, in the <code>mssql</code> package.</p>
<p>It comes with one restriction, and Microsoft states it plainly. Other techniques, "such as SQL bulk copy, only permit the insertion of new rows." So the rows land in a staging table first, and one statement afterwards decides what each of them becomes. Below a thousand rows the middle rung is the shorter road, and <a href="https://updog.tech/blog/import-csv-into-azure-sql/">importing a CSV into Azure SQL Database</a> takes it.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>A city conservation office keeps a register of listed buildings. The consultancy that ran this season's survey sends one export.</p>
<p><code>heritage-survey-2026.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Ref</td><td class="sheet__cell">Site Address</td><td class="sheet__cell">Listing Grade</td><td class="sheet__cell">First Recorded</td><td class="sheet__cell">Date Surveyed</td><td class="sheet__cell">Conditon</td><td class="sheet__cell">Floor Area (sqm)</td><td class="sheet__cell">Statutory</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">HA-0142</td><td class="sheet__cell">ul. Świętego Tomasza 24</td><td class="sheet__cell">II*</td><td class="sheet__cell">11/04/1698</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">Good</td><td class="sheet__cell">1,240.50</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">HA-0143</td><td class="sheet__cell">Kanonicza 7</td><td class="sheet__cell">Grade 2</td><td class="sheet__cell">29/09/1802</td><td class="sheet__cell">17/11/2025</td><td class="sheet__cell">fair</td><td class="sheet__cell">487.456</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">HA-0144</td><td class="sheet__cell">Grodzka 53</td><td class="sheet__cell">Local list</td><td class="sheet__cell">02/05/1936</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">at-risk</td><td class="sheet__cell">96</td><td class="sheet__cell">N</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">HA-0142</td><td class="sheet__cell">ul. Świętego Tomasza 24</td><td class="sheet__cell">II</td><td class="sheet__cell">11/04/1698</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">POOR</td><td class="sheet__cell">1,240.50</td><td class="sheet__cell">Yes</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">313 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">319</th><td class="sheet__cell">HA-0459</td><td class="sheet__cell">Floriańska 41</td><td class="sheet__cell">Grade 2</td><td class="sheet__cell">17/06/1874</td><td class="sheet__cell">22/05/2026</td><td class="sheet__cell">Good</td><td class="sheet__cell">612.30</td><td class="sheet__cell">Y</td></tr></tbody></table>
<p>The header row says <code>Ref</code> where the register says reference, and <code>Conditon</code> because somebody typed it that way. Grades arrive as <code>II*</code>, <code>Grade 2</code>, <code>II</code> and <code>Local list</code>. Dates run day first across three centuries. <code>HA-0142</code> appears twice, once <code>Good</code> and once <code>POOR</code>, because the surveyor revisited and left both lines in.</p>
<p>The person drags the file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, holds the grades to your lists, and puts every row in front of them. Your <code>onComplete</code> handler posts the clean rows to a route you own. That route streams them into a staging table and calls one procedure.</p>
<p>No Updog server stands between the browser and the database.</p>
<h2 id="the-table-and-the-one-in-front-of-it">The table and the one in front of it</h2>
<p>Two tables hold the work. The register is the destination, and the staging table is the landing strip bulk copy needs.</p>
<pre><code class="language-sql">CREATE TABLE dbo.heritage_asset (
    reference       NVARCHAR(20)  NOT NULL PRIMARY KEY,
    address         NVARCHAR(160) NOT NULL,
    grade           NVARCHAR(10)  NOT NULL,
    first_recorded  DATE          NULL,
    surveyed_on     DATE          NOT NULL,
    asset_condition NVARCHAR(20)  NOT NULL,
    floor_area_sqm  DECIMAL(9, 2) NULL,
    listed          BIT           NOT NULL,
    updated_at      DATETIME2(0)  NOT NULL DEFAULT SYSUTCDATETIME()
);

CREATE TABLE dbo.heritage_asset_stage (
    batch_id        UNIQUEIDENTIFIER NOT NULL,
    reference       NVARCHAR(20)  NOT NULL,
    address         NVARCHAR(160) NOT NULL,
    grade           NVARCHAR(10)  NOT NULL,
    first_recorded  DATE          NULL,
    surveyed_on     DATE          NOT NULL,
    asset_condition NVARCHAR(20)  NOT NULL,
    floor_area_sqm  DECIMAL(9, 2) NULL,
    listed          BIT           NOT NULL,
    op              NVARCHAR(6)   NOT NULL,
    INDEX IX_stage_batch NONCLUSTERED (batch_id)
);</code></pre>
<p>The staging table repeats every declaration and adds two columns. <code>op</code> carries what the person did to the row, and <code>batch_id</code> keeps one import apart from another, since a permanent staging table can hold two people's chunks at the same time.</p>
<p>Three of those declarations were chosen against the file rather than by habit.</p>
<p><code>address</code> is <code>NVARCHAR</code> because the second field of the first row reads <code>ul. Świętego Tomasza 24</code>. Under <code>char</code> and <code>varchar</code>, "If a non-UTF-8 collation is specified, then these data types store only a subset of characters supported by the corresponding code page of that collation." Microsoft's own advice is a UTF-8 enabled collation on SQL Server 2019 and later, or <code>nchar</code> and <code>nvarchar</code> before that.</p>
<p><code>first_recorded</code> is <code>DATE</code> because <code>11/04/1698</code> is 55 years below the floor of <code>datetime</code>, which runs "1753-01-01 (January 1, 1753) through 9999-12-31 (December 31, 9999)". Microsoft says the rest out loud. "Avoid using <strong>datetime</strong> for new work. Instead, use the <strong>time</strong>, <strong>date</strong>, <strong>datetime2</strong>, and <strong>datetimeoffset</strong> data types."</p>
<p><code>floor_area_sqm</code> is <code>DECIMAL(9, 2)</code>, which keeps seven digits in front of the point and two behind it.</p>
<h2 id="what-the-declaration-decides">What the declaration decides</h2>
<p>Each declaration decides how a value that does not fit will die, and SQL Server has two ways of doing it.</p>
<p><strong>One of them is loud.</strong> A string longer than its column raises an error carrying the table, the column and the value, since SQL Server 2019 phrases it as "String or binary data would be truncated in table '%.*ls', column '%.*ls'. Truncated value: '%.*ls'." That is error 2628 under database compatibility level 150, where <code>VERBOSE_TRUNCATION_WARNINGS</code> defaults to <code>ON</code>. Turn the setting off at the same level and the same failure arrives as the older error 8152, which names nothing.</p>
<p><strong>Two of them are quiet.</strong> A character outside the collation's code page is replaced on the way in, and Microsoft states the consequence in one sentence. "As with earlier versions of SQL Server, data loss during code page translations isn't reported." A third decimal digit is dropped the same way, since "By default, SQL Server uses rounding when converting a number to a <strong>decimal</strong> or <strong>numeric</strong> value with a lower precision and scale", and "Loss of only precision and scale isn't sufficient to raise an error".</p>
<p>So <code>487.456</code> becomes <code>487.46</code> and nothing says so. Only the person who measured that building knows whether it matters. A browser-side importer is the last place they are still in the room.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array carries the same widths and lists the tables declared.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const GRADES = ["Grade I", "Grade II*", "Grade II", "Local"];
const CONDITIONS = ["Good", "Fair", "Poor", "At risk"];
const YES_NO = ["Yes", "No"];

export const columns: DataEditorColumn[] = [
  {
    id: "reference",
    title: "Reference",
    size: 130,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^HA-\\d{4}$" },
      { type: "unique" },
    ],
  },
  {
    id: "address",
    title: "Address",
    size: 260,
    validators: [
      { type: "required" },
      { type: "function", fn: (value) => String(value).length > 160
        ? { level: "error", message: "160 characters at most" }
        : null },
    ],
  },
  {
    id: "grade",
    title: "Grade",
    size: 130,
    editor: { type: "select", options: GRADES, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: GRADES }],
  },
  {
    id: "firstRecorded",
    title: "First recorded",
    size: 150,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "surveyedOn",
    title: "Survey date",
    size: 150,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "condition",
    title: "Condition",
    size: 130,
    editor: { type: "select", options: CONDITIONS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: CONDITIONS }],
  },
  {
    id: "floorAreaSqm",
    title: "Floor area",
    size: 140,
    editor: { type: "number" },
    formatter: (value) => (value ? value + " m2" : ""),
    validators: [
      { type: "number", min: 0, max: 9_999_999, decimalPlaces: 2 },
    ],
  },
  {
    id: "listed",
    title: "Statutory listing",
    size: 160,
    editor: { type: "select", options: YES_NO, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: YES_NO }],
  },
];</code></pre>
<p>Each rule answers a line in the table definition. The <code>regex</code> holds the reference inside <code>NVARCHAR(20)</code> and inside the register's own format. The <code>function</code> validator counts the address against 160 characters, so truncation is reported in a grid cell. <code>decimalPlaces: 2</code> holds the floor area to two decimal digits. The <code>select</code> editors hold the grade and the condition to fixed lists, and a value nobody maps is dropped.</p>
<p><code>{ type: "unique" }</code> on the reference is the rule that saves the write. Uniqueness is checked against every other row in the same column, so both <code>HA-0142</code> cells light up before submit. That matters because the merge refuses the pair, where "The <code>MERGE</code> statement can't update the same row more than once, or update and delete the same row."</p>
<h2 id="what-the-person-reads-and-what-travels">What the person reads and what travels</h2>
<p>A grid of bare numbers reads badly, and a database column has no room for the unit. The <code>formatter</code> settles that split.</p>
<p>It formats the display value while the stored data stays as it was. The person reads <code>1240.5 m2</code>, the store holds <code>1240.5</code>, and the store reaches <code>DECIMAL(9, 2)</code>. Search runs on the formatted text, so somebody typing the unit still finds the cell. Find and replace writes back to the stored value.</p>
<p>The <code>transformer</code> works from the other end. It runs as rows are uploaded, so <code>ha-0142 </code> arrives trimmed and upper case, ahead of the pattern check.</p>
<h2 id="the-headers-the-consultancy-sends">The headers the consultancy sends</h2>
<p>Updog scores each header against the column id and the column title, and the higher score wins.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Ref</code></td>
<td><code>reference</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Site Address</code></td>
<td><code>address</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Listing Grade</code></td>
<td><code>grade</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>First Recorded</code></td>
<td><code>firstRecorded</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Date Surveyed</code></td>
<td><code>surveyedOn</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Conditon</code></td>
<td><code>condition</code></td>
<td>edit distance, 65</td>
</tr>
<tr>
<td><code>Floor Area (sqm)</code></td>
<td><code>floorAreaSqm</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Statutory</code></td>
<td><code>listed</code></td>
<td>contains, 80</td>
</tr>
</tbody>
</table></div>
<p><code>Conditon</code> is the interesting one. The contains tier refuses at eight characters against nine, and no whole word is shared. One edit sits inside the three allowed at that length, so the typo lands anyway. <code>Ref</code> is three characters, below the floor of every tier, and no built-in group carries it. It needs the one <code>synonyms</code> entry in the mount below.</p>
<p>Values follow the same ladder. <code>at-risk</code> normalizes to <code>atrisk</code> and equals the option. <code>Local list</code> contains <code>Local</code>. <code>Grade 2</code> shares one word of two with <code>Grade II</code> and lands at seventy. <code>Y</code> and <code>N</code> reach <code>Yes</code> and <code>No</code> at ninety, since the built-in table already carries them. <code>II</code> and <code>II*</code> are too short to reach anything, so the mount spells them out.</p>
<p>The file settles its own dates. <code>29/09/1802</code> and <code>17/11/2025</code> both carry a value above twelve in the second position, so the scan reads the whole file day first, and <code>11/04/1698</code> and <code>03/04/2026</code> follow.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the file, the schema and the register together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;HeritageAsset>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="reference"
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      reference: ["ref", "asset ref", "uprn"],
    },
    values: {
      "Grade II*": ["ii*", "2*", "grade 2*"],
      "Grade II": ["ii", "grade 2"],
      "Grade I": ["i", "grade 1"],
      Local: ["local list", "locally listed"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> is the reference alone, which is also the table's primary key and the <code>ON</code> clause of the merge. One column carries the identity of a building through all three.</p>
<p><code>enableDeleteRow="all"</code> lets the person drop the stale <code>HA-0142</code> line by hand once the grid shows both. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, the duplicate reference included. Whatever they fix by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed through <code>synonyms</code> next season.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying four independent flags.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 5000;

const toRow = (entry: ResultRow&#x3C;HeritageAsset>) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  return [{
    reference: entry.row.reference,
    address: entry.row.address,
    grade: entry.row.grade,
    firstRecorded: entry.row.firstRecorded || null,
    surveyedOn: entry.row.surveyedOn,
    assetCondition: entry.row.condition,
    floorAreaSqm: entry.row.floorAreaSqm ? Number(entry.row.floorAreaSqm) : null,
    listed: entry.row.listed === "Yes",
    op: entry.isDeleted ? "delete" : "upsert",
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;HeritageAsset>) => {
  for (const source of result.sources) {
    const rows = source.rows.flatMap(toRow);

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const answer = await fetch("/api/heritage/write", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
      });
      if (!answer.ok) throw new Error((await answer.json()).message);
    }
  }
  await storeSynonyms(result.learnedSynonyms);
}, []);</code></pre>
<p>A new building and an edited building become the same payload, since one <code>MERGE</code> decides which of the two it is. A row the person added and then deleted goes nowhere. The names change shape here on purpose, since the staging table calls the column <code>asset_condition</code>.</p>
<p>Every value leaves in the shape its declared type accepts. The floor area becomes a number, the statutory flag becomes a boolean for <code>BIT</code>, and an empty first-recorded date becomes <code>null</code>.</p>
<p>The chunk size is yours. Bulk copy publishes no row cap, and Microsoft's own batching tests report that "there was typically no advantage to breaking large batches into smaller chunks. In fact, this subdivision often resulted in slower performance than submitting a single large batch." So five thousand rows is a number chosen against what your own endpoint accepts, and the ladder is the only published figure in this section.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the whole survey clears the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-streams-the-rows">The route that streams the rows</h2>
<p>The route holds the connection string, and the browser stops there.</p>
<pre><code class="language-ts">import sql from "mssql";
import { randomUUID } from "node:crypto";

const pool = await sql.connect(process.env.SQL_CONNECTION_STRING);

const toTable = (rows, batchId) => {
  const table = new sql.Table("dbo.heritage_asset_stage");
  table.columns.add("batch_id", sql.UniqueIdentifier, { nullable: false });
  table.columns.add("reference", sql.NVarChar(20), { nullable: false });
  table.columns.add("address", sql.NVarChar(160), { nullable: false });
  table.columns.add("grade", sql.NVarChar(10), { nullable: false });
  table.columns.add("first_recorded", sql.Date, { nullable: true });
  table.columns.add("surveyed_on", sql.Date, { nullable: false });
  table.columns.add("asset_condition", sql.NVarChar(20), { nullable: false });
  table.columns.add("floor_area_sqm", sql.Decimal(9, 2), { nullable: true });
  table.columns.add("listed", sql.Bit, { nullable: false });
  table.columns.add("op", sql.NVarChar(6), { nullable: false });

  for (const row of rows) {
    table.rows.add(
      batchId,
      row.reference,
      row.address,
      row.grade,
      row.firstRecorded,
      row.surveyedOn,
      row.assetCondition,
      row.floorAreaSqm,
      row.listed,
      row.op,
    );
  }
  return table;
};

app.post("/api/heritage/write", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });
  if (!session.canEditRegister) {
    return response.status(403).json({ message: "No register access" });
  }

  const batchId = randomUUID();

  try {
    await pool.request().bulk(toTable(request.body.rows, batchId));

    const answer = await pool
      .request()
      .input("batch", sql.UniqueIdentifier, batchId)
      .execute("dbo.usp_MergeHeritageBatch");

    response.json(answer.recordset[0]);
  } catch (error) {
    request.log.error({ number: error.number, message: error.message });
    await discardBatch(batchId);
    return response.status(502).json({ message: describe(error) });
  }
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. The register permission is checked before a row is read. <code>sql.Table</code> names the staging table and then declares each column, in the order the table declares them, with the same widths. A value the declared type cannot take is refused at the driver, so the boundary check happens in one place.</p>
<p>The batch id is minted here and never leaves the server. It is what lets the procedure find this import's rows among anybody else's, and what lets <code>discardBatch</code> clean up after a failure. Microsoft asks for one thing beside it. "Avoid parallel execution of batches that operate on a single table in one database."</p>
<h2 id="the-statement-that-settles-the-batch">The statement that settles the batch</h2>
<p>The procedure reads the rows this batch landed and writes the register once.</p>
<pre><code class="language-sql">CREATE PROCEDURE dbo.usp_MergeHeritageBatch
    @batch UNIQUEIDENTIFIER
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE @verdicts TABLE (verdict NVARCHAR(10));

    BEGIN TRANSACTION;

    MERGE dbo.heritage_asset WITH (HOLDLOCK) AS target
    USING (SELECT * FROM dbo.heritage_asset_stage
            WHERE batch_id = @batch AND op = N'upsert') AS source
        ON target.reference = source.reference
    WHEN MATCHED THEN
        UPDATE SET address         = source.address,
                   grade           = source.grade,
                   first_recorded  = source.first_recorded,
                   surveyed_on     = source.surveyed_on,
                   asset_condition = source.asset_condition,
                   floor_area_sqm  = source.floor_area_sqm,
                   listed          = source.listed,
                   updated_at      = SYSUTCDATETIME()
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (reference, address, grade, first_recorded, surveyed_on,
                asset_condition, floor_area_sqm, listed)
        VALUES (source.reference, source.address, source.grade,
                source.first_recorded, source.surveyed_on,
                source.asset_condition, source.floor_area_sqm, source.listed)
    OUTPUT $action INTO @verdicts;

    DELETE target
      FROM dbo.heritage_asset AS target
      JOIN dbo.heritage_asset_stage AS source
        ON source.reference = target.reference
     WHERE source.batch_id = @batch AND source.op = N'delete';

    DELETE FROM dbo.heritage_asset_stage WHERE batch_id = @batch;

    COMMIT TRANSACTION;

    SELECT SUM(CASE WHEN verdict = N'INSERT' THEN 1 ELSE 0 END) AS inserted,
           SUM(CASE WHEN verdict = N'UPDATE' THEN 1 ELSE 0 END) AS updated
      FROM @verdicts;
END;</code></pre>
<p><code>OUTPUT $action</code> counts the verdicts. It is "a column of type <strong>nvarchar(10)</strong> that returns one of three values for each row", and Microsoft calls the <code>OUTPUT</code> clause "the recommended way to query or count rows affected by a <code>MERGE</code>". Those two numbers travel back through the route to the browser, so the person learns how many buildings were added and how many were revised.</p>
<p>The merge, the deletes and the staging cleanup share one transaction, so a batch either lands whole or leaves nothing behind. <code>XACT_ABORT</code> rolls it back on any error the statement raises. <code>HOLDLOCK</code> is on the target because the same statement inserts buildings that are new and updates buildings that are already there.</p>
<p>Two footnotes belong on any page that shows this statement. The semicolon is required, and a missing one raises error 10713. And Microsoft's own caution stands. "At scale, <code>MERGE</code> might introduce complicated concurrency issues or require advanced troubleshooting. As such, plan to thoroughly test any <code>MERGE</code> statement before deploying to production."</p>
<h2 id="when-the-write-fails">When the write fails</h2>
<p>A rejected write arrives in Node as a <code>RequestError</code>. <code>err.number</code> holds the SQL Server error number the driver read off the wire, beside <code>lineNumber</code>, <code>state</code> and <code>procName</code>. One request can produce several errors at once, and the package says where they land. "SQL Server may generate more than one error for one request so you can access preceding errors with <code>err.precedingErrors</code>."</p>
<p>A bulk copy that fails partway leaves its own rows behind, which is why <code>discardBatch</code> deletes them by batch id before the route answers. Log the number, answer the browser with a sentence a conservation officer can act on, and let the handler throw.</p>
<p>All of this happens with the confirm dialog open and a spinner on the button. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no SQL Server connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route, the staging table and the procedure in the middle are work you do.</p>
<p>SQL Server already ships its own way in for the other case. <code>BULK INSERT</code> reads a file the server itself can reach, and <code>bcp</code> runs on a machine somebody signs into. The Import Flat File Wizard copies a flat file "to a new table in your database" once SQL Server Management Studio is installed. It previews "the first 50 rows", types the columns from "the first 200 rows", and encodes with "the system's active code page. On most machines this defaults to ANSI." For a file your own team assembled, those are the shorter way in. Everything above exists for the export a consultancy sends, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-survey">The pieces you wrote and the next survey</h2>
<p>You wrote two tables carrying the same declarations, a schema with eight columns, one <code>synonyms</code> block, a route that streams a chunk over the connection, and one procedure that settles a batch and clears its own staging rows. The file stays on the machine that opened it. The rows travel from your own front end to your own route and into SQL Server. The only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The next survey brings the same consultancy and a fourth spelling of <code>Grade II*</code>. The mappings from this season are already stored, the new spelling costs one more line in <code>synonyms</code>, and a value SQL Server would have rewritten in silence sits in a grid cell instead, in front of the person who measured it.</p>]]></content:encoded></item>
<item><title>Data Compliance for SaaS: What Vendors Receive</title><link>https://updog.tech/blog/data-compliance-for-saas/</link><guid isPermaLink="true">https://updog.tech/blog/data-compliance-for-saas/</guid><pubDate>Mon, 03 Aug 2026 00:00:00 GMT</pubDate><description>What controller and processor mean, what a product can do with the data it receives, and how the kind of vendor you add changes what you have to check.</description><content:encoded><![CDATA[<p>Every software company holds data that belongs to someone else. Every vendor it adds carries that data further. Where your users live decides which rules apply, and what your vendors receive decides how much of the work lands on you.</p>
<h2 id="the-kinds-of-rules-people-call-compliance">The kinds of rules people call compliance</h2>
<p><strong>Privacy laws.</strong> They cover personal data, anything that points to a person. They say why you may hold it, what you must tell people, and what rights people keep over their own records. Almost every country now has one of its own. Europe has the GDPR, the General Data Protection Regulation. California has the CCPA, the California Consumer Privacy Act. Brazil has the LGPD, its general data protection law, and China the PIPL, the Personal Information Protection Law.</p>
<p><strong>Industry laws.</strong> They sit on top and cover one trade and one kind of data. They ask for more than the privacy law does, and they follow the data to your vendors. HIPAA, the Health Insurance Portability and Accountability Act, covers US health plans, billing clearinghouses, and providers who bill electronically. GLBA, the Gramm-Leach-Bliley Act, covers US financial companies. FERPA covers school records where the school takes federal money, and COPPA services aimed at children under 13.</p>
<p><strong>Audits and certificates.</strong> They are not laws. An outside auditor checks that a company's controls existed and worked for a period, then writes a report. That is proof about the company, not proof that it follows a law, so a SOC 2 report does not make a company GDPR compliant. SOC 2 is a US report on how a service company handles security, access, and monitoring. ISO 27001 is the international standard for running security, and an accredited body issues the certificate. PCI DSS is the card industry's own rule set for anyone who touches card numbers.</p>
<p><strong>Product and supply chain rules.</strong> They target how a company is run and what it sells, not the personal data inside. NIS2, the second Network and Information Security Directive, puts security duties on essential and important organizations across 18 EU sectors, and DORA, the Digital Operational Resilience Act, does the same for finance and its tech providers. Both reach a small vendor through its bigger customers' contracts. The EU Data Act works the other way. It applies to anyone selling a cloud service in the EU, at any size, and the contract must let a customer leave with their data inside 30 days.</p>
<h2 id="who-answers-for-the-data">Who answers for the data</h2>
<p><strong>Controller.</strong> The controller decides why data is collected and what happens to it next. A company that signs people up and asks them for a phone number is the controller of those numbers, because it chose to ask. It answers to the people in the data and to the regulator, and it picks every vendor that touches the data after that.</p>
<p><strong>Processor.</strong> The processor handles the data for the controller and follows written instructions. It has no purpose of its own. A hosting company, a mail sender, and an import tool are processors as long as they only do the job they were given. A processor that starts using the data for something it wants becomes a controller for that part.</p>
<p>Your customer is the controller of their users' data, which makes you the processor. Your hosting provider and error tracker sit under you as subprocessors, and you answer to the customer for what they do. Every link needs a written contract, and the law sets what it covers, from security and confidentiality to deletion and audit rights.</p>
<p>The role follows the data, not the label. A contract can call a vendor a processor while its privacy policy claims the right to use your content for its own analytics. There, it is a controller. Your own responsibility stays where it is either way, and someone harmed can claim against both of you.</p>
<h2 id="what-a-product-does-with-your-data">What a product does with your data</h2>
<p>Any product that receives your data does a small number of things with it. It can keep a copy and decide who opens that copy, hand parts of it to its own vendors, move it across borders, hold it for years, and feed it to a model.</p>
<p><strong>Data can be stored.</strong> It sits in a database, and copies of it sit in backups, often in another country. A product's privacy page should name both places.</p>
<p><strong>Data can be opened by people.</strong> Support staff and engineers reach live records to do their work. What matters is how they get that access, how they lose it when they leave, and whether anything records who looked.</p>
<p><strong>Data can end up in logs.</strong> An error report carries the values that caused the error, so one broken row travels to whoever runs the error tracker. Data leaves this way with nobody deciding to send it.</p>
<p><strong>Data can cross a border.</strong> Once it leaves your region it needs legal cover, either a country the EU has ruled safe or the standard clauses inside the vendor contract. The vendor's pages should say where its servers sit and which route it relies on.</p>
<p><strong>Data can outlive its use.</strong> Each kind of record has a number of days attached to it, and deletion counts only when it clears the backups and the vendors too.</p>
<p><strong>Data can be encrypted.</strong> On the way and at rest, and someone holds the keys. Know who that is.</p>
<p><strong>Data can train a model.</strong> Prompts and files sent to an AI feature may be stored, and they may feed a model shared with other customers. The terms should say whether that happens and whether you can turn it off.</p>
<h2 id="the-kinds-of-vendors-you-can-add">The kinds of vendors you can add</h2>
<p><strong>Infrastructure you build on.</strong> You rent servers, a database, file storage, and an error tracker, and your whole product stands on them. All of your users' data reaches these companies, because there is nowhere else for it to live. Auditing a company that size is out of reach, and you do not have to. Sign the data processing agreement they already publish, name them on your subprocessor page so your customers can see who holds their data, and check which region that data sits in.</p>
<p><strong>A library you install.</strong> You run an install command, and someone else's code ships inside your own bundle. It runs with the same rights as the code you wrote, so it can read anything on the page, including your users' data and whatever the browser has saved. A library can also send data to its own server, so watch the requests it makes. Watch who can publish the package too, because stolen publishing rights put new code inside your product on your next install. A library that stays in the browser can do less, because all the work happens on the user's machine, and it also never receives your users' data.</p>
<p><strong>A script loaded from the vendor's server.</strong> You paste a snippet into your page for analytics, a chat window, or a session recorder. The browser downloads that code from the vendor every time someone opens the page. These products collect data as their job. A session recorder can save your users' data as they move through the page. You can usually control what goes to these services, through their own settings or through cookie consent.</p>
<p><strong>An API you call from your backend.</strong> Your server sends data to theirs for payments, email, a model, or a check on a document. Their code stays on their side, so pay attention to which data you share with them. Everything in the request is data they now hold. Their terms say how long they keep that request, who can read it, and whether it trains a model.</p>
<p><strong>A SaaS product.</strong> You sign up, and from that day your users' data lives on someone else's servers. It sits in their database and in their backups, their support staff can open it, and their own subprocessors hold pieces of it. Pay attention to who those subprocessors are and which countries they sit in, because you answer to your customer for all of them. The contract says what the vendor may do with the data, and it also sets how you get the data back and how their copies are deleted the day you leave.</p>
<p>You can answer most of this yourself. In the browser, open developer tools, go to the Network tab, then reload the page and use the feature you are checking. Every request the page makes shows up as a line with the domain it went to, and clicking a line shows what was sent inside it. A vendor that promises your data stays in the browser is confirmed or caught right there.</p>
<p>On your own server the requests are yours to read. Log one call to the vendor's API and look at the body of it. Those fields are what the vendor receives, and that list is the one worth shortening.</p>
<h2 id="where-updog-sits">Where Updog sits</h2>
<p>Updog is a CSV and spreadsheet importer you install as a library. When someone uploads a file, it lives only in their browser. They match the columns to your fields, fix what the checks flag, and press submit, and your own API receives the finished rows. File data is never sent to Updog servers, so we hold no copy of it.</p>
<p>One request goes to us, and it checks the license. It carries the API key and the domain, with no file contents, rows, or headers. The SDK also keeps one key in the browser storage, a signed grant that lets the editor work while our API is down, and it holds no personal data. You can turn that off if you would rather nothing was stored. Every field in that request and in that key is listed on our <a href="https://docs.updog.tech/data-and-privacy/">data and privacy page</a>.</p>
<p>For the file itself, your subprocessor list stays as it was, because the file never reaches us.</p>
<p>Your own duties stay where they are. Once the rows reach your API, they sit under the same rules as the rest of your data. Account data for our Console is ours, and it sits in the European Union. Support email is a real path for data to reach us, so pay attention when you are about to send us something sensitive.</p>
<p>As of August 2026, we hold no SOC 2 report and no ISO 27001 certificate, and we sign no business associate agreements. How to report a security problem is on our <a href="https://updog.tech/security/">security page</a>.</p>
<p>Every vendor you add puts another copy of your users' data somewhere you do not control. We built Updog so that importing a file adds none. The file stays in the browser where it was opened, and the only thing left to answer for is what your own API does with the rows.</p>]]></content:encoded></item>
<item><title>CSV Import for Accounting and Finance Software</title><link>https://updog.tech/blog/csv-import-for-accounting-finance-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-accounting-finance-software/</guid><pubDate>Sun, 02 Aug 2026 00:00:00 GMT</pubDate><description>A journal report writes the entry number once and leaves it blank on every line below. How to rebuild the grouping and check that each entry balances.</description><content:encoded><![CDATA[<p>Accounting runs on exports. A bookkeeper closes a period, prints a journal
report or a trial balance out of the ledger, and sends that file on to whoever
asked for it. The file is a report first and a data feed second, so it carries
subtotals, a grand total at the bottom, and blank cells under a value that was
written once.</p>
<p>It also carries money and dates in whatever shape the old system printed them.
Amounts arrive with thousands separators and a minus sign after the digits,
account codes lose their leading zeros the moment a spreadsheet opens them,
and the same day is written three ways across three exports.</p>
<p>The journal report a client sends holds 1,886 rows and closes with a grand
total. That total reads 5,688,871.26 on the debit side and 5,688,871.26 on the
credit side. The credit lines above it add up to 5,658,300.32.</p>
<p>An accounting platform keeps journal lines. Its customers export a report out of
the system they are leaving, and moving that report into your tables is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>. The
30,570.94 between the total and the lines went missing on the way out of the old
system, and the report is the only place it shows.</p>
<p>The schema belongs to you. The report belongs to the accountant at the customer,
who ran it out of whatever kept the books before. The one below is 167 KB of
<code>.csv</code> over 10 columns, and one import of it produced every number printed here.</p>
<h2 id="several-rows-one-entry">Several rows, one entry</h2>
<p>A journal entry is a group of lines whose debits equal its credits. The group is
the unit. One line of it says nothing.</p>
<p>MindBridge publishes the checklist its own platform asks a client's ledger to
meet. Four fields are required, being Account ID, Effective Date, Debit and
Credit. Transaction ID is described as "the unique code used to group entries
within a given transaction", and both amount fields carry a control point named
Unbalanced Debits and Credits.</p>
<p>A report prints that group the way a person reads it. The date, the type, the
number and the author sit on the first line, and every line under it carries an
account and an amount and nothing else.</p>
<h2 id="the-file-the-accountant-drops-in">The file the accountant drops in</h2>
<p>Eleven of its rows and the grand total it closes with, spelled the way the export
spelled them.</p>
<p><code>journal-report-2025.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Date</td><td class="sheet__cell">Transaction Type</td><td class="sheet__cell">No.</td><td class="sheet__cell">Memo/Description</td><td class="sheet__cell">Account No.</td><td class="sheet__cell">Account</td><td class="sheet__cell">Debit</td><td class="sheet__cell">Credit</td><td class="sheet__cell">Created By</td><td class="sheet__cell">Created</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">01/01/2025</td><td class="sheet__cell">Journal Entry</td><td class="sheet__cell">1039</td><td class="sheet__cell">Payroll journal</td><td class="sheet__cell">6010</td><td class="sheet__cell">Salaries and wages</td><td class="sheet__cell">43,958.73</td><td class="sheet__cell"></td><td class="sheet__cell">d.okonkwo</td><td class="sheet__cell">01/01/2025 2:47:25 PM</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Payroll journal</td><td class="sheet__cell">6020</td><td class="sheet__cell">Employee benefits</td><td class="sheet__cell">3,956.29</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Payroll journal</td><td class="sheet__cell">2150</td><td class="sheet__cell">Payroll liabilities:Withholding</td><td class="sheet__cell"></td><td class="sheet__cell">10,550.10</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Payroll journal</td><td class="sheet__cell">2160</td><td class="sheet__cell">Payroll liabilities:Pension</td><td class="sheet__cell"></td><td class="sheet__cell">2,197.94</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Payroll journal</td><td class="sheet__cell">01020</td><td class="sheet__cell">Cash and cash equivalents:Payroll account</td><td class="sheet__cell"></td><td class="sheet__cell">35,166.98</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">01/03/2025</td><td class="sheet__cell">Sales Receipt</td><td class="sheet__cell">1011</td><td class="sheet__cell">Licence renewal 4221</td><td class="sheet__cell">1010</td><td class="sheet__cell">Cash and cash equivalents:Operating account</td><td class="sheet__cell">3,719.65-</td><td class="sheet__cell"></td><td class="sheet__cell">s.pettersen</td><td class="sheet__cell">01/03/2025 3:17:45 PM</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Licence renewal 4221</td><td class="sheet__cell">4010</td><td class="sheet__cell">Revenue:Product</td><td class="sheet__cell"></td><td class="sheet__cell">3,099.71-</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Licence renewal 4221</td><td class="sheet__cell">2100</td><td class="sheet__cell">Sales tax payable</td><td class="sheet__cell"></td><td class="sheet__cell">619.94-</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Total for January 2025</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">513,774.17</td><td class="sheet__cell">513,774.17</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">11</th><td class="sheet__cell">02/01/2025</td><td class="sheet__cell">Bill</td><td class="sheet__cell">1122</td><td class="sheet__cell">Supplier invoice 4448</td><td class="sheet__cell">6420</td><td class="sheet__cell">Travel and entertainment:Conferences</td><td class="sheet__cell">8,346.58</td><td class="sheet__cell"></td><td class="sheet__cell">a.varga</td><td class="sheet__cell">02/01/2025 10:03:42 AM</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">12</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Supplier invoice 4448</td><td class="sheet__cell">2010</td><td class="sheet__cell">Accounts payable</td><td class="sheet__cell"></td><td class="sheet__cell">8,346.58</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">1874 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1887</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">Grand total</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">5,688,871.26</td><td class="sheet__cell">5,688,871.26</td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr></tbody></table>
<p>Entry <code>1039</code> runs five lines and only the first one says so. Entry <code>1011</code> writes
its three amounts with the minus sign after the digits. The row between the two
entries is a monthly total. One account code arrives padded to five characters,
one names a sub-account after a colon, and one belongs to no account this
customer had when they signed up.</p>
<p>The accountant drops that file into your platform and Updog opens it in the tab
they are already sitting in. Reading, matching and checking all happen there, and
your API sees a line of this ledger only after they press submit.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
puts the two designs next to each other.</p>
<h2 id="your-side-of-the-ledger">Your side of the ledger</h2>
<p>Ten fields. Intuit publishes six of them as what a journal entry import needs,
being <code>Journal No.</code>, <code>Journal Date</code>, <code>Account Name</code>, <code>Journal/Description</code>,
<code>Debits</code> and <code>Credits</code>. MindBridge adds the entered date and the user.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { accountCodeColumn } from "./accountCode";
import { signedAmount } from "./signedAmount";

const TYPES = ["Journal", "Sale", "Purchase", "Payment", "Transfer", "Adjustment"];

export const buildColumns = (chart: Set&#x3C;string>): DataEditorColumn[] => {
  return [
    { id: "entryNo", title: "Entry number" },
    { id: "postingDate", title: "Posting date", editor: { type: "date" } },
    {
      id: "entryType",
      title: "Entry type",
      editor: { type: "select", options: TYPES, enableCustomValue: false },
    },
    { id: "memo", title: "Memo", size: 220 },
    accountCodeColumn(chart),
    { id: "accountName", title: "Account name", size: 260 },
    {
      id: "debit",
      title: "Debit",
      editor: { type: "number" },
      transformer: signedAmount,
      validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
    },
    {
      id: "credit",
      title: "Credit",
      editor: { type: "number" },
      transformer: signedAmount,
      dependentFields: ["debit"],
      validators: [
        { type: "number", min: 0, decimalPlaces: 2 },
        {
          type: "function",
          fn: (value, row) => {
            const debit = String(row.debit ?? "").trim();
            const credit = String(value ?? "").trim();
            return Boolean(debit) === Boolean(credit)
              ? { level: "error", message: "A line carries a debit or a credit" }
              : null;
          },
        },
      ],
    },
    { id: "createdBy", title: "Created by" },
    {
      id: "enteredDate",
      title: "Entered date",
      editor: { type: "date" },
      validators: [{ type: "date" }],
      transformer: (value) => {
        const parts = /^(\d{2})\/(\d{2})\/(\d{4})/.exec(String(value ?? ""));
        return parts ? parts[3] + "-" + parts[1] + "-" + parts[2] : value;
      },
    },
  ];
};</code></pre>
<p>Every amount passes through the number editor before it is stored, so
<code>43,958.73</code> lands as <code>43958.73</code> and a currency symbol falls away with the comma.
1,581 rows carry a grouped amount and 1,529 of them lose the comma with no rule
of yours. The two <code>transformer</code> entries are there for the shapes that editor
leaves alone, and both have a section below.</p>
<h2 id="two-headers-that-both-say-account">Two headers that both say account</h2>
<p>Nine of the ten headers land with no configuration. <code>Debit</code>, <code>Credit</code> and
<code>Created By</code> are the field name under different punctuation. <code>Date</code>,
<code>Memo/Description</code> and <code>Account</code> each sit inside the field they claim. <code>No.</code>,
<code>Transaction Type</code> and <code>Account No.</code> share one word out of two with theirs.</p>
<p>Two headers say account and two fields say account. One assignment runs over the
whole header row, so <code>Account</code> takes <code>accountName</code> and <code>Account No.</code> takes
<code>accountCode</code>. Neither one crowds the other.</p>
<p><code>Created</code> reaches nothing. It shares no word with <code>entered date</code> and sits too far
from it to score. One alias settles that, and the rest of the table exists for
the next customer, whose export out of Xero calls the same columns
<code>JournalNumber</code>, <code>JournalDate</code>, <code>AccountCode</code> and <code>NetAmount</code>.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    entryNo: ["no.", "journalnumber", "transaction number"],
    postingDate: ["journaldate", "effective date"],
    accountCode: ["accountcode", "account number", "account id"],
    memo: ["details", "description"],
    enteredDate: ["created", "entered date"],
  },
  values: {
    Sale: ["invoice", "deposit", "credit memo"],
    Purchase: ["bill", "expense", "vendor credit"],
  },
};</code></pre>
<h2 id="where-each-transaction-type-lands">Where each transaction type lands</h2>
<p>Value matching collects the type column across the whole upload. Eleven distinct
strings arrive against six options, and five of them land on their own.</p>
<div class="blog-table blog-table--fixed blog-table--ledger-types"><table>
<thead>
<tr>
<th>In the file</th>
<th>Rows</th>
<th>Reaches</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Invoice</code></td>
<td>166</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Bill</code></td>
<td>131</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Payment</code></td>
<td>121</td>
<td>Payment, exact</td>
</tr>
<tr>
<td><code>Bill Payment (Check)</code></td>
<td>102</td>
<td>Payment, contains</td>
</tr>
<tr>
<td><code>Expense</code></td>
<td>82</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Journal Entry</code></td>
<td>74</td>
<td>Journal, contains</td>
</tr>
<tr>
<td><code>Sales Receipt</code></td>
<td>50</td>
<td>Sale, contains</td>
</tr>
<tr>
<td><code>Credit Memo</code></td>
<td>27</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Transfer</code></td>
<td>26</td>
<td>Transfer, exact</td>
</tr>
<tr>
<td><code>Deposit</code></td>
<td>23</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Vendor Credit</code></td>
<td>19</td>
<td>nothing on its own</td>
</tr>
</tbody>
</table></div>
<p>The six left over are decisions about accounting, and the spelling has nothing to
do with it. A deposit and a credit memo both touch a customer, and a vendor
credit reverses a purchase. Which side of your enum each one lands on is your
platform's call. Writing all six into the <code>values</code> table settles them once, in
code, where an accountant never has to meet them.</p>
<h2 id="what-each-field-receives">What each field receives</h2>
<div class="blog-table blog-table--fixed blog-table--ledger-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Date</code></td>
<td>filled on 821 rows in 1,886</td>
<td>no rule, because the entry above it holds the date</td>
</tr>
<tr>
<td><code>Transaction Type</code></td>
<td>eleven strings</td>
<td>six options</td>
</tr>
<tr>
<td><code>No.</code></td>
<td>821 numbers over 1,873 lines</td>
<td>no rule, and a sweep that rebuilds the grouping</td>
</tr>
<tr>
<td><code>Memo/Description</code></td>
<td>free text, and a total line's label</td>
<td>no rule at all</td>
</tr>
<tr>
<td><code>Account No.</code></td>
<td><code>1010</code>, <code>01020</code>, and 13 empty cells</td>
<td><code>required</code>, and a code the chart of accounts holds</td>
</tr>
<tr>
<td><code>Account</code></td>
<td><code>Payroll liabilities:Withholding</code></td>
<td>no rule, because the code carries the identity</td>
</tr>
<tr>
<td><code>Debit</code></td>
<td><code>43,958.73</code>, <code>3,719.65-</code>, and an empty cell</td>
<td>a number of zero and up</td>
</tr>
<tr>
<td><code>Credit</code></td>
<td>the same, and 9 lines carrying neither</td>
<td>a number, and one of the two filled</td>
</tr>
<tr>
<td><code>Created By</code></td>
<td>five user names</td>
<td>no rule</td>
</tr>
<tr>
<td><code>Created</code></td>
<td><code>01/01/2025 2:47:25 PM</code></td>
<td>ISO, written by a transformer</td>
</tr>
</tbody>
</table></div>
<p><a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> covers those
failures in the shape any file can produce. The sections below take the ones a
ledger produces.</p>
<h2 id="the-entry-number-written-once">The entry number written once</h2>
<p>1,065 of the 1,886 rows leave <code>No.</code> blank. The value those rows need sits on a
row above them, and how far above depends on how many lines that entry ran to.</p>
<p><strong>No rule that reads one row can see it.</strong> A <code>function</code> validator receives a
value and the row around it, and the row around it is exactly what is missing.
The entry number is the one field a ledger line cannot supply for itself.</p>
<p><code>{ type: "asyncFunction" }</code> is the rule that reaches the rest. It receives every
cell in the column at once, in the order the file arrived in, and each cell
carries its row. So the sweep walks the column, remembers the last number it saw,
and hands that number to every line under it.</p>
<p>That is the fill-down, and it happens inside the rule that needs it. Nothing is
written back into the grid, so the person still sees the report the way the
report was printed.</p>
<h2 id="the-minus-that-arrives-after-the-number">The minus that arrives after the number</h2>
<p>23 entries in this file carry every amount negative, and the export wrote the
sign at the end of each one. That is 55 cells reading <code>3,719.65-</code>. An entry
written that way undoes an earlier one.</p>
<p>The convention comes from mainframe accounting output and it is still shipping.
SAP's own ABAP documentation says that for a numeric type "the last place on the
right is reserved for the sign", and that negative values are given a minus there
while positive values are given a blank.</p>
<p>Updog reads a number by peeling display noise off both ends and taking the sign
from the front. The four ways a ledger writes a negative land in three places.</p>
<div class="blog-table blog-table--fixed blog-table--ledger-signs"><table>
<thead>
<tr>
<th>Written</th>
<th>Becomes</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$1,250.00</code></td>
<td><code>1250.00</code></td>
<td>a currency symbol and the file's grouping come off</td>
</tr>
<tr>
<td><code>(1,250.00)</code></td>
<td><code>-1250.00</code></td>
<td>accounting parentheses peel off and set the sign</td>
</tr>
<tr>
<td><code>-1,250.00</code></td>
<td><code>-1250.00</code></td>
<td>the sign sits where the reader looks for it</td>
</tr>
<tr>
<td><code>1,250.00-</code></td>
<td><code>1,250.00-</code></td>
<td>a trailing sign leaves a character no number can hold</td>
</tr>
</tbody>
</table></div>
<p>So all 55 reach the grid untouched and the <code>number</code> rule reports each one.</p>
<p><strong>A number the importer cannot read casts no vote either.</strong> The scan that decides
whether a file writes <code>1,250.00</code> or <code>1.250,00</code> skips those 55 entirely, so 23
reversals settle nothing about the other 798 entries.</p>
<p>Three lines in the schema take the sign back to the front.</p>
<pre><code class="language-ts">export const signedAmount = (value: unknown): unknown => {
  const written = String(value ?? "");
  return written.endsWith("-")
    ? "-" + written.slice(0, -1).replace(/,/g, "")
    : value;
};</code></pre>
<p>All 55 become numbers, and every one of them is negative, so <code>min: 0</code> reports
each as out of range. A negative debit is an accounting decision, and your
platform is the one that settles whether it stores one.</p>
<h2 id="the-date-with-a-time-after-it">The date with a time after it</h2>
<p>Every filled <code>Created</code> cell carries a time after the date, as
<code>01/01/2025 2:47:25 PM</code>. The date patterns the importer holds all end at the
year, so a trailing time matches none of them. All 821 stay as text and the
<code>date</code> rule flags each one.</p>
<p>The posting date beside it needs nothing. The file writes <code>01/13/2025</code>, the
thirteen can only be a day, and one verdict of month-first covers every date
column in the file. All twelve months of 2025 come out where they belong.</p>
<p><strong>A transformer runs after the parser and its output is never sent back.</strong> So a
transformer that returns <code>01/01/2025</code> leaves the cell exactly as flagged as it
was. The one on <code>enteredDate</code> in the schema above writes the ISO string itself,
and the 821 flags go to zero.</p>
<h2 id="the-account-your-customer-never-opened">The account your customer never opened</h2>
<p>Your app already holds this customer's chart of accounts, so the account column
is checked against the codes that customer actually keeps. 19 rows in this ledger
name codes <code>4030</code>, <code>6260</code> and <code>6420</code>, which the customer opened after the chart
was pulled. Intuit tells its own users to add new accounts to the chart of
accounts before the import runs.</p>
<p>114 rows write the code padded to five characters, so <code>1020</code> arrives as <code>01020</code>.
Xero asks for account codes that match exactly, leading zeros included. Padding
both sides before the comparison lets one rule accept both spellings, and no row
in this file fails for that reason.</p>
<p>The name beside the code carries its parent, as <code>Payroll liabilities:Withholding</code>.
Intuit requires that full path on the way in and answers a bare sub-account with
a Line Account Invalid error. Keeping the whole string is the cheaper choice,
because the code is what identifies the account and the name is what a person
reads.</p>
<h2 id="when-the-two-sides-do-not-agree">When the two sides do not agree</h2>
<p>The same sweep that rebuilds the grouping adds up each entry.</p>
<pre><code class="language-ts">import type { DataEditorColumn, ValidationError } from "@updog/data-editor";

const cents = (value: unknown): number => {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
};

export const accountCodeColumn = (chart: Set&#x3C;string>): DataEditorColumn => {
  return {
    id: "accountCode",
    title: "Account code",
    validators: [
      { type: "required" },
      {
        type: "function",
        fn: (value) => {
          const code = String(value ?? "").trim().padStart(5, "0");
          return chart.has(code)
            ? null
            : { level: "error", message: "No account with this code" };
        },
      },
      {
        type: "asyncFunction",
        fn: async (cells) => {
          const totals = new Map&#x3C;string, number>();
          const entryOf: string[] = [];
          let current = "";

          for (const cell of cells) {
            const declared = String(cell.row.entryNo ?? "");
            if (declared) current = declared;
            entryOf.push(current);
            totals.set(
              current,
              (totals.get(current) ?? 0) +
                cents(cell.row.debit) -
                cents(cell.row.credit),
            );
          }

          return entryOf.map((entry): ValidationError | null => {
            const off = totals.get(entry) ?? 0;
            return off === 0
              ? null
              : {
                  level: "error",
                  message: "Entry " + entry + " is out by " + (off / 100).toFixed(2),
                };
          });
        },
      },
    ],
  };
};</code></pre>
<p>Debits and credits are totalled in whole cents, because two floating-point sums
of 1,873 amounts disagree in the last place often enough to matter. Every line of
a failing entry carries the message, so the person sees the whole entry.</p>
<p>The sweep flags 50 entries over 118 rows. 17 of them are out by 0.01, which is a
rounding difference on a foreign-currency line. The rest are out by between
449.46 and 18,037.83, and behind each one is a line that left the file on the way
out.</p>
<p><strong>A sweep is handed the clean cells only.</strong> Anything empty, or already carrying
an error, waits until the person settles it, so this account column handed over
1,854 of its 1,873 lines. The 19 held back are the off-chart codes, and an entry
missing a line stops balancing.</p>
<p>So 19 of those 50 entries carry the flag because the rule above them fired. Fix
the codes first. The sweep then runs on all 1,873 lines, the flag lands on 31
entries over 68 rows, and those 31 go back to the client.</p>
<h2 id="the-rows-that-are-not-lines">The rows that are not lines</h2>
<p>Every total line in the report leaves the account column empty, so <code>required</code>
catches all 13. They sit in the same list as everything else the person works
through, and the person selects the 13 and deletes them in one move.</p>
<p>MindBridge tells its own users that subtotal lines do not belong in a general
ledger file. Deleting them in the grid marks them <code>isDeleted</code>, and
the handler below drops them before it groups anything.</p>
<h2 id="the-code-that-stays-in-your-repository">The code that stays in your repository</h2>
<p>Updog ships no chart of accounts, no ledger template, no document type list and
no connector to any accounting system. Updog Importer reads CSV, TSV, JSON, XML,
XLSX, XLS, XLSB and ODS, so a Xero export that lands as tab-separated text opens
the same way a spreadsheet does. A bank statement that lands as a PDF reaches
<a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a> and comes back as rows the
wizard treats like any other. Above that layer, the ten columns, the six options,
the alias table and the sweep are all yours to maintain.</p>
<p>A sweep carries one cost, and it is worth knowing before you write your first.
The file's arrival is the only moment the rule sees the whole column. After that
it is called with whatever one edit touched, so correcting a single account code
hands it one cell and no entry around that cell. The balance flag on that entry
keeps whatever the opening pass gave it.</p>
<p>This file arrives once, on the day a customer moves in. The SDK holds no
schedule, no queue and no server of ours between the accountant and your API.</p>
<h2 id="what-the-handler-writes">What the handler writes</h2>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={useMemo(() => buildColumns(chart), [chart])}
  synonyms={synonyms}
  primaryKey="entryNo"
  blockSubmitOnError
  onComplete={async (result) => {
    const lines = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row);

    const entries = new Map&#x3C;string, LedgerLine[]>();
    let current = "";
    let header = { postingDate: "", enteredDate: "", entryType: "", createdBy: "" };

    for (const line of lines) {
      if (line.entryNo) {
        current = line.entryNo;
        header = {
          postingDate: line.postingDate,
          enteredDate: line.enteredDate,
          entryType: line.entryType,
          createdBy: line.createdBy,
        };
      }
      entries.set(current, [
        ...(entries.get(current) ?? []),
        {
          ...header,
          entryNo: current,
          accountCode: line.accountCode.padStart(5, "0"),
          memo: line.memo,
          amount: Number(line.debit || 0) - Number(line.credit || 0),
        },
      ]);
    }

    await postEntries([...entries.entries()]);
  }}
/></code></pre>
<p>Every row comes back through <code>onComplete</code> under the source it arrived in, tagged
<code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. The handler walks them the way
the sweep did, because they come back in the order they were read.</p>
<p>The signed amount is folded here, in the handler. A transformer receives one
value and nothing else, so a rule that spans two columns lives in a validator and
a value that spans two columns lives in your handler.</p>
<p><code>primaryKey</code> is required, and this report offers it one column. The entry number
is filled on the first line of each entry, distinct across all 821 of them, and
blank on the 1,065 lines under them. A key on it merges those 821 and lands the
other 1,065 again, so a second upload of the same year takes 1,886 rows to 2,951.
The identity your platform assigns to a line is the only thing that settles it.</p>
<h2 id="the-list-the-accountant-works-down">The list the accountant works down</h2>
<p>Out of 1,886 rows, 199 carry something a rule caught. 118 rows in an entry that
does not balance, 55 amounts written with a trailing minus, 27 lines carrying
both amounts or neither, 19 off-chart account codes and 13 total lines. 33 rows
carry two of those at once, and the same file against a schema with no
transformers carried 940.</p>
<p>The accountant works down that list against the ledger the report came out of,
which is the only place those answers live. Then 1,873 lines become 821 entries,
the two sides of each one agree to the cent, and the 30,570.94 the grand total
was carrying on its own is back on the lines.</p>]]></content:encoded></item>
<item><title>CSV Import for Property Management Software</title><link>https://updog.tech/blog/csv-import-for-property-management-software/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-property-management-software/</guid><pubDate>Sun, 02 Aug 2026 00:00:00 GMT</pubDate><description>A property management platform keeps four records where a rent roll keeps one row. How to take that file into your property, unit, lease and resident tables.</description><content:encoded><![CDATA[<p>The rent roll is the document a property manager lives by. It lists every unit
in the portfolio, who lives there, what they pay and when their lease ends,
and it gets pulled fresh for lenders, for owners and for the monthly review.
The system a portfolio runs prints one on demand.</p>
<p>It prints one page. A line on that page mixes the building, the unit, the
lease and the resident together, because a person reading it wants all four at
once. A database keeps them apart.</p>
<p>The rent roll a portfolio sends holds 1,905 rows. Behind it sit 6 properties,
1,710 units, 1,573 leases and 1,680 residents. None of those four numbers is
written anywhere on the page.</p>
<p>A property management platform keeps each of those four as its own record. Its
customers export a rent roll out of the system they are leaving, and that file
flattens all four onto one line. Moving those lines into your tables is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The schema belongs to you. The roll belongs to the portfolio manager at the
customer, who pulled it out of whatever ran the portfolio before. The one below
runs 1,905 rows over 14 columns, 270 KB of <code>.csv</code>, and every figure in this
article was read off a single import of it.</p>
<h2 id="the-four-tables-behind-one-row">The four tables behind one row</h2>
<p>A property owns units. A unit holds leases over time. A lease carries one
resident or several. Each of those is a row in a different table, and each child
row stores the id of the parent above it.</p>
<p>The order is published. Buildium tells its own customers to import rentals
first and people second, because "after your properties and units have been
entered into Buildium, you can begin to add your people". Its tenant template
asks every row for a property and a unit number.</p>
<p>A rent roll carries all four levels on one line. The property name repeats down
every row of that property, the unit repeats for every resident in it, and the
lease dates repeat for every roommate.</p>
<h2 id="the-rent-roll-a-portfolio-sends">The rent roll a portfolio sends</h2>
<p>Eight rows out of it, in the spelling the export used.</p>
<p><code>rent-roll.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th><th class="sheet__column" scope="col">N</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Prop</td><td class="sheet__cell">Property</td><td class="sheet__cell">Property Address</td><td class="sheet__cell">Unit</td><td class="sheet__cell">SqFt</td><td class="sheet__cell">Beds</td><td class="sheet__cell">Baths</td><td class="sheet__cell">Status</td><td class="sheet__cell">Resident</td><td class="sheet__cell">Email</td><td class="sheet__cell">Lease From</td><td class="sheet__cell">Lease To</td><td class="sheet__cell">Market Rent</td><td class="sheet__cell">Rent</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">GRN</td><td class="sheet__cell">Greenfield Commons</td><td class="sheet__cell">1400 Greenfield Road</td><td class="sheet__cell">A101</td><td class="sheet__cell">689</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">Occupied</td><td class="sheet__cell">Villanueva, Nadim</td><td class="sheet__cell">nadim.villanueva@mail.example.net</td><td class="sheet__cell">2025-11-08</td><td class="sheet__cell">2026-09-01</td><td class="sheet__cell">1,565.00</td><td class="sheet__cell">$1,565.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">GRN</td><td class="sheet__cell">GREENFIELD COMMONS</td><td class="sheet__cell">1400 Greenfield Rd</td><td class="sheet__cell">A102</td><td class="sheet__cell">710</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">Vacant-Ready</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">$1,535.00</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">GRN</td><td class="sheet__cell">Greenfield Commons</td><td class="sheet__cell">1400 Greenfield Rd</td><td class="sheet__cell">A122</td><td class="sheet__cell">530</td><td class="sheet__cell">0</td><td class="sheet__cell">1</td><td class="sheet__cell">Occupied</td><td class="sheet__cell">Beaumont, Valentina</td><td class="sheet__cell">valentina.beaumont@example.com</td><td class="sheet__cell">2024-08-21</td><td class="sheet__cell">2025-09-16</td><td class="sheet__cell">$1,140.00</td><td class="sheet__cell">1,100.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">GRN</td><td class="sheet__cell">Greenfield Commons</td><td class="sheet__cell">1400 Greenfield Rd</td><td class="sheet__cell">A122</td><td class="sheet__cell">530</td><td class="sheet__cell">0</td><td class="sheet__cell">1</td><td class="sheet__cell">Occupied</td><td class="sheet__cell">Radulescu, Quentin</td><td class="sheet__cell">quentin.radulescu@mail.example.net</td><td class="sheet__cell">2024-08-21</td><td class="sheet__cell">2025-09-16</td><td class="sheet__cell">$1,140.00</td><td class="sheet__cell">1,100.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">RIV</td><td class="sheet__cell">Riverbend Terrace</td><td class="sheet__cell">60 Riverbend Way</td><td class="sheet__cell">B403</td><td class="sheet__cell">704</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">Occ</td><td class="sheet__cell">Ishikawa, Joaquin</td><td class="sheet__cell">joaquin.ishikawa@example.com</td><td class="sheet__cell">07/2024</td><td class="sheet__cell">2025-07-10</td><td class="sheet__cell">$1,530.00</td><td class="sheet__cell">$1,495.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">RIV</td><td class="sheet__cell">Riverbend Terrace</td><td class="sheet__cell">60 Riverbend Way</td><td class="sheet__cell">B403</td><td class="sheet__cell">704</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">Occupied</td><td class="sheet__cell">Haddad, Wilhelmina</td><td class="sheet__cell">wilhelmina.haddad@example.com</td><td class="sheet__cell">2024-09-06</td><td class="sheet__cell">2025-03-30</td><td class="sheet__cell">1,530.00</td><td class="sheet__cell">$1,520.00</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="14"><span class="sheet__break-text">1196 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1204</th><td class="sheet__cell">HAW</td><td class="sheet__cell">Hawksmoor Court</td><td class="sheet__cell">215 Hawksmoor Lane</td><td class="sheet__cell">C210</td><td class="sheet__cell">845</td><td class="sheet__cell">2</td><td class="sheet__cell">1</td><td class="sheet__cell">Vacant</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">-</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="14"><span class="sheet__break-text">701 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1906</th><td class="sheet__cell">WLB</td><td class="sheet__cell">Willowbank Mews</td><td class="sheet__cell">8 Willowbank Drive</td><td class="sheet__cell">D118</td><td class="sheet__cell">612</td><td class="sheet__cell">1</td><td class="sheet__cell">1</td><td class="sheet__cell">Occupied</td><td class="sheet__cell">Okafor, Selina</td><td class="sheet__cell">selina.okafor@example.com</td><td class="sheet__cell">2025-04-14</td><td class="sheet__cell">2026-04-13</td><td class="sheet__cell">1,285.00</td><td class="sheet__cell">$1,285.00</td></tr></tbody></table>
<p><code>A102</code> is empty from the resident column rightward, because nobody lives there.
The two <code>A122</code> rows are roommates on one lease. The two <code>B403</code> rows are two
leases on one unit, and the first of them carries a lease start with a month, a
year, and no day. <code>C210</code> writes its market rent as a dash.</p>
<p>The roll names 1,680 people and the address each one lives at. Updog reads that
file, matches it and checks it in the tab the portfolio manager opened, so your
endpoint is the first machine to receive a row of it.
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side import</a>
sets the two designs side by side.</p>
<h2 id="what-a-lease-looks-like-in-your-schema">What a lease looks like in your schema</h2>
<p>Fourteen fields, and the status list is published. Fannie Mae's multifamily rent
roll template allows three values for <code>Lease Status Type</code>, Employee, Occupied
and Vacant, and it says a unit used as a model or a rental office is reported as
Vacant. The same template makes <code>Market Comparable Rent Amount</code> required and
caps <code>Tenant Contract Rent Amount</code> at 999,999.99.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { leaseFrom } from "./leaseFrom";
import { propertyName } from "./propertyName";

const STATUS = ["Occupied", "Vacant", "Employee"];

export const columns: DataEditorColumn[] = [
  { id: "propertyCode", title: "Property code", validators: [{ type: "required" }] },
  propertyName,
  { id: "propertyAddress", title: "Property address", size: 220 },
  {
    id: "unitNumber",
    title: "Unit number",
    validators: [{ type: "required" }],
    dependentFields: ["leaseFrom"],
  },
  {
    id: "squareFeet",
    title: "Square feet",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
  {
    id: "bedrooms",
    title: "Bedrooms",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
  {
    id: "bathrooms",
    title: "Bathrooms",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 1 }],
  },
  {
    id: "leaseStatus",
    title: "Lease status",
    editor: { type: "select", options: STATUS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: STATUS }],
    dependentFields: ["residentName"],
  },
  {
    id: "residentName",
    title: "Resident name",
    size: 200,
    validators: [
      {
        type: "function",
        fn: (value, row) => {
          const name = String(value ?? "").trim();
          if (row.leaseStatus === "Vacant" &#x26;&#x26; name) {
            return { level: "error", message: "A vacant unit carries no resident" };
          }
          if (row.leaseStatus &#x26;&#x26; row.leaseStatus !== "Vacant" &#x26;&#x26; !name) {
            return { level: "error", message: "An occupied unit needs a resident" };
          }
          return null;
        },
      },
    ],
  },
  { id: "residentEmail", title: "Resident email", size: 240, validators: [{ type: "email" }] },
  leaseFrom,
  { id: "leaseTo", title: "Lease to", editor: { type: "date" }, dependentFields: ["leaseFrom"] },
  {
    id: "marketRent",
    title: "Market rent",
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", min: 0, decimalPlaces: 2 }],
  },
  {
    id: "rent",
    title: "Rent",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 999999.99, decimalPlaces: 2 }],
  },
];</code></pre>
<p>The number editor strips a currency symbol and the file's own grouping as rows
enter the store, so <code>$1,565.00</code> arrives as <code>1565.00</code> and <code>1,039</code> as <code>1039</code>.
Neither needs a rule of your own. The 36 market rents written <code>-</code> are a
different case, since a dash is a value, so <code>required</code> passes and the number
rule reports them.</p>
<h2 id="beds-baths-and-sqft">Beds, Baths and SqFt</h2>
<p>Every header is scored against your schema, and anything under 60 out of 100
claims no column. Eleven of the fourteen clear that bar here with no
configuration. The three that miss sit beside each other in the file.</p>
<div class="blog-table blog-table--fixed blog-table--property-headers"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>SqFt</code></td>
<td>nothing</td>
<td>the camel hump splits it into <code>sq</code> and <code>ft</code>, against <code>square</code> and <code>feet</code></td>
</tr>
<tr>
<td><code>Beds</code></td>
<td>nothing</td>
<td><code>beds</code> sits nowhere inside <code>bedrooms</code>, and the lengths differ by four</td>
</tr>
<tr>
<td><code>Baths</code></td>
<td>nothing</td>
<td>the same, against <code>bathrooms</code></td>
</tr>
</tbody>
</table></div>
<p><strong>The edit-distance tier weighs lengths before it weighs characters.</strong> A string
of eight characters allows two edits. <code>beds</code> against <code>bedrooms</code> needs four, so
the matcher stops there and the header claims nothing. Three aliases settle all
three.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    squareFeet: ["sqft", "sq ft", "net rentable area"],
    bedrooms: ["beds", "br"],
    bathrooms: ["baths", "ba"],
  },
  values: {
    Occupied: ["occ", "mtm", "notice", "ntv"],
    Vacant: ["vac", "vacant-ready", "down", "model"],
  },
};</code></pre>
<h2 id="occ-ntv-and-the-words-your-schema-knows">Occ, NTV and the words your schema knows</h2>
<p>Value matching collects the status column across the whole upload. Eleven
distinct strings arrive and four of them land on their own. <code>Occupied</code>, <code>Vacant</code>
and <code>Employee</code> are exact. <code>Vacant-Ready</code> reaches Vacant because <code>vacant</code> sits
inside it.</p>
<div class="blog-table blog-table--fixed blog-table--property-status"><table>
<thead>
<tr>
<th>In the file</th>
<th>Rows</th>
<th>Reaches</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Occupied</code></td>
<td>816</td>
<td>Occupied, exact</td>
</tr>
<tr>
<td><code>Occ</code></td>
<td>365</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>MTM</code></td>
<td>181</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Notice</code></td>
<td>159</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>NTV</code></td>
<td>118</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Vacant</code></td>
<td>97</td>
<td>Vacant, exact</td>
</tr>
<tr>
<td><code>Employee</code></td>
<td>46</td>
<td>Employee, exact</td>
</tr>
<tr>
<td><code>VAC</code></td>
<td>43</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Vacant-Ready</code></td>
<td>40</td>
<td>Vacant, contains</td>
</tr>
<tr>
<td><code>Down</code></td>
<td>25</td>
<td>nothing on its own</td>
</tr>
<tr>
<td><code>Model</code></td>
<td>15</td>
<td>nothing on its own</td>
</tr>
</tbody>
</table></div>
<p><code>Occ</code>, <code>VAC</code>, <code>MTM</code> and <code>NTV</code> all fail for one mechanical reason. The contains
tier ignores a string under four characters once case and punctuation come off,
so an abbreviation cannot reach the word it abbreviates.</p>
<p><code>Notice</code>, <code>Down</code> and <code>Model</code> fail for a different reason. They name states your
enum does not carry, and where each one lands is a decision. A notice to vacate
is an occupied unit with a departure date. A month-to-month tenancy is occupied
with no end date. A unit down for repair holds nobody, and Fannie Mae writes the
model rule out in full. The <code>values</code> table above carries all four, so the
decision sits in your repository and the person is never asked to make it.</p>
<p><code>enableCustomValue: false</code> closes the column, so a status nobody mapped is
dropped before it reaches your API.</p>
<h2 id="column-by-column-what-arrives">Column by column, what arrives</h2>
<div class="blog-table blog-table--fixed blog-table--property-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Prop</code></td>
<td>six codes, and half of what identifies a row</td>
<td><code>required</code></td>
</tr>
<tr>
<td><code>Property</code></td>
<td>eleven names for six properties</td>
<td>one name for each code</td>
</tr>
<tr>
<td><code>Property Address</code></td>
<td>three properties spell their street two ways</td>
<td>no rule at all</td>
</tr>
<tr>
<td><code>Unit</code></td>
<td>540 labels over 1,710 units, <code>A101</code> on seven rows</td>
<td><code>required</code>, and unique inside its property alone</td>
</tr>
<tr>
<td><code>SqFt</code></td>
<td><code>1,039</code>, and 41 empty cells</td>
<td>a whole number, with the comma taken off on the way in</td>
</tr>
<tr>
<td><code>Status</code></td>
<td>eleven strings</td>
<td>three options</td>
</tr>
<tr>
<td><code>Resident</code></td>
<td>empty on 214 rows, filled on 11 that hold nobody</td>
<td>a name wherever the status says somebody lives there</td>
</tr>
<tr>
<td><code>Email</code></td>
<td>30 addresses written <code>name@example,com</code></td>
<td>a valid address, or nothing</td>
</tr>
<tr>
<td><code>Lease From</code></td>
<td>43 written <code>07/2024</code></td>
<td>ISO, and those 43 stay flagged</td>
</tr>
<tr>
<td><code>Lease To</code></td>
<td>empty on 366 rows, 146 of them month to month</td>
<td>no rule, because an open lease is normal</td>
</tr>
<tr>
<td><code>Market Rent</code></td>
<td><code>-</code> on 36 rows</td>
<td>a number of zero and up</td>
</tr>
<tr>
<td><code>Rent</code></td>
<td>empty on every vacant row</td>
<td>a number, and empty stays empty</td>
</tr>
</tbody>
</table></div>
<p>The plain version of every failure in that table sits in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>. What follows is the
four that turn on the shape of a rent roll.</p>
<h2 id="the-property-name-that-disagrees-with-itself">The property name that disagrees with itself</h2>
<p><code>Greenfield Commons</code> sits on 489 rows. <code>Greenfield Commons Apartments</code> sits on
40 and <code>GREENFIELD COMMONS</code> on 9, and all 538 are one building. A rule that
reads one row cannot see that, because a <code>function</code> validator is handed a value
and the row around it, and the answer lives in the other 537 rows.</p>
<p><code>{ type: "asyncFunction" }</code> is the rule that reaches them. It receives every
cell in the column at once, and each cell carries the row it sits in.</p>
<pre><code class="language-ts">import type { DataEditorColumn, ValidationError } from "@updog/data-editor";

export const propertyName: DataEditorColumn = {
  id: "propertyName",
  title: "Property name",
  size: 200,
  validators: [
    { type: "required" },
    {
      type: "asyncFunction",
      fn: async (cells) => {
        const tally = new Map&#x3C;string, Map&#x3C;string, number>>();
        for (const cell of cells) {
          const code = String(cell.row.propertyCode ?? "");
          const names = tally.get(code) ?? new Map&#x3C;string, number>();
          const name = String(cell.value ?? "");
          names.set(name, (names.get(name) ?? 0) + 1);
          tally.set(code, names);
        }

        const agreed = new Map&#x3C;string, string>();
        for (const [code, names] of tally) {
          const ranked = [...names].sort((a, b) => b[1] - a[1]);
          agreed.set(code, ranked[0][0]);
        }

        return cells.map((cell): ValidationError | null => {
          const settled = agreed.get(String(cell.row.propertyCode ?? ""));
          return String(cell.value ?? "") === settled
            ? null
            : { level: "error", message: "The rest of this property is called " + settled };
        });
      },
    },
  ],
};</code></pre>
<p>The sweep tallies names under each property code and keeps the one that appears
most. Every cell holding anything else is flagged with the name the rest of the
file agrees on. In this roll that is 81 rows, being 49 at Greenfield, 19 at
Hawthorn, 9 at Lakeside and 4 at Riverbend. Two properties spell their name one
way throughout, and the sweep leaves every row of them alone.</p>
<p><strong>The address column disagrees on 91 rows and nothing flags it.</strong> Greenfield
writes <code>1400 Greenfield Rd</code> on 485 rows and <code>1400 Greenfield Road</code> on 53, and
Hawthorn and Stonegate do the same with <code>St</code> and <code>Ln</code>. A sweep covers the column
it was declared on, and the address column declares none.</p>
<h2 id="two-leases-on-one-unit">Two leases on one unit</h2>
<p>195 units in this roll carry more than one row, and three different things
produce that.</p>
<p>Two roommates on one lease arrive as two rows with the same unit and the same
dates. A unit that turned over arrives as two rows whose leases run end to end.
And 15 units carry two leases whose dates overlap, which is the one case that is
wrong.</p>
<p>Buildium publishes the rule for its own import. Rows sharing a property name, a
unit number, a lease start and a lease end belong to one lease, and Buildium
rejects any pair of leases on one unit whose dates overlap.</p>
<pre><code class="language-ts">import type { DataEditorColumn, ValidationError } from "@updog/data-editor";

const openEnded = (value: unknown): string => {
  return String(value ?? "") || "9999-12-31";
};

export const leaseFrom: DataEditorColumn = {
  id: "leaseFrom",
  title: "Lease from",
  editor: { type: "date" },
  validators: [
    { type: "date" },
    {
      type: "asyncFunction",
      fn: async (cells) => {
        const byUnit = new Map&#x3C;string, number[]>();
        cells.forEach((cell, index) => {
          const unit = cell.row.propertyCode + "|" + cell.row.unitNumber;
          byUnit.set(unit, [...(byUnit.get(unit) ?? []), index]);
        });

        const verdicts: (ValidationError | null)[] = cells.map(() => null);
        for (const group of byUnit.values()) {
          for (const a of group) {
            for (const b of group) {
              if (b &#x3C;= a) continue;
              const oneFrom = String(cells[a].value ?? "");
              const twoFrom = String(cells[b].value ?? "");
              const oneTo = openEnded(cells[a].row.leaseTo);
              const twoTo = openEnded(cells[b].row.leaseTo);
              if (oneFrom === twoFrom &#x26;&#x26; oneTo === twoTo) continue;
              if (oneFrom &#x3C;= twoTo &#x26;&#x26; twoFrom &#x3C;= oneTo) {
                const error: ValidationError = {
                  level: "error",
                  message: "Two leases on this unit overlap",
                };
                verdicts[a] = error;
                verdicts[b] = error;
              }
            }
          }
        }
        return verdicts;
      },
    },
  ],
};</code></pre>
<p>The rule groups rows by property and unit. A pair carrying identical dates is
one lease, so it skips those, and it flags both rows of every remaining pair
whose intervals meet. An empty end date counts as open, so a month-to-month
lease overlaps everything that starts after it. 28 rows carry that flag, being
14 units.</p>
<h2 id="the-lease-that-starts-in-a-month-with-no-day">The lease that starts in a month with no day</h2>
<p>43 lease starts in this roll are written <code>07/2024</code>. Every numeric date pattern
the importer reads wants a day, so all 43 stay in the grid as the text the
export wrote, and the <code>date</code> rule reports every one of them.</p>
<p>That flag has a second effect. <strong>A cell that fails a sync rule never reaches the
async sweep.</strong> The SDK holds back any cell that is empty or already carries an
error, so the first pass over the lease column received 1,642 cells, being 1,905
less 220 empty and 43 left as text.</p>
<p>One of those 43 sits on unit <code>B403</code> at Riverbend. Its lease runs to 10 July
2025, and the row beneath it runs from 6 September 2024 to 30 March 2025. Those
two overlap. The sweep was handed the second row alone, which has nothing to
compare against, so the file holds 15 overlapping units and the flag reaches 14.</p>
<h2 id="the-vacant-unit-with-a-name-against-it">The vacant unit with a name against it</h2>
<p>11 rows say the unit is vacant and still carry the last resident. 5 rows say
somebody lives there and name nobody. Both matter more here than they would in a
flat schema, because the status decides how many records the row becomes.</p>
<p>A row landing on Vacant produces a unit and stops. A row on Occupied or Employee
produces a unit, a lease and a person. So a vacant row carrying a name writes a
resident with no lease behind them, and an occupied row with no name writes a
lease nobody holds.</p>
<p>The rule is the <code>function</code> validator on <code>residentName</code> in the schema above, and
it reads the status beside it. <code>dependentFields</code> on the status column names the
resident column, so changing one rechecks the other.</p>
<h2 id="nothing-here-knows-what-a-lease-is">Nothing here knows what a lease is</h2>
<p>Updog ships no property template, no unit status list and no connector to any
property management system. Updog Importer reads CSV, TSV, JSON, XML, XLSX, XLS,
XLSB and ODS, and a rent roll that arrives as a PDF goes to
<a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a>, whose rows join the queue
where a spreadsheet joins it. The fourteen columns, the three options, the alias
table and both sweeps sit on top of that as code you keep.</p>
<p>The sweeps carry a limit worth knowing before you write one. Opening the file
calls each rule once with the whole column. Every call after that carries the
cells one edit touched. Correcting the <code>07/2024</code> start on unit <code>B403</code> calls the
overlap rule with a single cell, and a single cell has nothing beside it, so
that pair carries no flag for the rest of the session. Each cell hands you its
row, and the row holds your fields and no identity of its own, so a rule cannot
keep an index between calls.</p>
<p>What a sweep paints is the file as it arrived.</p>
<h2 id="the-order-the-writes-go-in">The order the writes go in</h2>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey={["propertyCode", "unitNumber"]}
  onComplete={async (result) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .filter((r) => r.isValid &#x26;&#x26; !r.isDeleted)
      .map((r) => r.row);

    const properties = await postProperties(rows);
    const units = await postUnits(properties, rows);
    await postLeases(units, rows.filter((r) => r.leaseStatus !== "Vacant"));
  }}
/></code></pre>
<p><code>onComplete</code> hands back flat rows grouped by source, each carrying <code>isNew</code>,
<code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Turning them into four tables is a loop
you write, and the order inside it is the one Buildium publishes for its own
import. Properties go first, because a unit stores a property id. Units go next,
because a lease stores a unit id. Leases and residents go last.</p>
<p><code>primaryKey</code> takes the pair, because a unit number means nothing without the
property it sits in. <code>A101</code> is a real unit at all six properties in this roll.
Putting <code>{ type: "unique" }</code> on the unit column instead would flag 1,770 of the
1,905 rows, since uniqueness is checked one column at a time and a unit number
is unique inside its property and nowhere else.</p>
<h2 id="from-one-file-to-four-tables">From one file to four tables</h2>
<p>Out of 1,905 rows, 227 carry something a rule caught. 81 property names that
disagree with the rest of their property, 43 lease starts with no day, 36 market
rents written <code>-</code>, 30 addresses with a comma where a dot belongs, 28 rows in an
overlapping pair, 11 vacant units with a name against them and 5 occupied units
with none. Seven rows carry two of those at once.</p>
<p>The portfolio manager works down that list against the leases in their own
filing cabinet, which is the only place those answers live. Then the loop turns
1,905 rows into 6 properties, 1,710 units, 1,573 leases and 1,680 residents,
and every reference between them points at a record that exists.</p>]]></content:encoded></item>
<item><title>The Best CSV Importers for React in 2026</title><link>https://updog.tech/blog/best-csv-importer-for-react/</link><guid isPermaLink="true">https://updog.tech/blog/best-csv-importer-for-react/</guid><pubDate>Sat, 01 Aug 2026 00:00:00 GMT</pubDate><description>CSV import tools with a React SDK, what each one does well, where it stops, and how to pick between them.</description><content:encoded><![CDATA[<p>At some point in most products, a user needs to bring their own data in. A list of contacts, a price sheet, a month of transactions, exported from somewhere else and handed to your app as a CSV or an Excel file. The first time you build for that, it looks like a small job. Read the file, show the rows, save them. Then the real files arrive, and you find out how much sits under that small job: headers that do not match your fields, dates in three formats, values that are valid for the user but not for your schema, and rows that only a person can fix.</p>
<p>That is why a market of import tools exists. Some run on their own servers, some run in the browser, some are full data platforms, and a few are parsers you wire up yourself. They are not all solving the same problem, and the right one depends on what you are building and what your users' data looks like. This is a guide to the ones worth knowing, what each is good at, and where each one fits.</p>
<p>Almost every one of them ships a React package, so "works with React" tells you nothing. What matters is what that package actually does once it is in your bundle. Some parse the file on the user's machine and hand you rows. Some mount an iframe pointed at the vendor's own app. Some pull a script from the vendor's CDN at runtime. Some parse locally but post your column names, your cell values, or the finished rows to an API. Those are four different products with the same install command, so this roundup names the package and says which one it is. Everything below was checked against the published packages and the vendors' own pages in August 2026.</p>
<h2 id="what-a-csv-importer-has-to-do">What a CSV importer has to do</h2>
<p>Before any names, agree on the job. A tool that only reads the file is a parser, not an importer. A real importer carries a file from upload to clean, structured data your app can trust. That means a handful of steps, in the order a person hits them:</p>
<ul>
<li><strong>Upload and read</strong> the file, including Excel workbooks with more than one sheet, and detect encoding so accented names do not turn into noise.</li>
<li><strong>Find the real header row</strong>, even when the file opens with a title and a few blank lines.</li>
<li><strong>Map columns</strong> from whatever the file calls them to the fields your app expects.</li>
<li><strong>Match values</strong> inside those columns, so <code>Eng</code>, <code>engineering</code>, and <code>R&#x26;D</code> all land as the one option your app accepts.</li>
<li><strong>Validate and let people fix errors</strong> in place, without sending them back to Excel.</li>
<li><strong>Submit clean data</strong> to your backend in a shape you control.</li>
</ul>
<h2 id="the-tools-worth-knowing">The tools worth knowing</h2>
<h3 id="flatfile">Flatfile</h3>
<p>Flatfile is the incumbent, a hosted data platform. In late 2025 the company rebranded to Obvious, with an AI workspace product under that name, while the Flatfile import product keeps its name and API. It runs server-side: files upload to Flatfile's servers, and the importer embeds as a UI rendered in an iframe. You define the schema in code. Column matching is built in with AI, and Transform, its agentic AI step, cleans values and casts them to your field types. Validation and fixes happen inline, with filtering to problem rows, find and replace, bulk transforms, and version snapshots you can revert. It processes large datasets on the server, with streaming advised above 500,000 rows, and adds multi-user collaboration with roles and permissions.</p>
<p>On privacy, because files upload to its servers, Flatfile acts as a data processor, with SOC 2 Type II, ISO 27001, GDPR and CCPA, a HIPAA-ready posture, and a DPA available, what enterprise procurement asks for. Pricing is usage-based and measured in processed data values, the cells it reads: free for up to 50 files and 10 million processed data values a month, then pay-as-you-go on files and data, with volume discounts. It fits teams that want a hosted platform with collaboration and built-in AI, and are fine with cost that grows with volume. See the <a href="https://updog.tech/alternative-to-flatfile/">Flatfile alternative</a> page.</p>
<h3 id="oneschema">OneSchema</h3>
<p>OneSchema is the enterprise, sales-led option, now a wider data platform. It runs server-side: files upload to its servers to validate and transform, and the importer embeds as a modal rendered in an iframe. You build templates in a dashboard or via API. Column mapping is learned from historical mappings across its user base, plus OneSchema AI, with a normalization library for dates, numbers, and addresses. Validation is inline with one-click autofix, find and replace, bulk edits, and webhook validation against your backend, and users can export an annotated Excel of flagged rows to fix outside. It handles spreadsheets up to 10 million rows on Pro, more on Enterprise via custom Rust servers, and adds FileFeeds AI for ongoing SFTP, API, and PDF pipelines, where an agent learns the cleanup from a sample file and replays it on every run.</p>
<p>On privacy, because files upload to its servers, OneSchema acts as a data processor, with SOC 2 Type II, SOC 3, GDPR, CCPA, and HIPAA, regional hosting, and a default 7-day retention you can delete via API. Pricing is quote-based and sales-led, not published, so you book a demo before you see a number. It fits teams that need certifications, a DPA, and server-side data work beyond a single import. See the <a href="https://updog.tech/alternative-to-oneschema/">OneSchema alternative</a> page.</p>
<h3 id="dromo">Dromo</h3>
<p>Dromo is the privacy-forward importer, the closest in spirit to a client-side tool. It runs in the browser by default, with an opt-in server mode (server sync) that turns on its dashboard, webhooks, API, and AI auto-mapping. It embeds as a native component that renders inline in your page, with no iframe. You build the schema in a no-code Schema Studio or in code. Column matching is fuzzy in the browser, with AI auto-mapping once backend sync is on, including a mappings-only mode that stores the mappings without the row data, plus lifecycle hooks for custom logic. Validation is real-time with type, regex, and custom rules, an error panel for inline fixing, and AI-assisted cleanup in plain language, and invalid rows can block submit, be removed, or be included. Browser imports handle several hundred thousand rows, with Pro capping at 100,000 per import, and Enterprise Headless processes files server-side up to 10 million or more.</p>
<p>On privacy, the default browser mode sends no file data to its servers, while the opt-in server mode does, and that path holds SOC 2 Type II, HIPAA, and GDPR, with bring-your-own-storage and custom retention on Enterprise. Pricing is published: a free sandbox, then Pro at $599 a month for 250 imports with $3 per import over, and custom Enterprise with unlimited imports. It fits teams that want a choice of browser or server processing in one product, with built-in AI. See the <a href="https://updog.tech/alternative-to-dromo/">Dromo alternative</a> page.</p>
<h3 id="csvbox">CSVbox</h3>
<p>CSVbox is the budget option, with public tiered pricing. It parses files in the browser, then runs server-side by default: it uploads them to its servers to process and deliver, with an opt-in Private Mode that keeps data in the browser and posts it straight to your system. It embeds as a modal rendered in an iframe. You set templates and validation in a no-code dashboard or via API. Column matching is fuzzy with AI mapping suggestions, and AI document import extracts tables from PDFs, images, and documents. Validation covers email, date, number, regex, and required fields, with custom in-line rules and errors highlighted at cell, row, or table level, plus server-side JavaScript transforms, AI bulk transforms, and natural-language cleanup. It validates on the server, with per-tier row caps up to 500,000 and files up to 500 MB.</p>
<p>On privacy, the default mode uploads files to its servers, stored at rest and auto-deleted after a month, with SOC 2 Type II and GDPR and a DPA, but no HIPAA, and data residency in the US or Europe; Private Mode keeps data in the browser. Pricing is published and tiered by imports and rows: a free sandbox, then Startup $19, Pro $49, Growth $99, and Plus $199 a month. It fits teams that want a low-cost, AI-assisted importer configured in a dashboard. See the <a href="https://updog.tech/alternative-to-csvbox/">CSVbox alternative</a> page.</p>
<h3 id="usecsv">UseCSV</h3>
<p>UseCSV is a mid-priced importer. It runs either in the browser, in frontend callback mode, or server-side, in webhook mode, where data goes to its servers. It embeds as a modal rendered in an iframe, triggered from any button. You set columns and validation in a no-code dashboard or in code. Column matching is automatic by name, with validation hooks for custom checks. Validation uses an inline spreadsheet editor to fix errors, data healing for common issues, and hooks that flag rows against your rules. It is browser-based, with per-tier row caps up to 500,000 and 1 million or more on Enterprise.</p>
<p>On privacy, frontend callback mode sends nothing to its servers, while webhook mode sends import data and keeps it up to 24 hours. It is GDPR compliant, hosted on Vercel and PlanetScale, with no SOC 2 audit of its own, and a DPA available on request. Pricing is published and tiered: a free Hobby tier, then Starter $49, Plus $99, and Pro $199 a month, with a custom Enterprise tier for 1 million or more rows. Branding removal starts on Plus at $99 a month, and custom styling on Pro at $199. It fits teams that want a low-cost importer with data delivered to a backend by webhook. See the <a href="https://updog.tech/alternative-to-usecsv/">UseCSV alternative</a> page.</p>
<h3 id="ingestro">Ingestro</h3>
<p>Ingestro is the AI-heavy option, formerly known as nuvo, and it comes as two products. The Importer SDK is a white-label web component, with packages for React, Angular, Vue, and vanilla JavaScript rather than an iframe: by its own account it processes data in the front end by default, so sensitive data does not pass through Ingestro's servers until an import completes. AI maps incoming columns to your schema, with validation rules and AI cleaning for bulk edits, and it reads CSV, Excel, TSV, XML, JSON, and PDF, with unlimited file size. Data Pipelines is the other product, for recurring imports: it pulls files on a schedule or an event from (S)FTP, HTTP(S), email, Amazon S3, Azure Blob Storage, and Google Cloud Storage, then maps, validates, and cleans them with the same AI, and monitors each run.</p>
<p>Both run cloud-hosted by default, with an optional self-hosted deployment on your own infrastructure. On privacy, it is SOC 2 and ISO 27001 certified and GDPR compliant. Pricing is not published as figures: the model is a base rate plus a usage fee on completed production imports, with development-key imports free, a 14-day trial, and a discount for companies under 20 employees. It fits teams that want an embedded importer, recurring file pipelines, or both, with a European compliance posture.</p>
<h3 id="updog">Updog</h3>
<p>Updog is ours. It is the client-side option, an importer and a spreadsheet editor in one. The file is parsed, mapped, validated, and edited in the browser, on the person's own machine, and row data never reaches our servers. There is no server mode. It embeds as a native component inside your page, with no iframe. It ships as a React component, plus a web component for Vue, Angular, Svelte, and plain JavaScript. You define the schema in code. Column matching is fuzzy with a synonym dictionary you can extend, it maps values to the options your fields accept, and it detects number and date formats on its own. A second import upserts on a key: existing rows update in place, new ones append.</p>
<p>The editor works like a spreadsheet: copy and paste from Excel and Google Sheets, a fill handle, typed cell editors, column transforms, spreadsheet formulas, find and replace, and full undo and redo, with errors highlighted inline. It handles CSV, TSV, JSON, XML, and every Excel format, on import and export. The grid renders on a canvas with virtual scrolling and worker-based filtering, so it holds about 1 million rows of around twenty columns, twenty million cells, in the browser without lag, bound only by the machine's memory. The grid is accessible, built on ARIA semantics, and supports right-to-left layouts.</p>
<p>Updog ships no AI model of its own. You connect the one your organization already approves through a hook, so it runs on infrastructure you control with no new vendor to clear, and the person cleans data with a prompt. More on <a href="https://updog.tech/blog/bring-your-own-ai/">bringing your own AI</a>.</p>
<p>Because nothing is uploaded, there is no data processor, no DPA to sign, no SOC 2 or HIPAA audit, and nothing on a server to breach. It is free for development and free in production up to 100,000 rows a month. Team costs $100 a month for any number of domains, with no row limit, white-label on both plans.</p>
<h3 id="open-source-and-do-it-yourself">Open source and do-it-yourself</h3>
<p>You can also assemble the pieces yourself, and for simple cases that is the right call. <a href="https://www.papaparse.com/">PapaParse</a> is the most-used CSV parser, with more than 11 million weekly downloads, stable and infrequently updated, last released in January 2025. But it is a parser: it reads the file and hands you rows, and the mapping, validation, and editing are yours to build. <a href="https://github.com/tableflowhq/csv-import">TableFlow csv-import</a> and <a href="https://github.com/UgnisSoftware/react-spreadsheet-import">react-spreadsheet-import</a> are both MIT-licensed import wizards with column matching and validation, positioned as open-source alternatives to Flatfile and Dromo. react-csv-importer by Beamworks wraps Papa Parse and react-dropzone, but it was archived in January 2024 with its last release in May 2023, so treat it as a reference, not a dependency.</p>
<p>Open source costs nothing up front and you own every line. AI can get a first version of the steps past parsing, the column matching, value matching, validation UI, and the editor where users fix their data, standing up in weeks now. The real cost is owning all of it after that, and keeping it working as your schema and edge cases grow.</p>
<h2 id="smaller-and-newer-options">Smaller and newer options</h2>
<p>Below those there is a second tier, mostly young projects and mostly free or close to it. They are worth knowing because they are cheap to try and because a few of them do one thing well. What follows is what each package is, not a verdict.</p>
<h3 id="filefeed">FileFeed</h3>
<p><code>@filefeed/react</code>, MIT, React only. The embeddable importer is free and genuinely client-side, with no network calls in the published bundle at all. It parses with PapaParse and SheetJS and hands the rows back through a callback. The grid is built from Mantine components with no virtualization, so it is meant for ordinary files rather than very large ones, and it arrives with Mantine, an icon set and SheetJS as peer dependencies you install yourself. The free importer sits next to a paid product, Automated FileFeeds, for scheduled SFTP and email ingestion. See the <a href="https://updog.tech/alternative-to-filefeed/">FileFeed alternative</a> page.</p>
<h3 id="importkit">ImportKit</h3>
<p><code>@importkit/react</code>, MIT, first published in January 2026. The file is parsed in the browser, but the AI features are not local. Column suggestions post your headers to its API, value suggestions post the unique values found in your columns, and a relay step can post the finished mapped rows. There is also import telemetry. If the point of choosing an in-browser tool was that data stays on the machine, read those four endpoints before you wire it in. The free tier covers 5,000 rows a month and carries a watermark, and paid plans run from $49 to $149 a month. See the <a href="https://updog.tech/alternative-to-importkit/">ImportKit alternative</a> page.</p>
<h3 id="impler">Impler</h3>
<p><code>@impler/react</code>, MIT, open source with a hosted cloud. The React package is a thin wrapper with a single dependency. At runtime it injects a script from <code>embed.impler.io</code> into your page, and that script renders the importer in an iframe served from <code>widget.impler.io</code>. So it is a hosted widget rather than a component, and it means third-party code arrives in your app on page load, which is a conversation with whoever owns your CSP. The cloud is metered, free to 2,500 rows a month and then $35 to $75, with Impler branding removed only on the top plan. See the <a href="https://updog.tech/alternative-to-impler/">Impler alternative</a> page.</p>
<h3 id="xlork">Xlork</h3>
<p><code>@xlork/react</code>, MIT. The package renders an iframe pointed at <code>app.xlork.com</code> and talks to it over postMessage with a license key. Everything the user sees runs inside that frame, so your CSS stops at its edge and focus and ARIA relationships do not cross it. Every plan is free during a launch promotion, after which they run $9 to $49 a month, and the row caps are per import rather than per month, from 10 rows on the free tier to 500 on Premium. The React package was last published in June 2025. See the <a href="https://updog.tech/alternative-to-xlork/">Xlork alternative</a> page.</p>
<h3 id="importok">ImportOK</h3>
<p><code>@importok/react</code> is a small wrapper around <code>@importok/javascript</code>, which registers a web component, so the same build works outside React. Files are parsed locally and Excel is supported. The AI features are not local, though. Mapping suggestions and transformations are posted to ImportOK's servers with a bearer token. Pricing is published and cheap, at €149 a year for Pro or $299 once for a lifetime licence, with branding removal included and no row limits stated. See the <a href="https://updog.tech/alternative-to-importok/">ImportOK alternative</a> page.</p>
<h3 id="hellocsv">HelloCSV</h3>
<p><code>hello-csv</code>, MIT, written in Preact and mountable in React. It is the cleanest of the small ones and there is no vendor API anywhere in it. It reads CSV and TSV, and only those, so an Excel file has nowhere to go. The table is virtualized with TanStack, it does column mapping and validation, and it stops there. There is no value mapping, no primary key or upsert on re-import, and no clipboard, fill handle, undo, or find and replace in the editor. See the <a href="https://updog.tech/alternative-to-hellocsv/">HelloCSV alternative</a> page.</p>
<h3 id="importcsv">ImportCSV</h3>
<p><code>@importcsv/react</code>, MIT on the frontend and AGPL-3.0 on the backend and admin dashboard. In local mode you pass columns or a Zod schema in code and nothing leaves the browser. It reads CSV and Excel, with Excel behind a separate <code>xlsx</code> install, and virtualizes the table with TanStack. AI column mapping, plain-English fixes, webhooks, and the dashboard all need the backend, which you either run yourself or take hosted, free up to 100 imports a month and $49 or $149 above that, with 10k to 500k rows per import by tier. Backend mode also changes the contract, since the rows go to the API and <code>onComplete</code> comes back empty. In the editor there is no undo, no value mapping, and no upsert on re-import. See the <a href="https://updog.tech/alternative-to-importcsv/">ImportCSV alternative</a> page.</p>
<h2 id="the-tools-side-by-side">The tools side by side</h2>
<div class="blog-table"><table><colgroup><col><col><col><col><col><col></colgroup><thead><tr><th scope="col">Tool</th><th scope="col">Processing</th><th scope="col">Integration</th><th scope="col">Pricing</th><th scope="col">White-label</th><th scope="col">Row limits</th></tr></thead><tbody><tr><th scope="row">Flatfile</th><td>Server</td><td>iframe</td><td>Free tier, then usage-based</td><td>Paid</td><td>Metered by cells</td></tr><tr><th scope="row">OneSchema</th><td>Server</td><td>iframe</td><td>Quote-based, not published</td><td>Paid</td><td>10M on Pro</td></tr><tr><th scope="row">Dromo</th><td>Browser (opt-in server)</td><td>Native SDK</td><td>Free tier, then $599/mo for 250 imports, $3 per import over</td><td>Paid</td><td>100k per import</td></tr><tr><th scope="row">CSVbox</th><td>Server (opt-in browser)</td><td>iframe</td><td>Free tier, then $19 to $199/mo</td><td>Paid</td><td>Up to 500k</td></tr><tr><th scope="row">UseCSV</th><td>Browser or server</td><td>iframe</td><td>Free tier, then $49 to $199/mo</td><td>Free</td><td>Up to 500k</td></tr><tr><th scope="row">Ingestro</th><td>Browser (server on completion)</td><td>Web component</td><td>Base plus usage, not published</td><td>Paid</td><td>None stated</td></tr><tr><th scope="row">FileFeed</th><td>Browser</td><td>React component</td><td>Free</td><td>Free</td><td>None stated</td></tr><tr><th scope="row">ImportKit</th><td>Browser, AI on their API</td><td>React component</td><td>Free tier, then $49 to $149/mo</td><td>Paid</td><td>5k to 100k a month</td></tr><tr><th scope="row">Impler</th><td>Browser or their cloud</td><td>Remote script, iframe</td><td>Free tier, then $35 to $75/mo</td><td>Paid</td><td>2.5k to 150k a month</td></tr><tr><th scope="row">Xlork</th><td>Inside their frame</td><td>iframe</td><td>Free during launch, then $9 to $49/mo</td><td>Paid</td><td>10 to 500 per import</td></tr><tr><th scope="row">ImportOK</th><td>Browser, AI on their API</td><td>Web component</td><td>€149/yr or $299 once</td><td>Free</td><td>None stated</td></tr><tr><th scope="row">HelloCSV</th><td>Browser</td><td>Preact component</td><td>Free</td><td>Free</td><td>None stated</td></tr><tr><th scope="row">ImportCSV</th><td>Browser, or their backend</td><td>React component</td><td>Free self-hosted, or $0 to $149/mo hosted</td><td>Free self-hosted, paid on cloud</td><td>10k to 500k per import on cloud</td></tr><tr><th scope="row">Updog</th><td>Browser</td><td>React component</td><td>Free to 100K rows/mo, then $100/mo</td><td>Free</td><td>About 1M, no plan cap</td></tr></tbody></table></div>
<h2 id="how-to-choose">How to choose</h2>
<p>The tool follows the constraint that matters most to you, so start there rather than from a feature count.</p>
<p>If procurement needs SOC 2 or HIPAA and a signed DPA, look at OneSchema, Dromo, or Flatfile, the tools built around server-side processing and the paperwork that comes with it. If your import is really an ongoing pipeline, with scheduled jobs, SFTP drops, or recurring feeds, that is server work, and OneSchema's FileFeeds or Ingestro fit it better than any browser tool. If you want the lowest published price and are happy configuring templates in a dashboard, CSVbox starts at $19 a month and UseCSV at $49. If you only need to read a file and will build the rest yourself, PapaParse is the right foundation.</p>
<p>If the budget is zero, the honest answers are in the second tier. FileFeed and HelloCSV are both free, both genuinely client-side, and both fine for ordinary files. HelloCSV reads CSV and TSV only, so pick FileFeed if your users send Excel. ImportOK is the cheapest paid option at €149 a year and it works outside React too, as long as you are comfortable with its AI calls leaving the browser. If you want AI mapping without a vendor holding your data, <code>@importcsv/react</code> lets you self-host the backend that does it.</p>
<p>One thing to check before any of them, whatever you pick. Ask where the file goes and where the AI runs, because those are different questions and a tool can answer the first one well and the second one badly. Several of the free ones parse locally and then post your headers, your column values, or the finished rows to an API, which is easy to miss when the marketing says client-side.</p>
<p>If you want a white-label embedded importer that handles large files in the browser, with a free plan to start, that is Updog.</p>
<h2 id="what-about-vue-angular-svelte-and-plain-javascript">What about Vue, Angular, Svelte, and plain JavaScript</h2>
<p>Most of this list is React-first, and a few of these tools are React-only. That sounds like a problem outside React and usually is not, because the ones that render in an iframe do not care what framework surrounds them. Flatfile, OneSchema, CSVbox, UseCSV, and Xlork all mount a frame, so they drop into any stack, at the cost of the frame itself. Your CSS stops at its edge, focus order and ARIA relationships do not cross it, and any data you want in or out goes through postMessage.</p>
<p>The tools that render as real elements split by how they are packaged. Ingestro, ImportOK, and Updog ship a web component, so they work in Vue, Angular, Svelte, and plain JavaScript without a wrapper. Expect the usual custom-element friction along the way. Vue needs <code>isCustomElement</code> configured and cannot pass objects or arrays as attributes. Angular needs <code>CUSTOM_ELEMENTS_SCHEMA</code>. Both frameworks need care around SSR, since a custom element has nothing to render on the server. Dromo takes the third route, a JavaScript SDK with per-framework wrappers, which renders inline like a component but ties you to whichever wrapper they maintain.</p>
<p>That leaves the React-first ones. FileFeed ships a React build and nothing else. <code>@importcsv/react</code> and HelloCSV both add a Preact build and a bundled one you can mount by hand, so they will run on a page without React, though neither is a custom element. You can host a React root inside a Vue or Angular app to use FileFeed, but at that point you are shipping React to run one screen, and a web component is the cheaper answer.</p>
<p>If the import belongs inside your own web app, the fastest way to judge any of this is to try it. You can install Updog and have a working importer running in a few minutes, whether you build in <a href="https://updog.tech/react-csv-importer/">React</a>, <a href="https://updog.tech/vue-csv-importer/">Vue</a>, <a href="https://updog.tech/angular-csv-importer/">Angular</a>, <a href="https://updog.tech/svelte-csv-importer/">Svelte</a>, or <a href="https://updog.tech/js-csv-importer/">plain JavaScript</a>.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Elasticsearch</title><link>https://updog.tech/blog/import-csv-into-elasticsearch/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-elasticsearch/</guid><pubDate>Fri, 31 Jul 2026 00:00:00 GMT</pubDate><description>Match a partner seed bank export in the browser, post the clean rows to your own route, and index them into Elasticsearch with the bulk API.</description><content:encoded><![CDATA[<p>An Elasticsearch index takes a document that declares nothing and works out the rest. "The automatic detection and addition of new fields is called dynamic mapping." A string becomes <code>text</code> with a <code>.keyword</code> sub-field. A whole number becomes <code>long</code>. A string that matches a date pattern becomes a <code>date</code>, because date detection is on by default.</p>
<p>Then the guess stands. Elastic states the consequence in one sentence. "Except for supported mapping parameters, you can't change the mapping or field type of an existing field." The way back is a new index and a reindex of everything in the old one.</p>
<p>So the first document through the door writes the schema for every document after it. In an import feature, the first document is built from a file somebody else sent you.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>A seed bank runs a public search over its collection. The partner banks that collect for it send accession exports, each out of whatever field system that partner keeps.</p>
<p><code>nordvik-partner-accessions.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Accession No</td><td class="sheet__cell">Scientific Name</td><td class="sheet__cell">Vernacular</td><td class="sheet__cell">Date Collected</td><td class="sheet__cell">Cntry</td><td class="sheet__cell">Locality</td><td class="sheet__cell">Storage</td><td class="sheet__cell">Viability %</td><td class="sheet__cell">Seed Count</td><td class="sheet__cell">Donor</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">NV-2026-0117</td><td class="sheet__cell">Silene stenophylla</td><td class="sheet__cell">narrow-leaved campion</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">ru</td><td class="sheet__cell">Kolyma river terrace, 62 m</td><td class="sheet__cell">orthodox</td><td class="sheet__cell">92</td><td class="sheet__cell">1,450</td><td class="sheet__cell">Kolyma Field Station</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">NV-2026-0118</td><td class="sheet__cell">Papaver radicatum</td><td class="sheet__cell">arctic poppy</td><td class="sheet__cell">29/09/2025</td><td class="sheet__cell">NO</td><td class="sheet__cell">Adventdalen, scree slope</td><td class="sheet__cell">Orth.</td><td class="sheet__cell">88.5</td><td class="sheet__cell">860</td><td class="sheet__cell">Nordvik Survey</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">NV-2026-0119</td><td class="sheet__cell">Quercus robur</td><td class="sheet__cell">pedunculate oak</td><td class="sheet__cell">17/11/2025</td><td class="sheet__cell">GB</td><td class="sheet__cell">Wistman's Wood, granite clitter</td><td class="sheet__cell">Recalcitrant</td><td class="sheet__cell">n/a</td><td class="sheet__cell">240</td><td class="sheet__cell">Devon Partner Bank</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">NV-2026-0117</td><td class="sheet__cell">Silene stenophylla</td><td class="sheet__cell">narrow-leaved campion</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">RU</td><td class="sheet__cell">Kolyma river terrace, 62 m</td><td class="sheet__cell">Intermed.</td><td class="sheet__cell">92</td><td class="sheet__cell">1,450</td><td class="sheet__cell">Kolyma Field Station</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">91 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">97</th><td class="sheet__cell">NV-2026-0212</td><td class="sheet__cell">Dryas octopetala</td><td class="sheet__cell">mountain avens</td><td class="sheet__cell">22/03/2026</td><td class="sheet__cell">IS</td><td class="sheet__cell">Skaftafell, lava field</td><td class="sheet__cell">orthodox</td><td class="sheet__cell">95</td><td class="sheet__cell">2,100</td><td class="sheet__cell">Nordvik Survey</td></tr></tbody></table>
<p>The header row says <code>Cntry</code> where the collection says country, and <code>Vernacular</code> where it says common name. Storage behaviour arrives as <code>orthodox</code>, <code>Orth.</code>, <code>Recalcitrant</code> and <code>Intermed.</code>. Dates run day first. <code>NV-2026-0117</code> appears twice, once orthodox and once intermediate, because the partner revised the storage class and left both lines in.</p>
<p><code>Donor</code> is the column the collection has no field for.</p>
<p>The person drags the file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, holds the storage classes to your list, and puts every row in front of them. Your <code>onComplete</code> handler posts the clean rows to a route you own. That route holds the API key and calls the bulk API.</p>
<p>No Updog server stands between the browser and the cluster.</p>
<h2 id="the-index-and-what-it-declares">The index and what it declares</h2>
<p>Every field the collection cares about is declared before a single document arrives.</p>
<pre><code class="language-json">{
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "accession":   { "type": "keyword" },
      "taxon": {
        "type": "text",
        "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } }
      },
      "commonName":  { "type": "text" },
      "collectedOn": { "type": "date", "format": "strict_date_optional_time" },
      "country":     { "type": "keyword" },
      "locality":    { "type": "text" },
      "storage":     { "type": "keyword" },
      "viability":   { "type": "float" },
      "seedCount":   { "type": "integer" },
      "extra":       { "type": "flattened" }
    }
  }
}</code></pre>
<p><code>"dynamic": "strict"</code> is the line that keeps the mapping yours. Elastic describes what it does plainly. "If new fields are detected, an exception is thrown and the document is rejected." A partner's spare column can no longer mint a field.</p>
<p><code>taxon</code> is <code>text</code> with a <code>keyword</code> sub-field, because the collection searches on the species name and also sorts by it. Keyword fields are "often used in sorting, aggregations, and term-level queries, such as term", and Elastic's own advice for the other job is "Avoid using keyword fields for full-text search. Use the text field type instead." <code>ignore_above</code> at 256 keeps a runaway string out of the sorted copy while leaving it in <code>_source</code>.</p>
<p><code>collectedOn</code> names one format. A bare <code>date</code> field defaults to <code>"strict_date_optional_time||epoch_millis"</code>, and the <code>strict_</code> family is exact about digits, where "year, month and day parts of the month must use respectively 4, 2 and 2 digits exactly, potentially prepending zeros". Updog stores every parsed date as <code>YYYY-MM-DD</code>, so the two line up.</p>
<p><code>extra</code> is <code>flattened</code>, and the section on the created column is where it earns its place.</p>
<h2 id="what-happens-to-a-field-nobody-declared">What happens to a field nobody declared</h2>
<p>Under the default setting, a new field gets a type from the value that carried it. Elastic publishes the whole table. <code>true</code> and <code>false</code> become <code>boolean</code>. A decimal becomes <code>float</code>. A whole number becomes <code>long</code>. A string with no date or numeric match becomes "<code>text</code> with a <code>.keyword</code> sub-field". Numeric detection is off by default, so <code>"92"</code> stays a string.</p>
<p>Two costs follow. The first is the mapping you cannot change, which sends you to a new index and a reindex. The second has a number on it. <code>index.mapping.total_fields.limit</code> defaults to 1000, and "Field and object mappings, field aliases, and mapped runtime fields all count towards this limit." Elastic has a name for what happens next. "Runaway field growth is colloquially called 'mapping explosion'."</p>
<p>The <code>dynamic</code> setting has four values, and each one is a different answer to the same partner column. <code>true</code> adds the field. <code>runtime</code> adds it as a runtime field, "not indexed and are loaded from <code>_source</code> at query time". <code>false</code> ignores it, so it "will not be indexed or searchable". <code>strict</code> rejects the document.</p>
<p>This collection takes <code>strict</code> and gives the spare columns one field of their own. Under <code>flattened</code>, "the entire object is mapped as a single field", which "can help prevent a mappings explosion from having too many distinct field mappings". Leaf values inside it are "indexed as string keywords, without analysis or special handling for numbers or dates". A donor name stays findable by its exact value and the mapping stays the size you wrote it.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array carries the nine fields the index declares beside <code>extra</code>.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const STORAGE = ["Orthodox", "Recalcitrant", "Intermediate"];

export const columns: DataEditorColumn[] = [
  {
    id: "accession",
    title: "Accession",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^NV-\\d{4}-\\d{4}$" },
      { type: "unique" },
    ],
  },
  {
    id: "taxon",
    title: "Scientific name",
    size: 220,
    validators: [
      { type: "required" },
      { type: "function", fn: (value) => String(value).length > 256
        ? { level: "error", message: "256 characters at most" }
        : null },
    ],
  },
  { id: "commonName", title: "Common name", size: 200 },
  {
    id: "collectedOn",
    title: "Collected on",
    size: 150,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "country",
    title: "Country",
    size: 110,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^[A-Z]{2}$" },
    ],
  },
  { id: "locality", title: "Locality", size: 260 },
  {
    id: "storage",
    title: "Storage behaviour",
    size: 170,
    editor: { type: "select", options: STORAGE, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: STORAGE }],
  },
  {
    id: "viability",
    title: "Viability",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, max: 100, decimalPlaces: 1 },
    ],
  },
  {
    id: "seedCount",
    title: "Seed count",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 1 },
    ],
  },
];</code></pre>
<p>Each rule answers a line in the mapping. The <code>regex</code> on the accession holds it to the collection's own format, which also keeps it far inside the 512 bytes an <code>_id</code> allows. The <code>function</code> validator counts the species name against 256 characters, the same figure <code>ignore_above</code> uses, so a string that would fall out of the sorted copy is reported in a grid cell. <code>number</code> holds viability between 0 and 100.</p>
<p><code>{ type: "unique" }</code> on the accession is the rule that saves the write. Uniqueness is checked against every other row in the same column, so both <code>NV-2026-0117</code> cells light up before submit. That matters because Elasticsearch answers a duplicate id with silence. The <code>index</code> action "adds or replaces a document as necessary", so the second row wins and the bulk response reports two successes.</p>
<p>The <code>select</code> on storage behaviour is closed, and <code>n/a</code> in the viability column is caught by <code>{ type: "number" }</code>. A value like that reaching a <code>float</code> field is refused by the index, since <code>ignore_malformed</code> defaults to <code>false</code>. Turn it on and the field is dropped instead, its name recorded in the <code>_ignored</code> field and its value left out of the index, where no search reaches it.</p>
<h2 id="the-column-your-schema-never-had">The column your schema never had</h2>
<p><code>enableCreateColumn</code> is on by default, and it is what a person does with <code>Donor</code>.</p>
<p>An unmatched header opens a select in the column matching step, listing your fields and one more entry underneath a divider. Create column. The person names it, and the file column keeps its data. Once the grid opens, that column has a context menu of its own, so it can be renamed or dropped.</p>
<p>The created column then arrives on the result as a key your schema never declared. Your handler compares each key against the ids you wrote and puts the rest in one place. Everything the partner brought stays searchable, and the index gains no field, because <code>flattened</code> maps the whole object as one.</p>
<p>The alternative is the same decision made by a machine that cannot take it back. A donor name reaching a dynamic index becomes <code>text</code> with a <code>.keyword</code> sub-field for the life of that index.</p>
<h2 id="the-headers-the-partner-sends">The headers the partner sends</h2>
<p>Updog scores each header against the column id and the column title, and the higher score wins.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Accession No</code></td>
<td><code>accession</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Scientific Name</code></td>
<td><code>taxon</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Vernacular</code></td>
<td><code>commonName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Date Collected</code></td>
<td><code>collectedOn</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Cntry</code></td>
<td><code>country</code></td>
<td>edit distance, 65</td>
</tr>
<tr>
<td><code>Locality</code></td>
<td><code>locality</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Storage</code></td>
<td><code>storage</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Viability %</code></td>
<td><code>viability</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Seed Count</code></td>
<td><code>seedCount</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Donor</code></td>
<td>nothing</td>
<td>0, the person creates a column</td>
</tr>
</tbody>
</table></div>
<p><code>Cntry</code> is the interesting one. Neither string sits inside the other, so the contains tier refuses, no whole word is shared, and the built-in country group carries <code>nation</code> and <code>countryname</code> without <code>cntry</code>. Two insertions sit inside the two edits allowed at that length, so the abbreviation lands anyway. <code>Vernacular</code> shares nothing with <code>commonName</code> at any tier, so it needs the one <code>synonyms</code> entry in the mount below.</p>
<p>Values follow the same ladder. <code>orthodox</code> and <code>Recalcitrant</code> are exact. <code>Orth.</code> normalizes to four characters, which is the floor of the contains tier, and <code>Orthodox</code> contains it. <code>Intermed.</code> reaches <code>Intermediate</code> the same way.</p>
<p>The file settles its own dates. <code>29/09/2025</code> and <code>17/11/2025</code> both carry a value above twelve in the first position, so the scan reads the whole file day first, and <code>03/04/2026</code> follows as the third of April.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the file, the schema and the index together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;SeedAccession>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="accession"
  enableCreateColumn
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      commonName: ["vernacular", "vernacular name", "local name"],
    },
    values: {
      Orthodox: ["long term", "desiccation tolerant"],
      Recalcitrant: ["recalc", "desiccation sensitive"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> is the accession alone, and it becomes the <code>_id</code> of the document. There is no upsert to configure here, since one <code>index</code> action creates a document that is new and replaces a document that is there.</p>
<p><code>enableCreateColumn</code> is written out even though it is the default, because the whole donor column depends on it. <code>enableDeleteRow="all"</code> lets the person drop the stale <code>NV-2026-0117</code> line once the grid shows both. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error. Whatever they fix by hand comes back as <code>learnedSynonyms</code>, two lists of <code>{ source, target }</code> pairs to store and fold into the <code>synonyms</code> tables next season.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying four independent flags.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 2000;
const DECLARED = new Set(columns.map((column) => column.id));

const readLabel = (key: string) => {
  return key
    .replace(/^__dynamic__:/, "")
    .replace(/-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/, "");
};

const extraFields = (row: SeedAccession) => {
  const extra: Record&#x3C;string, unknown> = {};
  for (const [key, value] of Object.entries(row)) {
    if (DECLARED.has(key) || value === "" || value == null) continue;
    extra[readLabel(key)] = value;
  }
  return extra;
};

const toDocument = (row: SeedAccession) => ({
  accession: row.accession,
  taxon: row.taxon,
  commonName: row.commonName,
  collectedOn: row.collectedOn,
  country: row.country,
  locality: row.locality,
  storage: row.storage,
  viability: row.viability === "" ? null : Number(row.viability),
  seedCount: Number(row.seedCount),
  extra: extraFields(row),
});

const toAction = (entry: ResultRow&#x3C;SeedAccession>) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  if (entry.isDeleted) {
    return [{ op: "delete", accession: entry.row.accession }];
  }
  return [{
    op: "index",
    accession: entry.row.accession,
    document: toDocument(entry.row),
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;SeedAccession>) => {
  for (const source of result.sources) {
    const actions = source.rows.flatMap(toAction);

    for (let start = 0; start &#x3C; actions.length; start += CHUNK_SIZE) {
      const answer = await fetch("/api/accessions/index", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          actions: actions.slice(start, start + CHUNK_SIZE),
          last: start + CHUNK_SIZE >= actions.length,
        }),
      });
      if (!answer.ok) throw new Error((await answer.json()).message);
    }
  }
  await storeSynonyms(result.learnedSynonyms);
}, []);</code></pre>
<p>A new accession and an edited accession become the same action, since one <code>index</code> call decides which of the two it is. A row the person added and then deleted goes nowhere. Anything the person created shows up in <code>extra</code> under the name they typed, with the generated suffix trimmed off the key.</p>
<p>Two boundaries size this write, and they belong to different parties. The chunk of two thousand is yours, sized against what your own route accepts. The size of the Elasticsearch request belongs to the client, which flushes its body at five million bytes by default. Elastic publishes no row count at all. "There is no 'correct' number of actions to perform in a single bulk request." What it does publish is a ceiling of <code>100mb</code> on an HTTP request, and one line of advice, that "it is advisable to avoid going beyond a couple tens of megabytes per request".</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the whole export clears the grid unindexed. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-indexes-the-rows">The route that indexes the rows</h2>
<p>The route holds the API key, and the browser stops there.</p>
<pre><code class="language-ts">import { Client, errors } from "@elastic/elasticsearch";

const client = new Client({
  node: process.env.ELASTIC_NODE,
  auth: { apiKey: process.env.ELASTIC_API_KEY },
});

const INDEX = "seed-accession";

const droppedId = (operation: unknown) => {
  const [line] = Object.values(operation as Record&#x3C;string, { _id: string }>);
  return line._id;
};

app.post("/api/accessions/index", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });
  if (!session.canEditCollection) {
    return response.status(403).json({ message: "No collection access" });
  }

  const lost: { accession: string; status: number; reason: string }[] = [];

  try {
    const stats = await client.helpers.bulk({
      datasource: request.body.actions,
      onDocument: (action) => {
        if (action.op === "delete") {
          return { delete: { _index: INDEX, _id: action.accession } };
        }
        return [
          { index: { _index: INDEX, _id: action.accession } },
          action.document,
        ];
      },
      onDrop: (dropped) => {
        lost.push({
          accession: droppedId(dropped.operation),
          status: dropped.status,
          reason: dropped.error?.reason ?? "no document with that id",
        });
      },
      refreshOnCompletion: request.body.last ? INDEX : false,
    });

    if (lost.length > 0) {
      request.log.error({ lost });
      return response.status(502).json({
        message: "The index refused " + lost.length + " of these rows",
        lost,
      });
    }

    response.json({ indexed: stats.successful });
  } catch (error) {
    if (error instanceof errors.ResponseError) {
      request.log.error({ status: error.statusCode, type: error.message });
    } else {
      request.log.error({ type: String(error) });
    }
    return response.status(502).json({ message: "Elasticsearch refused the batch" });
  }
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check, and the collection permission is read before a document is built. An Elasticsearch API key is the credential for this seat, one of the "token-based authentication mechanisms designed to authenticate applications and services accessing Elasticsearch", and it can be narrowed, since "you can opt to configure access to specific Elasticsearch APIs and resources by assigning the key with predefined roles or custom privileges".</p>
<p>The bulk API speaks newline-delimited JSON, where an action line is followed by a document line, a delete stands as one line on its own, and "The final line of data must end with a newline character". The helper builds that body from what <code>onDocument</code> returns, so the route writes actions and the client writes NDJSON. Deletes ride in the same request as the writes.</p>
<h2 id="the-200-that-carries-failures">The 200 that carries failures</h2>
<p>A bulk request that fails halfway still answers with HTTP 200. The verdict sits in the body, on a flag Elastic describes as true when "one or more of the operations in the bulk request did not complete successfully", with a <code>status</code> and an <code>error</code> on each item that failed.</p>
<p>The helper reads that array for you and splits it two ways. A document rejected with 429 goes back into the queue, and the client's own source says why. "429 is the only status code where we might want to retry a document, because it was not an error in the document itself, but the ES node was handling too many operations." That is the code Elasticsearch answers with under load, "TOO_MANY_REQUESTS (429) response codes", and the advice beside it is to "pause indexing a bit before trying again, ideally with randomized exponential backoff".</p>
<p>Everything else reaches <code>onDrop</code>, which receives the status, the error, the action line, whether it had already been retried, and, on a write, the document that followed the action. A delete has no document line to hand back, so the accession has to come off the action, where the id sits either way. One case arrives with no error either. A delete whose document was never there answers <code>"result": "not_found"</code> with <code>"status": 404</code> and nothing else, so the reason has to be written by you.</p>
<p>A request the cluster refuses outright throws instead. The client raises a <code>ResponseError</code> whose <code>statusCode</code> holds the HTTP status and whose message holds the error type Elasticsearch named. Log both, answer the browser with a sentence a curator can act on, and let the handler throw.</p>
<h2 id="the-rows-nobody-can-find-yet">The rows nobody can find yet</h2>
<p>An indexed document is durable before it is findable. Search runs over segments, and "A refresh makes all operations performed on an index since the last refresh available for search."</p>
<p>Elasticsearch does this on its own, with one condition worth knowing. "By default, Elasticsearch periodically refreshes indices every second, but only on indices that have received one search request or more in the last 30 seconds." A collection index that nobody has searched this minute sits unrefreshed, and the curator who just imported four thousand accessions searches for one and finds nothing.</p>
<p>So the last chunk asks for a refresh by name. <code>refreshOnCompletion</code> takes the index string and runs one refresh after the final flush, which is why the browser marks the last request. The same result is available per request through the <code>refresh</code> parameter, where <code>wait_for</code> will "Wait for the changes made by the request to be made visible by a refresh before replying". One refresh at the end of an import costs less than one on every chunk.</p>
<p><a href="https://updog.tech/blog/import-csv-into-clickhouse/">Importing a CSV into ClickHouse</a> carries the other version of this gap, where the write is visible immediately and the deduplication behind it happens later.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Elasticsearch connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the index, the route and the API key in the middle are work you do.</p>
<p>Elasticsearch already ships its own way in for the other case. Kibana's file upload takes a CSV, works out the fields, and lands them in an index, and Elastic states the scope itself. "The upload feature is not intended for use as part of a repeated production process, but rather for the initial exploration of your data." Logstash covers the repeated case for files a server can reach. For a file your own team assembled, both are the shorter way in. Everything above exists for the export a partner sends, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-partner">The pieces you wrote and the next partner</h2>
<p>You wrote one mapping that refuses a field it never declared, a schema with nine columns, one <code>synonyms</code> block, a handler that sorts declared keys from created ones, and a route that indexes a chunk and refreshes once at the end. The file stays on the machine that opened it. The rows travel from your own front end to your own route and into Elasticsearch. The only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The next partner sends a spreadsheet with two spare columns and a fourth spelling of <code>Orthodox</code>. The mappings from this season are already stored, the spelling costs one more line in <code>synonyms</code>, and the spare columns land in one field that was there before they arrived.</p>]]></content:encoded></item>
<item><title>How to Import CSV Contacts Into HubSpot</title><link>https://updog.tech/blog/import-csv-into-hubspot/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-hubspot/</guid><pubDate>Thu, 30 Jul 2026 00:00:00 GMT</pubDate><description>Import CSV contacts into HubSpot through your own endpoint. Match the file values to the portal enumeration options in the browser, then upsert 100 at a time.</description><content:encoded><![CDATA[<p>The import screen inside a HubSpot portal takes a .csv, .xlsx or .xls file with one sheet and fewer than 1,000 columns. On a paid tier that file reaches 512 MB and 1,048,576 rows. A <code>POST</code> to <code>/crm/v3/imports</code> takes the same file from a server you run, with a <code>columnMappings</code> entry for every column in it. Three of those imports run at once and the next one waits in a <code>DEFERRED</code> state. Both of those paths belong to the portal owner, who holds the credentials and the file. Your customer stands outside that portal with a badge-scan lead list from booth H-214.</p>
<p>Their export arrives looking like this.</p>
<p><code>booth-h214-leads.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">badge_id</td><td class="sheet__cell">work_email</td><td class="sheet__cell">company</td><td class="sheet__cell">job_title</td><td class="sheet__cell">lead_rating</td><td class="sheet__cell">marketing_opt_in</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">BX-4471</td><td class="sheet__cell">p.raman@Northwind-Robotics.COM </td><td class="sheet__cell">Northwind Robotics</td><td class="sheet__cell">Head of Automation</td><td class="sheet__cell">Hot</td><td class="sheet__cell">Yes</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">BX-4472</td><td class="sheet__cell">t.lindqvist@haldenmarine.se</td><td class="sheet__cell">Halden Marine</td><td class="sheet__cell">Procurement Lead</td><td class="sheet__cell">A</td><td class="sheet__cell">No</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">BX-4473</td><td class="sheet__cell">a.okafor@bluecrest.foods</td><td class="sheet__cell">Bluecrest Foods</td><td class="sheet__cell">Plant Engineer</td><td class="sheet__cell">1</td><td class="sheet__cell">Yes</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">BX-4474</td><td class="sheet__cell">i.duarte@vantorsystems.pt</td><td class="sheet__cell">Vantor Systems</td><td class="sheet__cell">Automation Buyer</td><td class="sheet__cell">rating_warm</td><td class="sheet__cell">Y</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">209 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">215</th><td class="sheet__cell">BX-4684</td><td class="sheet__cell">s.mikkelsen@fjordline.dk</td><td class="sheet__cell">Fjordline Pumps</td><td class="sheet__cell">Maintenance Manager</td><td class="sheet__cell">Warm</td><td class="sheet__cell">No</td></tr></tbody></table>
<p>The property names on the other side are <code>email</code>, <code>company</code>, <code>jobtitle</code> and three the exhibitor created. The <code>lead_rating</code> column carries three conventions for one rating, because three people at the booth scanned badges their own way. The Vantor Systems row already holds <code>rating_warm</code>, pasted out of the portal by somebody who knew where to look. The opt-in column says <code>Yes</code>, <code>No</code> and <code>Y</code>. HubSpot calls the property behind it a single checkbox, for values that are true or false. The first email trails a space and shouts its domain.</p>
<p>The exhibitor hands that lead list to the importer inside your app. Updog Importer opens it in the browser, lines its headers up with your schema, and shows them every value it read. Your <code>onComplete</code> handler receives the rows. The handler posts them in batches to an endpoint you own. The endpoint holds the private app token and calls the batch upsert. HubSpot writes the contacts.</p>
<p>No Updog server stands between that booth and that portal.</p>
<h2 id="the-value-behind-the-label">The value behind the label</h2>
<p>Lead rating is an enumeration property, which is HubSpot's word for a dropdown, a radio select or a set of checkboxes. Each option inside one carries two strings, a label and an internal value. HubSpot's instructions for adding one say that "by default, the internal value will be the same as the label". Somebody can type a different value into that field, and once it is saved "you won't be able to change this". So the string a person reads in the portal and the string the API takes are two separate things.</p>
<p>That gap is why the option list comes off the account itself.</p>
<pre><code class="language-ts">import { Client } from "@hubspot/api-client";

const hubspot = new Client({
  accessToken: process.env.HUBSPOT_PRIVATE_APP_TOKEN,
});

export async function leadRatingOptions() {
  const { results } = await hubspot.crm.properties.coreApi.getAll("contacts");
  const rating = results.find((property) => property.name === "lead_rating");

  return (rating?.options ?? [])
    .filter((option) => !option.hidden)
    .map((option) => ({ value: option.value, label: option.label }));
}</code></pre>
<p>The call needs the <code>crm.schemas.contacts.read</code> scope, and it answers with that portal's own vocabulary.</p>
<pre><code class="language-json">[
  { "value": "rating_hot",  "label": "Hot" },
  { "value": "rating_warm", "label": "Warm" },
  { "value": "rating_cold", "label": "Cold" }
]</code></pre>
<p>The same call against a second exhibitor answers with three different strings under the same three labels. Reading the property is also how you confirm the spelling of every other field, because the <code>name</code> on each result is the string the API takes.</p>
<h2 id="a-column-schema-built-from-the-portal">A column schema built from the portal</h2>
<p>The <code>columns</code> array is what the person reads while they work, so it gets built from the options that call returned.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

type RatingOption = { value: string; label: string };

export const buildColumns = (ratings: RatingOption[]): DataEditorColumn[] => {
  const values = ratings.map((option) => option.value);
  const labels = Object.fromEntries(
    ratings.map((option) => [option.value, option.label]),
  );

  return [
    {
      id: "badgeId",
      title: "Badge ID",
      size: 130,
      validators: [{ type: "required" }, { type: "unique" }],
    },
    {
      id: "email",
      title: "Work email",
      size: 240,
      transformer: (value) =>
        typeof value === "string" ? value.toLowerCase() : value,
      validators: [
        { type: "required" },
        { type: "email" },
        { type: "unique" },
      ],
    },
    { id: "company", title: "Company", size: 190 },
    { id: "jobTitle", title: "Job title", size: 190 },
    {
      id: "leadRating",
      title: "Lead rating",
      size: 150,
      editor: { type: "select", options: values, enableCustomValue: false },
      formatter: (value) => labels[value] ?? value,
      validators: [{ type: "required" }, { type: "oneOf", values }],
    },
    {
      id: "marketingOptIn",
      title: "Marketing opt-in",
      size: 160,
      editor: {
        type: "select",
        options: ["true", "false"],
        enableCustomValue: false,
      },
      validators: [{ type: "oneOf", values: ["true", "false"] }],
    },
  ];
};</code></pre>
<p>The select editor stores each option string as both the stored value and the display label. So <code>options</code> carries the internal values, and the <code>formatter</code> puts the readable half back on the screen without touching the data. Setting <code>enableCustomValue</code> to false closes the enum, so nobody invents a fourth rating inside the grid. The <code>oneOf</code> validator holds the same list and flags a cell that lands outside it. An unmatched select value is dropped on import, which is what the <code>required</code> validator on the rating catches.</p>
<p>The email <code>transformer</code> lowercases the value, so <code>Northwind-Robotics.COM</code> and its lowercase twin count as one address under the <code>unique</code> check. The trailing space costs nothing, because the parser trims every cell before the grid sees it.</p>
<p>The matching props and the key go on the mount.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Lead>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="email"
  synonyms={{
    values: {
      rating_hot: ["a"],
      rating_warm: ["b"],
      rating_cold: ["c"],
    },
  }}
  onValueMatch={matchScannerCodes}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> set to <code>email</code> names the identity HubSpot itself uses, since its contacts guide calls email address "the primary unique identifier to avoid duplicate contacts". The headers need no help. Matching lowercases a header and drops spaces and underscores before it scores, so <code>work_email</code> reaches <code>email</code> and <code>job_title</code> reaches <code>jobTitle</code> on their own. Every snippet here is React, and the web component build takes the same props. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>. <code>synonyms</code> holds two tables that stay apart, one feeding column matching and one feeding value matching, and only the value half has work here.</p>
<h2 id="the-values-the-matcher-cannot-reach">The values the matcher cannot reach</h2>
<p>Updog scores every imported value against every option and keeps the best one that reaches 60. An exact match scores 100, a synonym 90, one string containing the other 80, and half the words shared 70.</p>
<p><code>rating_warm</code> is already an internal value, so it lands at 100 and nothing has to happen. <code>Yes</code>, <code>Y</code> and <code>No</code> reach <code>true</code> and <code>false</code> at 90, because the built-in table already pairs yes with y and true. <code>Hot</code> reaches <code>rating_hot</code> at 70, since the two share the word <code>hot</code> out of two words. <code>A</code> and <code>1</code> reach nothing. A single letter and a single digit share no word with <code>rating_hot</code>, and the edit distance between them sits far past what the matcher allows.</p>
<p>Those two values take different props, because they are different problems.</p>
<p><strong>A letter grade is a convention you know in advance.</strong> Every badge scanner the platform ships writes <code>A</code>, <code>B</code> and <code>C</code>. The alias is static, so it belongs in <code>synonyms</code>. Each key is the canonical option value and the array lists what people type. Your entries merge with the built-in table as a union per key, so the yes and no pairs above survive.</p>
<p><strong>A digit means whatever the exhibitor decided.</strong> One booth writes <code>1</code> for the hottest lead and the next writes <code>1</code> for the coldest. That answer lives in the exhibitor's own record, so your code fetches it while the wizard is open.</p>
<pre><code class="language-ts">type ValueMatchInput = { importedValues: string[]; options: string[] };

const matchScannerCodes = async (
  valuesToMatch: Record&#x3C;string, ValueMatchInput>,
) => {
  const rating = valuesToMatch.leadRating;
  if (!rating) return {};

  const url = "/api/exhibitors/" + exhibitorId + "/scanner-codes";
  const codebook: Record&#x3C;string, string> = await fetch(url).then((response) =>
    response.json(),
  );

  const matched: Record&#x3C;string, string> = {};
  for (const value of rating.importedValues) {
    const option = codebook[value];
    if (option) matched[value] = option;
  }

  return { leadRating: matched };
};</code></pre>
<p><code>onValueMatch</code> fires once for the whole upload, when the person first reaches the value-matching step, with every select column's imported values and allowed options. Return a map of column ID to imported-value pairs. Anything you leave out falls back to Updog's own matching, and a value set to <code>null</code> stays deliberately unmatched. When the call throws or runs past 30 seconds, the SDK uses built-in matching instead, so a slow codebook service leaves the import with Updog's own answer.</p>
<p>Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back through <code>synonyms</code> next time. Saving those fixes against the exhibitor who made them is what <a href="https://updog.tech/blog/remember-csv-import-mappings/">how to remember CSV import mappings between uploads</a> walks through.</p>
<h2 id="the-handler-that-posts-in-hundreds">The handler that posts in hundreds</h2>
<p>When the exhibitor submits, Updog Importer hands your handler every lead grouped by source, each row flagged <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. Three scanners at one booth send three files into a single import, each arriving as its own source entry, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const BATCH_SIZE = 100;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Lead>) => {
  await saveSynonyms(result.learnedSynonyms);

  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += BATCH_SIZE) {
    const response = await fetch("/api/leads/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + BATCH_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>The batch size comes from HubSpot. Its contacts guide states it in one line, "Batch operations are limited to 100 records at a time." Four thousand leads is forty calls.</p>
<p>A private app on a Professional subscription gets 190 calls every 10 seconds and 625,000 a day across the whole account. Enterprise keeps the 190 and raises the day to 1,000,000, while Free and Starter sit at 100 and 250,000. Past the limit every call comes back 429, and <code>policyName</code> in the body names which limit was hit. HubSpot's advice for the ten-second one is to throttle the requests your app is making to stay under it.</p>
<p><strong>Throw when a batch of leads fails.</strong> Updog waits on your handler and empties the grid as soon as it resolves. A handler that swallows the failure and returns looks like success, and the leads disappear off the screen unwritten. A spinner in the confirm dialog covers the whole round trip, which is the second reason those batches stay small. Throwing leaves every lead, every mapping and every hand fix in place, so the exhibitor submits again on data still in front of them.</p>
<p>Every piece of the result you plan to keep gets copied while the handler runs. After the promise resolves the editor drops its rows, its sources, its history and its learned synonyms, which is why <code>saveSynonyms</code> runs on the first line.</p>
<h2 id="the-endpoint-that-holds-the-token">The endpoint that holds the token</h2>
<p>The endpoint is where the token lives and where the browser stops.</p>
<pre><code class="language-ts">import { Hono } from "hono";
import { Client } from "@hubspot/api-client";

const hubspot = new Client({
  accessToken: process.env.HUBSPOT_PRIVATE_APP_TOKEN,
  numberOfApiCallRetries: 3,
});

export const app = new Hono();

app.post("/api/leads/import", async (c) => {
  const session = await verifySession(c.req.header("cookie"));
  if (!session) {
    return c.json({ message: "Not signed in" }, 401);
  }

  const { rows } = await c.req.json();
  const inputs = rows.map((row) => ({
    id: row.email,
    idProperty: "email",
    properties: {
      email: row.email,
      company: row.company,
      jobtitle: row.jobTitle,
      badge_id: row.badgeId,
      lead_rating: row.leadRating,
      marketing_opt_in: row.marketingOptIn,
    },
  }));

  const written = await hubspot.crm.contacts.batchApi.upsert({ inputs });

  if ("numErrors" in written &#x26;&#x26; written.numErrors) {
    return c.json(
      {
        message: written.errors?.[0]?.message ?? "Part of the batch failed",
        errors: written.errors,
      },
      502,
    );
  }

  return c.json({ written: written.results.length });
});</code></pre>
<p><code>verifySession</code> stands in for your own server-side check. The token is a private app access token, created from the Legacy apps page under Development in the portal, and it travels in the <code>Authorization</code> header as a bearer token. It carries the scopes you ticked when you made the app, so this endpoint needs <code>crm.objects.contacts.write</code> for the upsert alongside the schema scope the property call used. A portal holds up to 20 private apps, and a token rotates with a seven-day overlap or expires on the spot.</p>
<p>HubSpot watches for that token leaving your control. Its authentication documentation says HubSpot uses GitHub's secret scanning to find tokens exposed in public repositories. "Any detected tokens will automatically be deactivated", and an email and an in-app notice follow.</p>
<p><code>idProperty</code> set to <code>email</code> turns the call into a create or an update per record. HubSpot's contacts guide adds one consequence worth reading twice, that "Partial upserts are not supported when using <code>email</code> as the <code>idProperty</code> for contacts". Every input therefore carries the whole property set, which is what the mapping above builds. A custom property flagged as a unique identifier takes partial upserts, at the cost of a second identity to keep in step with the grid.</p>
<h2 id="a-partial-success-inside-one-response">A partial success inside one response</h2>
<p>The batch call answers 200 when every record landed, and 207 when some of them did not.</p>
<pre><code class="language-json">{
  "status": "COMPLETE",
  "startedAt": "2026-08-18T09:14:02.113Z",
  "completedAt": "2026-08-18T09:14:02.470Z",
  "numErrors": 1,
  "results": [
    { "id": "701551", "new": false, "properties": { "email": "t.lindqvist@haldenmarine.se" } }
  ],
  "errors": [
    { "status": "error", "category": "VALIDATION_ERROR", "message": "...", "context": {} }
  ]
}</code></pre>
<p>Both of those resolve. The client's own type says so, since <code>upsert()</code> returns <code>BatchResponseSimplePublicUpsertObjectWithErrors | BatchResponseSimplePublicUpsertObject</code>, and only a response outside the 2xx range throws an <code>ApiException</code> carrying <code>code</code>, <code>body</code> and <code>headers</code>. So the endpoint reads <code>numErrors</code> before it answers, and an unread <code>numErrors</code> is a half-write that looks clean.</p>
<p>Each entry in <code>errors</code> carries <code>category</code>, <code>message</code> and <code>context</code>. HubSpot adds that every field in an error response "should all be treated as optional in any error parsing", so read them defensively and pass the message up. Records that already landed stay landed, because an upsert against the same <code>idProperty</code> writes the same values a second time.</p>
<p>The client retries some failures on its own. <code>numberOfApiCallRetries</code> accepts a number from 0 to 6, and on a 429 whose body names <code>TEN_SECONDLY_ROLLING</code> the client waits ten seconds times the retry number before trying again.</p>
<h2 id="the-part-updog-leaves-to-you">The part Updog leaves to you</h2>
<p>Updog Importer integrates with nobody. There is no HubSpot connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the endpoint in the middle is work you do.</p>
<p>HubSpot already ships its own import for the other case. The portal's import screen takes a .csv, .xlsx or .xls file. A paid tier allows 512 MB and 1,048,576 rows a file. Free Tools allows 20 MB and 500,000 rows a day. <code>POST /crm/v3/imports</code> does the same job from your server with a <code>columnMappings</code> array. Those two paths are shorter whenever the file is already in the portal owner's hands.</p>
<p>One line on HubSpot's own troubleshooting page marks the edge of that path. A value matching no option raises <code>Invalid enumeration option</code>, and "The affected records were still imported, but the enumeration property does not contain a value". The contact lands and the rating stays blank. Everything above exists so the mismatch gets settled in front of the person who created it. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> weighs the browser route against the server route for a job like this one.</p>
<h2 id="the-chain-you-built">The chain you built</h2>
<p>You read one property off the destination account, built a schema from what it returned, added two matching props, wrote a handler that posts in hundreds, and stood up one endpoint holding one token. The lead list never leaves the machine that opened it. The rows travel from your own front end to your own endpoint, and from there into the exhibitor's portal, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> page or a plain modal and the middle stays the same.</p>
<p>That exhibitor will send another list after the next conference. By then the codes are stored, the ratings map themselves, and the leads reach the portal carrying the words the portal reads.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Oracle Database</title><link>https://updog.tech/blog/import-csv-into-oracle/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-oracle/</guid><pubDate>Wed, 29 Jul 2026 00:00:00 GMT</pubDate><description>Validate a messy asset register in the browser against Oracle's own byte widths, then merge the clean rows with executeMany from your own route.</description><content:encoded><![CDATA[<p>Oracle's own documentation covers SQL*Loader, external tables, the Data Import Wizard inside SQL Developer, and <code>DBMS_CLOUD.COPY_DATA</code> on Autonomous Database. SQL*Loader runs from a machine that can reach both the data file and the database. An external table wants a directory object and a grant on it. The wizard runs from a desktop holding a connection. <code>DBMS_CLOUD.COPY_DATA</code> wants the file in cloud object storage or in a database directory first. Each one starts from a seat that holds database credentials. Your customer sits outside that seat, holding an asset register out of the system their plant is leaving.</p>
<p>Their export arrives looking like this.</p>
<p><code>anlagenregister.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Anlagennummer</td><td class="sheet__cell">Bezeichnung</td><td class="sheet__cell">Technischer Platz</td><td class="sheet__cell">Kritikalität</td><td class="sheet__cell">Inbetriebnahme</td><td class="sheet__cell">Wiederbeschaffungswert</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">P-1042</td><td class="sheet__cell">Wälzlagerprüfstand Süd Halle 3 (Umbau)</td><td class="sheet__cell">WERK1-H3-MECH</td><td class="sheet__cell">A</td><td class="sheet__cell">14.03.2019</td><td class="sheet__cell">128.500,00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">P-1043</td><td class="sheet__cell">Förderband Süd</td><td class="sheet__cell">WERK1-H2-FOERD</td><td class="sheet__cell">kritisch</td><td class="sheet__cell">02.11.2021</td><td class="sheet__cell">64.200,00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">P-1044</td><td class="sheet__cell">Kühlmittelpumpe</td><td class="sheet__cell">WERK1-H3-MECH</td><td class="sheet__cell">B</td><td class="sheet__cell">07.09.2020</td><td class="sheet__cell">12.750,00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">P-1042</td><td class="sheet__cell">Wälzlagerprüfstand Süd Halle 3</td><td class="sheet__cell">WERK1-H3-MECH</td><td class="sheet__cell">A</td><td class="sheet__cell">14.03.2019</td><td class="sheet__cell">128.500,00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">P-1051</td><td class="sheet__cell">Späneförderer</td><td class="sheet__cell">WERK1-H1-SPAN</td><td class="sheet__cell">C</td><td class="sheet__cell">30.06.2018</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="6"><span class="sheet__break-text">480 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">487</th><td class="sheet__cell">P-1527</td><td class="sheet__cell">Hydraulikaggregat Nord</td><td class="sheet__cell">WERK1-H1-HYDR</td><td class="sheet__cell">B</td><td class="sheet__cell">18.05.2022</td><td class="sheet__cell">41.900,00</td></tr></tbody></table>
<p>The plant's old system wrote six German headers and put semicolons between them. <code>Anlagennummer</code> is the asset tag and <code>Technischer Platz</code> is the functional location. Two rows carry the same tag, <code>P-1042</code>, with two different descriptions. The criticality column mixes <code>A</code>, <code>B</code> and <code>C</code> with the word <code>kritisch</code>. Dates run day first with dots, prices carry a comma for the decimal point, and one price is missing.</p>
<p>The maintenance planner opens your app and hands the register to the importer. Updog Importer matches the German headers to your fields, puts every value in front of them, and checks each one. Your <code>onComplete</code> handler receives the rows. The handler cuts them into chunks and sends each chunk to a route you own. The route holds the Oracle credentials and runs one <code>MERGE</code> per record through <code>executeMany</code>. Oracle writes the table.</p>
<p>No Updog server sits anywhere in that chain.</p>
<h2 id="the-table-and-its-widths">The table and its widths</h2>
<p>Oracle stores a nonquoted identifier in uppercase, whatever case you typed. Names run to 128 bytes once <code>COMPATIBLE</code> is 12.2 or higher, and to 30 bytes below that, which is why an older plant schema is full of abbreviations.</p>
<pre><code class="language-sql">create table maint.asset_register (
  asset_id        number generated always as identity primary key,
  plant_id        number        not null,
  asset_tag       varchar2(20)  not null,
  description     varchar2(40)  not null,
  func_loc        varchar2(30)  not null,
  crit_cd         varchar2(1)   not null,
  commissioned_on date,
  repl_value      number(12, 2),
  updated_at      timestamp default systimestamp not null,
  constraint uq_asset_plant_tag unique (plant_id, asset_tag),
  constraint ck_asset_crit check (crit_cd in ('A', 'B', 'C'))
);</code></pre>
<p><code>varchar2(40)</code> on the description column holds forty bytes while <code>NLS_LENGTH_SEMANTICS</code> is <code>BYTE</code>. That is where Oracle sets it and where Oracle recommends leaving it. On an AL32UTF8 database each of those German umlauts takes two bytes, so <code>Wälzlagerprüfstand Süd Halle 3 (Umbau)</code> runs 38 characters and 41 bytes. A length check written in JavaScript counts 38 and waves it through. Oracle answers ORA-12899, <code>value too large for column</code>, and reports both widths in bytes for a column with byte semantics.</p>
<p>The unique constraint on <code>plant_id</code> and <code>asset_tag</code> decides which rows merge and which arrive new. Both columns are made of digits and short codes, so the width question never reaches them. The description is where it lands, and the browser is where it gets answered.</p>
<h2 id="the-columns-the-person-sees">The columns the person sees</h2>
<p>The <code>columns</code> array carries <code>asset_register</code> in the words the planner reads. Each entry holds a <code>title</code> for the header, an editor that decides how a cell gets typed, and validators that mark failures.</p>
<pre><code class="language-ts">import type { CellValidator, DataEditorColumn } from "@updog/data-editor";

const CRITICALITY = ["A", "B", "C"];
const encoder = new TextEncoder();

const maxBytes = (limit: number): CellValidator => {
  return (value) => {
    const size = encoder.encode(String(value ?? "")).length;
    if (size &#x3C;= limit) return null;
    return {
      level: "error",
      message: "Too long for Oracle by " + (size - limit) + " bytes",
    };
  };
};

export const columns: DataEditorColumn[] = [
  {
    id: "assetTag",
    title: "Asset tag",
    size: 120,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "function", fn: maxBytes(20) },
      { type: "unique" },
    ],
  },
  {
    id: "description",
    title: "Description",
    size: 280,
    validators: [
      { type: "required" },
      { type: "function", fn: maxBytes(40) },
    ],
  },
  {
    id: "funcLoc",
    title: "Functional location",
    size: 180,
    validators: [
      { type: "required" },
      { type: "function", fn: maxBytes(30) },
    ],
  },
  {
    id: "criticality",
    title: "Criticality",
    size: 120,
    editor: { type: "select", options: CRITICALITY, enableCustomValue: false },
    validators: [{ type: "oneOf", values: CRITICALITY }],
  },
  {
    id: "commissionedOn",
    title: "Commissioned on",
    size: 160,
    editor: { type: "date" },
  },
  {
    id: "replacementValue",
    title: "Replacement value",
    size: 160,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, max: 9_999_999_999.99, decimalPlaces: 2 },
    ],
  },
];</code></pre>
<p><code>maxBytes</code> is where Oracle's width reaches the browser. A <code>function</code> validator receives the cell value and returns a <code>ValidationError</code> or <code>null</code>, so <code>TextEncoder</code> measures the same UTF-8 bytes the column counts. Every limit in that file comes off a <code>varchar2</code> declaration and nowhere else. <code>{ type: "unique" }</code> on the asset tag catches the repeated <code>P-1042</code>, and it runs once every other validator on the column passes, so a cell holding an invalid value reports that error first. The <code>select</code> editor with <code>enableCustomValue</code> off holds criticality to three options and sends everything else to the value matching step.</p>
<p>The <code>synonyms</code> prop hands matching the German words your customers already use, and the mount below puts every prop in one place.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Asset>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="assetTag"
  synonyms={{
    columns: {
      assetTag: ["anlagennummer", "equipment no"],
      description: ["bezeichnung", "benennung"],
      criticality: ["kritikalität", "abc kennzeichen"],
    },
    values: { A: ["kritisch"], B: ["wichtig"], C: ["gering"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>Anlagennummer</code>, <code>Bezeichnung</code> and <code>Kritikalität</code> each score too low against an English field title, so they reach their column through <code>synonyms</code>. <code>Technischer Platz</code> reaches nothing at all, so the planner maps it by hand, and that pair comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> walks that pair from the grid into the next register. <code>kritisch</code> reaches option <code>A</code> the same way, from <code>synonyms.values</code>.</p>
<p>Date order is one verdict for the whole file. The first value carrying a part above 12 settles it, and <code>14.03.2019</code> does that on the opening row, so the column reads day first and every date normalises to <code>2019-03-14</code>. A price carrying both separators settles the number format on its own, because the last separator is the decimal point, and <code>128.500,00</code> reaches your handler as <code>128500.00</code>. <a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> walks the rest of that list.</p>
<p><code>primaryKey</code> decides how an imported row meets a row already in the grid. Inside one import the plant is fixed, so the asset tag alone identifies an asset on the browser side. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<p>Every snippet here is React. The web component build takes the same props, so a Vue, Angular or Svelte front end declares the same columns and the same handler.</p>
<h2 id="the-chunked-post-to-your-own-route">The chunked post to your own route</h2>
<p>The planner presses submit, and Updog Importer hands your handler every asset row grouped by source, carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. A planner can drop three register exports in one import, and each file lands as its own source entry, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 400;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Asset>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/assets/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>Four hundred comes from two numbers you can work out before the first chunk leaves. The first is the bind buffer. <code>bindDefs</code> declares a <code>maxSize</code> in bytes for every string bind, the driver allocates that many bytes for each value it processes, and 20 plus 40 plus 30 plus 1 gives 91 bytes a record. Four hundred records allocate about 36KB, whatever the values themselves hold.</p>
<p>The second is the body your own route accepts. The JSON parser Express bundles defaults to a 100kb limit and answers a larger body with 413 and <code>entity.too.large</code>.</p>
<pre><code class="language-json">{"assetTag":"P-1042","description":"Wälzlagerprüfstand Süd Halle 3","funcLoc":"WERK1-H3-MECH","criticality":"A","commissionedOn":"2019-03-14","replacementValue":"128500.00"}</code></pre>
<p>One asset row of these six fields serializes to 176 bytes, so four hundred of them reach roughly 69KB. Run that division against your own widest row before raising the number. The driver's own documentation names no row ceiling for <code>executeMany</code>. It names the failure instead, <code>DPI-1015: array size is too large</code>, with the instruction to call the method again over subsets of the data.</p>
<p><strong>A failed chunk has to throw.</strong> Updog holds the editor open only while your handler runs, and empties it the moment the promise resolves. A handler that catches its own failure and returns reads as success, and the asset rows leave the screen unsaved. A spinner covers the confirm dialog until the last chunk answers, which is the other reason chunks stay small. Throwing leaves every row, every mapping and every correction on the screen, so the planner submits again on data still in front of them.</p>
<p>Copy anything off the result you plan to keep while the handler is still running. The editor releases its rows, its sources, its history and its learned synonyms as soon as the promise resolves.</p>
<p>The <code>isValid</code> filter in that snippet costs this register a row. A failed validator marks the cell and lets the person submit anyway, so an over-wide description reaches your handler and the filter leaves it behind. Pass <code>blockSubmitOnError</code> to the editor and submit stays locked until every row passes.</p>
<h2 id="the-write-from-your-own-server">The write from your own server</h2>
<p>One statement carries the whole chunk, run once per record.</p>
<pre><code class="language-sql">merge into maint.asset_register t
using (select :plantId as plant_id, :assetTag as asset_tag from dual) s
   on (t.plant_id = s.plant_id and t.asset_tag = s.asset_tag)
 when matched then
   update set t.description     = :description,
              t.func_loc        = :funcLoc,
              t.crit_cd         = :critCd,
              t.commissioned_on = :commissionedOn,
              t.repl_value      = :replValue,
              t.updated_at      = systimestamp
 when not matched then
   insert (plant_id, asset_tag, description, func_loc,
           crit_cd, commissioned_on, repl_value)
   values (:plantId, :assetTag, :description, :funcLoc,
           :critCd, :commissionedOn, :replValue)</code></pre>
<p><code>MERGE</code> reads one row out of <code>dual</code> for each record, matches it against the unique constraint, and takes the update branch or the insert branch. <code>plant_id</code> and <code>asset_tag</code> stay out of the <code>when matched</code> half, since Oracle refuses to update a column referenced in the <code>on</code> condition. The statement wants <code>INSERT</code> and <code>UPDATE</code> on the target table and <code>SELECT</code> on the source.</p>
<p>The browser goes no further than your route, and the Oracle credentials wait on the other side of it.</p>
<pre><code class="language-ts">import express from "express";
import oracledb from "oracledb";

const app = express();
app.use(express.json());

await oracledb.createPool({
  user: process.env.ORACLE_USER,
  password: process.env.ORACLE_PASSWORD,
  connectString: process.env.ORACLE_CONNECT_STRING,
  poolMin: 2,
  poolMax: 10,
});

const bindDefs = {
  plantId: { type: oracledb.NUMBER },
  assetTag: { type: oracledb.STRING, maxSize: 20 },
  description: { type: oracledb.STRING, maxSize: 40 },
  funcLoc: { type: oracledb.STRING, maxSize: 30 },
  critCd: { type: oracledb.STRING, maxSize: 1 },
  commissionedOn: { type: oracledb.DB_TYPE_DATE },
  replValue: { type: oracledb.NUMBER },
};

const toOracleDate = (iso: string) => {
  if (!iso) return null;
  const [year, month, day] = iso.split("-").map(Number);
  return new Date(year, month - 1, day);
};

app.post("/api/assets/import", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const { rows } = request.body as { rows: Asset[] };
  const binds = rows.map((row) => ({
    plantId: session.plantId,
    assetTag: row.assetTag,
    description: row.description,
    funcLoc: row.funcLoc,
    critCd: row.criticality,
    commissionedOn: toOracleDate(row.commissionedOn),
    replValue: row.replacementValue === "" ? null : Number(row.replacementValue),
  }));

  const connection = await oracledb.getConnection();
  try {
    const result = await connection.executeMany(MERGE_ASSET, binds, {
      autoCommit: false,
      batchErrors: true,
      bindDefs,
    });

    if (result.batchErrors?.length) {
      await connection.rollback();
      return response.status(409).json({
        message: "Oracle rejected part of this batch",
        failures: result.batchErrors.map((error) => ({
          row: error.offset,
          code: error.errorNum,
          message: error.message,
        })),
      });
    }

    await connection.commit();
    response.json({ written: result.rowsAffected });
  } finally {
    await connection.close();
  }
});</code></pre>
<p><code>MERGE_ASSET</code> holds the statement above as a string. node-oracledb runs in Thin mode by default, connects to Oracle Database 12.1 or later straight from Node, and needs no Oracle Client libraries. <code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>plant_id</code> comes off that session and never off the request body, because a planner who can post rows can also post a different plant id.</p>
<p><code>bindDefs</code> names a type and a width for every bind, and those widths are the ones in the table. Leaving it out makes the driver scan every record to find the longest value, which is work the browser already did. <code>oracledb.DB_TYPE_DATE</code> is the Oracle <code>DATE</code> type. The constant named <code>oracledb.DATE</code> maps to <code>TIMESTAMP WITH LOCAL TIME ZONE</code>, so the two constants stand for two different column types. <code>toOracleDate</code> splits the ISO date the browser produced and builds the value out of its three parts.</p>
<h2 id="what-a-failed-chunk-hands-back">What a failed chunk hands back</h2>
<p>With <code>batchErrors</code> off, <code>executeMany</code> stops at the first error and the whole call rejects. With it on, every valid record is processed and the failures come back as an array on the result.</p>
<pre><code class="language-plaintext">[
  { Error: ORA-00001: unique constraint (MAINT.UQ_ASSET_PLANT_TAG) violated
    errorNum: 1, offset: 12 },
  { Error: ORA-12899: value too large for column
    "MAINT"."ASSET_REGISTER"."DESCRIPTION" (actual: 41, maximum: 40)
    errorNum: 12899, offset: 37 }
]</code></pre>
<p>Each entry carries an <code>offset</code>, the 0-based index of the record inside the binds array. Add the offset to the start of the chunk and you have the row the planner is looking at. <code>errorNum</code> is Oracle's own number. ORA-00001 is a unique constraint violated. ORA-12899 is a value too large for a column. ORA-01438 is a number carrying more digits than the precision allows.</p>
<p>The transaction stays open. <code>batchErrors</code> starts one and leaves it uncommitted even when <code>autoCommit</code> is <code>true</code>, so your route examines the errors and then commits or rolls back. The route above rolls back and returns the offsets, which keeps a chunk whole. Committing the survivors is the other choice, and it costs the planner a partial import to reconcile.</p>
<p>One class of failure never reaches that array. A value longer than the <code>maxSize</code> you declared throws out of <code>executeMany</code> itself and takes the whole chunk with it, and no transaction is created. That failure is what the byte validator in the browser exists to prevent.</p>
<p>A repeated asset tag inside one chunk behaves differently again. <code>executeMany</code> runs the statement once per record, so the second <code>MERGE</code> finds the row the first one inserted and updates it. No error is raised, and the later row wins. ORA-30926, where the operation attempted to update the same row twice, belongs to a <code>MERGE</code> whose source is a table or a query carrying two rows for one target key. The <code>unique</code> validator is what puts both rows in front of the planner while they can still choose.</p>
<h2 id="oracles-own-import-paths">Oracle's own import paths</h2>
<p>Updog Importer integrates with nobody. There is no Oracle connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route between it and Oracle is yours to write.</p>
<p>Oracle already ships an import for the other case. SQL*Loader loads external files into database tables, driven by a control file, with an express mode for simple data types. An external table reads the file in place and needs a directory object, plus READ on that directory granted to the user directly. SQL Developer's Data Import Wizard offers a plain insert, a generated insert script, an external table, a staging external table and a SQL*Loader run, and it sizes the columns of a new table from the rows it previewed. On Autonomous Database, <code>DBMS_CLOUD.COPY_DATA</code> loads into a table that already exists, from cloud object storage with a credential stored in the database, or from a directory the loading user can read.</p>
<p>Every one of those is the shorter path when the file belongs to the developer. Everything above exists for the asset register that belongs to a customer, arriving through a browser, in a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> lays out which of the two a job wants.</p>
<h2 id="the-finished-chain">The finished chain</h2>
<p>The plant's file never left the planner's laptop. The rows travelled from your own front end to your own route, and from there into Oracle, and the only party added to the chain is yourself. The widths in the schema became the widths in the bind, and the description that would have overflowed was flagged while somebody could still fix it.</p>
<p>If the validator counts the same bytes the column counts, the rows the planner cleaned in the browser reach Oracle whole.</p>]]></content:encoded></item>
<item><title>How to Import a CSV File Into a Vue App With the Updog Importer</title><link>https://updog.tech/blog/how-to-import-csv-into-vue-app/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-csv-into-vue-app/</guid><pubDate>Tue, 28 Jul 2026 00:00:00 GMT</pubDate><description>Add CSV and Excel import to a Vue app. Register the Web Component, define your schema, set up matching, and get clean rows back.</description><content:encoded><![CDATA[<p>This guide shows how to add a CSV and Excel importer to a Vue app. Import takes more than a parser. Read <a href="https://updog.tech/blog/csv-import-is-more-than-parsing/">CSV import is more than parsing a file</a> for the reasons.</p>
<p>The example is an employee importer with seven columns. You install the package, tell Vue about the element, describe your data, match the file to your schema, and read the result.</p>
<p>Two words in this guide mean two different things. <strong>Upload</strong> is when someone puts a file into the data editor. The file is read in the browser, and nothing has reached you yet. <strong>Import</strong> is the last step, when the cleaned rows land in your system. Everything between the two happens inside the editor, and that is where the messy data gets fixed.</p>
<p>Updog comes to Vue as a Web Component. You register the custom element once, then use it in templates like any other tag. The same package works in Angular, Svelte, and plain JavaScript. React has its own package.</p>
<h2 id="step-1-install-the-web-component">Step 1. Install the web component</h2>
<pre><code class="language-bash">npm install @updog/data-editor-wc</code></pre>
<p>The package is on npm as <a href="https://www.npmjs.com/package/@updog/data-editor-wc">@updog/data-editor-wc</a>. Two imports register it. The module defines <code>&#x3C;updog-editor></code> globally. The stylesheet adds the styles. You need both, and you import them once for the whole app.</p>
<h2 id="step-2-tell-vue-it-is-a-custom-element">Step 2. Tell Vue it is a custom element</h2>
<p>Vue treats every unknown tag as a component. It looks for a component named <code>updog-editor</code>, finds nothing, and renders nothing. The console shows <code>Failed to resolve component: updog-editor</code>. One compiler option fixes this.</p>
<pre><code class="language-ts">import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          isCustomElement: (tag) => {
            return tag.startsWith("updog-");
          },
        },
      },
    }),
  ],
});</code></pre>
<p>This is the only Vue-specific setup in the guide.</p>
<h2 id="step-3-mount-the-editor">Step 3. Mount the editor</h2>
<p>Put the element in your template. Get a reference to it, then pass your configuration to <code>configure()</code>. In this example the editor sits behind a button. Modal is the default mode, so <code>show()</code> opens the editor. The <code>close</code> event fires when the person closes it.</p>
<pre><code class="language-vue">&#x3C;script setup lang="ts">
import { useTemplateRef, watchEffect } from "vue";
import "@updog/data-editor-wc";
import "@updog/data-editor-wc/styles.css";
import type { UpdogEditorElement } from "@updog/data-editor-wc";
import { columns } from "./columns";

const editorElement = useTemplateRef&#x3C;UpdogEditorElement>("editor");

watchEffect((onCleanup) => {
  const element = editorElement.value;

  if (!element) {
    return;
  }

  element.configure({
    apiKey: "your-license-key",
    columns,
    primaryKey: "email",
    onComplete: (result) => {
      console.log(result);
      element.hide();
    },
  });

  const handleClose = () => {
    element.hide();
  };

  element.addEventListener("close", handleClose);

  onCleanup(() => {
    element.removeEventListener("close", handleClose);
  });
});

function open() {
  editorElement.value?.show();
}
&#x3C;/script>

&#x3C;template>
  &#x3C;button type="button" @click="open">Import employees&#x3C;/button>
  &#x3C;updog-editor ref="editor" variant="uploader" />
&#x3C;/template></code></pre>
<p>Set <code>variant</code> to <code>uploader</code> to open the upload wizard first, so the person starts by picking a file. The default <code>editor</code> variant opens the grid first, for data you already have. Sign up at <a href="https://console.updog.tech/">console.updog.tech</a> to get the <code>apiKey</code>. Updog is free on localhost and on the preview domains from hosts like Vercel and Netlify.</p>
<h2 id="step-4-pass-props-the-right-way">Step 4. Pass props the right way</h2>
<p>The element takes two kinds of input. You set them in two different places.</p>
<h3 id="simple-values-can-be-attributes">Simple values can be attributes</h3>
<p>Eight props are primitives, so they work as plain HTML attributes. Five take a string value, <code>api-key</code>, <code>primary-key</code>, <code>variant</code>, <code>mode</code>, and <code>locale</code>. Three are boolean, <code>open</code>, <code>rtl</code>, and <code>readonly</code>, where the presence of the attribute means true.</p>
<pre><code class="language-html">&#x3C;updog-editor
  ref="editor"
  api-key="your-license-key"
  primary-key="email"
  variant="uploader"
/></code></pre>
<p><code>open</code> controls the modal. Setting it does the same as calling <code>show()</code> and <code>hide()</code>, which set and remove that attribute internally. Bind <code>:open</code> to your own ref to keep the state in Vue instead.</p>
<h3 id="inline-mode-replaces-the-modal">Inline mode replaces the modal</h3>
<p><code>mode</code> picks where the editor renders. The default is <code>modal</code>. Use <code>mode="inline"</code> to render the editor in place, as part of your page.</p>
<pre><code class="language-html">&#x3C;updog-editor ref="editor" variant="uploader" mode="inline" /></code></pre>
<p>Inline mode has no modal, so the modal API does nothing. <code>show()</code> and <code>hide()</code> return without an effect, and the element sends no <code>close</code> event. Remove the button and the listener from step 3, then give the element the space it should fill.</p>
<h3 id="everything-else-goes-through-configure">Everything else goes through configure</h3>
<p>Columns, callbacks, translations, remote sources, and every other object or function go through <code>configure()</code>. It takes any number of props at once and applies them in one render.</p>
<p>Never write a callback as a template binding. Vue reads anything that starts with <code>on</code> as an event listener, so <code>:onComplete</code> registers a listener for an event that never fires. Your callback never runs, and you get no warning.</p>
<pre><code class="language-tsx">// wrong: Vue reads this as an event listener and never sets the prop
&#x3C;updog-editor :onComplete="save" />

// right
element.configure({ onComplete: save });</code></pre>
<p>The same applies to <code>onComplete</code>, <code>onError</code>, <code>onColumnMatch</code>, and <code>onValueMatch</code>. Angular refuses to compile that line, and Svelte fails as silently as Vue does. Keep the habit in every framework.</p>
<h3 id="closing-is-an-event">Closing is an event</h3>
<p>There is no <code>onClose</code> prop. The element sends a real <code>close</code> event. The example above listens for it and removes the listener in <code>onCleanup</code>. In a template, <code>@close</code> works too.</p>
<h2 id="step-5-describe-your-data">Step 5. Describe your data</h2>
<p>The <code>columns</code> array describes the shape your app expects. Updog changes every uploaded file to match it. More detail here means less manual fixing later.</p>
<h3 id="start-with-the-columns">Start with the columns</h3>
<p>Each column needs an <code>id</code> and a <code>title</code>. The <code>id</code> matches the key in your row data. The <code>title</code> is the text people see. <code>size</code> is optional. Add it in pixels to make a column wider or narrower.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor-wc";

export const columns: DataEditorColumn[] = [
  {
    id: "firstName",
    title: "First name",
    size: 150,
  },
  {
    id: "lastName",
    title: "Last name",
    size: 150,
  },
  {
    id: "email",
    title: "Email",
    size: 260,
  },
  {
    id: "startDate",
    title: "Start date",
    size: 140,
  },
  {
    id: "salary",
    title: "Salary",
    size: 120,
  },
  {
    id: "skills",
    title: "Skills",
    size: 220,
  },
  {
    id: "status",
    title: "Status",
    size: 140,
  },
];</code></pre>
<h3 id="choose-an-editor-for-each-column">Choose an editor for each column</h3>
<p>Text is the default, so the name and email columns need nothing. Use <code>date</code> for the start date, <code>number</code> for salary, <code>multiselect</code> for skills, and <code>select</code> for status. An editor sets what people can type. For <code>select</code> and <code>multiselect</code> it also gives the matching step a list of values to match against.</p>
<pre><code class="language-ts">{
  id: "startDate",
  title: "Start date",
  size: 140,
  editor: {
    type: "date",
  },
},
{
  id: "salary",
  title: "Salary",
  size: 120,
  editor: {
    type: "number",
  },
},
{
  id: "skills",
  title: "Skills",
  size: 220,
  editor: {
    type: "multiselect",
    options: ["React", "TypeScript", "Node", "Design"],
  },
},
{
  id: "status",
  title: "Status",
  size: 140,
  editor: {
    type: "select",
    options: ["Active", "Onboarding", "On leave", "Terminated"],
  },
},</code></pre>
<h3 id="add-the-rules">Add the rules</h3>
<p>Validators run on every edit. The grid highlights a value that fails. Here is the full schema, with editors and validators together.</p>
<pre><code class="language-ts">const STATUSES = ["Active", "Onboarding", "On leave", "Terminated"];

export const columns: DataEditorColumn[] = [
  {
    id: "firstName",
    title: "First name",
    size: 150,
    validators: [{ type: "required", message: "First name is required" }],
  },
  {
    id: "lastName",
    title: "Last name",
    size: 150,
    validators: [{ type: "required", message: "Last name is required" }],
  },
  {
    id: "email",
    title: "Email",
    size: 260,
    validators: [
      { type: "required", message: "Email is required" },
      { type: "email", message: "Enter a valid email address" },
      { type: "unique" },
    ],
  },
  {
    id: "startDate",
    title: "Start date",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "date", message: "Enter a valid date" }],
  },
  {
    id: "salary",
    title: "Salary",
    size: 120,
    editor: { type: "number" },
    validators: [
      {
        type: "number",
        min: 0,
        decimalPlaces: 0,
        message: "Salary must be zero or greater",
      },
    ],
  },
  {
    id: "skills",
    title: "Skills",
    size: 220,
    editor: {
      type: "multiselect",
      options: ["React", "TypeScript", "Node", "Design"],
    },
  },
  {
    id: "status",
    title: "Status",
    size: 140,
    editor: { type: "select", options: STATUSES },
    validators: [
      {
        type: "oneOf",
        values: STATUSES,
        message: "Select a status from the list",
      },
    ],
  },
];</code></pre>
<p>Email uses <code>required</code> and <code>email</code>. The <code>unique</code> validator flags a duplicate address in the file. Salary uses a <code>number</code> check that rejects anything below zero. Status uses <code>oneOf</code> against the same list its dropdown offers, which catches a value that slips past matching. A failed rule marks the cell. It does not block submission by default. Invalid rows still reach you with the <code>isValid</code> flag. Set <a href="https://docs.updog.tech/api-reference/core-props/#blocksubmitonerror"><code>blockSubmitOnError</code></a> to hold submission until every error is fixed.</p>
<p>Validators come in three kinds, and the schema above uses only the first. Built-in rules are declarative objects, and there are seven of them, <code>required</code>, <code>regex</code>, <code>oneOf</code>, <code>number</code>, <code>email</code>, <code>date</code>, and <code>unique</code>.</p>
<p>For logic no built-in covers, a <code>function</code> rule takes your own function. It receives the cell value and the whole row, and returns an error or <code>null</code>. Pair it with <code>dependentFields</code> to revalidate a column when another column changes.</p>
<p>For a check against your own backend, an <code>asyncFunction</code> rule receives every affected cell in one batch and reports failures as they arrive. Async rules run after all the sync ones, so a value reaches your server only after it passes the format checks. The <a href="https://docs.updog.tech/api-reference/columns/#validators">columns reference</a> covers all three.</p>
<h3 id="fix-common-errors-before-anyone-sees-them">Fix common errors before anyone sees them</h3>
<p>A validator flags a bad value. A <code>transformer</code> fixes it first. Add one to a column, and Updog runs it on each cell as the uploaded file is turned into rows, before anyone sees the grid. Use it to trim spaces, lowercase an email, or drop a currency symbol.</p>
<pre><code class="language-ts">{
  id: "email",
  title: "Email",
  size: 260,
  transformer: (value) => {
    return String(value).trim().toLowerCase();
  },
},</code></pre>
<h3 id="shape-how-columns-show-and-filter">Shape how columns show and filter</h3>
<p>Two more column props work on the grid. A <code>formatter</code> changes how a value looks, and the stored value stays the same. Salary can show a <code>$</code> while the number underneath stays clean. A <code>filter</code> adds a control to the sidebar.</p>
<pre><code class="language-ts">{
  id: "salary",
  title: "Salary",
  size: 120,
  formatter: (value) => {
    return value ? "$" + value : "";
  },
  filter: {
    type: "number-range",
    label: "Salary",
  },
},</code></pre>
<h2 id="step-6-help-updog-match-the-file">Step 6. Help Updog match the file</h2>
<p>The schema is ready. The file rarely matches it word for word. Updog runs fuzzy matching first and catches small differences on its own, like extra spaces, different capitalization, or a common alternate spelling. Your data may also use terms it cannot guess, such as an internal code or a word from your industry. For those you add your own dictionary.</p>
<h3 id="match-the-columns">Match the columns</h3>
<p>The file might say <code>E-mail</code> and <code>Employment Status</code> where your columns are <code>email</code> and <code>status</code>. Built-in matching pairs the obvious ones. List the headers your users send in the <code>columns</code> table of <code>synonyms</code>, and they map on their own.</p>
<pre><code class="language-ts">element.configure({
  synonyms: {
    columns: {
      email: ["e-mail", "email address", "work email"],
      status: ["employment status", "employee status", "state"],
    },
  },
});</code></pre>
<p>For a header no list catches, pass the decision to your own model through <code>onColumnMatch</code>. Updog gives it the file headers and your columns. You return a map of which goes where.</p>
<pre><code class="language-ts">element.configure({
  onColumnMatch: async (headers, columns) => {
    // headers = ["Emp Email", "Emp Status", ...] from the file
    // columns = your firstName, lastName, email, ... schema
    const map = await askYourModel(headers, columns);
    return map; // { "Emp Email": "email", "Emp Status": "status" }
  },
});</code></pre>
<p>See <a href="https://updog.tech/blog/bring-your-own-ai/">bring your own AI to CSV and Excel import</a> for that path and how the data stays private.</p>
<h3 id="match-the-values">Match the values</h3>
<p>The same works inside the status column. A file can send <code>loa</code> and <code>leave</code> for the status <code>On leave</code>. Value aliases go in the <code>values</code> table, keyed by the option, with the array listing what maps to it. The two tables stay apart, so a word learned inside a dropdown never competes for a column.</p>
<p>One object holds both tables, so write it once. A second <code>configure()</code> call with a new <code>synonyms</code> object replaces the first one, and your column aliases disappear without a warning.</p>
<pre><code class="language-ts">element.configure({
  synonyms: {
    columns: {
      email: ["e-mail", "email address", "work email"],
      status: ["employment status", "employee status", "state"],
    },
    values: {
      "On leave": ["loa", "on-leave", "leave"],
      Terminated: ["term", "left"],
    },
  },
});</code></pre>
<p>For values no list covers, <code>onValueMatch</code> works the same way one level down. Updog gives you the values found in each select column and the options you allow. You return the mapping.</p>
<pre><code class="language-ts">element.configure({
  onValueMatch: async (valuesToMatch) => {
    // valuesToMatch = { status: { importedValues: ["loa", "left"], options: [...] } }
    const map = await askYourModel(valuesToMatch);
    return map; // { status: { loa: "On leave", left: "Terminated" } }
  },
});</code></pre>
<h2 id="step-7-import-the-result-into-your-system">Step 7. Import the result into your system</h2>
<p>This is the import. Everything before it happened in the browser, and nothing has left the page yet.</p>
<p>When the person is done cleaning the data, Updog passes it to <code>onComplete</code>, grouped by source. Each row carries four flags, <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code>. Routing depends on your backend, so Updog leaves it to you. Filter on the flags and send each row where it belongs.</p>
<pre><code class="language-ts">import type { DataEditorResult } from "@updog/data-editor-wc";

element.configure({
  onComplete: async (result: DataEditorResult) => {
    for (const source of result.sources) {
      const inserts = source.rows.filter((row) => {
        return row.isNew &#x26;&#x26; !row.isDeleted &#x26;&#x26; row.isValid;
      });

      const updates = source.rows.filter((row) => {
        return !row.isNew &#x26;&#x26; row.isChanged &#x26;&#x26; !row.isDeleted &#x26;&#x26; row.isValid;
      });

      await saveEmployees(inserts, updates);
    }

    element.hide();
  },
});</code></pre>
<p>Rows arrive keyed by your column IDs, typed as <code>Record&#x3C;string, unknown></code>. The custom element takes no generic parameter. Cast to your own row type here if you want one.</p>
<h2 id="step-8-localize-it">Step 8. Localize it</h2>
<p>Three props control language and layout, and each does one job.</p>
<pre><code class="language-ts">element.configure({
  translations: arabicTranslations, // changes the language
  locale: "ar",                     // picks Arabic plural forms
  rtl: true,                        // flips the layout
});</code></pre>
<p><code>translations</code> is the prop that changes the language. Pass an object with the strings you override. Only the keys you provide are replaced.</p>
<p><code>locale</code> takes a BCP 47 tag and selects the plural form for keys that end in <code>_one</code>, <code>_few</code>, <code>_many</code>, or <code>_other</code>. That is its only job. It loads no translations, and on its own it leaves the UI in English. Set it when your language pluralizes differently from English. Arabic has six forms, Russian has three.</p>
<p><code>rtl</code> flips the layout for Arabic, Hebrew, and other right-to-left languages. It changes grid direction, text alignment, and scrollbar position, and it reverses the column order in exported files.</p>
<p>You do not have to translate every string by hand. Copy the defaults object from the <a href="https://docs.updog.tech/localization/#defaults">localization docs</a>, paste it into your AI, and ask it to translate the values.</p>
<h2 id="style-it-to-match-your-app">Style it to match your app</h2>
<p>The editor renders in the light DOM, so your CSS can reach it. This has one consequence in Vue. A <code>scoped</code> style block does not apply inside the editor. Vue marks the elements it renders with a data attribute, and the editor builds its own DOM without one. Use <code>:deep()</code> and the rule applies.</p>
<pre><code class="language-vue">&#x3C;style scoped>
/* Does not reach inside the editor. */
.updog-button {
  border-radius: 0;
}

/* Does. */
.host :deep(.updog-button) {
  border-radius: 0;
}
&#x3C;/style></code></pre>
<p>Colors come from CSS variables. Fonts come from your page. If your app sets no font, the editor uses the browser default, so set one on the element or on your app.</p>
<pre><code class="language-css">updog-editor {
  font-family: "Inter", system-ui, sans-serif;
  --updog-grid-cell-bg-idle: #ffffff;
  --updog-grid-header-bg-idle: #f8f9fa;
}</code></pre>
<p>For the full variable list, see the <a href="https://docs.updog.tech/styling/">styling reference</a>. There is a longer walkthrough in <a href="https://updog.tech/blog/style-updog-to-match-your-product/">style Updog to match your product</a>.</p>
<h2 id="what-it-costs-and-how-to-pay-less">What it costs, and how to pay less</h2>
<p>The web component carries its own copy of React and the engine that reads Excel files. Here is the same Vue app built three ways, measured after Brotli compression.</p>
<div class="blog-table blog-table--narrow"><table><thead><tr><th>Build</th><th>First load</th></tr></thead><tbody><tr><td>Vue on its own</td><td>21 KB</td></tr><tr><td>Updog loaded at the top of a component</td><td>460 KB</td></tr><tr><td>Updog loaded inside the click handler</td><td>22 KB</td></tr></tbody></table></div>
<p>React accounts for about a tenth of that. The spreadsheet engine takes most of the rest, and the single-file build cannot split it out.</p>
<p>The weight buys one thing. The editor runs inside your page as a single custom element. The usual alternative is an iframe, where the code lives somewhere else and the cost moves instead of going away. Your CSS and your fonts stop at the frame boundary. The frame clips dropdowns and modals instead of letting them float over your layout. Focus and scrolling need their own handling. Every row of data crosses a <code>postMessage</code> protocol, and you maintain that protocol.</p>
<p>An importer opens when someone clicks a button, so it does not belong in your first bundle. Move the module import into the click handler, as in the third row above. Then only the person who opens the importer downloads it.</p>
<pre><code class="language-vue">&#x3C;script setup lang="ts">
import { nextTick, ref, useTemplateRef } from "vue";
import type { UpdogEditorElement } from "@updog/data-editor-wc";
import { columns } from "./columns";

const ready = ref(false);
const editorElement = useTemplateRef&#x3C;UpdogEditorElement>("editor");

let setupPromise: Promise&#x3C;void> | null = null;

function setupEditor() {
  if (!setupPromise) {
    setupPromise = (async () => {
      await import("@updog/data-editor-wc");
      await import("@updog/data-editor-wc/styles.css");
      ready.value = true;

      await nextTick();
      await customElements.whenDefined("updog-editor");

      const element = editorElement.value;

      if (!element) {
        return;
      }

      element.configure({
        apiKey: "your-license-key",
        columns,
        primaryKey: "email",
        onComplete: (result) => {
          console.log(result);
          element.hide();
        },
      });

      element.addEventListener("close", () => {
        element.hide();
      });
    })();
  }

  return setupPromise;
}

async function open() {
  await setupEditor();
  editorElement.value?.show();
}
&#x3C;/script>

&#x3C;template>
  &#x3C;button type="button" @click="open">Import employees&#x3C;/button>
  &#x3C;updog-editor v-if="ready" ref="editor" variant="uploader" />
&#x3C;/template></code></pre>
<p>Both <code>nextTick</code> and <code>whenDefined</code> matter here. The reference does not exist until Vue has rendered the element, and <code>configure()</code> has to run after the browser upgrades it. The total download grows by about a kilobyte this way. The bytes move off the first load.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Azure SQL Database</title><link>https://updog.tech/blog/import-csv-into-azure-sql/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-azure-sql/</guid><pubDate>Mon, 27 Jul 2026 00:00:00 GMT</pubDate><description>Match two fuel card statements in the browser, then merge the clean rows into Azure SQL through one table-valued parameter from your own route.</description><content:encoded><![CDATA[<p>Azure SQL Database documents several ways to move a CSV into a table. The <code>bcp</code> utility loads a file from a command line. <code>BULK INSERT</code> reads one out of Azure Storage. The Import Flat File Wizard in SQL Server Management Studio copies a file "to a <strong>new table</strong> in your database". Azure Data Factory schedules the whole thing. Every one of those starts from a seat that already holds the database. Your customer sits outside that seat, holding the fuel card statement their card platform emailed this morning.</p>
<h2 id="the-ceiling-a-request-hits">The ceiling a request hits</h2>
<p>The obvious design writes one parameter per cell. Microsoft closes that road in a single sentence. "You're limited to a total of 2,100 query parameters, so this limits the total number of rows that can be processed in this manner." A ten-column row therefore fits 210 times into one statement, and the 211th raises error 8003, "The incoming request has too many parameters. The server supports a maximum of %d parameters."</p>
<p>Microsoft names its own way past that. A table-valued parameter is one parameter carrying many rows, "declared by using user-defined table types", and it sends them "without creating a temporary table or many parameters". Inside the database "Transact-SQL passes table-valued parameters to routines by reference to avoid making a copy of the input data". The rows are "strongly typed", and they "do not acquire locks for the initial population of data from a client". The recommendation is stated plainly. "If you choose a single batching technique, table-valued parameters offer the best performance and flexibility."</p>
<p>One more sentence decides the rest of this article. "Other techniques, such as SQL bulk copy, only permit the insertion of new rows. But with table-valued parameters, you can use logic in the stored procedure to determine which rows are updates and which are inserts."</p>
<h2 id="the-files-that-arrive">The files that arrive</h2>
<p>Two card issuers send September in the same week. Each one exports from a different card platform.</p>
<p><code>allstar-september.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Card No</td><td class="sheet__cell">VRM</td><td class="sheet__cell">Driver</td><td class="sheet__cell">Txn Date</td><td class="sheet__cell">Site</td><td class="sheet__cell">Product</td><td class="sheet__cell">Litres</td><td class="sheet__cell">Net</td><td class="sheet__cell">Odo</td><td class="sheet__cell">Ref</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">7083440012345678</td><td class="sheet__cell">AK21 XVR</td><td class="sheet__cell">J. Okonkwo</td><td class="sheet__cell">03/09/2026</td><td class="sheet__cell">BP Keele M6</td><td class="sheet__cell">DSL</td><td class="sheet__cell">412.550</td><td class="sheet__cell">566.21</td><td class="sheet__cell">184220</td><td class="sheet__cell">ALS-99120</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">7083440012345678</td><td class="sheet__cell">AK21 XVR</td><td class="sheet__cell">J. Okonkwo</td><td class="sheet__cell">03/09/2026</td><td class="sheet__cell">BP Keele M6</td><td class="sheet__cell">DSL</td><td class="sheet__cell">412.550</td><td class="sheet__cell">566.21</td><td class="sheet__cell">184220</td><td class="sheet__cell">ALS-99120</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">7083440012345678</td><td class="sheet__cell">AK21 XVR</td><td class="sheet__cell">J. Okonkwo</td><td class="sheet__cell">17/09/2026</td><td class="sheet__cell">Moto Donington</td><td class="sheet__cell">SHOP</td><td class="sheet__cell">0.000</td><td class="sheet__cell">9.40</td><td class="sheet__cell"></td><td class="sheet__cell">ALS-99188</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">7083440012399001</td><td class="sheet__cell">LT70 HGB</td><td class="sheet__cell">A. Whitfield</td><td class="sheet__cell">21/09/2026</td><td class="sheet__cell">Shell Lymm</td><td class="sheet__cell">ADB</td><td class="sheet__cell">18.000</td><td class="sheet__cell">31.05</td><td class="sheet__cell">197004</td><td class="sheet__cell">ALS-99241</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">297 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">303</th><td class="sheet__cell">7083440012399001</td><td class="sheet__cell">LT70 HGB</td><td class="sheet__cell">A. Whitfield</td><td class="sheet__cell">30/09/2026</td><td class="sheet__cell">BP Keele M6</td><td class="sheet__cell">DSL</td><td class="sheet__cell">395.220</td><td class="sheet__cell">542.85</td><td class="sheet__cell">201338</td><td class="sheet__cell">ALS-99904</td></tr></tbody></table>
<p><code>ukfuels-september.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Card Number</td><td class="sheet__cell">VRN</td><td class="sheet__cell">Cardholder</td><td class="sheet__cell">Transaction Date</td><td class="sheet__cell">Location</td><td class="sheet__cell">Fuel Grade</td><td class="sheet__cell">Litres Dispensed</td><td class="sheet__cell">Value Net</td><td class="sheet__cell">Mileage</td><td class="sheet__cell">Transaction Reference</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">6503440077881234</td><td class="sheet__cell">DV19 KLM</td><td class="sheet__cell">R. Petrescu</td><td class="sheet__cell">2026-09-04</td><td class="sheet__cell">Esso Rugby</td><td class="sheet__cell">ULSD</td><td class="sheet__cell">388.140</td><td class="sheet__cell">531.75</td><td class="sheet__cell">301880</td><td class="sheet__cell">UKF-4471</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">6503440077881234</td><td class="sheet__cell">DV19 KLM</td><td class="sheet__cell">R. Petrescu</td><td class="sheet__cell">2026-09-18</td><td class="sheet__cell">Applegreen Corley</td><td class="sheet__cell">Unleaded</td><td class="sheet__cell">52.900</td><td class="sheet__cell">74.06</td><td class="sheet__cell">304115</td><td class="sheet__cell">UKF-4530</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">211 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">215</th><td class="sheet__cell">6503440077885000</td><td class="sheet__cell"></td><td class="sheet__cell">R. Petrescu</td><td class="sheet__cell">2026-09-22</td><td class="sheet__cell">Esso Rugby</td><td class="sheet__cell">Truck Wash</td><td class="sheet__cell"></td><td class="sheet__cell">26.00</td><td class="sheet__cell"></td><td class="sheet__cell">UKF-4972</td></tr></tbody></table>
<p>The first issuer calls the registration <code>VRM</code> and the second calls it <code>VRN</code>. One writes dates day first and the other writes them ISO. <code>DSL</code>, <code>ULSD</code> and <code>ADB</code> are the trade's shorthand for two fuel grades. The first file repeats <code>ALS-99120</code> on two lines, because the platform re-sent it. Row 4 of that file is a shop purchase carrying <code>0.000</code> litres. The last row of the second file has no registration at all.</p>
<p>The person drags both files into the importer inside your app. Updog Importer reads them in the browser, matches each file's headers to your schema, holds the products to your list, and puts every row in front of them. Your <code>onComplete</code> handler receives the rows grouped by file. The handler posts them to a route you own, and that route hands each chunk to a stored procedure.</p>
<p>No Updog server stands between the browser and Azure SQL.</p>
<h2 id="the-table-and-the-type-in-front-of-it">The table and the type in front of it</h2>
<p>One table holds the transactions, keyed by the issuer and the issuer's own reference.</p>
<pre><code class="language-sql">CREATE TABLE dbo.card_transaction
(
    issuer           NVARCHAR(20)  NOT NULL,
    transaction_ref  NVARCHAR(30)  NOT NULL,
    card_number      NVARCHAR(19)  NOT NULL,
    vehicle_reg      NVARCHAR(12)  NOT NULL,
    driver_name      NVARCHAR(80)  NOT NULL,
    transaction_date DATE          NOT NULL,
    site_name        NVARCHAR(60)  NOT NULL,
    product_type     NVARCHAR(20)  NOT NULL,
    litres           DECIMAL(9, 3) NULL,
    net_amount       DECIMAL(11,2) NOT NULL,
    odometer         INT           NULL,
    updated_at       DATETIME2(0)  NOT NULL,
    CONSTRAINT pk_card_transaction
        PRIMARY KEY (issuer, transaction_ref),
    CONSTRAINT ck_card_transaction_litres CHECK
    (
        (product_type IN ('Diesel', 'Petrol', 'AdBlue') AND litres > 0)
        OR
        (product_type NOT IN ('Diesel', 'Petrol', 'AdBlue') AND litres IS NULL)
    )
);</code></pre>
<p>The <code>CHECK</code> constraint reads two columns at once. A diesel, petrol or AdBlue line carries litres above zero, and a shop, wash or toll line carries none. That is the rule the third line of the first file breaks, and a row breaking it raises error 547, "The %ls statement conflicted with the %ls constraint".</p>
<p><code>nvarchar(20)</code> counts byte-pairs, since "<em>n</em> never defines numbers of characters that can be stored", and a character above the basic plane can take two of them. A driver name in Latin script never reaches that boundary.</p>
<p>The type in front of the table declares the shape of one chunk.</p>
<pre><code class="language-sql">CREATE TYPE dbo.card_transaction_batch AS TABLE
(
    op               NVARCHAR(6)   NOT NULL,
    issuer           NVARCHAR(20)  NOT NULL,
    transaction_ref  NVARCHAR(30)  NOT NULL,
    card_number      NVARCHAR(19)  NULL,
    vehicle_reg      NVARCHAR(12)  NULL,
    driver_name      NVARCHAR(80)  NULL,
    transaction_date DATE          NULL,
    site_name        NVARCHAR(60)  NULL,
    product_type     NVARCHAR(20)  NULL,
    litres           DECIMAL(9, 3) NULL,
    net_amount       DECIMAL(11,2) NULL,
    odometer         INT           NULL
);</code></pre>
<p>The <code>op</code> column is Microsoft's own suggestion. "The table type can also be modified to contain an "Operation" column that indicates whether the specified row should be inserted, updated, or deleted." Every column past the key is nullable here, so a delete row travels carrying its key alone.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array describes the table as the person sees it.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const PRODUCTS = ["Diesel", "Petrol", "AdBlue", "Shop", "Wash", "Toll"];
const FUELS = ["Diesel", "Petrol", "AdBlue"];

export const columns: DataEditorColumn[] = [
  {
    id: "transactionRef",
    title: "Transaction ref",
    size: 160,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "cardNumber",
    title: "Card number",
    size: 190,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^[0-9]{16,19}$" },
    ],
  },
  {
    id: "vehicleReg",
    title: "Vehicle reg",
    size: 140,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [{ type: "required" }],
  },
  {
    id: "driverName",
    title: "Driver name",
    size: 170,
    validators: [{ type: "required" }],
  },
  {
    id: "transactionDate",
    title: "Transaction date",
    size: 160,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "siteName",
    title: "Site name",
    size: 180,
    validators: [{ type: "required" }],
  },
  {
    id: "productType",
    title: "Product type",
    size: 150,
    editor: { type: "select", options: PRODUCTS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: PRODUCTS }],
    dependentFields: ["litres"],
  },
  {
    id: "litres",
    title: "Litres",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "function", fn: litresAgainstProduct },
      { type: "number", min: 0, max: 5_000, decimalPlaces: 3 },
    ],
  },
  {
    id: "netAmount",
    title: "Net amount",
    size: 140,
    editor: { type: "number" },
    validators: [{ type: "required" }, { type: "number", decimalPlaces: 2 }],
  },
  {
    id: "odometer",
    title: "Odometer",
    size: 130,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 2_000_000, decimalPlaces: 0 }],
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>date</code> editor turns <code>17/09/2026</code> into <code>2026-09-17</code>, and since 17 is above 12 the first file settles day first, so <code>03/09/2026</code> lands as <code>2026-09-03</code>. That verdict matters on the way out, because SQL Server reads a date string by the session's language setting, and <code>yyyy-MM-dd</code> is "the only format defined as an international standard". The <code>select</code> editor holds the product to six values, and a value nobody maps is dropped from the row. <code>{ type: "required" }</code> on the registration catches the blank cell while somebody can still type into it.</p>
<h2 id="the-rule-that-reads-two-columns">The rule that reads two columns</h2>
<p>No single-column validator can see the table's <code>CHECK</code>, since the answer for litres depends on the product type sitting beside it.</p>
<pre><code class="language-ts">function litresAgainstProduct(value, row) {
  const isFuel = FUELS.includes(String(row.productType));
  const litres = Number(value);
  const filled = value !== null &#x26;&#x26; value !== "" &#x26;&#x26; litres > 0;

  if (isFuel &#x26;&#x26; !filled) {
    return { level: "error", message: "A fuel line needs litres above zero" };
  }
  if (!isFuel &#x26;&#x26; value !== null &#x26;&#x26; value !== "") {
    return { level: "error", message: "Only a fuel line carries litres" };
  }
  return null;
}</code></pre>
<p><code>{ type: "function" }</code> receives the cell value and the whole row, so the rule reads <code>row.productType</code> and decides. Every cell is validated as the rows land, so the <code>0.000</code> on the shop line is flagged the moment the grid appears. <code>dependentFields</code> points forward, from the column being edited to the columns that need rechecking, so the entry sits on <code>productType</code> and names <code>litres</code>. Change a line from <code>Shop</code> to <code>Diesel</code> and the litres cell is judged again against its new neighbour.</p>
<p>Two rules cover the same ground twice on purpose. The browser refuses the row a person can still fix, and the constraint refuses anything that reaches the table another way.</p>
<h2 id="the-headers-each-issuer-sends">The headers each issuer sends</h2>
<p>Column matching repeats per file. Each file gets its own screen and its own mapping, so the same schema column is fed by a different header in each one.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>File</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Card No</code></td>
<td>Allstar</td>
<td><code>cardNumber</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Card Number</code></td>
<td>UK Fuels</td>
<td><code>cardNumber</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>VRM</code></td>
<td>Allstar</td>
<td><code>vehicleReg</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>VRN</code></td>
<td>UK Fuels</td>
<td><code>vehicleReg</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Driver</code></td>
<td>Allstar</td>
<td><code>driverName</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Cardholder</code></td>
<td>UK Fuels</td>
<td><code>driverName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Txn Date</code></td>
<td>Allstar</td>
<td><code>transactionDate</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Site</code></td>
<td>Allstar</td>
<td><code>siteName</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Location</code></td>
<td>UK Fuels</td>
<td><code>siteName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Product</code></td>
<td>Allstar</td>
<td><code>productType</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Fuel Grade</code></td>
<td>UK Fuels</td>
<td><code>productType</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Litres Dispensed</code></td>
<td>UK Fuels</td>
<td><code>litres</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Net</code></td>
<td>Allstar</td>
<td><code>netAmount</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Odo</code></td>
<td>Allstar</td>
<td><code>odometer</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Mileage</code></td>
<td>UK Fuels</td>
<td><code>odometer</code></td>
<td>synonym, 90</td>
</tr>
</tbody>
</table></div>
<p><code>Site</code> is four characters, exactly at the contains floor, which fires once the shorter string runs to four. <code>Net</code> is three and reaches nothing that way, though it is one of the two words in <code>netAmount</code>, so word overlap carries it. <code>Location</code> needs no configuration, since the built-in synonym table already groups it with <code>sitename</code>. <code>VRM</code>, <code>VRN</code>, <code>Odo</code> and <code>Mileage</code> are all too short or too far for any tier, so four <code>synonyms</code> entries cover six headers across the two files.</p>
<p>Value matching runs once for the whole import and collects values per schema column across both files. <code>SHOP</code> equals its option and <code>Truck Wash</code> contains <code>Wash</code>, which lands at eighty. <code>DSL</code>, <code>ULSD</code>, <code>ADB</code> and <code>Unleaded</code> reach nothing, so three more <code>synonyms</code> entries carry the trade's shorthand.</p>
<p>Each file also settles its own dates. The verdict comes from a sample of that file alone, so the day-first export and the ISO export never borrow each other's reading.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the two files, the schema and the table together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;CardTransaction>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="transactionRef"
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: {
      vehicleReg: ["vrm", "vrn"],
      driverName: ["cardholder"],
      productType: ["fuel grade"],
      odometer: ["odo", "mileage"],
    },
    values: {
      Diesel: ["dsl", "ulsd"],
      AdBlue: ["adb"],
      Petrol: ["unleaded"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> names the reference column. Every column it names has to be a column the schema declares, and the issuer is not one of them, since it comes from the file the rows arrived in rather than from any cell. The table keeps its two-column key for the day two issuers hand out the same reference, and the browser holds every reference in the session apart from every other. Values are compared after trimming, and a row with no reference matches nothing and arrives as new.</p>
<p><code>{ type: "unique" }</code> on that same column flags the repeated <code>ALS-99120</code> line as both copies land, and <code>enableDeleteRow="all"</code> lets the person drop one by hand. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, the duplicate reference, the blank registration and the shop line's litres included. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back through <code>synonyms</code> next month.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source. Each file lands as its own entry, carrying the file name, so the row that came from UK Fuels still says so on the way out.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 1_000;

const toRow = (entry: ResultRow&#x3C;CardTransaction>, issuer: string) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  return [{
    op: entry.isDeleted ? "delete" : "upsert",
    issuer,
    transaction_ref: entry.row.transactionRef,
    card_number: entry.row.cardNumber,
    vehicle_reg: entry.row.vehicleReg,
    driver_name: entry.row.driverName,
    transaction_date: entry.row.transactionDate,
    site_name: entry.row.siteName,
    product_type: entry.row.productType,
    litres: entry.row.litres === "" ? null : Number(entry.row.litres),
    net_amount: Number(entry.row.netAmount),
    odometer: entry.row.odometer === "" ? null : Number(entry.row.odometer),
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;CardTransaction>) => {
  for (const source of result.sources) {
    const issuer = issuerFor(source.sourceName);
    const rows = source.rows.flatMap((entry) => toRow(entry, issuer));

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const written = await fetch("/api/fuel-cards/write", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
      });
      if (!written.ok) throw new Error((await written.json()).message);
    }
  }
}, []);</code></pre>
<p>Three flags become one field. A new transaction and a changed one are the same payload, since the <code>MERGE</code> decides which by looking at the table. A row the person added and then deleted goes nowhere. Nothing here loads from your backend, so every row arrives new and <code>op</code> reads <code>upsert</code> on all of them. The <code>delete</code> branch waits on the month you feed the stored transactions in through <code>loadData</code>.</p>
<p>The chunk size sits inside Microsoft's own ladder. It publishes three rungs, a single parameterized <code>INSERT</code> under 100 rows, table-valued parameters under 1,000, and <code>SqlBulkCopy</code> at 1,000 and above. Bulk copy is refused here because it inserts only, so 1,000 is the top of the rung this design lives on. Microsoft's batch-size test points the same way, since 1,000 rows in one batch beat ten batches of 100 and twenty of 50, and it notes "there was typically no advantage to breaking large batches into smaller chunks".</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and both statements clear the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-writes">The route that writes</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import sql from "mssql";

const pool = new sql.ConnectionPool({
  server: process.env.SQL_SERVER,
  database: process.env.SQL_DATABASE,
  authentication: { type: "azure-active-directory-msi-app-service" },
  options: { encrypt: true },
});

const COLUMNS = [
  ["op", sql.NVarChar(6), false],
  ["issuer", sql.NVarChar(20), false],
  ["transaction_ref", sql.NVarChar(30), false],
  ["card_number", sql.NVarChar(19), true],
  ["vehicle_reg", sql.NVarChar(12), true],
  ["driver_name", sql.NVarChar(80), true],
  ["transaction_date", sql.Date, true],
  ["site_name", sql.NVarChar(60), true],
  ["product_type", sql.NVarChar(20), true],
  ["litres", sql.Decimal(9, 3), true],
  ["net_amount", sql.Decimal(11, 2), true],
  ["odometer", sql.Int, true],
];

const dedupe = (rows) => {
  const latest = new Map();
  for (const row of rows) latest.set(row.issuer + "|" + row.transaction_ref, row);
  return [...latest.values()];
};

const toTable = (rows) => {
  const table = new sql.Table("dbo.card_transaction_batch");
  for (const [name, type, nullable] of COLUMNS) {
    table.columns.add(name, type, { nullable });
  }
  for (const row of rows) {
    table.rows.add(...COLUMNS.map(([name]) => row[name] ?? null));
  }
  return table;
};</code></pre>
<p><code>azure-active-directory-msi-app-service</code> means the route holds no password at all. The host hands it a token for its managed identity, and the database grants that identity the rights it needs.</p>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. The issuer arrives in the body, so the route checks it against the issuers that session is allowed to load. A guessed name reaches no other fleet's transactions.</p>
<p><code>dedupe</code> is there because the <code>MERGE</code> refuses a source that matches one target row twice. Microsoft says so directly. "The <code>MERGE</code> statement can't update the same row more than once, or update and delete the same row." The browser already flagged the repeated <code>ALS-99120</code> line and the person deleted one, and the route runs the map anyway, because a route your app can call is a route anyone with a session can call. The map keeps the last of any pair that reaches it.</p>
<p><code>sql.Table</code> builds the parameter with the same column names and types the database type declares, in the same order, because the driver matches them by position.</p>
<h2 id="the-procedure-that-merges">The procedure that merges</h2>
<p>One call, one statement, one transaction.</p>
<pre><code class="language-sql">CREATE PROCEDURE dbo.merge_card_transactions
    @batch dbo.card_transaction_batch READONLY
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRANSACTION;

    MERGE dbo.card_transaction WITH (HOLDLOCK) AS target
    USING @batch AS source
        ON  target.issuer = source.issuer
        AND target.transaction_ref = source.transaction_ref

    WHEN MATCHED AND source.op = 'delete' THEN
        DELETE

    WHEN MATCHED THEN UPDATE SET
        card_number      = source.card_number,
        vehicle_reg      = source.vehicle_reg,
        driver_name      = source.driver_name,
        transaction_date = source.transaction_date,
        site_name        = source.site_name,
        product_type     = source.product_type,
        litres           = source.litres,
        net_amount       = source.net_amount,
        odometer         = source.odometer,
        updated_at       = SYSUTCDATETIME()

    WHEN NOT MATCHED BY TARGET AND source.op &#x3C;> 'delete' THEN
        INSERT (issuer, transaction_ref, card_number, vehicle_reg, driver_name,
                transaction_date, site_name, product_type, litres, net_amount,
                odometer, updated_at)
        VALUES (source.issuer, source.transaction_ref, source.card_number,
                source.vehicle_reg, source.driver_name, source.transaction_date,
                source.site_name, source.product_type, source.litres,
                source.net_amount, source.odometer, SYSUTCDATETIME());

    COMMIT TRANSACTION;
END;</code></pre>
<p><code>READONLY</code> is required on every table parameter, since you "cannot perform DML operations such as UPDATE, DELETE, or INSERT on a table-valued parameter in the body of a routine". So the parameter is the source and never the target.</p>
<p>Three branches read the <code>op</code> column. A matched row marked <code>delete</code> is deleted, any other matched row is updated, and an unmatched row that is not a delete is inserted. <code>HOLDLOCK</code> is on the target because Microsoft recommends it here, since "in some scenarios where unique keys are expected to be both inserted and updated by the <code>MERGE</code>, specifying the <code>HOLDLOCK</code> will prevent against unique key violations".</p>
<p>Nothing is staged. The parameter is the source table, so there is no temporary table to create, fill and drop, and the whole chunk commits or rolls back together.</p>
<h2 id="the-errors-that-come-back-by-number">The errors that come back by number</h2>
<p><code>mssql</code> raises a <code>RequestError</code> whose <code>err.number</code> is the database's own error number, so the route can turn each one into a sentence.</p>
<pre><code class="language-ts">const MESSAGES = {
  2627: "One reference is already stored under this issuer",
  2601: "One reference is already stored under this issuer",
  2628: "A value is longer than its column allows",
  547:  "A row breaks a rule on the table, most likely litres against product",
  8672: "The same reference arrived twice in one batch",
  8003: "The batch carried too many parameters",
};

const explain = (error) => MESSAGES[error.number] ?? "The write did not finish";</code></pre>
<p>Each number carries a published message. 2628 reads "String or binary data would be truncated in table '%.*ls', column '%.*ls'. Truncated value: '%.*ls'", so a row that overflows a width names the column and the value on its way back. 8672 is the <code>MERGE</code> matching one target row twice. <a href="https://updog.tech/blog/import-csv-into-postgresql/">Importing a CSV into PostgreSQL</a> shows the other relational destination in this cluster answering a failed write with its own five-character codes.</p>
<p>A second group is worth sending again. Azure SQL publishes a list of transient fault codes, among them 40501, "The service is currently busy", and 40613, "Database '%.*ls' on server '%.*ls' is not currently available". The resource errors 10928 and 10929 sit under resource governance instead, and both appear on the six-number transient list <code>tedious</code> carries from Microsoft's own SqlClient. A number that lands while the request is in flight arrives as a <code>RequestError</code> and the loop below catches it. The same number during login arrives as a <code>ConnectionError</code> with the code <code>ELOGIN</code> and no number on it, and <code>tedious</code> retries that itself, three times by default. Microsoft asks for a specific cadence. "We recommend that you delay for 5 seconds before your first retry… For each subsequent retry, the delay should grow exponentially, up to a maximum of 60 seconds."</p>
<p>That cadence sizes the retry loop, because all of it happens with the confirm dialog open and a spinner on the button. Five, ten and twenty seconds is thirty-five seconds on top of the write, which is about as long as a person will sit before the thrown error puts them back on their own rows. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Azure SQL connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route and the stored procedure in the middle are work you do. Our uniqueness rule reads one column, so a key spanning two is checked by your own code.</p>
<p>Azure SQL already ships its own ways in for the other case. <code>bcp</code> reads a UTF-8 file once you name the code page, <code>-C 65001</code>, and that switch is Windows only, "not supported on Linux and macOS". <code>BULK INSERT</code> reads from Azure Storage, needs <code>ADMINISTER DATABASE BULK OPERATIONS</code>, and "doesn't support skipping headers". The Import Flat File Wizard writes to a new table whose name "should be unique", infers types "based on the first 200 rows", and uses "encoding based on the system's active code page. On most machines this defaults to ANSI." For a one-off load your own team assembled, those are the shorter ways in. Everything above exists for the statements your fleet's card issuers send, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-next-month">The pieces you wrote and next month</h2>
<p>You wrote one table with a two-column key and a two-column <code>CHECK</code>, a table type carrying an operation column, a schema with ten columns, one validator that reads two of them, four <code>synonyms</code> entries for the headers and three for the values, a dedupe map, one route that sends 1,000 rows as a single parameter, and one procedure that merges them inside a transaction. The files stay on the machine that opened them. The rows travel from your own front end to your own route and into Azure SQL, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>Next month brings the same two issuers and a third one with a third spelling of <code>Fuel grade</code>. The mappings from September are already stored, the table type is unchanged, and the new issuer costs one more line in <code>synonyms</code>.</p>]]></content:encoded></item>
<item><title>CSV Import for Healthcare and Patient Data SaaS</title><link>https://updog.tech/blog/csv-import-for-healthcare-saas/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-healthcare-saas/</guid><pubDate>Sun, 26 Jul 2026 00:00:00 GMT</pubDate><description>A clinic sends the roster it keeps in a spreadsheet. How to take those files into your patient schema, allergy lists and all.</description><content:encoded><![CDATA[<p>A clinic keeps its patient list in two places. One is the EHR the practice
bought, and the other is the spreadsheet the front desk keeps beside it for
everything the EHR makes hard. When the practice goes live on a new platform,
both of them come along.</p>
<p>Nothing in those files is written for a machine. Sex is recorded as F in one
export and Female in the next, a date of birth arrives in the American order
in one file and the international order in another, and an allergy column
holds three allergens in one cell.</p>
<p>A clinic's patient roster arrives with thirteen columns. Your schema has a field
for eleven of them. The other two carry a social security number and a list of
diagnosis codes, and your product stores neither.</p>
<p>A patient platform stores one record per person. Its customers export that
population out of an EHR, or out of the spreadsheet the front desk keeps beside
it. Taking those files into a schema of your own is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The practice manager at the clinic is the one who uploads the roster, in the
week that clinic goes live on your product. The schema it lands in is yours.</p>
<p>The roster below holds 3,200 patients over thirteen columns, 378 KB of <code>.csv</code>.
Every count below was measured by running that file through the importer once.</p>
<h2 id="what-a-clinic-hands-over">What a clinic hands over</h2>
<p>Four kinds of file reach a health platform.</p>
<p>A patient roster is the whole panel, one row per person, sent when a customer
moves onto your product. A member eligibility list is a payer's version of that
same population, keyed on the member number the payer issued. An employer census
carries the people a benefits plan covers, one row per employee and one more per
dependent. A provider directory carries the clinicians, with a specialty and an
NPI against each name.</p>
<p>Everything below follows one roster.</p>
<h2 id="the-row-the-front-desk-typed">The row the front desk typed</h2>
<p>Six rows out of it, in the spelling the spreadsheet holds.</p>
<p><code>patient-roster.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">MRN</td><td class="sheet__cell">Last Name</td><td class="sheet__cell">First Name</td><td class="sheet__cell">DOB</td><td class="sheet__cell">Sex</td><td class="sheet__cell">Email</td><td class="sheet__cell">Insurance</td><td class="sheet__cell">Member #</td><td class="sheet__cell">Coverage Start</td><td class="sheet__cell">Coverage End</td><td class="sheet__cell">Allergies</td><td class="sheet__cell">SSN</td><td class="sheet__cell">Problem List</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">204010</td><td class="sheet__cell">Ionescu</td><td class="sheet__cell">Adriana</td><td class="sheet__cell">2011-11-18</td><td class="sheet__cell">F</td><td class="sheet__cell"></td><td class="sheet__cell">United Healthcare</td><td class="sheet__cell">97955138</td><td class="sheet__cell">2025-06-27</td><td class="sheet__cell">2026-09-29</td><td class="sheet__cell">Latex, Penicillin</td><td class="sheet__cell">900-18-6880</td><td class="sheet__cell">I10</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">204013</td><td class="sheet__cell">Halvorsen</td><td class="sheet__cell">Julien</td><td class="sheet__cell">1931-01-31</td><td class="sheet__cell">M</td><td class="sheet__cell">julien.halvorsen@example.com</td><td class="sheet__cell">BCBS TX</td><td class="sheet__cell">ZGP4648350</td><td class="sheet__cell">2026-03-06</td><td class="sheet__cell"></td><td class="sheet__cell">NKDA</td><td class="sheet__cell">900-54-1298</td><td class="sheet__cell">E11.9; I10; J45.909</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">204021</td><td class="sheet__cell">Novotny</td><td class="sheet__cell">Kwame</td><td class="sheet__cell">1944-08-17</td><td class="sheet__cell">M</td><td class="sheet__cell">kwame.novotny@mail.example.net</td><td class="sheet__cell">Self Pay</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">NKDA</td><td class="sheet__cell">900-82-8964</td><td class="sheet__cell">I10; J45.909</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">204045</td><td class="sheet__cell">Vasquez</td><td class="sheet__cell">Luz</td><td class="sheet__cell">6/16/86</td><td class="sheet__cell">Female</td><td class="sheet__cell"></td><td class="sheet__cell">Medicare</td><td class="sheet__cell">1EG45433874</td><td class="sheet__cell">2023-08-13</td><td class="sheet__cell"></td><td class="sheet__cell">Shellfish</td><td class="sheet__cell">900-40-5476</td><td class="sheet__cell">I10</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">55 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">61</th><td class="sheet__cell">204068</td><td class="sheet__cell">Adeyemi</td><td class="sheet__cell">Folasade</td><td class="sheet__cell">1978-04-02</td><td class="sheet__cell">F</td><td class="sheet__cell">f.adeyemi@example.org</td><td class="sheet__cell">Aetna</td><td class="sheet__cell">W273441905</td><td class="sheet__cell">2024-11-01</td><td class="sheet__cell"></td><td class="sheet__cell">NSAIDs; Shellfish</td><td class="sheet__cell">900-27-3319</td><td class="sheet__cell">E11.9</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="13"><span class="sheet__break-text">3139 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3201</th><td class="sheet__cell">209884</td><td class="sheet__cell">Whitlock</td><td class="sheet__cell">Marguerite</td><td class="sheet__cell">1957-09-12</td><td class="sheet__cell">F</td><td class="sheet__cell">m.whitlock@example.com</td><td class="sheet__cell">Cigna</td><td class="sheet__cell">U884120773</td><td class="sheet__cell">2025-01-01</td><td class="sheet__cell"></td><td class="sheet__cell">NKDA</td><td class="sheet__cell">900-61-4470</td><td class="sheet__cell">I10</td></tr></tbody></table>
<p>The allergy cell on row 2 separates two allergens with a comma, and row 3
writes <code>NKDA</code>, the clinic's shorthand for no known drug allergies. Row 61 puts a
semicolon between its two allergens, which is how most of the file writes them.
<code>6/16/86</code> is a birth date whose century nobody wrote down. The self-pay row
carries no member number and no coverage dates, because there is no payer behind
it.</p>
<h2 id="the-eleven-fields-the-platform-keeps">The eleven fields the platform keeps</h2>
<p>One of the three option lists is published and two are yours. HL7 defines
administrative gender as <code>male</code>, <code>female</code>, <code>other</code> and <code>unknown</code>, and those four
codes are what the sex column stores. The payer list is the set your platform
holds contracts with. The allergen list is the vocabulary your clinical team
maintains.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const SEX = ["male", "female", "other", "unknown"];

const PAYERS = [
  "Aetna",
  "Blue Cross Blue Shield of Texas",
  "Cigna",
  "Humana",
  "Medicare",
  "United Healthcare",
  "Self pay",
];

const ALLERGENS = [
  "Penicillins",
  "Sulfonamides",
  "NSAIDs",
  "Latex",
  "Peanut",
  "Shellfish",
  "Iodinated contrast",
];

export const columns: DataEditorColumn[] = [
  { id: "mrn", title: "MRN", validators: [{ type: "required" }] },
  { id: "lastName", title: "Last name", validators: [{ type: "required" }] },
  { id: "firstName", title: "First name", validators: [{ type: "required" }] },
  {
    id: "dateOfBirth",
    title: "Date of birth",
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date", max: "2026-07-26" }],
  },
  {
    id: "sex",
    title: "Sex",
    editor: { type: "select", options: SEX, enableCustomValue: false },
  },
  { id: "email", title: "Email", validators: [{ type: "email" }] },
  {
    id: "payer",
    title: "Payer",
    editor: { type: "select", options: PAYERS, enableCustomValue: false },
  },
  { id: "memberId", title: "Member ID" },
  { id: "coverageStart", title: "Coverage start", editor: { type: "date" } },
  { id: "coverageEnd", title: "Coverage end", editor: { type: "date" } },
  {
    id: "allergies",
    title: "Allergies",
    editor: { type: "multiselect", options: ALLERGENS },
  },
];</code></pre>
<p>Eleven of the thirteen incoming headers reach one of those fields. Eight of them
land on the column name exactly, <code>DOB</code> reaches <code>dateOfBirth</code> on a built-in
synonym, and <code>Member #</code> reaches <code>memberId</code> on the one word the two strings
share. <code>Insurance</code> reaches nothing on its own and takes an alias.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    payer: ["insurance", "carrier"],
  },
  values: {
    "Blue Cross Blue Shield of Texas": ["bcbs tx", "bcbstx"],
    "United Healthcare": ["uhc"],
    Penicillins: ["pcn"],
    Sulfonamides: ["sulfa drugs", "sulfa"],
  },
};</code></pre>
<p>The value half of the same table carries <code>BCBS TX</code>, <code>UHC</code>, <code>PCN</code> and
<code>Sulfa drugs</code> to the options your schema spells out in full. <code>U</code> and <code>X</code> in the
sex column reach no code. Those 77 rows arrive with an empty sex until the
person maps the two spellings, alongside 48 cells the file left blank.</p>
<h2 id="the-two-columns-you-do-not-map">The two columns you do not map</h2>
<p><code>SSN</code> and <code>Problem List</code> reach nothing, because the schema declares no field for
either. HL7's US Core profile says a patient's social security number should not
be used as the patient identifier. It points at the medical record number, which
is the column your key already reads.</p>
<p><strong>An unmapped header contributes no field to the row.</strong> The import plan is built
from the headers that carry a column id, so the values under <code>SSN</code> never enter
the store, never reach the grid, and never appear in <code>onComplete</code>. The row your
API receives holds the eleven fields above and nothing else.</p>
<p><code>enableCreateColumn={false}</code> is what keeps it that way. Left at its default, the
matching step offers the person a way to keep an unmatched header by creating a
column for it. A practice manager tidying up a roster can take that offer, and
the diagnosis codes travel with it.</p>
<p>The file itself stays where it was dropped. Updog parses it, matches it and
validates it inside the tab the person already has open, so a roster full of
names and birth dates reaches your endpoint and no other server. The two
execution models are compared in
<a href="https://updog.tech/blog/client-side-vs-server-side-importer/">client-side versus server-side import</a>.</p>
<h2 id="where-a-clinic-roster-and-a-patient-record-disagree">Where a clinic roster and a patient record disagree</h2>
<div class="blog-table blog-table--fixed blog-table--health-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>MRN</code></td>
<td><code>204010</code>, and three numbers that appear on a second row</td>
<td><code>required</code>, and a value your database does not hold yet</td>
</tr>
<tr>
<td><code>DOB</code></td>
<td><code>2011-11-18</code> on 2,816 rows, <code>6/16/86</code> on the other 384</td>
<td>ISO, and a century the file never recorded</td>
</tr>
<tr>
<td><code>Sex</code></td>
<td>nine spellings, <code>F</code> through <code>Non-binary</code>, and 48 empty cells</td>
<td>four codes</td>
</tr>
<tr>
<td><code>Email</code></td>
<td>575 empty cells and 60 addresses ending at the <code>@</code></td>
<td>a valid address, or nothing</td>
</tr>
<tr>
<td><code>Insurance</code></td>
<td>ten strings for seven payers</td>
<td>the payer your contracts name</td>
</tr>
<tr>
<td><code>Member #</code></td>
<td>empty on every self-pay row</td>
<td>text, and empty stays empty</td>
</tr>
<tr>
<td><code>Coverage End</code></td>
<td>empty on 2,758 rows, earlier than the start on 25</td>
<td>a date after the coverage start</td>
</tr>
<tr>
<td><code>Allergies</code></td>
<td>several allergens in one cell, under two separators</td>
<td>a list of options your team maintains</td>
</tr>
<tr>
<td><code>SSN</code></td>
<td>a number your product has no use for</td>
<td>no field at all</td>
</tr>
</tbody>
</table></div>
<p>Every failure in that table has a generic twin in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>. Four of them behave
in a way worth watching here, and each one takes a section below.</p>
<h2 id="the-allergy-cell-holding-three-values">The allergy cell holding three values</h2>
<p>A multiselect column stores a list, so every cell in this column is split into
tokens on the way in. The separator is detected per column. Five candidates are
tested against your option list, <code>,</code>, <code>;</code>, <code>|</code>, a newline and a tab, and the one
that splits the most cells into recognised tokens wins. In this roster 928 cells
separate their allergens with a semicolon and 111 use a comma, so <code>;</code> takes the
column. The value-matching step prints it in a field the person can overwrite.</p>
<p>Ten distinct tokens come out of that split, and nine of them find an option.
<code>Latex</code>, <code>NSAIDs</code> and <code>Shellfish</code> are exact. <code>Penicillin</code> and <code>Peanuts</code> differ
from their options by one letter, and one string containing the other is enough.
<code>Contrast dye</code> shares a word with <code>Iodinated contrast</code>. <code>PCN</code> and <code>Sulfa drugs</code>
arrive through the alias table.</p>
<p><code>NKDA</code> reaches nothing, and that is the correct outcome, since no known drug
allergies is the absence of an allergen. A multiselect value is imported only
when it is mapped, so those 441 cells land as an empty list, alongside the 987
cells that were empty in the file.</p>
<p><strong>The comma cells lose an allergen.</strong> <code>Latex, Penicillin</code> is one token once the
column splits on <code>;</code>, and it matches <code>Latex</code> because that option sits inside it.
The row reaches your API with one allergen where the clinic wrote two, and 111
rows in this roster do that.</p>
<p>A token the option list does not recognise is split again on a second separator.
That second split holds only where every piece it produces is an option,
character for character. <code>Latex</code> is one. <code>Penicillin</code> misses, because the schema
spells the option <code>Penicillins</code>. Spell the option the way the file writes it and
the same cell arrives as two values.</p>
<h2 id="the-year-written-with-two-digits">The year written with two digits</h2>
<p>384 birth dates in this roster are written <code>6/16/86</code>. Every numeric date pattern
the importer reads wants a four-digit year, so those cells reach the grid as the
text the file carried, and the <code>date</code> validator flags all 384.</p>
<p>Nothing in the file records the century. A patient born in 1986 and a patient
born in 2086 are one keystroke apart, and the person who sent the roster is the
one who can settle which. The other 2,816 rows carry an ISO date and pass
without a decision.</p>
<h2 id="the-end-date-that-is-empty-on-purpose">The end date that is empty on purpose</h2>
<p>2,758 rows carry no coverage end date. 2,514 of them are patients whose coverage
is current, and 244 are the self-pay rows, which carry no coverage at all. An
empty cell answers to <code>required</code> alone, and this column declares none, so both
kinds of row travel.</p>
<p>The 25 rows that do carry a bad end date carry it in relation to the cell beside
them.</p>
<pre><code class="language-ts">{
  id: "coverageStart",
  title: "Coverage start",
  editor: { type: "date" },
  dependentFields: ["coverageEnd"],
},
{
  id: "coverageEnd",
  title: "Coverage end",
  editor: { type: "date" },
  validators: [
    {
      type: "function",
      fn: (value, row) => {
        const end = String(value ?? "");
        const start = String(row.coverageStart ?? "");
        if (!end || !start) return null;
        return end &#x3C; start
          ? { level: "error", message: "Coverage ends before it starts" }
          : null;
      },
    },
  ],
},</code></pre>
<p><code>dependentFields</code> on the coverage start names the column to check again, so
editing a start date clears the verdict left on the end date. An open enrollment
is the normal case in this schema, and the rule above says so by leaving every
empty cell alone.</p>
<h2 id="an-mrn-your-database-already-holds">An MRN your database already holds</h2>
<p><code>{ type: "unique" }</code> on the MRN column checks every value against every other
row in the file. Six rows in this roster share a chart number with a second row,
and all six carry the flag, the earliest of each pair included.</p>
<p>The duplicate that matters more is the one the file cannot see.</p>
<pre><code class="language-ts">{
  id: "mrn",
  title: "MRN",
  validators: [
    { type: "required" },
    {
      type: "unique",
      fn: async (values) => {
        const res = await fetch("/api/patients/known-mrns", {
          method: "POST",
          body: JSON.stringify(values),
        });
        return res.json();
      },
    },
  ],
}</code></pre>
<p>The optional <code>fn</code> hands your endpoint the distinct MRNs from the column and
takes back the ones you already hold. Seven come back here, and they carry
their own message, <code>Already exists in your database</code>, so the person can tell a
typo inside the file from a patient your system registered last month.</p>
<p><strong>Your endpoint is asked last.</strong> A cell that fails a rule of its own, or repeats
another cell inside the file, is held back and never reaches <code>fn</code>, and neither
does an empty one. A blank chart number reports that it is required, and your
service never sees it.</p>
<p><code>primaryKey="mrn"</code> names the same column as the key a later upload merges on.
That later upload is where the remote check stops being right, since a roster
sent again to update patients carries MRNs your database is supposed to hold.
Take <code>fn</code> off the column for that flow and let the key do the work.</p>
<h2 id="everything-clinical-here-is-yours-to-write">Everything clinical here is yours to write</h2>
<p>Updog ships no healthcare template, no EHR connector and no code lists. The
allergen vocabulary, the payer list, the coverage rule and the MRN endpoint are
code in your repository, and the four FHIR gender codes are one line of your
own. Updog Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A
scanned intake form or a faxed referral reaches
<a href="https://updog.tech/blog/import-pdf-with-updog/">a parser you supply</a>, and whatever rows it
returns enter the same matching step this roster entered.</p>
<h2 id="the-468-rows-that-need-a-person">The 468 rows that need a person</h2>
<p>Out of 3,200 rows, 468 carry something a rule caught, and sixteen of those carry
two. 384 birth dates with no century, 60 addresses that stop at the <code>@</code>, 25
coverage periods that end before they start, 7 chart numbers your database
already holds, 6 that repeat inside the file, and 2 rows missing a name. Each of
those messages is its own line in the rows panel, and checking one leaves the
rows behind it on screen and hides the rest.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey="mrn"
  enableCreateColumn={false}
  onComplete={async (result) => {
    for (const source of result.sources) {
      const ready = source.rows.filter((r) => r.isValid &#x26;&#x26; !r.isDeleted);
      await postPatients(source.sourceName, ready);
    }
  }}
/></code></pre>
<p>Every row reaches <code>onComplete</code>, and each one carries <code>isValid</code>, so the filter
above decides what a row still holding an error becomes. Send those to a review
queue, or keep them out of the write and let the clinic upload again.</p>
<p>The practice manager works down the list of flagged rows against the paperwork
on their own desk, which is the only place the answers live. Then <code>onComplete</code>
hands you 3,200 patient records carrying eleven fields each, and the two columns
you never mapped stayed in the file they arrived in.</p>]]></content:encoded></item>
<item><title>Excel Import for Ecommerce and PIM Software</title><link>https://updog.tech/blog/excel-import-for-ecommerce-pim-software/</link><guid isPermaLink="true">https://updog.tech/blog/excel-import-for-ecommerce-pim-software/</guid><pubDate>Sat, 25 Jul 2026 00:00:00 GMT</pubDate><description>Merchants send the catalog their store exported, one row per size. How to take those files into your product schema with every size under its product.</description><content:encoded><![CDATA[<p>A catalog is never finished. A merchant adds products through the season,
edits prices in bulk in a spreadsheet, and exports the whole thing whenever it
has to move somewhere else. What comes out is the catalog plus every decision
the old platform made about how to write it down.</p>
<p>The largest of those decisions is what counts as a product. One item in seven
sizes is one product to the merchandiser, and the file has to hold it as
several rows that belong together.</p>
<p>Six rows in every seven of a merchant catalog arrive with no title. The vendor
cell beside them is empty, and so is the category. Those rows are variants, and
the file is correct.</p>
<p>A commerce or PIM platform keeps one product record. Its customers export
catalogs out of Shopify, WooCommerce, a PIM or a spreadsheet somebody maintains
by hand. Moving those into your schema is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>You write the schema. The person who uploads the catalog is the merchandiser at
the merchant, and the file came out of whatever they sell on.</p>
<p>The catalog below is an apparel export. 28,000 products in seven sizes each, so
196,000 rows over twelve columns, 8.6 MB of <code>.xlsx</code>. Every number in this post
comes from running that file through the importer once.</p>
<h2 id="six-rows-in-seven-arrive-with-no-title">Six rows in seven arrive with no title</h2>
<p>Shopify tells merchants to write variants that way. Its own CSV documentation
says to fill every field on the first row, then "enter the URL handle" on the
rows below it and "skip the Title, Description, Vendor, and Tags columns".</p>
<p><code>ridgeline-catalog.xlsx</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">URL handle</td><td class="sheet__cell">Title</td><td class="sheet__cell">Vendor</td><td class="sheet__cell">Product category</td><td class="sheet__cell">SKU</td><td class="sheet__cell">Barcode</td><td class="sheet__cell">Option1 name</td><td class="sheet__cell">Option1 value</td><td class="sheet__cell">Price</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell">Cirque Hooded Fleece, Slate</td><td class="sheet__cell">Ridgeline Outfitters</td><td class="sheet__cell">Apparel &#x26; Accessories > Clothing > Outerwear</td><td class="sheet__cell">RO-00001-XS</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell">Size</td><td class="sheet__cell">XS</td><td class="sheet__cell">$18.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-S</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">S</td><td class="sheet__cell">$19.99</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-M</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">M</td><td class="sheet__cell">$20.99</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-L</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">L</td><td class="sheet__cell">$21.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-XL</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">XL</td><td class="sheet__cell">$22.00</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-2XL</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">2XL</td><td class="sheet__cell">$23.99</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">cirque-hooded-fleece-slate-00001</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-00001-3XL</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">3XL</td><td class="sheet__cell">$24.00</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="9"><span class="sheet__break-text">195992 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">196001</th><td class="sheet__cell">linnet-quilted-vest-ember-28000</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell">RO-28000-3XL</td><td class="sheet__cell">5.065E+12</td><td class="sheet__cell"></td><td class="sheet__cell">3XL</td><td class="sheet__cell">$74.00</td></tr></tbody></table>
<p>Nine of the twelve columns, with the barcode as the spreadsheet displays it. One
product, seven sizes, seven rows. The handle repeats down all seven and carries
the grouping. The row at the bottom is where the file ends, 27,999 products
later, and it carries no title either.</p>
<p>WooCommerce writes the same idea with two columns instead. Its <code>Type</code> column
holds <code>variable</code> on the parent and <code>variation</code> on each child, and its <code>Parent</code>
column holds the parent SKU. Akeneo publishes <code>parent</code> on the product and reads
an <code>entity_type</code> of <code>product</code> or <code>product_model</code> per row.</p>
<p><strong>A flat grid holds rows, and a parent is a row like any other.</strong> So the schema
below leaves <code>title</code> without a <code>required</code> rule. Marking it required would flag
168,000 rows in this file and help nobody. The product-level check belongs on
your side, against the handle.</p>
<h2 id="the-barcode-that-reads-5065e12">The barcode that reads 5.065E+12</h2>
<p>Excel's General format switches to scientific notation at twelve digits. Below
that the digits stay on screen.</p>
<div class="blog-table blog-table--fixed blog-table--commerce-digits"><table>
<thead>
<tr>
<th>Digits</th>
<th>The number in the cell</th>
<th>What a General-format cell displays</th>
</tr>
</thead>
<tbody>
<tr>
<td>8, a GTIN-8</td>
<td>96385074</td>
<td><code>96385074</code></td>
</tr>
<tr>
<td>11</td>
<td>12345678901</td>
<td><code>12345678901</code></td>
</tr>
<tr>
<td>12, a GTIN-12</td>
<td>123456789012</td>
<td><code>1.23457E+11</code></td>
</tr>
<tr>
<td>13, a GTIN-13</td>
<td>8901234567890</td>
<td><code>8.90123E+12</code></td>
</tr>
<tr>
<td>14, a GTIN-14</td>
<td>18901234567897</td>
<td><code>1.89012E+13</code></td>
</tr>
</tbody>
</table></div>
<p>A GTIN-8 stays legible. A GTIN-12, a GTIN-13 and a GTIN-14 all land above that
line. The <code>.xlsx</code> file still holds the number underneath, and the scientific
text is only a display format, so Updog reads the stored value instead.
<code>5.065E+12</code> reaches the grid as <code>5065000000011</code>.</p>
<p>In this catalog that recovers 185,671 barcodes. It does not recover 6,631 of
them.</p>
<p><strong>A leading zero is gone before the file is written.</strong> A UPC-12 printed
<code>076543000290</code> is stored as the number 76543000290, eleven digits, under the
scientific-notation line and therefore untouched by the fallback. Nothing in the
file records the zero.</p>
<p>Google's product data specification publishes what a GTIN has to be. Eight,
twelve, thirteen or fourteen digits, with a correct check digit. Both halves
become rules.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const GTIN = /^(\d{8}|\d{12,14})$/;

const gtinCheckDigit = (digits: string): number => {
  const body = digits.slice(0, -1);
  let sum = 0;
  for (let i = body.length - 1, weight = 3; i >= 0; i--, weight = 4 - weight) {
    sum += Number(body[i]) * weight;
  }
  return (10 - (sum % 10)) % 10;
};

export const gtin: DataEditorColumn = {
  id: "gtin",
  title: "GTIN",
  validators: [
    { type: "regex", pattern: GTIN.source, message: "8, 12, 13 or 14 digits" },
    {
      type: "function",
      fn: (value) => {
        const digits = String(value ?? "");
        if (!GTIN.test(digits)) return null;
        return Number(digits.at(-1)) === gtinCheckDigit(digits)
          ? null
          : { level: "error", message: "Check digit does not match" };
      },
    },
  ],
};</code></pre>
<p>The regex catches the 6,631 shortened UPCs. The check digit catches one more
row, thirteen digits long and therefore past the regex, which a length rule
never sees.</p>
<p><code>required</code> is the only built-in rule that reacts to an empty cell. So the 3,698
products with no barcode at all pass both rules above and reach your API without
one.</p>
<h2 id="what-the-platform-stores-per-variant">What the platform stores per variant</h2>
<p>Twelve fields. The category arrives as one string and lands in three of them,
and the variant axis and its value take two more.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";
import { gtin } from "./gtin";

export const columns: DataEditorColumn[] = [
  {
    id: "productCode",
    title: "Product code",
    validators: [{ type: "required" }],
  },
  {
    id: "sku",
    title: "SKU",
    validators: [{ type: "required" }, { type: "unique" }],
  },
  { id: "title", title: "Title" },
  gtin,
  { id: "department", title: "Department" },
  { id: "category", title: "Category" },
  { id: "subCategory", title: "Sub category" },
  { id: "variantAxis", title: "Variant axis" },
  {
    id: "variantValue",
    title: "Variant value",
    validators: [{ type: "required" }],
  },
  {
    id: "price",
    title: "Price",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
  },
  {
    id: "quantity",
    title: "Quantity",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
  {
    id: "weightGrams",
    title: "Weight (g)",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
];</code></pre>
<p>The price column carries <code>$18.00</code> and <code>$1,299.00</code> in the file and needs no rule
of its own. A number column is reduced to its canonical form on the way in, and
currency symbols and the file's own grouping come off there.</p>
<h2 id="what-the-headers-reach">What the headers reach</h2>
<p>Ten of the twelve incoming headers reach a field. <code>Title</code>, <code>SKU</code> and <code>Price</code>
land on the name alone, and so does <code>Product category</code>, because <code>Category</code> sits
inside it. The other six need the alias table.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    productCode: ["url handle", "handle"],
    gtin: ["barcode", "upc", "ean"],
    variantAxis: ["option1 name"],
    variantValue: ["option1 value"],
    quantity: ["inventory quantity", "stock"],
    weightGrams: ["weight value (grams)", "grams"],
  },
};</code></pre>
<p><code>Vendor</code> and <code>Status</code> reach nothing, since the schema carries no field for
either, and their values stay out of the import. Shopify also renamed its export
headers and kept the old ones working, so <code>Handle</code> and <code>Variant SKU</code> arrive from
one merchant and <code>URL handle</code> and <code>SKU</code> from the next. Aliases are what make one
schema accept both.</p>
<h2 id="where-a-catalog-export-and-a-product-schema-disagree">Where a catalog export and a product schema disagree</h2>
<div class="blog-table blog-table--fixed blog-table--commerce-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>URL handle</code></td>
<td>one slug repeated down all seven rows of a product</td>
<td><code>required</code>, and the key the grouping loop reads</td>
</tr>
<tr>
<td><code>Title</code></td>
<td>filled on one row in seven</td>
<td>no rule, because the product owns it</td>
</tr>
<tr>
<td><code>Product category</code></td>
<td>three levels welded into one cell</td>
<td>three fields</td>
</tr>
<tr>
<td><code>SKU</code></td>
<td><code>RO-00001-XS</code>, and four rows carrying that same one</td>
<td><code>required</code> and <code>unique</code></td>
</tr>
<tr>
<td><code>Barcode</code></td>
<td><code>5.065E+12</code>, an eleven-digit UPC, and an empty cell</td>
<td>eight, twelve, thirteen or fourteen digits, check digit included</td>
</tr>
<tr>
<td><code>Option1 value</code></td>
<td><code>XS</code> through <code>3XL</code>, in the merchant's spelling</td>
<td><code>required</code>, in the spelling your catalog uses</td>
</tr>
<tr>
<td><code>Price</code></td>
<td><code>$18.00</code> and <code>$1,299.00</code></td>
<td>two decimal places, zero and up</td>
</tr>
<tr>
<td><code>Inventory quantity</code></td>
<td>a count, and an empty cell</td>
<td>a whole number of zero and up</td>
</tr>
<tr>
<td><code>Weight value (grams)</code></td>
<td>a weight whose unit lives in the heading</td>
<td>a whole number of zero and up</td>
</tr>
</tbody>
</table></div>
<p>Those failures in their generic form are collected in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>. The barcode row is
the one settled above. Four more behave in a way worth watching, and each of
them has a section below.</p>
<h2 id="two-rows-with-the-same-sku">Two rows with the same SKU</h2>
<p>Uniqueness is relational, so every cell is checked against every other row in
the column. Four rows in this catalog carry <code>RO-00001-XS</code> and two carry
<code>RO-12858-XS</code>, and all six are flagged, the first occurrence included.</p>
<p><strong>The unique check always runs last.</strong> It waits until every other rule on the
column passes, wherever <code>{ type: "unique" }</code> sits in the array. So a blank SKU
reports that it is required, and it never reports that it is a duplicate.</p>
<p><code>primaryKey="sku"</code> names the same column as the key the import merges on, which
is what makes a second upload of this catalog update rows.</p>
<h2 id="no-product-template-ships-with-this">No product template ships with this</h2>
<p>Updog ships no Shopify or PIM connector, no attribute library and no category
taxonomy to start from either. The twelve columns, the GTIN rules and the alias
table are code in your repository. Updog Importer reads CSV, TSV, JSON, XML,
XLSX, XLS, XLSB and ODS. A supplier price list that arrives as a PDF or a
photograph goes to a parser you supply, and the rows it hands back walk the same
path.</p>
<p>The parent and child link is the other honest cost. <code>onComplete</code> hands you flat
rows, so grouping seven variants back under one product is a loop you write. The
handle is the key it groups on.</p>
<h2 id="the-category-path-in-one-cell">The category path in one cell</h2>
<p>The category arrives as free text with its levels welded together. Your schema
wants three fields.</p>
<p>Right-click the column heading, then <strong>Transform</strong>, then <strong>Split</strong>. Split by
<code>></code>, into <code>Department</code>, <code>Category</code> and <code>Sub category</code>. A source column can be
one of its own targets, so the middle level writes back where it came from. The
preview fills before anything is applied.</p>
<p><code>Apparel &#x26; Accessories > Clothing > Outerwear</code> becomes three cells. The 168,000
variant rows carry no category and stay empty, which is what the grouping loop
expects.</p>
<p>A column operation covers the column, so all 196,000 rows are walked to fill
28,000 of them. Afterwards the count of rows holding an empty cell drops from
196,000 to about 169,000, and the difference is the product rows that now have
every field your schema asked for.</p>
<h2 id="the-size-your-platform-spells-differently">The size your platform spells differently</h2>
<p>The file writes <code>2XL</code> where your catalog spells it <code>XXL</code>. Open find and replace
in the filters panel, set <strong>Search in columns</strong> to <code>Variant value</code>, and the
counter reads 28,000, one row per product.</p>
<p>Restricting the search to one column is what keeps <code>2XL</code> out of the SKU beside
it, where <code>RO-00001-2XL</code> carries the same three characters. Replace all rewrites
the 28,000 cells as a single operation.</p>
<p><strong>Those column choices move the counts too.</strong> With <code>Variant value</code> selected, the
rows panel counts errors, changed rows and empty cells inside that column alone.
Clear the selection and the counts describe the file again.</p>
<h2 id="a-blank-quantity-and-a-zero-quantity">A blank quantity and a zero quantity</h2>
<p>1,218 rows in this catalog carry no inventory quantity. The number rule on that
column leaves every one of them alone, because a number rule reports the values
it could not reduce and an empty cell holds no value to reduce.</p>
<p>So the blanks travel all the way to <code>onComplete</code> as empty, and what they mean is
your decision. Shopify treats a blank as zero on the way in, and its own
documentation says the column applies only to stores with a single location. A
merchant selling from two of them has a stock level that column cannot carry.</p>
<p><strong>Add <code>{ type: "required" }</code> when the platform needs the person to say which.</strong>
Leave it off when your API already reads an absent quantity as unknown. The rule
is one line either way, and the row it puts in front of the merchandiser is
where the question gets asked.</p>
<h2 id="what-196000-rows-cost">What 196,000 rows cost</h2>
<p>The catalog is 8.6 MB and holds 2.35 million cells. Reading it takes 4,424 ms in
a worker, so the tab stays live while it happens. Splitting the category column
writes three fields across 196,000 rows, 588,000 cells, in 916 ms.</p>
<p>An operation touching 50,000 cells or more is treated as heavy. It shows a
progress overlay and walks the rows in chunks of 25,000, so the browser paints
between them. The 28,000-cell replace above sits under that line and finishes
with no overlay at all.</p>
<p>One million rows of around twenty columns is
<a href="https://updog.tech/blog/browser-first-csv-import/">the practical ceiling</a> the grid is built
around, and 196,000 is a fifth of it. The rendering side of that number is
written up in
<a href="https://updog.tech/blog/canvas-grid-performance/">a canvas grid that renders a million rows</a>.</p>
<h2 id="what-the-person-sees-before-submit">What the person sees before submit</h2>
<p>Three counts, out of 196,000 rows. 6,631 barcodes that lost a leading zero, one
whose check digit does not match, and six rows sharing a SKU with another row.
The rows panel lists them under the message each rule carries, so each count is
one click away from being the only thing on screen.</p>
<p>Checking the first of them leaves 6,631 rows on screen and hides the other
189,369. The merchandiser types the missing zero back in against the printed
carton, or clears the cell so the row travels with no barcode at all, which is
what the 3,698 blanks already do.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  synonyms={synonyms}
  primaryKey="sku"
  onComplete={async (result) => {
    const byProduct = new Map();
    for (const source of result.sources) {
      for (const { row } of source.rows) {
        const group = byProduct.get(row.productCode) ?? [];
        group.push(row);
        byProduct.set(row.productCode, group);
      }
    }
    for (const [productCode, variants] of byProduct) {
      await postProduct(productCode, variants);
    }
  }}
/></code></pre>
<p>Then <code>onComplete</code> hands over 196,000 flat rows, and the loop above turns them
back into 28,000 products. Everything the importer could not settle was settled
by the person who sent the file, before a single row reached your API.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Google Sheets</title><link>https://updog.tech/blog/import-csv-into-google-sheets/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-google-sheets/</guid><pubDate>Fri, 24 Jul 2026 00:00:00 GMT</pubDate><description>Match a venue's box office return in the browser, then write it into a Google Sheet as a values.batchUpdate and a values.append under valueInputOption RAW.</description><content:encoded><![CDATA[<p>Google documents several ways to import a CSV into Google Sheets. <code>File > Import</code> takes a <code>.csv</code> and offers six placements, from "Create new spreadsheet" to "Append rows to current sheet", with a separator you pick or let Sheets detect. <code>IMPORTDATA</code> pulls a comma-separated file from a URL into a range of cells. Apps Script reads a file out of a Drive folder on a time-driven trigger. Every one of those starts from a seat that already holds edit access to the spreadsheet. Your customer sits outside that seat, holding the box office return their duty manager exported this morning.</p>
<h2 id="the-door-a-web-backend-has">The door a web backend has</h2>
<p>The Sheets API writes values two ways. <code>values.batchUpdate</code> "Sets values in one or more ranges of a spreadsheet", each range given in A1 notation like <code>Returns!A7:I7</code>. <code>values.append</code> "Appends values to a spreadsheet", and Google explains how it picks its target. "The input range is used to search for existing data and find a 'table' within that range", and the values land on "the next row of the table, starting with the first column of the table". Its <code>insertDataOption</code> chooses between <code>OVERWRITE</code>, where "The new data overwrites existing data in the areas it is written", and <code>INSERT_ROWS</code>, where "Rows are inserted for the new data".</p>
<p>Neither one takes a key. A sheet has no primary key, no unique index and no conflict target, so nothing on Google's side can tell a return that is already in the spreadsheet from one that is new. That decision belongs to whoever calls the API.</p>
<p>One published number shapes the rest. The API allows 60 write requests a minute per user per project, and 300 a minute per project. Google's own example runs against the project ceiling, where an app that sends 350 requests in one minute is told that "the additional 50 requests exceed the quota and generates a <code>429: Too many requests</code> HTTP status code response". A loop that appends one row per call spends the whole minute on 60 rows.</p>
<h2 id="the-return-that-arrives">The return that arrives</h2>
<p>An independent cinema sends its week 32 figures, exported from its own ticketing system.</p>
<p><code>kino-nord-week32.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Screening ID</td><td class="sheet__cell">Venue</td><td class="sheet__cell">Title</td><td class="sheet__cell">Date</td><td class="sheet__cell">Screen Format</td><td class="sheet__cell">Admits</td><td class="sheet__cell">Gross</td><td class="sheet__cell">Comments</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">SCR-00471</td><td class="sheet__cell">00318</td><td class="sheet__cell">Wolf at the Door</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">3-D</td><td class="sheet__cell">142</td><td class="sheet__cell">1240.00</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">SCR-00472</td><td class="sheet__cell">00318</td><td class="sheet__cell">Wolf at the Door</td><td class="sheet__cell">03/04/2026</td><td class="sheet__cell">Digital 3D</td><td class="sheet__cell">98</td><td class="sheet__cell">861.50</td><td class="sheet__cell">-2 seats out of service</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">SCR-00473</td><td class="sheet__cell">318</td><td class="sheet__cell">The Long Field</td><td class="sheet__cell">15/04/2026</td><td class="sheet__cell">2D</td><td class="sheet__cell">64</td><td class="sheet__cell">512.00</td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">SCR-00474</td><td class="sheet__cell">00204</td><td class="sheet__cell">The Long Field</td><td class="sheet__cell">15/04/2026</td><td class="sheet__cell">35 mm</td><td class="sheet__cell">31</td><td class="sheet__cell">248.00</td><td class="sheet__cell">+1 late show added</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">113 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">119</th><td class="sheet__cell">SCR-00588</td><td class="sheet__cell">00204</td><td class="sheet__cell">Harrow Lane</td><td class="sheet__cell">09/04/2026</td><td class="sheet__cell">2D</td><td class="sheet__cell">77</td><td class="sheet__cell">616.00</td><td class="sheet__cell"></td></tr></tbody></table>
<p>The venue calls the column <code>Admits</code> and the distributor calls it <code>Admissions</code>. Dates are written day first. <code>3-D</code>, <code>Digital 3D</code> and <code>35 mm</code> are three spellings the trade uses for two of the four formats the distributor tracks. Row 4 lost the leading zeros on its venue code, because that row went through Excel on the way out. Two comments begin with a character that Google's own parser reads as the start of a formula.</p>
<p>The person drags the file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, holds the format column to your list, and puts every row in front of them. Your <code>onComplete</code> handler receives the rows. The handler posts them to a route you own, and that route decides which rows update a line in the spreadsheet and which ones extend it.</p>
<p>No Updog server stands between the browser and the spreadsheet.</p>
<h2 id="the-sheet-the-rows-land-in">The sheet the rows land in</h2>
<p>One sheet holds the season. Column A carries the key.</p>
<p><code>Returns!A1:I1</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Screening ID</td><td class="sheet__cell">Venue code</td><td class="sheet__cell">Film title</td><td class="sheet__cell">Screening date</td><td class="sheet__cell">Format</td><td class="sheet__cell">Admissions</td><td class="sheet__cell">Gross box office</td><td class="sheet__cell">Notes</td><td class="sheet__cell">Updated at</td></tr></tbody></table>
<p>Column A is a key only because your code treats it as one. The spreadsheet enforces nothing, so two rows can carry <code>SCR-00471</code> and Sheets will hold both.</p>
<p>A spreadsheet takes "Up to 10 million cells or 18,278 columns (column ZZZ)", and Google states that the same restrictions apply to Excel and CSV imports. Nine columns of returns reach that ceiling at a little over a million rows. The spreadsheet owns that ceiling, and it is the number to check before a season of daily returns lands in one file.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array describes the sheet as the person sees it.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const FORMATS = ["2D", "3D", "IMAX", "35mm"];

export const columns: DataEditorColumn[] = [
  {
    id: "screeningId",
    title: "Screening ID",
    size: 150,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^SCR-[0-9]{5}$" },
      { type: "unique" },
    ],
  },
  {
    id: "venueCode",
    title: "Venue code",
    size: 130,
    transformer: (value) => String(value ?? "").trim().padStart(5, "0"),
    validators: [{ type: "required" }, { type: "regex", pattern: "^[0-9]{5}$" }],
  },
  {
    id: "filmTitle",
    title: "Film title",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "screeningDate",
    title: "Screening date",
    size: 160,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "format",
    title: "Format",
    size: 120,
    editor: { type: "select", options: FORMATS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: FORMATS }],
  },
  {
    id: "admissions",
    title: "Admissions",
    size: 130,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, max: 5000, decimalPlaces: 0 }],
  },
  {
    id: "grossBoxOffice",
    title: "Gross box office",
    size: 170,
    editor: { type: "number" },
    formatter: (value) =>
      value
        ? "GBP " + Number(value).toLocaleString("en-GB", {
            minimumFractionDigits: 2,
          })
        : "",
    validators: [{ type: "number", min: 0, max: 200_000, decimalPlaces: 2 }],
  },
  {
    id: "notes",
    title: "Notes",
    size: 260,
  },
];</code></pre>
<p>Each piece earns its place against what arrives. The <code>transformer</code> on the venue code runs as rows enter the store, so <code>318</code> and <code>00318</code> both become <code>00318</code> before anybody looks at the grid. The <code>date</code> editor turns <code>15/04/2026</code> into <code>2026-04-15</code>, and because 15 is above 12 the whole file settles day first, so <code>03/04/2026</code> lands as <code>2026-04-03</code>. The <code>select</code> on the format holds the column to four options, and a value nobody maps is dropped from the row.</p>
<p><code>{ type: "unique" }</code> on the screening id catches the case the spreadsheet cannot. Uniqueness is relational, so the SDK checks the value against every other row in the column, and the rule always runs last. That covers duplicates inside the file. Rows already sitting in the sheet are the route's job, further down.</p>
<p><a href="https://updog.tech/blog/import-csv-into-airtable/">Importing a CSV into Airtable</a> covers the other grid-shaped destination, where the option list is enforced by the destination instead of by your schema.</p>
<h2 id="what-the-person-sees-and-what-the-sheet-gets">What the person sees and what the sheet gets</h2>
<p><code>grossBoxOffice</code> carries a <code>formatter</code>, which formats the display value without changing stored data. The grid paints <code>GBP 1,240.00</code> and the store holds <code>1240.00</code>. The handler receives <code>1240.00</code>, the route sends the number <code>1240</code>, and the sheet's own number format paints the currency again.</p>
<p>Every layer here holds one value and shows another. The trouble starts when a layer is left to decide which of the two it keeps, and that is the decision the write call makes for you.</p>
<p>Search reads the formatted value, so a query for <code>GBP</code> finds every filled cell. Find and Replace writes back to the stored value and takes a match only where it sits inside the data, so a search for the <code>GBP</code> the formatter added reports no results.</p>
<h2 id="the-headers-the-venue-sends">The headers the venue sends</h2>
<p>Column matching scores each header against your column id and your column title, and the higher score wins.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Screening ID</code></td>
<td><code>screeningId</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Venue</code></td>
<td><code>venueCode</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Title</code></td>
<td><code>filmTitle</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Date</code></td>
<td><code>screeningDate</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Screen Format</code></td>
<td><code>format</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Admits</code></td>
<td><code>admissions</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Gross</code></td>
<td><code>grossBoxOffice</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Comments</code></td>
<td><code>notes</code></td>
<td>synonym, 90</td>
</tr>
</tbody>
</table></div>
<p><code>Date</code> sits exactly on the contains floor, which fires once the shorter normalized string runs to four characters. <code>Title</code> and <code>Gross</code> clear the same floor with a character to spare. The built-in synonym table lists the bare <code>title</code> under job title and <code>grosspay</code> under gross salary, and neither group holds a column of yours, so both headers fall through to the contains tier and land on the right column anyway.</p>
<p><code>Admits</code> and <code>Comments</code> reach nothing on their own. <code>Admits</code> shares no whole word with <code>admissions</code> and runs four characters shorter, past the three edits allowed at ten characters. <code>Comments</code> runs three characters longer than <code>notes</code>, past the two allowed at eight. One <code>synonyms</code> entry each carries them, and every entry you write is a header you never map again.</p>
<p>Value matching runs once across the import. <code>3-D</code> normalizes to <code>3d</code> and hits the option exactly, since normalization removes hyphens, spaces, underscores and dots. <code>35 mm</code> reaches <code>35mm</code> the same way. <code>Digital 3D</code> lands at seventy, because the contains tier refuses a two-character option and the words <code>digital</code> and <code>3d</code> give one match out of two.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the file, the schema and the sheet together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Return>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey="screeningId"
  blockSubmitOnError
  synonyms={{
    columns: {
      admissions: ["admits", "attendance", "tickets sold", "seats sold"],
      notes: ["comments", "remarks", "duty manager notes"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> is one column here, and it is the same column the sheet keeps in A. Values are compared after trimming. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, so a malformed screening id never reaches your route.</p>
<p>Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>. Store those pairs and feed them back through <code>synonyms</code>, and the next return from the same venue matches itself.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 2000;

const toRow = (entry: ResultRow&#x3C;Return>) => {
  if (entry.isDeleted) return [];
  return [{
    screeningId: entry.row.screeningId,
    venueCode: entry.row.venueCode,
    filmTitle: entry.row.filmTitle,
    screeningDate: entry.row.screeningDate,
    format: entry.row.format,
    admissions: entry.row.admissions,
    grossBoxOffice: entry.row.grossBoxOffice,
    notes: entry.row.notes,
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Return>) => {
  for (const source of result.sources) {
    const rows = source.rows.flatMap(toRow);

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const written = await fetch("/api/returns/write", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
      });
      if (!written.ok) throw new Error((await written.json()).message);
    }
  }
}, []);</code></pre>
<p>A deleted row goes nowhere, since removing a line from a spreadsheet shifts every row below it and that is a different job. New and changed rows carry the same payload, because the route works out which is which against the sheet.</p>
<p>The chunk size follows the write budget. Each chunk costs one read request and up to two write requests, so 60 writes a minute carries thirty chunks, and two thousand rows a chunk carries sixty thousand rows a minute. Two thousand is the number chosen against your own endpoint. Thirty chunks is what Google's published quota allows.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the whole return clears the grid unwritten. A thrown error keeps the grid as it stands, with every mapping and hand correction on it. The person submits again on rows that never left the screen.</p>
<h2 id="the-route-that-writes">The route that writes</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import { google } from "googleapis";

const SPREADSHEET_ID = process.env.RETURNS_SPREADSHEET_ID;
const SHEET = "Returns";

const auth = new google.auth.GoogleAuth({
  scopes: ["https://www.googleapis.com/auth/spreadsheets"],
});
const sheets = google.sheets({ version: "v4", auth });

const toValues = (row) => [
  row.screeningId,
  row.venueCode,
  row.filmTitle,
  row.screeningDate,
  row.format,
  Number(row.admissions),
  Number(row.grossBoxOffice),
  row.notes ?? "",
  new Date().toISOString(),
];

const readIndex = async () => {
  const answer = await sheets.spreadsheets.values.get({
    spreadsheetId: SPREADSHEET_ID,
    range: SHEET + "!A2:B",
  });

  const index = new Map();
  (answer.data.values ?? []).forEach((cells, offset) => {
    if (cells[0]) index.set(cells[0], { line: offset + 2, venue: cells[1] });
  });
  return index;
};</code></pre>
<p>A service account is "a special kind of account typically used by an application or compute workload", and Google adds that it "is identified by its email address, which is unique to the account". Google documents how it reaches one spreadsheet. "You can directly share individual files with the service account's email address using the standard UI", treating that address "as a user account in the document's share settings with no administrator privileges required". So the booking team shares the season sheet with the service account and nothing else. Google also warns that "Service account keys are a security risk if not managed correctly", so prefer an environment that hands your runtime a credential over a key file you carry.</p>
<p><code>readIndex</code> reads columns A and B and maps each screening id to its row number and the venue that owns that line, offset by two because row one is the header. Re-read it for every chunk. A key appended by the previous chunk is in the sheet already, and an index read once would append it twice.</p>
<pre><code class="language-ts">class NotYours extends Error {}

const writeReturns = async (rows, allowed) => {
  const index = await readIndex();
  const updates = [];
  const appends = [];

  for (const row of rows) {
    const found = index.get(row.screeningId);
    if (found) {
      if (!allowed.has(found.venue)) {
        throw new NotYours("A screening id belongs to another venue");
      }
      updates.push({
        range: SHEET + "!A" + found.line + ":I" + found.line,
        values: [toValues(row)],
      });
    } else {
      appends.push(toValues(row));
    }
  }

  if (updates.length > 0) {
    const answer = await sheets.spreadsheets.values.batchUpdate({
      spreadsheetId: SPREADSHEET_ID,
      requestBody: { valueInputOption: "RAW", data: updates },
    });
    if (answer.data.responses?.length !== updates.length) {
      throw new Error("The sheet answered for fewer ranges than were sent");
    }
  }

  if (appends.length > 0) {
    await sheets.spreadsheets.values.append({
      spreadsheetId: SPREADSHEET_ID,
      range: SHEET + "!A:I",
      valueInputOption: "RAW",
      insertDataOption: "INSERT_ROWS",
      requestBody: { values: appends },
    });
  }
};

app.post("/api/returns/write", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const rows = request.body.rows;
  if (!Array.isArray(rows)) {
    return response.status(400).json({ message: "Send an array of rows" });
  }

  const allowed = await venuesFor(session.accountId);
  if (rows.some((row) => !allowed.has(row.venueCode))) {
    return response.status(403).json({ message: "A venue code is not yours" });
  }

  try {
    await writeReturns(rows, allowed);
  } catch (error) {
    if (error instanceof NotYours) {
      return response.status(403).json({ message: error.message });
    }
    request.log.error({ err: error });
    return response.status(502).json({ message: "The sheet was not updated" });
  }

  response.json({ written: rows.length });
});</code></pre>
<p>Every row that matched an id becomes one A1 range in a single <code>batchUpdate</code>. Everything else goes to <code>append</code> with <code>INSERT_ROWS</code>, which extends the table rather than writing over whatever sits under it. The response carries "One UpdateValuesResponse per requested range, in the same order as the requests appeared", along with <code>totalUpdatedRows</code> and <code>totalUpdatedCells</code>, so the route counts the answers against what it sent before it reports success.</p>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. Two fields in the body carry a claim over somebody else's numbers. The venue code is checked against the venues that session may report for. The screening id picks the line the write lands on, so it is checked against the venue already sitting in column B of that line, and a row that would overwrite another cinema's return leaves the sheet untouched with a 403.</p>
<h2 id="why-raw">Why RAW</h2>
<p>Both write calls carry <code>valueInputOption: "RAW"</code>, and that word decides what the spreadsheet stores.</p>
<p>Google defines the two options plainly. Under <code>RAW</code>, "The values the user has entered will not be parsed and will be stored as-is". Under <code>USER_ENTERED</code>, "The values will be parsed as if the user typed them into the UI", following "the same rules that are applied when entering text into a cell via the Google Sheets UI". The values guide gives the example twice. Under <code>RAW</code> the input "'=1+2' places the string, not the formula, '=1+2' in the cell". Under <code>USER_ENTERED</code>, "'Mar 1 2016' becomes a date, and '=1+2' becomes a formula".</p>
<p>Two columns in this file depend on which one you send. <code>00318</code> is a five-character string that <code>USER_ENTERED</code> would read as the number 318. The comments column is free text a duty manager typed, and <code>USER_ENTERED</code> hands every one of those cells to the parser that runs behind the Sheets UI. The two comments here open with a minus and a plus, and a cell that opens with <code>=</code> becomes a live formula in your spreadsheet, running under your booking team's account.</p>
<p>Updog carries that cell through untouched. Its cell cleaner strips zero-width characters, turns non-breaking spaces into ordinary ones, normalizes to NFC and trims, and it inspects no first character. So a CSV holding <code>=SUM(A1:A9)</code> reaches your handler as that exact string. <code>RAW</code> is what keeps it a string once it lands.</p>
<p>Sending <code>RAW</code> puts the type decision in your route instead, which is why <code>toValues</code> wraps two fields in <code>Number()</code>. The API takes it from there. "For input, supported value types are: bool, string, and double. Null values will be skipped. To set a cell to an empty value, set the string value to an empty string." A JSON number becomes a number cell, a JSON string stays text with its leading zeros intact, and <code>notes</code> falls back to <code>""</code> so an empty comment writes a blank cell, since a null would be skipped.</p>
<h2 id="the-parts-nobody-ships-for-you">The parts nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Google Sheets connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route in the middle is work you do. Our cell cleaner leaves a leading <code>=</code> alone by design, so keeping a formula out of your spreadsheet is your <code>valueInputOption</code> and your call.</p>
<p>A Google Sheet is also already a shared spreadsheet. When the venue can simply be given edit access, hand them the link and let <code>File > Import</code> do it, since it offers "Append rows to current sheet" for exactly that. Everything above exists for the case where the season sheet holds forty venues and none of them may see another's numbers, so the file has to arrive through your app, inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-next-week">The pieces you wrote and next week</h2>
<p>You wrote one sheet with nine columns and a key in A, a schema with eight columns, one padding transformer, one <code>synonyms</code> block covering two headers, a route that reads column A and splits the import in two, and two write requests that carry the whole thing. The file stays on the machine that opened it. The rows travel from your own front end to your own route and into your own spreadsheet, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>Week 33 brings the same venue and a second one that writes <code>Seats</code> instead of <code>Admits</code>. The mappings from week 32 are already stored, the corrected rows update in place because their screening ids are already in column A, and the new venue costs one more line in <code>synonyms</code>.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Amazon Redshift</title><link>https://updog.tech/blog/import-csv-into-redshift/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-redshift/</guid><pubDate>Thu, 23 Jul 2026 00:00:00 GMT</pubDate><description>Reconcile a registrar's enrolment export against the rows already in Redshift, then land the inserts, updates and deletes in one Data API transaction.</description><content:encoded><![CDATA[<p>Amazon Redshift documents several ways to move a CSV into a table. Query editor v2 takes a local file up to 100 MB, once an administrator has named a staging bucket in Account settings. The same wizard loads from S3 and writes the COPY for you. COPY from S3 by hand reads every object under a key prefix in parallel. An S3 event integration turns new files under a prefix into COPY commands nobody has to run. Every one of those starts from a seat that already holds the cluster's IAM. Your customer sits outside that seat, holding an enrolment export a university registrar sent them.</p>
<h2 id="the-constraints-redshift-will-not-enforce">The constraints Redshift will not enforce</h2>
<p>Redshift takes the primary key you declare and reads it as a hint. AWS states it plainly. "Uniqueness, primary key, and foreign key constraints are informational only", and the same sentence says Amazon Redshift does not enforce them when you populate a table. An insert that violates one succeeds. The query planner still uses the key, and AWS says it "assumes that all keys in Amazon Redshift tables are valid as loaded", so a duplicate that reaches the table can make a <code>SELECT DISTINCT</code> return duplicate rows.</p>
<p>Redshift does enforce a <code>NOT NULL</code> column constraint.</p>
<p>So the duplicate has to be caught before the load. In <a href="https://updog.tech/blog/import-csv-into-postgresql/">how to import CSV into PostgreSQL</a> the database rejects the row and hands back an error code. Here nothing rejects anything, and the two places left are the browser and the merge.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>The registrar exports the term from the student information system, and it looks like this.</p>
<p><code>fa26-enrolments.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Student ID</td><td class="sheet__cell">Term</td><td class="sheet__cell">Course</td><td class="sheet__cell">Sec</td><td class="sheet__cell">Credits</td><td class="sheet__cell">Status</td><td class="sheet__cell">Enrolled</td><td class="sheet__cell">Campus</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">24-118392</td><td class="sheet__cell">FA26</td><td class="sheet__cell">BIOL 1010</td><td class="sheet__cell">001</td><td class="sheet__cell">3</td><td class="sheet__cell">Enrolled</td><td class="sheet__cell">24/08/2026</td><td class="sheet__cell">Riverbank</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">24-118392</td><td class="sheet__cell">FA26</td><td class="sheet__cell">BIOL 1010</td><td class="sheet__cell">001</td><td class="sheet__cell">3</td><td class="sheet__cell">ENR</td><td class="sheet__cell">24/08/2026</td><td class="sheet__cell">Riverbank</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">24-119045</td><td class="sheet__cell">FA26</td><td class="sheet__cell">MATH 2210</td><td class="sheet__cell">002</td><td class="sheet__cell">3,5</td><td class="sheet__cell">Withdrawn</td><td class="sheet__cell">02.09.2026</td><td class="sheet__cell">Northgate</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">24-119045</td><td class="sheet__cell">FA26</td><td class="sheet__cell">PSYC 1101</td><td class="sheet__cell">001</td><td class="sheet__cell">3</td><td class="sheet__cell">Registered</td><td class="sheet__cell">02.09.2026</td><td class="sheet__cell">Northgate</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">8935 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8941</th><td class="sheet__cell">24-121870</td><td class="sheet__cell">FA26</td><td class="sheet__cell">ENGL 1020</td><td class="sheet__cell">003</td><td class="sheet__cell">3</td><td class="sheet__cell">Enrolled</td><td class="sheet__cell">04/09/2026</td><td class="sheet__cell">Riverbank</td></tr></tbody></table>
<p>One header is short. <code>Sec</code> means the section number and no built-in synonym covers it. The first two lines carry the same student, term, course and section. The credits disagree about punctuation, one line writing <code>3</code> and another writing <code>3,5</code>. The dates disagree about order, one writing <code>24/08/2026</code> and another writing <code>02.09.2026</code>. The status column says <code>Enrolled</code> on one line, <code>ENR</code> on the next, and <code>Registered</code> further down.</p>
<p>The person drops that file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, and puts every value in front of them beside the rows already in the warehouse. Your <code>onComplete</code> handler receives each row with a verdict on it. The handler posts the rows to a route you own, the route writes them to S3, and one Data API call turns them into a load, a merge and a delete.</p>
<p>No Updog server stands between the browser and Redshift.</p>
<h2 id="the-table-the-rows-have-to-reach">The table the rows have to reach</h2>
<p>One table holds the enrolments, and it declares the key it will never enforce.</p>
<pre><code class="language-sql">create table analytics.enrolment (
  institution_id varchar(36)  not null,
  student_ref    varchar(16)  not null,
  term_code      varchar(8)   not null,
  course_code    varchar(16)  not null,
  section        varchar(8)   not null,
  credits        decimal(4,1),
  status         varchar(16),
  enrolled_on    date,
  campus         varchar(64),
  source_file    varchar(256),
  updated_at     timestamp    not null,
  primary key (institution_id, student_ref, term_code, course_code, section)
)
diststyle key
distkey (student_ref)
compound sortkey (institution_id, term_code);</code></pre>
<p>AWS says to "always declare primary and foreign keys and uniqueness constraints when you know that they are valid", because the planner uses them to order joins and drop redundant ones. <code>student_ref</code> is the distribution key, so a student's rows sit on one slice and the merge join stays local. The sort key runs institution then term, since every question anybody asks of enrolment names a term. <code>campus</code> takes <code>varchar(64)</code> because Redshift measures a character column in bytes, and a campus name outside ASCII spends more than one byte per letter.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array is the same table written for the person looking at the file.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const STATUSES = ["Enrolled", "Withdrawn", "Audit"];

export const columns: DataEditorColumn[] = [
  {
    id: "studentRef",
    title: "Student ref",
    size: 140,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^\\d{2}-\\d{6}$" },
    ],
  },
  {
    id: "termCode",
    title: "Term code",
    size: 110,
    validators: [{ type: "required" }],
  },
  {
    id: "courseCode",
    title: "Course code",
    size: 140,
    validators: [{ type: "required" }],
  },
  {
    id: "section",
    title: "Section",
    size: 100,
    validators: [{ type: "required" }],
  },
  {
    id: "credits",
    title: "Credits",
    size: 110,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, max: 12, decimalPlaces: 1 },
    ],
  },
  {
    id: "status",
    title: "Status",
    size: 140,
    editor: { type: "select", options: STATUSES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: STATUSES }],
  },
  {
    id: "enrolledOn",
    title: "Enrolled on",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "campus",
    title: "Campus",
    size: 180,
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>date</code> editor turns <code>02.09.2026</code> into <code>2026-09-02</code>. The scan settles the file's date order on the first value carrying a part above 12, which is the <code>24</code> in <code>24/08/2026</code>. The <code>number</code> editor swaps the comma for a dot, so <code>3,5</code> lands as <code>3.5</code>. One comma decimal and no dot decimal decide the whole file. The <code>select</code> editor with <code>enableCustomValue</code> off holds the status column to three options, and a value nobody maps is dropped from the row.</p>
<p>The mount ties the rest together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Enrolment>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey={["studentRef", "termCode", "courseCode", "section"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: { section: ["sec", "sect", "class section"] },
    values: { Enrolled: ["enr", "registered", "active"] },
  }}
  loadData={async (onChunk) => {
    const response = await fetch("/api/enrolment/current");
    const body = await response.json();
    if (!response.ok) throw new Error(body.message);
    onChunk(body.rows, { source: "Redshift", done: true });
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>Sec</code> reaches <code>section</code> through the <code>synonyms</code> table and through nothing else. Fuzzy matching scores it at zero. Three characters fall under the four-character floor the contains tier needs, <code>sec</code> shares no whole word with <code>section</code>, and the length gap of four exceeds the two edits allowed at that length. A match needs sixty. The same table carries <code>enr</code> and <code>registered</code> on the value side, where both stand too far from <code>Enrolled</code> to reach it alone. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time.</p>
<p><code>primaryKey</code> takes four columns, because one student takes several courses in one term. The warehouse key has a fifth part, and <code>institution_id</code> never reaches the browser at all. It comes off the session on your server. <code>enableDeleteRow="all"</code> lets the person remove a row that the registrar dropped, and <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-rows-already-in-the-warehouse">The rows already in the warehouse</h2>
<p><code>loadData</code> runs once when the editor opens, and it fills the grid with what Redshift holds today.</p>
<pre><code class="language-ts">import {
  RedshiftDataClient,
  ExecuteStatementCommand,
  DescribeStatementCommand,
  GetStatementResultCommand,
} from "@aws-sdk/client-redshift-data";

const redshift = new RedshiftDataClient({});
const TARGET = { WorkgroupName: "analytics", Database: "dev" };

const CURRENT_SQL =
  "select student_ref, term_code, course_code, section, " +
  "credits, status, enrolled_on, campus " +
  "from analytics.enrolment " +
  "where institution_id = :institution_id " +
  "order by student_ref, term_code, course_code, section";

const waitFor = async (id) => {
  for (;;) {
    const state = await redshift.send(
      new DescribeStatementCommand({ Id: id, WaitTimeSeconds: 30 }),
    );
    if (state.Status === "FINISHED") return state;
    if (state.Status === "FAILED" || state.Status === "ABORTED") {
      const failed = state.SubStatements?.find((sub) => sub.Error);
      throw new Error(failed?.Error ?? state.Error ?? "Statement failed");
    }
  }
};

app.get("/api/enrolment/current", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const started = await redshift.send(
    new ExecuteStatementCommand({
      ...TARGET,
      Sql: CURRENT_SQL,
      Parameters: [
        { name: "institution_id", value: session.institutionId },
      ],
    }),
  );

  await waitFor(started.Id);

  const rows = [];
  let token;
  do {
    const page = await redshift.send(
      new GetStatementResultCommand({ Id: started.Id, NextToken: token }),
    );
    rows.push(...page.Records.map(toEnrolmentRow));
    token = page.NextToken;
  } while (token);

  response.json({ rows });
});</code></pre>
<p>The Data API needs no driver, no connection pool and no password in the call. It reaches a provisioned cluster or a Serverless workgroup over HTTPS, and it authenticates through Secrets Manager, through IAM Identity Center, or through temporary credentials derived from the caller's own IAM identity. Every call is asynchronous, so a statement comes back as an id and <code>DescribeStatement</code> reports on it. <code>WaitTimeSeconds</code> holds that poll open for up to 30 seconds, which keeps the loop small.</p>
<p>Results live for 24 hours and cap at 500 MB after compression, and <code>GetStatementResult</code> pages through them. Each record arrives as typed fields with column metadata beside it, and a <code>DECIMAL</code> comes back as a string, which is the shape the editor wants anyway.</p>
<p>The person now sees the term as the warehouse has it. The registrar's file lands on top of it in the next step, and every row that matches on the four key columns merges into the row already there.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. The flags are independent, so one row can be new, changed and deleted at once. Rows that merged onto warehouse rows arrive under the Redshift source as changed. Rows the file added arrive under the file's own name as new. A warehouse row nobody touched never appears.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 2000;

const route = (entry: ResultRow&#x3C;Enrolment>, sourceFile: string) => {
  if (entry.isDeleted) {
    if (entry.isNew) return [];
    return [{ op: "delete", sourceFile, ...entry.row }];
  }
  if (entry.isNew) return [{ op: "insert", sourceFile, ...entry.row }];
  if (entry.isChanged) return [{ op: "update", sourceFile, ...entry.row }];
  return [];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Enrolment>) => {
  const rows = result.sources.flatMap((source) => {
    return source.rows.flatMap((entry) => route(entry, source.sourceName));
  });

  const batchId = crypto.randomUUID();

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const staged = await fetch("/api/enrolment/stage", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        batchId,
        offset: start,
        rows: rows.slice(start, start + CHUNK_SIZE),
      }),
    });
    if (!staged.ok) throw new Error((await staged.json()).message);
  }

  const merged = await fetch("/api/enrolment/merge", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ batchId }),
  });
  if (!merged.ok) throw new Error((await merged.json()).message);
}, []);</code></pre>
<p>That handler gives each row one verb before it leaves the browser. A row the person added and then deleted goes nowhere. Since <code>blockSubmitOnError</code> holds submit until every error is gone, the routing runs on the three change flags alone.</p>
<p>No Redshift number caps the rows in a chunk, because the rows travel to S3 as an object and never sit inside the SQL text. The numbers that do bind sit further along. One <code>BatchExecuteStatement</code> carries at most 40 statements, and this import uses four. The other ceiling is whatever your own endpoint accepts as a request body, so the chunk size above is a starting point to check against your own runtime.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the term clears the grid unwritten. A thrown error keeps the grid as it stands, with every match and hand correction on it. The person submits again on rows that never left the screen.</p>
<p>The staging posts and the merge all run behind a spinner in the confirm dialog. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-route-that-stages-the-batch">The route that stages the batch</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { BatchExecuteStatementCommand } from "@aws-sdk/client-redshift-data";
import { randomUUID } from "node:crypto";

const s3 = new S3Client({});
const BUCKET = "your-import-bucket";
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;

app.post("/api/enrolment/stage", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });
  if (!UUID.test(request.body.batchId)) {
    return response.status(400).json({ message: "Bad batch id" });
  }

  const csv = request.body.rows
    .map((row, index) =>
      csvLine([
        request.body.offset + index,
        row.op,
        session.institutionId,
        row.studentRef,
        row.termCode,
        row.courseCode,
        row.section,
        row.credits,
        row.status,
        row.enrolledOn,
        row.campus,
        row.sourceFile,
      ]),
    )
    .join("\n");

  const key =
    "enrolment/" + session.institutionId +
    "/" + request.body.batchId +
    "/" + randomUUID() + ".csv";

  await s3.send(
    new PutObjectCommand({
      Bucket: BUCKET,
      Key: key,
      Body: csv,
      ContentType: "text/csv",
    }),
  );

  response.json({ staged: request.body.rows.length });
});

app.post("/api/enrolment/merge", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });
  if (!UUID.test(request.body.batchId)) {
    return response.status(400).json({ message: "Bad batch id" });
  }

  const prefix =
    "s3://" + BUCKET +
    "/enrolment/" + session.institutionId +
    "/" + request.body.batchId + "/";

  const started = await redshift.send(
    new BatchExecuteStatementCommand({
      ...TARGET,
      Sqls: [CREATE_STAGE, copyFrom(prefix), MERGE_BATCH, DELETE_BATCH],
      Parameters: [
        { name: "institution_id", value: session.institutionId },
      ],
    }),
  );

  const finished = await waitFor(started.Id);
  response.json({ statements: finished.SubStatements.length });
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>institutionId</code> comes off that session and never off the request body, so a guessed batch id reaches no other tenant's prefix. The batch id is checked against a UUID shape before it goes anywhere near an S3 key. <code>line_no</code> carries the row's position in the whole import, which is what lets the merge keep the last copy of a repeated key.</p>
<p>Each chunk lands as its own object under one prefix. AWS loads every file under a key prefix in a single COPY and splits the work across slices, and it warns that several concurrent COPY commands into one table force a serialized load instead. So one COPY reads the whole batch.</p>
<p>The credential is the IAM role attached to the service. The COPY itself takes <code>iam_role default</code>, which uses the role set as default on the cluster, and AWS calls the access key alternative "not recommended". The bucket has to sit in the same Region as the cluster unless the COPY names a <code>REGION</code>.</p>
<h2 id="the-statements-that-land-the-import">The statements that land the import</h2>
<p>Four statements go out in one <code>BatchExecuteStatement</code>, and AWS runs them serially in array order. The default <code>ExecutionMode</code> is <code>TRANSACTION</code>, so the four commit together and a failure anywhere rolls all of them back.</p>
<pre><code class="language-sql">-- 1. the staging table, gone when the session ends
create temporary table stage_enrolment (
  line_no        integer      not null,
  op             varchar(8)   not null,
  institution_id varchar(36)  not null,
  student_ref    varchar(16)  not null,
  term_code      varchar(8)   not null,
  course_code    varchar(16)  not null,
  section        varchar(8)   not null,
  credits        decimal(4,1),
  status         varchar(16),
  enrolled_on    date,
  campus         varchar(64),
  source_file    varchar(256)
)
distkey (student_ref);

-- 2. every object under the batch prefix, loaded in parallel
copy stage_enrolment
from 's3://your-import-bucket/enrolment/inst-4471/9f2c.../'
iam_role default
format as csv
emptyasnull
blanksasnull;

-- 3. the inserts and the updates
merge into analytics.enrolment as t
using (
  select institution_id, student_ref, term_code, course_code, section,
         credits, status, enrolled_on, campus, source_file
  from (
    select s.*, row_number() over (
      partition by student_ref, term_code, course_code, section
      order by line_no desc
    ) as rn
    from stage_enrolment s
    where s.op &#x3C;> 'delete'
      and s.institution_id = :institution_id
  ) as ranked
  where rn = 1
) as s
on  t.institution_id = s.institution_id
and t.student_ref    = s.student_ref
and t.term_code      = s.term_code
and t.course_code    = s.course_code
and t.section        = s.section
when matched then update set
  credits     = s.credits,
  status      = s.status,
  enrolled_on = s.enrolled_on,
  campus      = s.campus,
  source_file = s.source_file,
  updated_at  = getdate()
when not matched then insert (
  institution_id, student_ref, term_code, course_code, section,
  credits, status, enrolled_on, campus, source_file, updated_at
)
values (
  s.institution_id, s.student_ref, s.term_code, s.course_code, s.section,
  s.credits, s.status, s.enrolled_on, s.campus, s.source_file, getdate()
);

-- 4. the rows the person deleted
delete from analytics.enrolment
using stage_enrolment s
where s.op = 'delete'
  and s.institution_id = :institution_id
  and analytics.enrolment.institution_id = s.institution_id
  and analytics.enrolment.student_ref    = s.student_ref
  and analytics.enrolment.term_code      = s.term_code
  and analytics.enrolment.course_code    = s.course_code
  and analytics.enrolment.section        = s.section;</code></pre>
<p>The staging table is temporary, and the Data API usually ends the session when the SQL finishes, so it has to be created and used inside the same batch. Session reuse through <code>SessionKeepAliveSeconds</code> is the other way, and it holds a session for up to 24 hours. The staging table takes the target's distribution key, which AWS says can improve a merge over a large source.</p>
<p>COPY carries two conversion options that match what the file did. <code>emptyasnull</code> and <code>blanksasnull</code> turn an empty character cell and a whitespace-only one into null, which is what a missing <code>campus</code> or <code>status</code> means here. The dates need no option, since COPY reads <code>YYYY-MM-DD</code> by default and that is the shape the editor produced.</p>
<p>The <code>MERGE</code> deduplicates in its <code>USING</code> subquery, and that is load-bearing. AWS writes that a row in the target may match only one row in the source, and its own example ends <code>ERROR: Found multiple matches to update the same tuple</code>. The registrar's file sent <code>BIOL 1010</code> twice, and Updog leaves both rows on screen because two rows from one file never merge into each other. <code>row_number()</code> keeps the highest line number per key, so the second copy wins and the statement survives.</p>
<p>The delete runs as <code>DELETE ... USING</code>, the join form AWS documents on <code>DELETE</code> for naming a second table in the <code>WHERE</code> condition. Both statements filter on the institution from the session, so a batch can only touch the tenant that posted it.</p>
<h2 id="the-report-on-a-failed-batch">The report on a failed batch</h2>
<p><code>DescribeStatement</code> answers with a status of <code>SUBMITTED</code>, <code>PICKED</code>, <code>STARTED</code>, <code>FINISHED</code>, <code>ABORTED</code> or <code>FAILED</code>. For a batch it also answers with <code>SubStatements</code>, one entry per statement, each with its own <code>Error</code>, <code>Duration</code> and <code>ResultRows</code>. The id of the failing one ends in a suffix, so <code>:2</code> is the second statement in the array, which is the COPY. <code>ResultRows</code> on the merge is the number of rows it affected.</p>
<p>A COPY that fails on the data writes the detail to <code>SYS_LOAD_ERROR_DETAIL</code>, one row per COPY, with the file name, the line number, the column and the message. <code>STL_LOAD_ERRORS</code> holds the same kind of record and covers main provisioned clusters alone, so a Serverless workgroup reports through the SYS view. The whole transaction rolls back, the staging table goes with the session, and the objects still sit under the batch prefix for the retry.</p>
<p>Throttling arrives as a <code>ThrottlingException</code> with a 400. The Data API allows 30 <code>ExecuteStatement</code> calls a second, 20 <code>BatchExecuteStatement</code> calls, and 100 <code>DescribeStatement</code> calls, and AWS says the retry strategy runs automatically for throttling errors in some of its SDKs.</p>
<h2 id="the-routes-nobody-ships-for-you">The routes nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no Redshift connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the routes in the middle are work you do.</p>
<p>Redshift already ships its own ways in for the other case. Query editor v2 takes a local file up to 100 MB and generates the COPY. The same wizard loads from an S3 bucket. COPY reads every object under a bucket prefix in one statement. An S3 event integration runs the COPY for every new file under a prefix, up to 200 jobs per cluster or workgroup. Every one of those needs an AWS seat with the cluster's IAM behind it. For an export your own team downloaded, those tools are the shorter way in. Everything above exists for the export a registrar sent, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-export">The pieces you wrote and the next export</h2>
<p>You wrote one table, a schema with eight columns, a read route, a handler that gives each row a verb, two write routes, and four statements that commit together. The file stays on the machine that opened it. The rows travel from your own front end to your own routes, into your own bucket, and from there into Redshift, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The registrar will send the term again once add and drop closes, with two sections cancelled and a handful of students moved. That time the mappings are already stored, the editor opens on the rows that landed last time, and the person sees the difference before anybody writes it down.</p>]]></content:encoded></item>
<item><title>Customer Data Onboarding: A Guide for B2B SaaS</title><link>https://updog.tech/blog/what-is-customer-data-onboarding/</link><guid isPermaLink="true">https://updog.tech/blog/what-is-customer-data-onboarding/</guid><pubDate>Wed, 22 Jul 2026 00:00:00 GMT</pubDate><description>What happens to a customer's file before their records work inside your product, and which stages of that work break most often.</description><content:encoded><![CDATA[<p>Customer data onboarding is everything between a customer choosing your product and their existing records being usable inside it. Whatever they need on day one already exists somewhere else. It sits in a spreadsheet a team has maintained for years, in an export from the tool they are leaving, or in a report someone pulled from a system nobody has admin access to any more. Onboarding is the work of moving those records out of that shape and into yours: getting the file, reading it, matching its columns to your fields, translating its values, checking the rows against your rules, and fixing what is wrong before any of it is submitted. This guide walks through those stages in the order a real customer hits them.</p>
<p>That work has an owner, and the owner is often not the person you would expect. Usually it is a customer success manager with the client's spreadsheet open in one window and your admin panel in the other. Sometimes it is an engineer writing a script for one client and a second script for the next. And sometimes it is the customer, alone in an upload screen you shipped two years ago, guessing what your fields expect.</p>
<h2 id="onboarding-migration-integrations-and-pipelines">Onboarding, migration, integrations, and pipelines</h2>
<p>Data migration is the one time bulk move of records out of an old system into a new one, run by your team as a project with an end date. Onboarding overlaps with it and then keeps going after the project closes, because every new customer arrives with the problem the last one had.</p>
<p>An integration is a live connection between two systems over an API, where data keeps flowing without anyone exporting anything. Where one exists, onboarding gets far easier. Often there is none, because the tool your customer is leaving has no API worth using, or because the data was never in a tool at all.</p>
<p>A data pipeline moves files on a schedule. A partner drops a file on a server every night, a job picks it up, and nobody watches it unless it breaks. That is a real category with real products in it, and a different shape of work from a person sitting down with one file on their first day.</p>
<p>Product onboarding is a different thing again: the tours, the checklists, the welcome emails. A customer can finish every step of a product tour and still have an empty account.</p>
<h2 id="nothing-in-the-product-works-until-the-data-is-in">Nothing in the product works until the data is in</h2>
<p>The account is created, the team is invited, and then someone has to put the data in. Until that happens the product is a set of empty screens and the value the customer paid for is theoretical. The dashboard, the first report, the automation that saves them an afternoon, all of it waits on the data being there, which is why onboarding gets attention out of proportion to how small it looks on a roadmap.</p>
<h2 id="getting-the-file-in-whatever-shape-it-arrives">Getting the file, in whatever shape it arrives</h2>
<p>You do not control the format. The customer exports from what they have, so CSV arrives from one team and XLSX from another, with XLS, XLSB, or ODS turning up from a machine nobody has updated in a while. JSON and XML appear when a developer on their side handled the export. Any tool promising to accept any file is promising something it cannot check, and the useful question is which formats it reads and what it does with the ones it cannot.</p>
<p>The source of a file tells you more than its extension does. Payroll data comes out of Workday or ADP. Accounting data comes out of QuickBooks, Xero, or NetSuite. Product catalogs come out of Shopify, and contact lists come out of Outlook or Google Contacts. Each of those exports has its own habits: a title row sitting above the headers, a column of internal IDs nobody needs, a total row at the bottom that is not a record at all.</p>
<h2 id="reading-what-the-file-says">Reading what the file says</h2>
<p>Reading a file sounds like the technical part, and it has the most solved problems in it. Parsers are mature and mostly free. The difficulty is that the file is often not the clean grid a parser expects. A spreadsheet saved in Germany separates its columns with semicolons, a file saved as Latin-1 turns accented names into nonsense when it is read as UTF-8, and rows arrive with more cells than the header row promised.</p>
<p>I wrote that whole catalog up separately in <a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>, so I will leave it there. It is the smallest part of the job, and the rest of this guide is about what comes after it.</p>
<h2 id="matching-their-columns-to-your-fields">Matching their columns to your fields</h2>
<p>Take one file and follow it through the rest of this guide: a staff export from the payroll system your customer is leaving, forty thousand employees, saved out of Excel that morning.</p>
<p>Your product has fields, the file has columns, and column matching is the step that decides which column feeds which field. It cannot be hardcoded, because the same field arrives under a different name from every customer. In the staff export the identifier is headed Staff No, in the next customer's file it is Employee ID or EmpID, and all three feed the same employeeId field, the way First Name, fname, and Contact First all mean firstName. Write a parser for one customer's header set and you have written the first of many.</p>
<p>The general solution is to match automatically where the names are close enough, then show the person what was matched and let them correct it. Fuzzy matching gets a good share of the columns on its own and the person handles the rest. That correction half carries the weight. A confident wrong guess is harder to spot than an empty dropdown, so automatic matching the person cannot override does more damage than no matching at all.</p>
<h2 id="the-values-inside-the-columns">The values inside the columns</h2>
<p>Getting the column right does not mean the values inside it are right, and in practice this is the stage that takes the longest. The staff export has an employment type column, and it matched your employment type field cleanly. Your field accepts Full time, Part time, and Contractor. The column contains FT, PT, Contract, Temp, Freelance, and a blank. The same gap opens everywhere else: a country field expecting a two letter code meets United States, USA, US, and America, and a status field expecting active or inactive meets Y, N, TRUE, FALSE, 1, and 0, sometimes in the same column.</p>
<p>None of this is broken data. It is one company's vocabulary meeting another company's vocabulary, and the translation between them is a decision a person has to make. Nothing in the file says whether Temp belongs in Part time or in Contractor, and only your customer can settle that.</p>
<p>What makes this stage hard to build is that the list of distinct values is unknown until the file is open. A schema can be written in advance, but a value map depends on what this particular customer typed into their spreadsheet over the last three years. So the work is to collect every distinct value in the column, show them beside the options your field accepts, let the person map them once, and apply that decision to every row that uses it.</p>
<p>It is also the stage where a mistake is hardest to see. A column mapped to the wrong field shows up in the preview. A value mapped to the wrong option looks correct.</p>
<h2 id="checking-the-rows-against-your-rules">Checking the rows against your rules</h2>
<p>Validation is the layer that decides whether a row is allowed into your system. It confirms that required fields are present, that the email column holds email addresses, that numbers are numbers even when they are written with a comma for a decimal point, and that identifiers meant to be unique are unique inside the file, so two people sharing a Staff No get caught before either of them lands. Dates need their own care, because a start date written as 03/04 has to be resolved to a real day rather than a guess.</p>
<p>The checks that matter most are often the ones only your own system can answer: whether this employee is already in your system, whether the manager ID in a row points at someone who is also in the file, whether a product code in a different customer's file is one you actually stock. None of those can be answered by looking at the file alone, which means an importer that validates shape and nothing else will pass rows your database later rejects.</p>
<p>One limit is worth stating plainly: validation confirms that a value is well formed, not that it is true. A phone number with the right number of digits, belonging to the wrong person, passes every check there is.</p>
<h2 id="where-the-person-fixes-what-is-wrong">Where the person fixes what is wrong</h2>
<p>By now the staff export has been read, matched, translated, and checked, and nine hundred of its forty thousand rows have something wrong with them: a missing start date, a Temp nobody decided about, the two people sharing a Staff No. The loop I saw over and over before building Updog went like this: the person downloads an error report, opens the file in Excel, hunts for the rows, fixes them, saves, and uploads again, then finds the next batch. That is where onboarding time goes, and it is avoidable, because everything needed to fix the data is already on the screen in front of them.</p>
<p>Fixing in place takes more than an editable table. The person needs to filter down to the rows with problems, so nine hundred are not hiding inside forty thousand, and they need to fix a repeated mistake once instead of nine hundred times, the way a spreadsheet fills a column. Undo matters too, because a bulk change applied to the wrong selection is otherwise a reason to start over. The screen also has to stay responsive with the full file loaded, since a table that stutters at forty thousand rows sends the person back to Excel, which handles that size without complaint.</p>
<h2 id="the-import-that-happens-again-next-month">The import that happens again next month</h2>
<p>Onboarding gets described as a one time event, and it rarely is. The corrected file arrives two days later, new hires arrive at the start of the next month, and the catalog gets refreshed for the season. The same person comes back to the same screen, and they expect it to remember what they decided last time, or at least not to make them decide all of it again.</p>
<p>There is a point where this stops being onboarding. If the file arrives on the same day every month, from a machine rather than a person, and nobody is meant to be watching, you are describing a feed rather than an import. That is server work and it wants a different product. Knowing which of the two you have is worth more than any feature comparison, because the tools are built for different jobs.</p>
<h2 id="who-does-this-work-today">Who does this work today</h2>
<p>Four approaches are in active use. The first is doing it by hand for the customer. This works, it is often the right first move, and it stops working at the point where onboarding becomes a full time job for a person who was hired to do something else.</p>
<p>The second is an engineer building an import screen. Every team has done this. A file input, a parser, and a table appear in an afternoon, and the long tail after that is the real project. I went through that math in <a href="https://updog.tech/blog/build-vs-buy-csv-importer/">build vs buy a CSV importer</a>.</p>
<p>The third is embedding an importer built for the job. It becomes a component inside your app, the customer does the work themselves, and your team stays out of the loop.</p>
<p>The fourth is running a file pipeline on a server, which is the right answer for recurring feeds between machines and a poor one for a person with a spreadsheet on their first day.</p>
<h2 id="where-updog-fits">Where Updog fits</h2>
<p>Updog is the third of those four, a JavaScript SDK you put inside your own app. It covers the stages above in the order they appear here. It reads CSV, JSON, XML, XLSX, XLS, XLSB, and ODS, matches columns to your schema, matches values to the options your fields accept, and validates against your rules. Then it hands the person a spreadsheet editor where they fix what is wrong before anything is submitted.</p>
<p>What is unusual is where the work happens. There is no Updog server in the path, and no setting or plan tier that puts one there. The SDK is a library that runs in your page, so the file is read, matched, validated, and edited in the browser of the person importing it, and the only data that moves is the rows you accept, sent to your API. For a security review, that shifts the question from which certifications a vendor holds to whether there is a vendor in the path at all.</p>
<p>Two limits are worth being honest about. There is no row cap in the SDK, so what bounds a file is the memory of the browser it opens in. We tested a million rows across twenty columns and treat that as a practical limit, though a stronger machine handles more without trouble, and a file large enough to strain the machine in front of the person is better served by server side tooling. I wrote up how the grid holds a file that size in <a href="https://updog.tech/blog/canvas-grid-performance/">a canvas grid that renders a million rows in the browser</a>. Updog also ships no AI model of its own. Column and value matching call an endpoint you host if you want AI in the loop, and fall back to fuzzy matching if you do not, so the data goes nowhere you do not already send it.</p>
<p>It is free on localhost and on preview domains, and free in production up to 100,000 rows a month. Above that, Team costs $100 a month for any number of domains.</p>
<p>Whichever of the four you choose, the work underneath is the same. Your customer has their data in their shape and needs it in yours, and the sooner that translation is done, the sooner they spend their first week looking at their own numbers inside the product they just bought.</p>]]></content:encoded></item>
<item><title>Excel Import for Logistics and Supply Chain SaaS</title><link>https://updog.tech/blog/excel-import-for-logistics-supply-chain-saas/</link><guid isPermaLink="true">https://updog.tech/blog/excel-import-for-logistics-supply-chain-saas/</guid><pubDate>Tue, 21 Jul 2026 00:00:00 GMT</pubDate><description>Suppliers send workbooks, a tab per site and quantities in cases. How to take those files into your item and stock schema with every unit settled.</description><content:encoded><![CDATA[<p>Warehouses trade in workbooks. A supplier sends a price list, a 3PL sends a
stock report, a customer sends a list of items to set up, and all three arrive
as <code>.xlsx</code> with a sheet for each topic. The workbook is how these companies
talk to each other.</p>
<p>A workbook meant for a person to open is laid out for reading. It carries a
cover block above the table, a tab for items and another for stock, and a
units column where each, case and pallet all appear.</p>
<p>Row one of the workbook a supplier sends carries the supplier's name. Row two
names the export, row three carries an effective date, row four is empty, and
the column headings start on row five.</p>
<p>A warehouse, inventory or 3PL platform keeps one item record. Its customers
export items and stock out of a WMS, an ERP or a spreadsheet somebody keeps by
hand. Each of those writes a different workbook. Moving them into your schema is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>You write the schema. The person who uploads the workbook is the operations
coordinator at the supplier, and the file came out of whatever they run.</p>
<h2 id="the-workbook-and-its-four-tabs">The workbook and its four tabs</h2>
<p>Supply chain systems hand their users workbooks. Extensiv tells you to open its
import template and "refer to the second worksheet for additional guidance".
Oracle puts the button that writes the CSV inside an "Instructions and CSV
Generation" worksheet. So a workbook arrives carrying tabs nobody wants.</p>
<pre><code class="language-plaintext">harbour-lane-items.xlsx
├── Instructions     4 lines of prose in one column
├── Item Master      4,200 items, headings on row 5
├── Stock by Site    11,600 stock lines, headings on row 1
└── Discontinued     empty</code></pre>
<p>Each tab becomes its own card with its own checkbox, labelled with the sheet
name and the file it came from. The empty tab arrives unchecked and reads
<strong>Empty sheet</strong>. The prose tab holds four lines, so it counts as data and
arrives checked. The person unchecks it before <strong>Next</strong>.</p>
<p>The two that matter go on as separate units. Column matching runs once per unit,
so the screen reads <strong>Match columns (1 of 2)</strong> and each tab gets its own
mapping.</p>
<h2 id="where-the-header-row-actually-is">Where the header row actually is</h2>
<p>Updog looks for the table first and classifies its top row second. A leading row
that fills less than half the sheet's column span counts as preamble. A name, a
title and a date stacked above the headings cost nothing.</p>
<p>The first row that clears that bar is scored. The type flip below it is weighted
heaviest. The body's consistency, the row's own text, its fullness and its
repeats carry the rest. Score 0.55 and above is confident. Under that, the
wizard adds a header-selection step and the person picks the row from a
preview.</p>
<div class="blog-table blog-table--fixed blog-table--logistics-detection"><table>
<thead>
<tr>
<th>Sheet shape</th>
<th>Headings found on</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>three title rows, a blank row, then the headings</td>
<td>row 5</td>
<td>0.73</td>
</tr>
<tr>
<td>headings on row one, half the columns numeric</td>
<td>row 1</td>
<td>0.78</td>
</tr>
<tr>
<td>a title row padded across the full width</td>
<td>row 3</td>
<td>0.61</td>
</tr>
<tr>
<td>headings on row one, every column text</td>
<td>row 1</td>
<td>0.55</td>
</tr>
<tr>
<td>text ids and no headings anywhere</td>
<td>row 1, flagged</td>
<td>0.45</td>
</tr>
<tr>
<td>numbers and no headings anywhere</td>
<td>none, flagged</td>
<td>0.40</td>
</tr>
</tbody>
</table></div>
<p><strong>The preamble costs nothing. A missing header row does.</strong> A sheet that opens
straight into values has no labels to promote. The detector says so and hands
the choice to the person. Tick <strong>My data has no header row</strong> on that
screen and every row stays as data under the names <code>Column 1</code>, <code>Column 2</code> and so
on. With two uncertain sheets there are two screens, in upload order, and the
sheets that scored well are skipped.</p>
<p>The item tab above scores 0.73 and never reaches that screen. Its 4,200 rows
land with the four rows above the headings dropped.</p>
<p><code>Item Master</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row"><th class="sheet__number" scope="row">1</th><td class="sheet__cell" colspan="10">Harbour Lane Provisions</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell" colspan="10">Item master export</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell" colspan="10">Effective 01 Sep 2026</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">Item</td><td class="sheet__cell">Supplier Ref</td><td class="sheet__cell">Description</td><td class="sheet__cell">Unit</td><td class="sheet__cell">Pack</td><td class="sheet__cell">On Hand</td><td class="sheet__cell">Site</td><td class="sheet__cell">Lot</td><td class="sheet__cell">Origin</td><td class="sheet__cell">Gross Wt (kg)</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">HLP-1042</td><td class="sheet__cell">884120</td><td class="sheet__cell">Rye crispbread 200g</td><td class="sheet__cell">CS</td><td class="sheet__cell">12/CS</td><td class="sheet__cell">40</td><td class="sheet__cell">LDN1</td><td class="sheet__cell">B7741</td><td class="sheet__cell">SE</td><td class="sheet__cell">0.18</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">HLP-1043</td><td class="sheet__cell">884121</td><td class="sheet__cell">Oat crackers 150g</td><td class="sheet__cell">EA</td><td class="sheet__cell">1/EA</td><td class="sheet__cell">77</td><td class="sheet__cell">MAN2</td><td class="sheet__cell">B7742</td><td class="sheet__cell">GB</td><td class="sheet__cell">0.28</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">8</th><td class="sheet__cell">HLP-1045</td><td class="sheet__cell">884123</td><td class="sheet__cell">Seeded flatbread 220g</td><td class="sheet__cell">Each</td><td class="sheet__cell">12/CS</td><td class="sheet__cell">151</td><td class="sheet__cell">ldn1</td><td class="sheet__cell">B7744</td><td class="sheet__cell">PL</td><td class="sheet__cell">0.48</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">9</th><td class="sheet__cell">HLP-1048</td><td class="sheet__cell">884126</td><td class="sheet__cell">Barley crackers 160g</td><td class="sheet__cell">Master Ctn</td><td class="sheet__cell">24/CS</td><td class="sheet__cell">262</td><td class="sheet__cell">GLA1</td><td class="sheet__cell">B7747</td><td class="sheet__cell">United Kingdom</td><td class="sheet__cell">0.78</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">10</th><td class="sheet__cell">HLP-1055</td><td class="sheet__cell">884133</td><td class="sheet__cell">Spelt breadsticks 125g</td><td class="sheet__cell">PLT</td><td class="sheet__cell">480/PLT</td><td class="sheet__cell">521</td><td class="sheet__cell">MAN2</td><td class="sheet__cell">B7754</td><td class="sheet__cell">Italy</td><td class="sheet__cell">1.48</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">4194 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4205</th><td class="sheet__cell">HLP-6198</td><td class="sheet__cell">889276</td><td class="sheet__cell">Wholegrain rye loaf 400g</td><td class="sheet__cell">EA</td><td class="sheet__cell">1/EA</td><td class="sheet__cell">94</td><td class="sheet__cell">GLA1</td><td class="sheet__cell">B8397</td><td class="sheet__cell">GB</td><td class="sheet__cell">0.42</td></tr></tbody></table>
<p><code>CS</code> is a unit of measure. <code>12/CS</code> is a pack configuration with the unit welded
onto it. <code>Master Ctn</code> is a third way of writing the second one. Each value is
correct inside the system that wrote it.</p>
<h2 id="the-item-record-on-your-side">The item record on your side</h2>
<p>Ten columns, and the option list comes from a vocabulary a platform in your
position publishes. ShipHero names four packaging levels. An Each is the base
product. An Inner Pack is a box of Eaches. A Master Case holds Inner Packs or
Eaches, and a Pallet holds Master Cases or Eaches. ShipHero also publishes
<code>Country Of Manufacture</code> as a two-digit country code, so the origin column
carries a <code>regex</code> rule.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const UNITS = ["Each", "Inner Pack", "Master Case", "Pallet"];

export const columns: DataEditorColumn[] = [
  {
    id: "itemCode",
    title: "Item code",
    validators: [{ type: "required" }],
  },
  { id: "supplierItemCode", title: "Supplier item code" },
  {
    id: "description",
    title: "Description",
    validators: [{ type: "required" }],
  },
  {
    id: "uom",
    title: "Unit of measure",
    editor: { type: "select", options: UNITS },
    validators: [{ type: "required" }],
    dependentFields: ["unitsPerPack"],
  },
  {
    id: "unitsPerPack",
    title: "Units per pack",
    editor: { type: "number" },
    validators: [{ type: "number", min: 1, decimalPlaces: 0 }],
  },
  {
    id: "quantityOnHand",
    title: "Quantity on hand",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 0 }],
  },
  {
    id: "siteCode",
    title: "Site code",
    validators: [{ type: "required" }],
  },
  { id: "lotCode", title: "Lot code" },
  {
    id: "countryOfOrigin",
    title: "Country of origin",
    validators: [
      { type: "regex", pattern: "^[A-Z]{2}$", message: "Two capital letters" },
    ],
  },
  {
    id: "grossWeightKg",
    title: "Gross weight (kg)",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 3 }],
  },
];</code></pre>
<p>Oracle publishes the model under that enum. A unit belongs to a class with a
base unit, and a standard conversion says how many base units it holds. So
<code>1 Case (CS) = 24 Each (EA)</code> is a fact about the customer's catalogue, and the
string in the cell is a label.</p>
<h2 id="what-your-warehouse-cannot-receive">What your warehouse cannot receive</h2>
<div class="blog-table blog-table--fixed blog-table--logistics-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Item</code></td>
<td>the code the supplier prints on the carton</td>
<td><code>required</code></td>
</tr>
<tr>
<td><code>Supplier Ref</code></td>
<td>the number the supplier's own system holds</td>
<td>text, and an alias to reach the field</td>
</tr>
<tr>
<td><code>Unit</code></td>
<td><code>EA</code>, <code>CS</code>, <code>CTN</code>, <code>IP</code>, <code>MC</code>, <code>PLT</code>, <code>Dozen</code>, and an empty cell</td>
<td>four options</td>
</tr>
<tr>
<td><code>Pack</code></td>
<td><code>12/CS</code>, <code>1/EA</code>, <code>480/PLT</code>, <code>12</code></td>
<td>a whole number of one and up</td>
</tr>
<tr>
<td><code>On Hand</code></td>
<td>a count whose meaning depends on the column beside it</td>
<td>a whole number of zero and up</td>
</tr>
<tr>
<td><code>Site</code></td>
<td><code>LDN1</code> and <code>ldn1</code> for one warehouse</td>
<td><code>required</code></td>
</tr>
<tr>
<td><code>Origin</code></td>
<td><code>SE</code>, <code>gb</code>, <code>Italy</code>, <code>United Kingdom</code></td>
<td>two capital letters</td>
</tr>
<tr>
<td><code>Gross Wt (kg)</code></td>
<td>a weight whose unit lives in the heading</td>
<td>three decimal places</td>
</tr>
</tbody>
</table></div>
<p>Those failures in their generic form are collected in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>. Two entries on that
list behave in a way worth watching, and both are below.</p>
<h2 id="when-the-schemas-own-names-collide">When the schema's own names collide</h2>
<p>The stock tab writes the same data in the WMS's words. Four of its seven
headings end in <code>Code</code>. Four columns of the schema above end in <code>Code</code> too, so
the word carries no information.</p>
<div class="blog-table blog-table--fixed blog-table--logistics-ties"><table>
<thead>
<tr>
<th>Header</th>
<th>Scores 70 against</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Product Code</code></td>
<td><code>itemCode</code>, <code>siteCode</code>, <code>lotCode</code></td>
</tr>
<tr>
<td><code>UOM Code</code></td>
<td><code>uom</code>, <code>itemCode</code>, <code>siteCode</code>, <code>lotCode</code></td>
</tr>
<tr>
<td><code>Whse Code</code></td>
<td><code>itemCode</code>, <code>siteCode</code>, <code>lotCode</code></td>
</tr>
<tr>
<td><code>Batch Code</code></td>
<td><code>itemCode</code>, <code>siteCode</code>, <code>lotCode</code></td>
</tr>
</tbody>
</table></div>
<p>Matching solves the whole board at once and keeps the highest total. Every
arrangement of those four scores the same total. So the answer moves with the
order the headings sit in.</p>
<div class="blog-table blog-table--fixed blog-table--logistics-order"><table>
<thead>
<tr>
<th>Order in the file</th>
<th>Where each one lands</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Product Code</code>, <code>UOM Code</code>, <code>Whse Code</code>, <code>Batch Code</code></td>
<td>item, unit, site, lot</td>
</tr>
<tr>
<td><code>Batch Code</code>, <code>Whse Code</code>, <code>UOM Code</code>, <code>Product Code</code></td>
<td><strong>item</strong>, <strong>site</strong>, unit, <strong>lot</strong></td>
</tr>
<tr>
<td><code>Whse Code</code>, <code>Batch Code</code>, <code>Product Code</code>, <code>UOM Code</code></td>
<td><strong>item</strong>, <strong>site</strong>, <strong>lot</strong>, unit</td>
</tr>
</tbody>
</table></div>
<p><strong>A header that reaches nothing leaves an empty column. A header that ties with
three others fills one and looks finished.</strong> <code>Qty</code> on the same tab reaches
nothing, and so does <code>Supplier Ref</code> on the item tab. The person sees both.</p>
<p>The alias table settles all of it. An alias under a column id scores 90, which
outranks every tie at 70. Check the built-in table against your own vocabulary
first. It carries <code>dob</code>, <code>salary</code> and <code>hiredate</code>, and it carries nothing for
<code>SKU</code>, <code>Qty</code>, <code>Warehouse</code>, <code>Batch</code> or <code>COO</code>.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    itemCode: ["item", "product code", "sku"],
    supplierItemCode: ["supplier ref", "vendor part"],
    uom: ["unit", "uom code"],
    unitsPerPack: ["pack", "pack size", "units/case"],
    quantityOnHand: ["on hand", "qty"],
    siteCode: ["site", "whse code", "warehouse"],
    lotCode: ["lot", "batch code"],
    countryOfOrigin: ["origin", "coo"],
    grossWeightKg: ["gross wt (kg)", "net wt"],
  },
  values: {
    Each: ["ea", "ea.", "pc", "piece"],
    "Inner Pack": ["ip", "inner ctn", "inner"],
    "Master Case": ["cs", "ctn", "carton", "mc", "master ctn"],
    Pallet: ["plt", "pal", "plt."],
  },
};</code></pre>
<h2 id="each-ea-and-dozen">Each, EA and Dozen</h2>
<p>Value matching runs once for the whole upload and collects the unit column
across both tabs. Nineteen distinct strings arrive and sixteen of them land.</p>
<p><code>Each</code>, <code>Pallet</code>, <code>Case</code> and <code>Inner</code> land on their own. An exact string is taken
at 100, and a value sitting inside an option at 80. <code>Inner Pk</code> and <code>Master Ctn</code>
land on a shared word at 70. The <code>values</code> table above carries the rest, so <code>EA</code>,
<code>CS</code>, <code>CTN</code>, <code>IP</code>, <code>MC</code>, <code>PLT</code> and <code>PAL</code> reach an option at 90.</p>
<p>Three are left, and they fail for a different reason. <code>BX</code>, <code>DZ</code> and <code>Dozen</code>
name packaging your schema does not carry. No alias helps. Either the schema
grows a fifth option, or the person picks the nearest one and owns that choice.</p>
<p><strong>A unit nobody mapped arrives as an empty cell.</strong> The string the supplier wrote
stays behind. In the sample above that leaves 840 rows with no unit, and the
<code>required</code> rule on that column puts every one of them in front of the person.</p>
<p>One landing is worth a second look. <code>Case</code> reaches <code>Master Case</code> because one
string sits inside the other. Whether the supplier meant a master case or an
inner pack is nowhere in the file.</p>
<h2 id="the-pack-size-welded-to-the-unit">The pack size welded to the unit</h2>
<p>The pack column carries <code>12/CS</code> where your schema wants <code>12</code>. A number column is
reduced to its canonical form first. <code>12/CS</code> is a shape the importer cannot
reduce, so it reaches the <code>transformer</code> whole.</p>
<pre><code class="language-ts">{
  id: "unitsPerPack",
  title: "Units per pack",
  editor: { type: "number" },
  transformer: (value) => {
    const digits = String(value ?? "").match(/^\s*(\d+)/);
    return digits ? digits[1] : value;
  },
  validators: [
    { type: "number", min: 1, decimalPlaces: 0 },
    {
      type: "function",
      fn: (value, row) =>
        row.uom === "Each" &#x26;&#x26; String(value) !== "1"
          ? { level: "error", message: "An Each holds one unit" }
          : null,
    },
  ],
}</code></pre>
<p><code>12/CS</code> is stored as <code>12</code>, <code>480/PLT</code> as <code>480</code> and <code>1/EA</code> as <code>1</code>. The unit half
is thrown away on purpose. That unit already has a column of its own, two fields
to the left.</p>
<h2 id="a-quantity-with-no-unit-behind-it">A quantity with no unit behind it</h2>
<p>Row 8 of that file says the unit is <code>Each</code> and the pack is twelve. One of those
two is wrong, and a count of 151 means either 151 pieces or 1,812 of them.</p>
<p>The <code>function</code> rule above reads the whole row, so it weighs the pack against the
unit beside it. <code>dependentFields</code> sits on the column the person edits and names
the columns to check again. Changing the unit rechecks the pack. In the sample
that rule flags 210 rows, and <code>gb</code>, <code>Italy</code> and <code>United Kingdom</code> fail the
two-letter rule on top of it.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey={["itemCode", "siteCode", "lotCode"]}
  synonyms={synonyms}
  onComplete={async (result) => {
    for (const source of result.sources) {
      const clean = source.rows.filter((r) => r.isValid);
      await postItems(source.sourceName, clean);
    }
  }}
/></code></pre>
<p>The key names three columns, because one item sits in several sites under
several lots. Each tab lands as its own data source, named
<code>harbour-lane-items.xlsx - Item Master</code>. So <code>onComplete</code> hands you the rows tab
by tab.</p>
<h2 id="what-updog-knows-about-warehouses">What Updog knows about warehouses</h2>
<p>Nothing. There is no item template, no unit list, no WMS connector and no
per-industry schema to start from. The ten columns, the four options, the alias
table, the transformer and the two rules live in your repository. Updog
Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A price list that
arrives as a PDF or a scanned image goes to a parser you supply, and the rows it
returns walk the same path, which is written up in
<a href="https://updog.tech/blog/import-pdf-with-updog/">importing PDFs with your own parser</a>.</p>
<p>The unit enum is the honest cost. Four options cover the packaging your platform
stores. Every supplier who ships by the dozen lands in front of a person. That
is the trade a fixed list makes, and widening the list moves the same decision
into your database.</p>
<h2 id="what-the-schema-leaves-out">What the schema leaves out</h2>
<p>There is no ordered quantity beside the received one, no rate, no delivery
window and no partner id. Every one of those belongs to a file that arrives on a
schedule. This import is one person opening one workbook and pressing a button.</p>
<p>What the ten columns hold is the state of a catalogue on the day somebody sent
it. If that is the file your customers attach to an email, then the header row,
the unit column and the pack size are the whole job. All three are settled
before a single row reaches your API.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Firebase Firestore</title><link>https://updog.tech/blog/import-csv-into-firebase/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-firebase/</guid><pubDate>Mon, 20 Jul 2026 00:00:00 GMT</pubDate><description>Map a messy CSV in the browser, post the rows to a Cloud Function you own, and write them into Firestore with a batched set and merge on a key from the file.</description><content:encoded><![CDATA[<p>A Cloud Firestore collection holds documents, and a document is a map of fields. A field can carry a string, a number, a timestamp, a map of its own, or an array. A CSV row is flat. Every column sits at the top level, every value arrives as text, and nothing nests. Turning one shape into the other is the work, and the place it happens is code you own.</p>
<p>A physiotherapy platform receives this roster when a customer leaves their old practice-management system.</p>
<p><code>physio-roster.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Patient Ref</td><td class="sheet__cell">Full Name</td><td class="sheet__cell">Mobile</td><td class="sheet__cell">Date of Birth</td><td class="sheet__cell">Clinic</td><td class="sheet__cell">SMS Consent</td><td class="sheet__cell">Care Plan</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">PT-10231</td><td class="sheet__cell">Aoife Brennan</td><td class="sheet__cell">+44 7700 900812</td><td class="sheet__cell">03/07/1984</td><td class="sheet__cell">NORTHGATE</td><td class="sheet__cell">Y</td><td class="sheet__cell">Post-op knee</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">PT-10232</td><td class="sheet__cell">Marcus Hale</td><td class="sheet__cell">07700 900 813</td><td class="sheet__cell">17.11.1990</td><td class="sheet__cell">Riverside Physio</td><td class="sheet__cell">yes</td><td class="sheet__cell">Lower back</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">PT-10233</td><td class="sheet__cell">Priya Raman</td><td class="sheet__cell">+44 7700 900814</td><td class="sheet__cell">22/09/1978</td><td class="sheet__cell">Harbour Pt.</td><td class="sheet__cell">TRUE</td><td class="sheet__cell">Shoulder</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">PT-10234</td><td class="sheet__cell">Tom Okafor</td><td class="sheet__cell">07700900815</td><td class="sheet__cell">05/02/1996</td><td class="sheet__cell">CL-03</td><td class="sheet__cell">N</td><td class="sheet__cell">Post-op knee</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">313 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">319</th><td class="sheet__cell">PT-10548</td><td class="sheet__cell">Nadia Whitcombe</td><td class="sheet__cell">+44 7700 900927</td><td class="sheet__cell">14/06/1988</td><td class="sheet__cell">Riverside Physio</td><td class="sheet__cell">Y</td><td class="sheet__cell">Lower back</td></tr></tbody></table>
<p>Seven flat headers, and the document keeps its own shape. <code>Patient Ref</code> becomes the document id and the <code>ref</code> field, <code>Mobile</code> and <code>SMS Consent</code> move inside a map the file has no column for, and <code>Care Plan</code> becomes an array. Two mobile numbers carry a country prefix and spaces, one carries spaces alone, and a fourth is bare digits. One date of birth reads <code>03/07/1984</code> and the next reads <code>17.11.1990</code>. The consent column says <code>Y</code>, <code>yes</code>, <code>TRUE</code> and <code>N</code>. The clinic column says <code>NORTHGATE</code>, <code>Riverside Physio</code>, <code>Harbour Pt.</code> and <code>CL-03</code>.</p>
<p>The person opens the importer inside your app and drops the roster in. Updog Importer parses it in the browser, lines the headers up against your schema, and puts every value on the screen. Your <code>onComplete</code> handler receives the rows. The handler posts them in chunks to a Cloud Function you own. The function builds one document per row and commits a write batch. Cloud Firestore stores the documents.</p>
<p>Updog runs no server anywhere between that browser and Cloud Firestore.</p>
<h2 id="step-1-decide-what-one-document-holds">Step 1. Decide what one document holds</h2>
<p>Start with the shape a single patient takes at <code>patients/PT-10231</code>.</p>
<pre><code class="language-json">{
  "ref": "PT-10231",
  "name": "Aoife Brennan",
  "dateOfBirth": "1984-07-03",
  "contact": {
    "mobile": "+447700900812",
    "smsConsent": true
  },
  "clinic": {
    "name": "Northgate",
    "tenantId": "clinic-group-7"
  },
  "carePlans": ["Post-op knee"],
  "updatedAt": "2026-08-18T09:14:22.310Z"
}</code></pre>
<p><code>contact</code> and <code>clinic</code> are maps, which Firestore describes as an object embedded within a document, and an indexed map can be queried on its subfields. <code>carePlans</code> is an array. Firestore caps one document at 1 MiB and allows twenty levels of nesting inside a map or an array, so a roster document sits well inside both.</p>
<p>The document id is the piece that decides what a second import does. <code>PT-10231</code> comes straight out of the file, so the same reference reaches the same document every time. Firestore publishes the rules an id has to satisfy. It must be valid UTF-8, stay within 1,500 bytes, hold no forward slash, avoid being a bare <code>.</code> or <code>..</code>, and avoid matching the regular expression <code>__.*__</code>. A reference like <code>PT-10231</code> clears all five.</p>
<p>That choice costs something, and the cost is published. Firestore's best practices warn against monotonically increasing document ids, naming the shape <code>Customer1</code>, <code>Customer2</code>, <code>Customer3</code>, because sequential ids can create hotspots that add latency. Automatic ids avoid it, since Firestore allocates those with a scatter algorithm. A roster import trades the scatter for a document you can find again by its reference, and the same page tells you how fast to ramp when the write rate climbs.</p>
<h2 id="step-2-describe-the-flat-file-to-updog-importer">Step 2. Describe the flat file to Updog Importer</h2>
<p>The <code>columns</code> array is your document written for the person looking at the file. Each entry sets a title they read, an editor that decides how a cell is typed, and validators that mark what fails.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const CLINICS = ["Northgate", "Riverside", "Harbour Point"];

export const columns: DataEditorColumn[] = [
  {
    id: "patientRef",
    title: "Patient reference",
    size: 150,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^PT-\\d{5}$" },
      { type: "unique" },
    ],
  },
  {
    id: "fullName",
    title: "Full name",
    size: 200,
    validators: [{ type: "required" }],
  },
  {
    id: "mobile",
    title: "Mobile",
    size: 170,
    transformer: (value) => {
      const digits = String(value).replace(/[^\d+]/g, "");
      return digits.startsWith("0") ? "+44" + digits.slice(1) : digits;
    },
    validators: [{ type: "regex", pattern: "^\\+\\d{10,15}$" }],
  },
  {
    id: "dateOfBirth",
    title: "Date of birth",
    size: 150,
    editor: { type: "date" },
    validators: [{ type: "required" }, { type: "date" }],
  },
  {
    id: "clinic",
    title: "Clinic",
    size: 170,
    editor: { type: "select", options: CLINICS, enableCustomValue: false },
    validators: [{ type: "required" }, { type: "oneOf", values: CLINICS }],
  },
  {
    id: "smsConsent",
    title: "SMS consent",
    size: 130,
    editor: { type: "select", options: ["Yes", "No"], enableCustomValue: false },
  },
  {
    id: "carePlan",
    title: "Care plan",
    size: 180,
  },
];</code></pre>
<p>The roster decides which editor each column carries. The <code>date</code> editor turns <code>03/07/1984</code> and <code>17.11.1990</code> into <code>1984-07-03</code> and <code>1990-11-17</code>. Detection reads the first value with a part above 12 and settles the whole file on that, so the <code>17</code> in row two is what makes row one land on the third of July. The <code>select</code> editor with <code>enableCustomValue</code> off holds the clinic column to three options and sends everything else to the value matching step.</p>
<p>Two validators mirror the destination. The <code>regex</code> on <code>patientRef</code> pins the format that becomes a document id, so a value carrying a slash gets flagged in the grid while the person can still fix it. The <code>unique</code> rule catches the same reference appearing twice in one roster, since both rows would resolve to a single document.</p>
<p>The <code>transformer</code> on <code>mobile</code> is where the flat value gets settled before it travels. Updog already strips zero-width characters, turns non-breaking spaces into ordinary ones, and trims both ends of every cell. Inner spaces survive that pass on purpose, so <code>+44 7700 900812</code> reaches the transformer intact and leaves it as <code>+447700900812</code>. The same function rewrites the leading zero on <code>07700 900 813</code>. Transformers run on text, number and date columns, so a select column takes its value from matching. For the install and the modal wiring underneath these props, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="step-3-match-the-values-the-old-system-used">Step 3. Match the values the old system used</h2>
<p>The <code>synonyms</code> prop teaches matching the words your customers already type, and the mount ties the schema to the handler.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Patient>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="patientRef"
  blockSubmitOnError
  synonyms={{
    columns: { patientRef: ["patient ref", "patient no", "chart no"] },
    values: { "Harbour Point": ["CL-03"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p>Matching scores every imported value against every option and takes the best one at 60 or above. <code>NORTHGATE</code> scores 100, because matching lowercases and strips spaces before it compares. <code>Riverside Physio</code> scores 80, since it contains <code>Riverside</code> once both sides are normalized. <code>Harbour Pt.</code> scores 70 on word overlap, one word of two against <code>Harbour Point</code>. <code>CL-03</code> shares nothing with any option and scores zero, which is why it sits in <code>synonyms.values</code>. The consent column needs no help at all. <code>yes</code> is an exact hit, and the built-in table already files <code>y</code> and <code>true</code> under <code>yes</code>, along with <code>n</code> and <code>false</code> under <code>no</code>.</p>
<p>Every value the person maps by hand returns on the result as <code>learnedSynonyms</code>, ready to store for the next import. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> shows where those live between rosters. <code>primaryKey</code> points at <code>patientRef</code> as well, so two files in one import merge on the same reference the document id uses.</p>
<p>Every snippet here is React. The web component build takes the same props, so a Vue, Angular or Svelte app writes the same schema and the same handler.</p>
<h2 id="step-4-chunk-the-result-inside-the-handler">Step 4. Chunk the result inside the handler</h2>
<p>When the person submits, every patient row reaches your handler grouped by source, tagged with <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. The person can drop three rosters into a single import, and each one lands in its own source entry. The handler flattens them before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 500;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Patient>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  const idToken = await auth.currentUser.getIdToken();

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch(IMPORT_ENDPOINT, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + idToken,
      },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>The token comes off the Firebase Auth session your app already holds, and every chunk carries it on the <code>Authorization</code> header. Five hundred is the chunk size, and Firestore no longer sets it. Its release notes carry an entry dated 29 March 2023 that reads "Firestore no longer limits the number of writes that can be passed to a <code>Commit</code> operation or performed in a transaction. Previously, the limit was 500." Three caps still stand. A Firestore API request tops out at 10 MiB. A 2nd gen Cloud Functions HTTP request accepts 32MB of uncompressed body, and that one cannot be raised. A single commit may perform 500 field transformations on one document, which is the 500 that survived.</p>
<p>One patient row of these seven fields serializes to 170 bytes.</p>
<pre><code class="language-json">{"patientRef":"PT-10231","fullName":"Aoife Brennan","mobile":"+447700900812","dateOfBirth":"1984-07-03","clinic":"Northgate","smsConsent":"Yes","carePlan":"Post-op knee"}</code></pre>
<p>Five hundred of those reach 83 KB, and 32MB holds around 188,000 of them. So the body cap is nowhere near binding at this chunk size. Five hundred is a choice about two other things. It is the size of the unit that fails together, and it is the length of the wait the person sits through with the confirm dialog open. Run the same division against your own widest document before you raise it, because a document carrying forty fields changes the answer.</p>
<p><strong>Throw when a chunk comes back with an error.</strong> Updog waits on your handler and wipes the editor the moment your promise resolves. A handler that catches the failure and returns looks like success, so the grid empties with the patients unsaved. A thrown error holds the whole roster, its mappings and its fixes on screen, so the person can submit again against rows they still see. Persist anything you want to keep inside the handler, <code>learnedSynonyms</code> included. The editor hands the result over once, then clears its rows and its mappings the moment the promise resolves.</p>
<p><code>blockSubmitOnError</code> on the mount holds submit disabled while any row carries an error, which is what keeps the <code>isValid</code> filter from dropping rows on the floor. <a href="https://updog.tech/blog/import-csv-into-supabase/">Importing a CSV into Supabase</a> runs the same chain against a SQL table, where a published statement timeout sets the ceiling.</p>
<h2 id="step-5-write-the-documents-from-your-own-function">Step 5. Write the documents from your own function</h2>
<p>The function is where the flat row becomes a nested document and where the browser stops.</p>
<pre><code class="language-ts">import { initializeApp } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
import { FieldValue, getFirestore } from "firebase-admin/firestore";
import { onRequest } from "firebase-functions/v2/https";

initializeApp();
const db = getFirestore();
const REFERENCE = /^PT-\d{5}$/;

export const importPatients = onRequest(
  { cors: ["https://app.example.com"], timeoutSeconds: 120 },
  async (request, response) => {
    const header = request.get("Authorization") ?? "";
    let claims;
    try {
      claims = await getAuth().verifyIdToken(header.replace("Bearer ", ""));
    } catch {
      response.status(401).json({ message: "Not signed in" });
      return;
    }

    const rows = request.body.rows;
    const batch = db.batch();

    for (const row of rows) {
      if (!REFERENCE.test(row.patientRef)) {
        response.status(400).json({ message: "Bad reference in the file" });
        return;
      }

      const contact: Record&#x3C;string, unknown> = { mobile: row.mobile };
      if (row.smsConsent !== undefined) {
        contact.smsConsent = row.smsConsent === "Yes";
      }

      batch.set(
        db.collection("patients").doc(row.patientRef),
        {
          ref: row.patientRef,
          name: row.fullName,
          dateOfBirth: row.dateOfBirth,
          contact,
          clinic: { name: row.clinic, tenantId: claims.tenantId },
          carePlans: FieldValue.arrayUnion(row.carePlan),
          updatedAt: FieldValue.serverTimestamp(),
        },
        { merge: true },
      );
    }

    await batch.commit();
    response.json({ written: rows.length });
  },
);</code></pre>
<p><code>initializeApp()</code> takes no arguments here. Firebase sets <code>FIREBASE_CONFIG</code> for you inside Cloud Functions, so no key file sits in the deployment. What the Admin SDK does carry is reach. Firestore states that the server client libraries bypass all Cloud Firestore Security Rules and authenticate through Google Application Default Credentials, so the rules protecting your web clients have no say in this write. Every check the rules would have made belongs in this function.</p>
<p><code>verifyIdToken</code> is the first of those checks. It returns the decoded token when the token has the right format, has not expired, and is properly signed. Firebase notes that the method leaves revocation alone, and its own page on detecting revoked tokens covers the stricter version. The tenant comes off the decoded claims and never off the request body, which is what keeps one customer out of another customer's collection.</p>
<p>The rest is the shape change. <code>row.contact</code> never existed on the flat row, so the function builds it, and <code>row.clinic</code> becomes a map carrying the tenant beside the name. <code>smsConsent</code> arrives as the word the person read in the grid, and <code>=== "Yes"</code> turns it into the boolean the document stores. <code>arrayUnion</code> adds a care plan to the array and adds only elements not already present, so a second import of the same roster leaves the array as it was. <code>serverTimestamp()</code> stamps the time the server processed the request, with millisecond precision, which the document above shows in its ISO form.</p>
<p><code>set</code> with <code>{ merge: true }</code> is what makes the whole thing repeatable. Firebase describes <code>set</code> plainly. A document that does not exist gets created, and a document that does exist has its contents overwritten with the data you supplied, unless you ask for a merge. Merge changes that to replacing only the values in the data argument, and Firestore's own words for the rest are that fields omitted from the <code>set()</code> call remain untouched. Firestore documents one exception, a field holding an empty map, which overwrites the map on the target document.</p>
<p>That behaviour reaches further than it looks. A consent value that matched no option never reaches your function as a key at all, because Updog drops an unmapped select value from the row. Under merge, the stored consent stays exactly as the last import left it. A plain <code>set</code> would have erased it along with every other field the file did not carry. Decide which of those two you want before this ships.</p>
<h2 id="step-6-send-a-failed-chunk-back-up-the-chain">Step 6. Send a failed chunk back up the chain</h2>
<p>A write batch fails as one thing. Firestore states that a batch of writes completes atomically, and its <code>commit()</code> reference adds that the call fails the entire write when any precondition is unmet. A rejected chunk therefore leaves its 500 documents exactly as they were. The chunks that already landed stay landed. Retrying the failed one costs a rewrite of documents that already hold the same values, which is the point of keying them by the reference in the first place.</p>
<p><code>BulkWriter</code> is the other way to write, and Firestore's best practices point at it for large volumes, saying to consider a bulk writer instead of the atomic batch writer when the document count climbs. It writes in parallel and ramps up as the 500/50/5 rule describes, starting at a maximum of 500 operations a second against a new collection and adding 50 percent every 5 minutes.</p>
<pre><code class="language-ts">const writer = db.bulkWriter();
const failures = [];

writer.onWriteError((error) => {
  if (error.failedAttempts &#x3C; 5) return true;
  failures.push(error.documentRef.id);
  return false;
});

for (const row of rows) {
  writer.set(db.collection("patients").doc(row.patientRef), toDocument(row), {
    merge: true,
  });
}

await writer.close();

if (failures.length > 0) {
  response.status(502).json({ message: "Some patients failed", failures });
  return;
}</code></pre>
<p><code>close()</code> resolves when no writes are pending and is documented as never being rejected, and <code>flush()</code> says the same, because the result of each individual operation travels on its own promise. A function that awaits <code>close()</code> and returns 200 therefore reports success for a failed write. <code>onWriteError</code> is where the failures get collected. Specifying a handler overwrites the default one, which retries UNAVAILABLE and ABORTED up to ten attempts, so the snippet above sets its own ceiling at five. Collecting the failures, then answering with a status your <code>onComplete</code> treats as a failure, is what puts the rows back in front of the person.</p>
<h2 id="the-import-firebase-does-not-ship">The import Firebase does not ship</h2>
<p>Updog Importer integrates with nobody. There is no Firebase connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the function in the middle is work you do.</p>
<p>Firebase ships its own bulk paths for the other case. <code>gcloud firestore import</code> reads the output of a previous Firestore export out of a Cloud Storage bucket, which makes it the tool for moving a database between projects. Dataflow covers processing data in bulk. For a CSV specifically, Firebase documents no import in the console. Its data page covers adding a document by hand, filtering a collection and the query builder. Desktop tools like Firefoo fill that gap, and their published setup starts by adding your Firebase project to the tool. A roster your own team exported takes one of those shorter paths. The chain above exists for the roster a customer owns, reaching you through a browser in a session your app opened. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> weighs a browser doing this work against a server doing it.</p>
<h2 id="the-roster-that-arrives-again">The roster that arrives again</h2>
<p>You wrote a document shape, a schema of seven columns, a handler that chunks and throws, and one function holding the checks your security rules cannot make. The roster never leaves the machine where the person opened it. The rows travel from your own front end to your own function, and from there into Cloud Firestore, and the only party you added to the chain is yourself.</p>
<p>The same roster will arrive again, exported by a different person at the same customer. If the file carries a reference you can turn into a document id, that second import updates the documents the first one wrote.</p>]]></content:encoded></item>
<item><title>CSV Import for CRM and Sales SaaS</title><link>https://updog.tech/blog/csv-import-for-crm-sales-saas/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-crm-sales-saas/</guid><pubDate>Sun, 19 Jul 2026 00:00:00 GMT</pubDate><description>Every new customer arrives with the address book out of their old CRM. How to take those files into your own schema and finish with one row per person.</description><content:encoded><![CDATA[<p>A sales team's contact list outlives the software it lives in. It starts in
one CRM, gets exported to a spreadsheet whenever somebody needs to work on it
away from the app, picks up a column or two by hand, and comes back. Switching
CRM means handing all of that to a new product in a single file.</p>
<p>Part of that file is already known to you. Some of those people sit in your
database from a form fill or a trial signup, and the file brings a second
version of the same person under a different email address.</p>
<p>Every contact list a customer uploads has been through another CRM first, and
that system decided how a name is spelled, what a lifecycle stage is called and
which day <code>03/07/2026</code> falls on. Your schema decided all three differently.
Moving those lists into it is
<a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>The schema is yours. The file belongs to the sales operations administrator at
the customer, who exported it out of an old CRM or a mail client.</p>
<h2 id="the-contact-list-the-account-list-the-lead-list">The contact list, the account list, the lead list</h2>
<p>A contact list is the whole address book, one row per person, exported the week
a customer moves onto your product. An account list is the companies those
people work at, and it arrives as a second file with a shared column. A lead
list is neither, a purchased or scraped set of rows with no history behind it.</p>
<p>Everything below follows one contact list of 15,000 rows and the small account
file beside it.</p>
<h2 id="what-the-old-crm-wrote">What the old CRM wrote</h2>
<p>Six rows of that contact list, in the words the system that held it used. It
files a person under the family name, so that is the order the name column
carries.</p>
<p><code>northgate-contacts.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">File as</td><td class="sheet__cell">Email 1 - Value</td><td class="sheet__cell">Business Phone</td><td class="sheet__cell">Job Title</td><td class="sheet__cell">Company</td><td class="sheet__cell">Company Domain</td><td class="sheet__cell">Lifecycle</td><td class="sheet__cell">Owner</td><td class="sheet__cell">Last Activity</td><td class="sheet__cell">Source</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">Okafor, Chidera</td><td class="sheet__cell">c.okafor@brightwaterdental.com</td><td class="sheet__cell">+44 20 7946 0102</td><td class="sheet__cell">Practice Manager</td><td class="sheet__cell">Brightwater Dental Group</td><td class="sheet__cell">brightwaterdental.com</td><td class="sheet__cell">MQL</td><td class="sheet__cell">r.delacroix@northgate.example</td><td class="sheet__cell">03/07/2026</td><td class="sheet__cell">Web form</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">Vahid Sarrafzadeh</td><td class="sheet__cell">info@kestrelfreight.co.uk</td><td class="sheet__cell">020 7946 0111</td><td class="sheet__cell">Operations Lead</td><td class="sheet__cell">Kestrel Freight</td><td class="sheet__cell">kestrelfreight.co.uk</td><td class="sheet__cell">Closed Won</td><td class="sheet__cell">j.whitlock@northgate.example</td><td class="sheet__cell">2026-03-07</td><td class="sheet__cell">tradeshow</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">dr. amara ngozi</td><td class="sheet__cell">info@kestrelfreight.co.uk</td><td class="sheet__cell">+44 20 7946 0111</td><td class="sheet__cell">Director</td><td class="sheet__cell">Kestrel Freight</td><td class="sheet__cell">kestrelfreight.co.uk</td><td class="sheet__cell">Opp</td><td class="sheet__cell">j.whitlock@northgate.example</td><td class="sheet__cell">7.3.2026</td><td class="sheet__cell">Referral</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">83 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">88</th><td class="sheet__cell">Priya Raghunathan</td><td class="sheet__cell">info@sablecourt.co.uk</td><td class="sheet__cell">+44 20 7946 0148</td><td class="sheet__cell">Clinical Director</td><td class="sheet__cell">Sable Court Clinics</td><td class="sheet__cell">sablecourt.co.uk</td><td class="sheet__cell">SQL</td><td class="sheet__cell">r.delacroix@northgate.example</td><td class="sheet__cell">2026-02-19</td><td class="sheet__cell">Web form</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">1115 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1204</th><td class="sheet__cell">Boateng, Kwabena</td><td class="sheet__cell">k.boateng@fennimore.co.uk</td><td class="sheet__cell">020 7946 0163</td><td class="sheet__cell">Head of Facilities</td><td class="sheet__cell">Fennimore Estates</td><td class="sheet__cell">fennimore.co.uk</td><td class="sheet__cell">Churned</td><td class="sheet__cell">j.whitlock@northgate.example</td><td class="sheet__cell">46082</td><td class="sheet__cell">Newsletter</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="10"><span class="sheet__break-text">13796 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">15001</th><td class="sheet__cell">Marta Silveira</td><td class="sheet__cell">m.silveira@hallowfield.example</td><td class="sheet__cell">+44 20 7946 0175</td><td class="sheet__cell">Buyer</td><td class="sheet__cell">Hallowfield Interiors</td><td class="sheet__cell">hallowfield.example</td><td class="sheet__cell">Lead</td><td class="sheet__cell">r.delacroix@northgate.example</td><td class="sheet__cell">2026-03-02</td><td class="sheet__cell">tradeshow</td></tr></tbody></table>
<p><code>MQL</code> is a lifecycle stage. <code>Opp</code> is another one. <code>info@</code> is a shared mailbox
sitting on two rows that belong to two different people. The system that wrote
each of those was right by its own rules. Your schema stores a stage from a
fixed list and one row per person, so none of the three lands as written.</p>
<h2 id="the-eleven-columns-your-api-accepts">The eleven columns your API accepts</h2>
<p>The option lists come from vocabularies the sending systems publish. HubSpot
publishes eight default lifecycle stages, Subscriber, Lead,
Marketing Qualified Lead, Sales Qualified Lead, Opportunity, Customer,
Evangelist and Other, and it lets a customer add more. Zoho publishes <code>Last Name</code> as mandatory and caps it at 40 characters, and it caps an email address at
100.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const LIFECYCLE = [
  "Subscriber",
  "Lead",
  "Marketing Qualified Lead",
  "Sales Qualified Lead",
  "Opportunity",
  "Customer",
  "Evangelist",
  "Other",
];

export const columns: DataEditorColumn[] = [
  {
    id: "accountDomain",
    title: "Account domain",
    size: 200,
    validators: [{ type: "required" }],
  },
  { id: "accountName", title: "Account name", size: 200 },
  {
    id: "contactEmail",
    title: "Contact email",
    size: 240,
    validators: [{ type: "required" }, { type: "email" }],
  },
  { id: "firstName", title: "First name" },
  {
    id: "lastName",
    title: "Last name",
    validators: [
      { type: "required" },
      {
        type: "function",
        fn: (value) =>
          String(value ?? "").length > 40
            ? { level: "error", message: "Last name is over 40 characters" }
            : null,
      },
    ],
  },
  { id: "jobTitle", title: "Job title", size: 180 },
  { id: "phone", title: "Phone", size: 160 },
  {
    id: "lifecycleStage",
    title: "Lifecycle stage",
    size: 200,
    editor: { type: "select", options: LIFECYCLE, enableCustomValue: false },
    validators: [{ type: "oneOf", values: LIFECYCLE }],
  },
  {
    id: "ownerEmail",
    title: "Owner email",
    size: 240,
    validators: [{ type: "email" }],
  },
  {
    id: "lastActivityDate",
    title: "Last activity date",
    size: 170,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "sourceChannel",
    title: "Source channel",
    size: 170,
    editor: {
      type: "select",
      options: ["Web form", "Trade show", "Referral", "Cold outreach", "Other"],
    },
  },
];</code></pre>
<p>The 40-character rule is a <code>function</code> validator, because that limit belongs to
your database rather than to the file.</p>
<h2 id="what-your-database-refuses">What your database refuses</h2>
<div class="blog-table blog-table--fixed blog-table--crm-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What your schema needs</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>File as</code></td>
<td><code>Okafor, Chidera</code> and <code>Vahid Sarrafzadeh</code> in one column</td>
<td>one field, and the order settled</td>
</tr>
<tr>
<td><code>Email 1 - Value</code></td>
<td>a numbered header, and a shared mailbox on two rows</td>
<td><code>required</code>, <code>email</code>, and a key that takes a second column</td>
</tr>
<tr>
<td><code>Company</code></td>
<td>the account name, spelled its own way</td>
<td>text</td>
</tr>
<tr>
<td><code>Company Domain</code></td>
<td>the account, again, as a domain</td>
<td><code>required</code>, and half of the key</td>
</tr>
<tr>
<td><code>Lifecycle</code></td>
<td><code>MQL</code>, <code>Opp</code>, <code>Closed Won</code>, <code>Churned</code></td>
<td>eight options</td>
</tr>
<tr>
<td><code>Last Activity</code></td>
<td><code>03/07/2026</code>, <code>2026-03-07</code>, <code>7.3.2026</code>, an Excel serial</td>
<td>ISO, and two of the four stay flagged</td>
</tr>
<tr>
<td><code>Owner</code></td>
<td>an address that owns rows in your system</td>
<td><code>email</code></td>
</tr>
<tr>
<td><code>Source</code></td>
<td>free text, one phrasing per exporter</td>
<td>five options</td>
</tr>
</tbody>
</table></div>
<p>Those failures in their generic form are collected in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>. Two entries on that
list behave in a way worth watching, and both are below.</p>
<h2 id="the-second-customers-header-row">The second customer's header row</h2>
<p>The same list arrives from the next customer under its own words. A header is
scored against both the column id and the column title, the better of the two
counts, and under 60 nothing is claimed. Run that header row against the schema
above and this is what lands.</p>
<div class="blog-table blog-table--fixed blog-table--crm-headers"><table>
<thead>
<tr>
<th>Header</th>
<th>Lands on</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Telephone</code></td>
<td><code>phone</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Position</code></td>
<td><code>jobTitle</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Domain</code></td>
<td><code>accountDomain</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Stage</code></td>
<td><code>lifecycleStage</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Work Email</code></td>
<td><code>contactEmail</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Lead Source</code></td>
<td><code>sourceChannel</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Full Name</code></td>
<td><code>accountName</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Last Touch</code></td>
<td><code>lastName</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Organization</code></td>
<td>nothing</td>
<td>no word shared, neither string inside the other</td>
</tr>
<tr>
<td><code>Assigned To</code></td>
<td>nothing</td>
<td>same</td>
</tr>
</tbody>
</table></div>
<p>Read the last four rows together. <code>Organization</code> reaches nothing and leaves an
empty column the person can see. <code>Full Name</code> reaches <code>accountName</code>, because both
strings carry the word <code>name</code>, and it fills a column that then looks finished.</p>
<h2 id="the-name-column-that-lands-in-the-wrong-field">The name column that lands in the wrong field</h2>
<p><strong>A header that reaches nothing announces itself. A header that reaches the
wrong field does not.</strong> The account name column of that second file holds a
person, and every row looks complete on the mapping screen.</p>
<p>The first customer's file has the opposite problem. <code>File as</code> shares no word
with any column and contains none of them, so it scores zero and lands nowhere.
One export loses the name, the next one hides it.</p>
<p>Both are settled in the same table. Aliases under a column id win at 90, which
outranks the 70 that carried <code>Full Name</code> to the wrong place.</p>
<pre><code class="language-ts">export const synonyms = {
  columns: {
    accountName: ["company", "organization"],
    contactEmail: ["email 1 - value", "work email"],
    ownerEmail: ["owner", "assigned to"],
    lastActivityDate: ["last activity", "last touch"],
    lastName: ["file as", "full name", "contact"],
  },
  values: {
    "Marketing Qualified Lead": ["mql", "mkt qualified"],
    "Sales Qualified Lead": ["sql"],
    Opportunity: ["opp"],
    Customer: ["closed won"],
    Subscriber: ["newsletter"],
    Other: ["churned"],
  },
};</code></pre>
<p><code>file as</code>, <code>full name</code> and <code>contact</code> now reach <code>lastName</code>, and <code>organization</code>
and <code>company</code> reach <code>accountName</code>. The value table under it takes the seven
lifecycle strings that reach nothing on their own, <code>MQL</code>, <code>mkt qualified</code>,
<code>SQL</code>, <code>Closed Won</code>, <code>Newsletter</code>, <code>Opp</code> and <code>Churned</code>. Eight of the fifteen
strings in that column land without help, and <code>New Lead</code> reaches <code>Lead</code> because
one contains the other.</p>
<p>That leaves the name itself. One column reaches one field, so a combined name
lands whole in <code>lastName</code>, and a <code>transformer</code> takes the half that belongs
there.</p>
<pre><code class="language-ts">{
  id: "lastName",
  title: "Last name",
  transformer: (value) => {
    const name = String(value ?? "").trim();
    const comma = name.indexOf(",");
    return comma === -1 ? name : name.slice(0, comma).trim();
  },
}</code></pre>
<p>The transformer runs as rows enter the store, so <code>Okafor, Chidera</code> is stored as
<code>Okafor</code> and <code>Vahid Sarrafzadeh</code> is stored unchanged. The given name is gone.
Recovering it is guesswork the importer refuses to do, so either your schema
keeps one name field, or the person fills the second one in the grid.</p>
<h2 id="the-date-that-changes-meaning">The date that changes meaning</h2>
<p>Updog scans the date columns across the first thousand rows before it decides an
order, and the first value with a part above twelve settles it for the whole
file.</p>
<p>That makes <code>03/07/2026</code> a value with no meaning of its own. Put <code>02/14/2026</code>
anywhere in those rows and fourteen lands second, so the file reads month first
and <code>03/07/2026</code> becomes 7 March. Put <code>14/02/2026</code> there instead and the file
reads day first, so the same cell becomes 3 July. The value <code>7.3.2026</code> swaps the
other way in each case.</p>
<p><strong>When nothing in those rows settles the order, the fallback is the locale of
the machine that opened it.</strong> One file can then land on two different days in
two different offices, and a 15,000-row export that first disagrees with the
locale on row 4,000 lands on the locale's reading.</p>
<p><code>2026-03-07</code> carries its order inside it and reaches 7 March every time. An
Excel serial carries no order to read, so it lands as text, and the <code>date</code>
validator flags it for the person to fix.</p>
<h2 id="deciding-what-a-row-is">Deciding what a row is</h2>
<p>Now the identity question. Two rows in that file carry <code>info@kestrelfreight.co.uk</code>,
because a freight company put a shared mailbox on both of its people. A third
account also publishes an <code>info@</code> address.</p>
<p>Rows inside one file stay apart whatever the key says. Merging runs against what
the editor already holds, so the freight company's two people land as two rows,
and the key decides what happens on the upload after this one.</p>
<p>That upload is where the address alone breaks. Next quarter's file carries
<code>info@kestrelfreight.co.uk</code> again, this time on a contact filed under another
account. Key on the email column alone and the row merges into one of the
freight rows, taking that contact out of the import with nothing on the screen
to show for it.</p>
<p><code>primaryKey</code> takes a list, and a row merges only when every listed column
matches. Key on the email and the account domain together and that contact
arrives as its own row, because the domains differ. Values are compared after
trimming, so a padded export still merges with what you hold.</p>
<h2 id="the-second-upload">The second upload</h2>
<p>Open the same file again a quarter later and most of it repeats. <code>loadData</code>
hands the editor the contacts you already store, and the imported rows merge
into them by that composite key.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey={["contactEmail", "accountDomain"]}
  synonyms={synonyms}
  blockSubmitOnError
  loadData={async (onChunk) => {
    onChunk(await fetchContacts(), {
      id: "crm",
      source: "Already in your CRM",
    });
  }}
  onComplete={async (result) => {
    for (const source of result.sources) {
      const created = source.rows.filter((r) => r.isNew &#x26;&#x26; r.isValid);
      const updated = source.rows.filter(
        (r) => !r.isNew &#x26;&#x26; r.isChanged &#x26;&#x26; r.isValid,
      );
      await postContacts(source.sourceName, { created, updated });
    }
    await saveSynonyms(result.learnedSynonyms);
  }}
/></code></pre>
<p><code>onComplete</code> hands back one entry per file with <code>isNew</code>, <code>isChanged</code>,
<code>isDeleted</code> and <code>isValid</code> on every row, and a row that arrived from your own
data untouched is left out. So the second upload of 15,000 rows reaches your API
as the handful that changed. <code>learnedSynonyms</code> carries the pairs the person
fixed by hand, as <code>{ source, target }</code> entries under <code>columns</code> and <code>values</code>,
where the target is the column title for a header and the option value for a
value. Store them, add each source as an alias under its target, and the next
list matches itself. That loop is written up in
<a href="https://updog.tech/blog/remember-csv-import-mappings/">how to remember CSV import mappings</a>.</p>
<h2 id="what-you-write-yourself">What you write yourself</h2>
<p>Every CRM-shaped line above is yours. The columns, the validators, the alias
table, the enum and the key live in your repository, because Updog ships no CRM
template, no connector to any CRM and no schema library to start from. Updog
Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A contact sheet
that arrives as a PDF or an image goes to a parser you supply, and the rows it
returns walk the same path. The rest is configuration.</p>
<p>The composite key has a price of its own. A row missing either the email or the
domain builds no key, so it merges with nothing and arrives as new. That trades
a silent wrong merge for a visible duplicate, which is the better failure and
still a failure.</p>
<h2 id="what-reaches-your-api">What reaches your API</h2>
<p>The first upload posts 15,000 contacts. The second posts the rows whose key is
new and the rows whose values moved, and leaves the rest of the file out. Behind
that sit eleven columns, an alias table, seven lifecycle strings, a transformer
on the name column and a key made of two of those columns, all of it code you
keep. The two dates the importer refused and the given name it dropped wait in
the grid for the person who sent the file.</p>]]></content:encoded></item>
<item><title>CSV Import for Payroll and HR SaaS</title><link>https://updog.tech/blog/csv-import-for-hr-payroll-saas/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-for-hr-payroll-saas/</guid><pubDate>Sun, 19 Jul 2026 00:00:00 GMT</pubDate><description>Every new customer sends the employee file their own HRIS produced. How to take any of those exports into one schema, dependents and all.</description><content:encoded><![CDATA[<p>Every employer keeps a list of its people. It sits in an HRIS, it sits in the
payroll system, and it sits in the spreadsheet HR builds each time somebody
asks a question the HRIS cannot answer. Onboarding an employer onto a new
platform starts with one of those files.</p>
<p>That file is a census. It carries names, start dates, pay, cost centres,
managers and benefit elections, and every one of those fields is written the
way the source system writes it. Pay arrives annual in one export and hourly
in the next, and a manager is named in one file and referenced by employee ID
in another.</p>
<p>An HR, payroll or benefits platform keeps one employee schema. Its customers
export employees from Workday, BambooHR, Personio and from systems built in
house, and each of those writes a different file. Moving those files into your
schema is <a href="https://updog.tech/blog/what-is-customer-data-onboarding/">customer data onboarding</a>.</p>
<p>You write the schema. The person who uploads the file is the HR administrator at
the employer that sends it, and the file came out of their HRIS.</p>
<h2 id="what-your-customers-send">What your customers send</h2>
<p>Four kinds of file arrive at an HR platform.</p>
<p>An employee roster is the whole population, one row per person, exported when a
customer moves onto your product. A payroll register arrives every pay period
and carries earnings against each person. A benefits census is the roster plus
everyone the employee covers, and it is the widest of the four. A carrier
eligibility export is the census after a broker has reshaped it.</p>
<p>The rest of this article follows two benefits census files that land in the same
upload. One employer sends eighteen dependent columns, and the other sends
twelve under headers of its own.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>Three rows out of the first census, 640 people at a food manufacturer. The system
that exported it stores dependents as numbered columns.</p>
<p><code>harlow-foods-census.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th><th class="sheet__column" scope="col">I</th><th class="sheet__column" scope="col">J</th><th class="sheet__column" scope="col">K</th><th class="sheet__column" scope="col">L</th><th class="sheet__column" scope="col">M</th><th class="sheet__column" scope="col">N</th><th class="sheet__column" scope="col">O</th><th class="sheet__column" scope="col">P</th><th class="sheet__column" scope="col">Q</th><th class="sheet__column" scope="col">R</th><th class="sheet__column" scope="col">S</th><th class="sheet__column" scope="col">T</th><th class="sheet__column" scope="col">U</th><th class="sheet__column" scope="col">V</th><th class="sheet__column" scope="col">W</th><th class="sheet__column" scope="col">X</th><th class="sheet__column" scope="col">Y</th><th class="sheet__column" scope="col">Z</th><th class="sheet__column" scope="col">AA</th><th class="sheet__column" scope="col">AB</th><th class="sheet__column" scope="col">AC</th><th class="sheet__column" scope="col">AD</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Emp #</td><td class="sheet__cell">Last</td><td class="sheet__cell">First</td><td class="sheet__cell">Birth Date</td><td class="sheet__cell">Hire Dt</td><td class="sheet__cell">Status</td><td class="sheet__cell">FLSA</td><td class="sheet__cell">Pay Basis</td><td class="sheet__cell">Annual Comp</td><td class="sheet__cell">Work Email</td><td class="sheet__cell">Mgr Email</td><td class="sheet__cell">Coverage</td><td class="sheet__cell">Dep 1 Name</td><td class="sheet__cell">Dep 1 Rel</td><td class="sheet__cell">Dep 1 DOB</td><td class="sheet__cell">Dep 2 Name</td><td class="sheet__cell">Dep 2 Rel</td><td class="sheet__cell">Dep 2 DOB</td><td class="sheet__cell">Dep 3 Name</td><td class="sheet__cell">Dep 3 Rel</td><td class="sheet__cell">Dep 3 DOB</td><td class="sheet__cell">Dep 4 Name</td><td class="sheet__cell">Dep 4 Rel</td><td class="sheet__cell">Dep 4 DOB</td><td class="sheet__cell">Dep 5 Name</td><td class="sheet__cell">Dep 5 Rel</td><td class="sheet__cell">Dep 5 DOB</td><td class="sheet__cell">Dep 6 Name</td><td class="sheet__cell">Dep 6 Rel</td><td class="sheet__cell">Dep 6 DOB</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">004182</td><td class="sheet__cell">Ferreira</td><td class="sheet__cell">Nuno</td><td class="sheet__cell">3/7/68</td><td class="sheet__cell">02/14/2019</td><td class="sheet__cell">FT</td><td class="sheet__cell">EX</td><td class="sheet__cell">Year</td><td class="sheet__cell">$72,500.00</td><td class="sheet__cell">n.ferreira@harlowfoods.com</td><td class="sheet__cell">r.pike@harlowfoods.com</td><td class="sheet__cell">EE+SP</td><td class="sheet__cell">Ana Ferreira</td><td class="sheet__cell">SP</td><td class="sheet__cell">09/11/1971</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">004183</td><td class="sheet__cell">Okonkwo</td><td class="sheet__cell">Grace</td><td class="sheet__cell">1984-05-30</td><td class="sheet__cell">08/02/2021</td><td class="sheet__cell">Part Time</td><td class="sheet__cell">NE</td><td class="sheet__cell">Hour</td><td class="sheet__cell">31.40</td><td class="sheet__cell">g.okonkwo@harlowfoods.com</td><td class="sheet__cell">r.pike@harlowfoods.com</td><td class="sheet__cell">EE</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">004184</td><td class="sheet__cell">Salas</td><td class="sheet__cell">Miguel</td><td class="sheet__cell">24905</td><td class="sheet__cell">11/30/2015</td><td class="sheet__cell">FT</td><td class="sheet__cell">EX</td><td class="sheet__cell">Year</td><td class="sheet__cell">68 400</td><td class="sheet__cell">m.salas@harlowfoods.com</td><td class="sheet__cell">d.ayers@harlowfoods.com</td><td class="sheet__cell">FAM</td><td class="sheet__cell">Rosa Salas</td><td class="sheet__cell">Spouse</td><td class="sheet__cell">04/02/1980</td><td class="sheet__cell">Leo Salas</td><td class="sheet__cell">Child</td><td class="sheet__cell">07/19/2012</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="30"><span class="sheet__break-text">636 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">641</th><td class="sheet__cell">004821</td><td class="sheet__cell">Whitcombe</td><td class="sheet__cell">Deborah</td><td class="sheet__cell">1990-02-11</td><td class="sheet__cell">05/06/2023</td><td class="sheet__cell">FT</td><td class="sheet__cell">EX</td><td class="sheet__cell">Year</td><td class="sheet__cell">$58,900.00</td><td class="sheet__cell">d.whitcombe@harlowfoods.com</td><td class="sheet__cell">d.ayers@harlowfoods.com</td><td class="sheet__cell">EE</td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td><td class="sheet__cell"></td></tr></tbody></table>
<p><code>EX</code> is an FLSA code. <code>EE+SP</code> is a coverage tier. <code>24905</code> is a date of birth
that spent time in a spreadsheet cell. Each value is correct inside the system
that wrote it. Your schema stores a status, a tier and an ISO date, so all three
arrive in the wrong shape.</p>
<h2 id="the-fields-the-platform-keeps">The fields the platform keeps</h2>
<p>The schema is yours, and the option lists come from names those systems publish.
BambooHR publishes <code>employmentStatus</code> as Contractor, Full-Time, Part-Time,
Terminated, or a value the customer adds. It publishes <code>exempt</code> as the FLSA
overtime status, and <code>paidPer</code> as Hour, Day, Week, Month, Quarter and Year. The
coverage tier takes the federal enrollment types. 5 CFR 890.302 defines Self
Plus One as the enrollee and one eligible family member, Self and Family as
everyone eligible, and Self Only as the third.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const TIERS = ["Self Only", "Self Plus One", "Self and Family"];

export const columns: DataEditorColumn[] = [
  {
    id: "memberId",
    title: "Member ID",
    size: 120,
    validators: [{ type: "required" }, { type: "unique" }],
  },
  { id: "lastName", title: "Last name", validators: [{ type: "required" }] },
  { id: "firstName", title: "First name", validators: [{ type: "required" }] },
  {
    id: "dateOfBirth",
    title: "Date of birth",
    editor: { type: "date" },
    validators: [{ type: "date", max: "2026-07-19" }],
  },
  { id: "hireDate", title: "Hire date", editor: { type: "date" } },
  {
    id: "employmentStatus",
    title: "Employment status",
    editor: {
      type: "select",
      options: ["Full-Time", "Part-Time", "Contractor", "Terminated"],
    },
    validators: [
      { type: "oneOf", values: ["Full-Time", "Part-Time", "Contractor", "Terminated"] },
    ],
  },
  {
    id: "flsaStatus",
    title: "FLSA status",
    editor: { type: "select", options: ["Exempt", "Non-exempt"] },
  },
  {
    id: "payBasis",
    title: "Pay basis",
    editor: {
      type: "select",
      options: ["Hour", "Day", "Week", "Month", "Quarter", "Year"],
    },
  },
  {
    id: "annualComp",
    title: "Annual comp",
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
  },
  {
    id: "workEmail",
    title: "Work email",
    size: 240,
    validators: [{ type: "email" }, { type: "unique" }],
  },
  {
    id: "coverageTier",
    title: "Coverage tier",
    editor: { type: "select", options: TIERS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: TIERS }],
  },
];</code></pre>
<p><code>memberId</code> declares no editor, so the value lands as the file wrote it and
<code>004182</code> holds its zeros. The date and number editors carry a check
of their own kind, so a value the importer could not convert is flagged before
you declare any validator.</p>
<h2 id="what-breaks-field-by-field">What breaks, field by field</h2>
<div class="blog-table blog-table--fixed blog-table--hr-schema"><table>
<thead>
<tr>
<th>Column</th>
<th>What arrives</th>
<th>What has to happen</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Emp #</code></td>
<td><code>004182</code> from one employer, <code>4182</code> from the next</td>
<td>text, <code>unique</code>, padding is yours to settle</td>
</tr>
<tr>
<td><code>Birth Date</code></td>
<td><code>3/7/68</code>, <code>1984-05-30</code>, <code>24905</code></td>
<td>ISO, and two of the three stay flagged</td>
</tr>
<tr>
<td><code>Hire Dt</code></td>
<td>month first from one system, day first from another</td>
<td>one order per file, read from every date column</td>
</tr>
<tr>
<td><code>Status</code></td>
<td><code>FT</code>, <code>Part Time</code>, <code>Term</code></td>
<td>four options</td>
</tr>
<tr>
<td><code>FLSA</code></td>
<td><code>EX</code>, <code>NE</code>, <code>Exempt</code></td>
<td>two options</td>
</tr>
<tr>
<td><code>Pay Basis</code></td>
<td><code>Year</code>, <code>Hour</code>, <code>Annual</code></td>
<td>six options</td>
</tr>
<tr>
<td><code>Annual Comp</code></td>
<td><code>$72,500.00</code>, <code>68 400</code>, <code>31.40</code></td>
<td>digits, two decimal places</td>
</tr>
<tr>
<td><code>Work Email</code></td>
<td>a shared mailbox on two rows</td>
<td><code>unique</code></td>
</tr>
<tr>
<td><code>Mgr Email</code></td>
<td>an address that owns no row</td>
<td>resolved against the roster</td>
</tr>
<tr>
<td><code>Coverage</code></td>
<td>eleven distinct strings</td>
<td>three options</td>
</tr>
<tr>
<td><code>Dep 1</code> through <code>Dep 6</code></td>
<td>six numbered groups, two filled</td>
<td>flat fields, two aliases a block</td>
</tr>
</tbody>
</table></div>
<p><code>02/14/2019</code> puts fourteen second, so this census reads month first and every
date column in it follows that one order. The next employer's <code>14.02.2019</code> sends
its file the other way. Every numeric pattern wants a four-digit year, so
<code>3/7/68</code> reaches the grid as text, and the Excel serial <code>24905</code> lands as text
too. The <code>date</code> validator flags both cells for the person to fix. The general
version of this list is in
<a href="https://updog.tech/blog/common-csv-import-errors/">common CSV import errors</a>.</p>
<h2 id="the-headers-this-industry-sends">The headers this industry sends</h2>
<p>Updog scores each header against the column id and the column title, and the
higher score wins. Exact is 100. A synonym group is 90. One string containing
the other is 80. Half the words shared is 70. A typo inside the edit distance is
65. Anything under 60 reaches nothing.</p>
<div class="blog-table blog-table--fixed blog-table--hr-headers"><table>
<thead>
<tr>
<th>Header</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Last</code></td>
<td><code>lastName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>First</code></td>
<td><code>firstName</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Birth Date</code></td>
<td><code>dateOfBirth</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>Hire Dt</code></td>
<td><code>hireDate</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Status</code></td>
<td><code>employmentStatus</code></td>
<td>synonym, 90</td>
</tr>
<tr>
<td><code>FLSA</code></td>
<td><code>flsaStatus</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Pay Basis</code></td>
<td><code>payBasis</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Work Email</code></td>
<td><code>workEmail</code></td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Mgr Email</code></td>
<td><code>supervisorEmail</code></td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Coverage</code></td>
<td><code>coverageTier</code></td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>Dep 1 Name</code></td>
<td><code>dependent1Name</code></td>
<td>shared words, 70</td>
</tr>
<tr>
<td><code>Emp #</code></td>
<td>nothing</td>
<td>four characters carrying a symbol</td>
</tr>
<tr>
<td><code>Dep 1 Rel</code></td>
<td>nothing</td>
<td>one word shared out of three</td>
</tr>
<tr>
<td><code>Dep 1 DOB</code></td>
<td>nothing</td>
<td>same, and <code>dob</code> reaches a group <code>dep1dob</code> never joins</td>
</tr>
</tbody>
</table></div>
<p>The built-in table already carries this vocabulary. <code>dob</code>, <code>birthdate</code>,
<code>hiredate</code>, <code>empstatus</code>, <code>workerstatus</code>, <code>supervisor</code> and <code>mgr</code> are aliases the
SDK ships, so most of the file lands with no configuration. <code>Status</code> scores
against two of your columns, and the assignment gives it to <code>employmentStatus</code>,
because taking the higher total leaves <code>FLSA</code> its own column.</p>
<p>The second employer sends the same census in other words. <code>Employee ID</code> reaches
<code>memberId</code> on one shared word. <code>Surname</code> and <code>Given Name</code> land on synonyms.
<code>Overtime Status</code> reaches <code>flsaStatus</code>. <code>Email (Work)</code> reaches <code>workEmail</code>.
<code>Tier</code> sits inside <code>coverageTier</code>. <code>Paid Per</code> and <code>Base Salary</code> reach nothing.</p>
<h2 id="the-wide-dependent-block">The wide dependent block</h2>
<p>A benefits census stores dependents across the row, one group of columns per
dependent. Six groups of three columns is eighteen headers. The next employer
sends four groups in different words.</p>
<p>One column of the three matches on its own. <code>Dep 1 Name</code> shares two words of
three with your <code>Dependent 1 name</code> title and lands at 70, and every block after
it behaves the same way. <code>Dep 1 Rel</code> shares one word of three and reaches
nothing. <code>Dep 1 DOB</code> reaches nothing either, because the synonym group behind
<code>dob</code> fires only when both strings normalize into it, and <code>dep1dob</code> does not.</p>
<pre><code class="language-ts">const blocks = [1, 2, 3, 4, 5, 6];

const dependentAliases = Object.fromEntries(
  blocks.flatMap((n) => [
    ["dependent" + n + "Relationship", ["dep " + n + " rel", "dep " + n + " relation"]],
    ["dependent" + n + "DateOfBirth", ["dep " + n + " dob", "dependant " + n + " dob"]],
  ]),
);

export const synonyms = {
  columns: {
    memberId: ["emp #", "employee no", "payroll id"],
    payBasis: ["paid per", "pay frequency basis"],
    annualComp: ["base salary", "annual rate"],
    ...dependentAliases,
  },
  values: {
    "Self Only": ["ee", "e", "emp only", "single"],
    "Self Plus One": ["ee+sp", "ee+1", "employee + spouse", "employee + child"],
    "Self and Family": ["fam", "e+f", "ee+fam", "employee + family"],
    Exempt: ["ex"],
    "Non-exempt": ["ne", "nonex"],
    Year: ["annual", "annually", "salaried"],
  },
};</code></pre>
<p>The table is generated because the headers follow a pattern. Each block gets the
two entries the matcher misses. A file carrying four blocks maps four and leaves
the other two blocks empty. Column matching runs once per file, so the second
employer's <code>Dependant 1 First Name</code> reaches the field the first employer's
<code>Dep 1 Name</code> reached.</p>
<h2 id="the-coverage-tier-column">The coverage tier column</h2>
<p>Three enrollment types arrive as eleven distinct strings.</p>
<div class="blog-table blog-table--fixed blog-table--hr-coverage"><table>
<thead>
<tr>
<th>In the file</th>
<th>Reaches</th>
<th>How</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Self Only</code></td>
<td>Self Only</td>
<td>exact, 100</td>
</tr>
<tr>
<td><code>Employee Only</code></td>
<td>Self Only</td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>EE Only</code></td>
<td>Self Only</td>
<td>shared word, 70</td>
</tr>
<tr>
<td><code>Family</code></td>
<td>Self and Family</td>
<td>contains, 80</td>
</tr>
<tr>
<td><code>EE</code></td>
<td>Self Only</td>
<td>the <code>synonyms.values</code> table</td>
</tr>
<tr>
<td><code>E</code></td>
<td>Self Only</td>
<td>same</td>
</tr>
<tr>
<td><code>EE+SP</code></td>
<td>Self Plus One</td>
<td>same</td>
</tr>
<tr>
<td><code>EE+1</code></td>
<td>Self Plus One</td>
<td>same</td>
</tr>
<tr>
<td><code>Employee + Spouse</code></td>
<td>Self Plus One</td>
<td>same</td>
</tr>
<tr>
<td><code>FAM</code></td>
<td>Self and Family</td>
<td>same</td>
</tr>
<tr>
<td><code>E+F</code></td>
<td>Self and Family</td>
<td>same</td>
</tr>
</tbody>
</table></div>
<p>Four of the eleven resolve on their own and seven need the table. Value matching
runs once for the whole upload, so two employers uploaded together produce one
merged list and one decision per string.</p>
<p>The other three enum columns cost less. <code>FT</code>, <code>Part Time</code> and <code>Term</code> all reach
Full-Time, Part-Time and Terminated on the built-in table, so employment status
needs nothing. <code>Exempt</code> and <code>Non Exempt</code> land on their own, and the payroll
shorthand <code>EX</code> and <code>NE</code> takes one entry each. <code>Year</code> and <code>Hour</code> land, and
<code>Annual</code> takes one.</p>
<p><code>Waived</code> belongs to no enrollment type, and a select value is imported only when
it is mapped. Leave <code>enableCustomValue</code> at its default and the person can create
an option for it. Set it to <code>false</code>, as the schema above does, and the column
stays a closed enum where an unmapped value is dropped before it reaches your
API.</p>
<h2 id="the-manager-email-column">The manager email column</h2>
<p>A manager address has to be answered against the other rows in the file, and a
<code>function</code> validator sees one value and one row. That answer lives in the async
rule, which receives every cell in the column together with its row.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const supervisorColumn: DataEditorColumn = {
  id: "supervisorEmail",
  title: "Manager email",
  size: 240,
  validators: [
    { type: "email" },
    {
      type: "asyncFunction",
      fn: async (cells) => {
        const inFile = new Set(cells.map((cell) => cell.row.workEmail));
        const unresolved = cells
          .map((cell) => String(cell.value ?? ""))
          .filter((email) => email &#x26;&#x26; !inFile.has(email));
        const onRecord = new Set(await api.managersOnRecord(unresolved));

        return cells.map((cell) => {
          const email = String(cell.value ?? "");
          if (!email || inFile.has(email) || onRecord.has(email)) return null;
          return { level: "error", message: "No employee holds that address" };
        });
      },
    },
  ],
};</code></pre>
<p>Opening a file sweeps the column at once, so <code>cells</code> carries the manager
addresses with the row each one sits in. Empty cells stay out of the sweep, so
an employee who reports to nobody contributes no address to the set. The census
answers most of the question by itself, and whatever it cannot place goes to
your endpoint. The <code>unique</code> rule on <code>workEmail</code> runs last, once every other
validator on that column passes, so a malformed address reports the format
problem it has.</p>
<h2 id="the-next-import">The next import</h2>
<p>Open enrollment brings the census back with last year's rows inside it.
<code>primaryKey="memberId"</code> merges an imported row into the row it matches and adds
the rest as new. A row whose key is empty merges with nothing.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  columns={columns}
  primaryKey="memberId"
  synonyms={synonyms}
  blockSubmitOnError
  onComplete={async (result) => {
    for (const source of result.sources) {
      const created = source.rows.filter((r) => r.isNew &#x26;&#x26; r.isValid);
      const updated = source.rows.filter((r) => !r.isNew &#x26;&#x26; r.isChanged &#x26;&#x26; r.isValid);
      await postCensus(source.sourceName, { created, updated });
    }
    await saveSynonyms(result.learnedSynonyms);
  }}
/></code></pre>
<p><code>onComplete</code> returns one entry per file, each row carrying <code>isNew</code>,
<code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>, and <code>learnedSynonyms</code> carrying the pairs
the person fixed by hand. Turn those pairs into aliases under their targets and
the next census matches itself, a loop written up in
<a href="https://updog.tech/blog/remember-csv-import-mappings/">how to remember CSV import mappings</a>.</p>
<h2 id="what-updog-does-not-ship">What Updog does not ship</h2>
<p>Updog has no HR template, no HRIS connector and no per-industry schema library.
The columns above, the validators, the aliases and the enum are code you write.
Updog Importer reads CSV, TSV, JSON, XML, XLSX, XLS, XLSB and ODS. A census
that arrives as a PDF or a scan goes to a parser you supply, and the rows it
hands back walk the same path. Everything HR-shaped above sits on top of that as
configuration.</p>
<h2 id="what-you-built">What you built</h2>
<p>You wrote twelve columns, one aliases table for the headers the matcher misses,
one value table for the coverage enum, and one async rule for the manager
column. A census that carried three date shapes and eleven ways of writing three
coverage tiers reaches your API as rows your database accepts, with everything
the importer could not settle flagged for the person who sent the file.</p>]]></content:encoded></item>
<item><title>CSV Import Is More Than Parsing a File</title><link>https://updog.tech/blog/csv-import-is-more-than-parsing/</link><guid isPermaLink="true">https://updog.tech/blog/csv-import-is-more-than-parsing/</guid><pubDate>Sat, 18 Jul 2026 00:00:00 GMT</pubDate><description>A parser reads a file. An importer maps columns, matches values, validates, and lets users fix errors in the browser before anything is submitted.</description><content:encoded><![CDATA[<p>A few days ago I was watching a demo. The team had built something they were proud of, and it was time to load some real data. A couple of values were wrong, nothing serious, just the kind of thing every real file has. So one of them downloaded the file, opened it in Excel, fixed the cell, saved, and uploaded it again. The new upload had another bad row, and they did it once more. The room felt awkward while everyone waited. Nobody looked surprised, though. This was just how their import worked.</p>
<p>What stayed with me was how it felt to sit there. With every download and upload, the person presenting got more nervous. The room went quiet, the polite kind of quiet that feels worse than complaining out loud, and you could watch the minutes slip away from what was supposed to be the fun part of the demo. A simple task had become a small headache, and everyone could feel it.</p>
<p>A process this broken is easy to fix in theory, and a good solution would make the whole back-and-forth go away. What is harder is saying what good means, and how much care it takes to build it. Because parsing the file is the easy part. Everything after it is experience, and that is the part you have to get right.</p>
<h2 id="what-a-good-import-feels-like">What a good import feels like</h2>
<p>When I bring a file into a product, I want it to be fast, simple, and free of surprises. I want to hand it my data and have the product help me from there. And when my file is messy, which is most of the time, I do not want to be sent away to fix it somewhere else and then come back to try again. I want the product to help me clean it up while I am right there.</p>
<p>Reading a CSV is the part everyone can do. A parser takes the text in the file and turns it into rows you can work with, and free libraries have done that well for years. If reading the file were the whole job, a free library would be enough. Products keep building past the parser because a real file almost never comes in the shape your app expects, and closing that gap is the real work.</p>
<h2 id="getting-the-file-ready">Getting the file ready</h2>
<p>It is worth walking through what that gap looks like, in the order a person runs into it. Each step is a small place where the experience can help or get in the way. None of them is a big deal on its own, and you barely notice them when they work. But skip them and the import turns into a chore.</p>
<p>The first surprise is usually the file itself. We like to imagine a CSV as a neat grid with the column names on the first line, but plenty of real files do not look like that. There is a title across the top, a few blank rows, or a note someone left, and the real header row sits three lines down. A basic importer reads the first row, treats those stray words as the column names, and everything after that is wrong. Updog handles this without a word. It finds the real header row on its own, so the person uploading never has to think about it.</p>
<p>Excel files add a step of their own. A workbook can hold more than one sheet, and only one of them is the data the person wants to import. You do not think about this when you first picture file upload, but the moment a workbook shows up with three tabs, picking the right sheet becomes part of the job. So Updog asks which sheet to use and moves on.</p>
<p>Once there is a single table to work with, the real matching begins. The headers come in whatever words the person who made the file chose. One file says <code>First Name</code>, the next says <code>fname</code>, a third says <code>Contact First</code>. Your app expects <code>firstName</code>, and it does not care how anyone else named things. Fuzzy matching does most of the work on its own, pairing the obvious headers to your fields. For the ones it is not sure about, you can plug in your own logic, like a memory of how this customer mapped things before or <a href="https://updog.tech/blog/bring-your-own-ai/">your own AI</a>. If a header still has no clear match, the person can map it by hand. And if the file has a column your schema never planned for, they can create a new one instead of dropping the data. Nothing is lost or guessed at just because two people named their columns differently.</p>
<p>The same kind of mismatch shows up one level deeper, in the values inside the columns. Even when the headers line up, what a person typed may not be a value your app accepts. Say you have a <code>Department</code> field with a fixed set of options. The file arrives with <code>Eng</code> in one row, <code>engineering</code> in another, and <code>R&#x26;D</code> in a third. To a person it is plain that all three mean <code>Engineering</code>, but to your app none of them match, and they either get rejected or land in your data exactly as they came in. Value matching works the same way, only on the values inside a column instead of its name: fuzzy matching for the obvious ones, your own logic with a memory of past matches or your AI for the harder ones, and a manual fix for whatever is left.</p>
<p>The last decision before the data lands is how this file should join what is already there. With no key, the new rows just go to the end of what is already in the editor. With a key, like an email or an account ID, each new row is checked against the rows you already have, and a match updates that row instead of adding a duplicate. Without it, the same record can land twice and you clean up duplicates by hand later. It is a small choice you only think about after it goes wrong once.</p>
<h2 id="once-the-file-is-in-the-editor">Once the file is in the editor</h2>
<p>By now the data is in the editor, and it would be easy to call the import finished. But it has barely started. The file was messy when it arrived, and the person needs to fix it without leaving the product and without starting that Excel loop again.</p>
<p>So the editor has to feel like a place a person already knows. Updog gives you a spreadsheet that works like Excel and Google Sheets, because no one wants to learn a new tool in the middle of fixing their data. On the way in, you can write transformation functions that clean up the data first: trim extra spaces, lowercase emails, fix date formats, and handle the obvious things before anyone sees them. After that, validation checks each value against the rules you set in your schema. A lot of the mess clears up this way. But automatic cleanup can only do so much. Some values are wrong in a way only a person can judge, and if you pretend otherwise, bad data ends up sitting in your system for months.</p>
<p>This is where the spreadsheet does more than show rows: it marks the trouble. Every cell that fails validation is highlighted, and so are the rows with empty cells and the cells the person has changed, so they can always see what still needs work and what is done. On a small file they could find those by eye. A large file hides them, and going through errors one by one is slow. So Updog puts a deep set of filters down the left side of the grid. The person tells it what they care about, this kind of error, in that column, matching these words, and it narrows the whole file down to the rows that actually need attention. They fix those, and they are done.</p>
<p>And when describing a fix is faster than doing it by hand, there is an AI assistant that connects to your own model. The person types what they want in plain words, like remove the rows with no email, or put every phone number in the same format, and the change happens right there in the grid where they can see it. It is the same familiar spreadsheet, with a little more help when they want it.</p>
<h2 id="doing-the-math-on-those-round-trips">Doing the math on those round trips</h2>
<p>Come back to that demo for a moment. Picture the same team and the same messy file, but the fixing happens inside the editor instead of out in Excel. Each trip out to Excel and back was two or three minutes once you count finding the file, opening it, fixing the cell, saving, and uploading again. A messy file can take several of those. Call it ten or fifteen minutes of a demo spent not demoing, plus the cost of losing your focus each time and the chance of adding a new mistake on the way. Fixed in place with filters, that same cleanup takes a minute or two, done once, without leaving the page. The exact numbers change with the file, but the shape holds. You take a task that was spread across several stressful round trips and turn it into one calm one.</p>
<h2 id="a-product-that-leaves-you-in-a-better-mood">A product that leaves you in a better mood</h2>
<p>That is the whole idea behind Updog. You could call it one more SDK for importing CSV and Excel files into a web app, and that is true, but it misses what we were trying to do. The goal was never just to move rows from a file into an app. It was to take a moment that usually makes people nervous, when they hand over their messy real data and wait for it to go wrong, and make it quick, clear, and even a little pleasant. Parsing the file was always the easy part. The part worth building is everything around it: helping a person turn their own data into something clean, in one place, without the round trips and the stress, so they close the tab in a better mood than they opened it.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Airtable</title><link>https://updog.tech/blog/import-csv-into-airtable/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-airtable/</guid><pubDate>Fri, 17 Jul 2026 00:00:00 GMT</pubDate><description>Import CSV into Airtable from your own app. Map and validate the file in the browser, settle every select option, then upsert the rows from your own route.</description><content:encoded><![CDATA[<p>Airtable moves a CSV into a base from inside the base. A native upload reads a file up to 100MB. Copy and paste drops a block of spreadsheet cells into a grid. The CSV import extension maps columns to fields and merges on a field somebody picks. Sync integrations pull from Google Drive, GitHub Issues, Jira Cloud and Salesforce. Each of those runs from a seat in the base, and Airtable asks for Owner or Creator permissions before third-party data lands in an existing one. The grants manager sending you a quarter of applications sits in your product, holding an export from the system the foundation is leaving.</p>
<p>Their export arrives looking like this.</p>
<p><code>grants-q1-2026.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">app_ref</td><td class="sheet__cell">org_name</td><td class="sheet__cell">ein</td><td class="sheet__cell">programme</td><td class="sheet__cell">amount_requested</td><td class="sheet__cell">submitted_on</td><td class="sheet__cell">decision</td><td class="sheet__cell">focus_areas</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">GR-2026-0118</td><td class="sheet__cell">Harbor Youth Collective</td><td class="sheet__cell">45-3810922</td><td class="sheet__cell">Community Grants</td><td class="sheet__cell">$25,000</td><td class="sheet__cell">03/02/2026</td><td class="sheet__cell">Approved</td><td class="sheet__cell">Food security; youth ed</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">gr-2026-0119 </td><td class="sheet__cell">Rivera Food Alliance</td><td class="sheet__cell">81-2299047</td><td class="sheet__cell">Community Grants</td><td class="sheet__cell">25 000</td><td class="sheet__cell">17.02.2026</td><td class="sheet__cell">APPROVED</td><td class="sheet__cell">Nutrition; Housing</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">GR-2026-0120</td><td class="sheet__cell">Northside Literacy Trust</td><td class="sheet__cell">26-4471158</td><td class="sheet__cell">Rapid Response</td><td class="sheet__cell">12,500.00</td><td class="sheet__cell">4 Mar 2026</td><td class="sheet__cell">awarded</td><td class="sheet__cell">education youth; public health</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">236 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">241</th><td class="sheet__cell">GR-2026-0357</td><td class="sheet__cell">Elmgrove Arts Coalition</td><td class="sheet__cell">47-9920164</td><td class="sheet__cell">Community Grants</td><td class="sheet__cell">18000</td><td class="sheet__cell">28.04.2026</td><td class="sheet__cell">Declined</td><td class="sheet__cell">Public health</td></tr></tbody></table>
<p>Eight headers over 240 applications. <code>app_ref</code>, <code>org_name</code> and <code>programme</code> are the exporting system's words for fields the base calls <code>Application ref</code>, <code>Organization</code> and <code>Program</code>. One grant reference is lowercase and trails a space. One amount carries a dollar sign and a thousands comma, the next groups its thousands with a space, and the third writes cents. The submitted date appears in three shapes across three rows. The decision column says <code>Approved</code>, <code>APPROVED</code> and <code>awarded</code> against a field holding three fixed options. The focus areas column packs several values into one cell.</p>
<p>The grants manager drops that export into the importer inside your app. Updog Importer opens it in the browser, lines the headers up against your schema, and shows every value on screen. Your <code>onComplete</code> handler receives the rows. The handler cuts them into chunks and posts each chunk to a route you own. The route holds the Airtable token and upserts ten records a request.</p>
<p>Nothing in that chain runs on an Updog server.</p>
<h2 id="the-base-the-rows-land-in">The base the rows land in</h2>
<p>Start by reading the base you are writing to. <code>GET https://api.airtable.com/v0/meta/bases/{baseId}/tables</code> returns every table, and a token carrying the <code>schema.bases:read</code> scope is enough to call it.</p>
<pre><code class="language-json">{
  "tables": [
    {
      "id": "tblApplications1",
      "name": "Applications",
      "fields": [
        { "id": "fldRef000000001", "name": "Application ref", "type": "singleLineText" },
        { "id": "fldOrg000000002", "name": "Organization", "type": "singleLineText" },
        { "id": "fldEin000000003", "name": "EIN", "type": "singleLineText" },
        { "id": "fldPrg000000004", "name": "Program", "type": "singleLineText" },
        { "id": "fldAmt000000005", "name": "Amount requested", "type": "currency" },
        { "id": "fldSub000000006", "name": "Submitted on", "type": "date" },
        {
          "id": "fldDec000000007",
          "name": "Decision",
          "type": "singleSelect",
          "options": {
            "choices": [
              { "id": "selApproved001", "name": "Approved" },
              { "id": "selDeclined002", "name": "Declined" },
              { "id": "selUnderRev003", "name": "Under review" }
            ]
          }
        },
        {
          "id": "fldFoc000000008",
          "name": "Focus areas",
          "type": "multipleSelects",
          "options": {
            "choices": [
              { "id": "selFood0000001", "name": "Food security" },
              { "id": "selYouth000002", "name": "Youth education" },
              { "id": "selHousing0003", "name": "Housing" },
              { "id": "selHealth00004", "name": "Public health" }
            ]
          }
        }
      ]
    }
  ]
}</code></pre>
<p>Field ids start with <code>fld</code> and sit beside the names. A currency field takes a number, and a date field takes an ISO date string. <code>Decision</code> is a single select and <code>Focus areas</code> is a multiple select, each holding a <code>choices</code> array. With <code>typecast</code> off, those choice names are the values the two fields accept, so copying them into your column schema keeps the browser and the base agreed on one vocabulary.</p>
<h2 id="the-schema-in-the-browser">The schema in the browser</h2>
<p>The <code>columns</code> array is that base written for the person looking at the file. Each column gives the field a <code>title</code>, an editor that decides how the cell is typed, and validators that flag bad values.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const DECISIONS = ["Approved", "Declined", "Under review"];
const FOCUS_AREAS = [
  "Food security",
  "Youth education",
  "Housing",
  "Public health",
];

export const columns: DataEditorColumn[] = [
  {
    id: "appRef",
    title: "Application ref",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "organization",
    title: "Organization",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "ein",
    title: "EIN",
    size: 130,
    validators: [{ type: "regex", pattern: "^\\d{2}-\\d{7}$" }],
  },
  {
    id: "program",
    title: "Program",
    size: 170,
    validators: [{ type: "required" }],
  },
  {
    id: "amountRequested",
    title: "Amount requested",
    size: 160,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
  },
  {
    id: "submittedOn",
    title: "Submitted on",
    size: 140,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  {
    id: "decision",
    title: "Decision",
    size: 150,
    editor: { type: "select", options: DECISIONS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: DECISIONS }],
  },
  {
    id: "focusAreas",
    title: "Focus areas",
    size: 260,
    editor: {
      type: "multiselect",
      options: FOCUS_AREAS,
      enableCustomValue: false,
      delimiter: ";",
    },
    validators: [{ type: "oneOf", values: FOCUS_AREAS }],
  },
];</code></pre>
<p>The <code>date</code> editor reads all three date shapes in that column. The <code>17.02.2026</code> in the second row carries a day above 12, which settles the column as day-first and lands <code>03/02/2026</code> as <code>2026-02-03</code>. The third row writes <code>12,500.00</code> with both separators, and the last separator is the decimal, which settles the column as comma-grouped. On that verdict the <code>number</code> editor peels the dollar sign, collapses the space grouping and drops the thousands comma, so <code>$25,000</code> and <code>25 000</code> both arrive as <code>25000</code>. The <code>select</code> editor with <code>enableCustomValue</code> off holds <code>Decision</code> to the three choices the base published. The <code>multiselect</code> editor with a <code>;</code> delimiter turns <code>Food security; youth ed</code> into two values, and every cell in that column stores an array.</p>
<p>Those two editors are what keeps <code>typecast</code> out of the request later. The <code>oneOf</code> validators behind them apply per element on the multiple select, so one bad value in a list marks the row.</p>
<p>The <code>transformer</code> on <code>appRef</code> runs before the value enters the store, so <code>gr-2026-0119 </code> lands as <code>GR-2026-0119</code>, uppercase and trimmed. That matters because the same string becomes the merge key Airtable matches on.</p>
<p>The mount ties the whole thing together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Application>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="appRef"
  blockSubmitOnError
  synonyms={{
    columns: { organization: ["org_name", "legal name", "grantee"] },
    values: { Approved: ["awarded", "granted"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>primaryKey</code> decides how an imported row meets a row already in the grid, and values are compared after surrounding whitespace is trimmed. <code>blockSubmitOnError</code> keeps submit disabled while any row carries a validation error, so nothing reaches your route that a validator already rejected. The snippets here are React. The web component build takes the same props, so a Vue, Angular or Svelte app writes the same schema and the same handler. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-words-the-file-does-not-use">The words the file does not use</h2>
<p>Column matching scores a header against every column id and title, after lowercasing each one and dropping its spaces, underscores, hyphens and dots. <code>app_ref</code> comes out of that as <code>appref</code> and so does the column id <code>appRef</code>, which is a top-tier hit. <code>programme</code> and <code>Program</code> match on containment, because the shorter normalized string sits inside the longer one. <code>org_name</code> scores zero against <code>organization</code>, which is the pair the <code>synonyms</code> prop is there to cover.</p>
<p>Value matching runs the same ladder against the option list. <code>Approved</code> and <code>APPROVED</code> both land as exact hits, because case goes with the lowercasing. <code>awarded</code> reaches <code>Approved</code> from the <code>synonyms</code> values table, since it shares no run of letters with any option. <code>youth ed</code> lands because <code>youtheducation</code> contains it. <code>education youth</code> lands on word overlap, since both words appear in <code>Youth education</code> in the other order. <code>Nutrition</code> scores zero against all four options, so the person maps it by hand in the value-matching step.</p>
<p>That hand-made pair comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back through <code>synonyms</code> next time. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> follows that pair from the result back into the prop.</p>
<h2 id="the-handler-that-chunks-and-throws">The handler that chunks and throws</h2>
<p>When the person submits, Updog Importer hands your handler the applications grouped by source, each row flagged <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. One grants manager can bring three exports into a single import, and each one lands as its own source entry, so the handler flattens the list before slicing it.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 1000;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Application>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/grants/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>A thousand rows a request is a conservative choice of ours, sitting well inside the body your own route accepts. On Vercel a function body stops at 4.5 MB, and anything larger comes back as <code>413: FUNCTION_PAYLOAD_TOO_LARGE</code>.</p>
<pre><code class="language-json">{"appRef":"GR-2026-0118","organization":"Harbor Youth Collective","ein":"45-3810922","program":"Community Grants","amountRequested":"25000","submittedOn":"2026-02-03","decision":"Approved","focusAreas":["Food security","Youth education"]}</code></pre>
<p>One application row of these eight fields serializes to 238 bytes, so a thousand of them reach 232 KB. Measure your own widest application row and multiply again before you raise <code>CHUNK_SIZE</code>. A table of forty text fields changes the answer.</p>
<p><strong>Throw when the route rejects a chunk.</strong> Updog waits on your handler and empties the editor as soon as it resolves. A handler that swallows its own error and returns looks like success, so the grid empties with the applications unwritten. A thrown error keeps every application, every mapping and every correction on screen, so the person presses submit again on rows still in front of them. Copy anything off the result inside the handler, because once the promise resolves the editor lets go of its rows, its sources, its history and its learned synonyms.</p>
<h2 id="the-route-that-holds-the-token">The route that holds the token</h2>
<p>One route holds the token, and the browser reaches no further than that route.</p>
<pre><code class="language-ts">import { NextResponse } from "next/server";

const BATCH = 10;
const PACE_MS = 250;

const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));

export async function POST(request: Request) {
  const session = await getVerifiedSession();
  if (!session) {
    return NextResponse.json({ message: "Not signed in" }, { status: 401 });
  }

  const { baseId, tableId, token } = await getAirtableGrant(session.orgId);
  const { rows } = await request.json();

  const records = rows.map((row) => ({
    fields: {
      "Application ref": row.appRef,
      Organization: row.organization,
      EIN: row.ein,
      Program: row.program,
      "Amount requested":
        row.amountRequested === "" ? null : Number(row.amountRequested),
      "Submitted on": row.submittedOn,
      Decision: row.decision,
      "Focus areas": row.focusAreas,
    },
  }));

  for (let start = 0; start &#x3C; records.length; start += BATCH) {
    const response = await fetch(
      "https://api.airtable.com/v0/" + baseId + "/" + tableId,
      {
        method: "PATCH",
        headers: {
          Authorization: "Bearer " + token,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          performUpsert: { fieldsToMergeOn: ["Application ref"] },
          records: records.slice(start, start + BATCH),
        }),
      },
    );

    if (!response.ok) {
      const body = await response.json();
      const detail =
        typeof body.error === "string" ? body.error : body.error.message;
      return NextResponse.json(
        { message: detail, written: start },
        { status: response.status },
      );
    }

    await sleep(PACE_MS);
  }

  return NextResponse.json({ written: records.length });
}</code></pre>
<p>Airtable authenticates on an <code>Authorization: Bearer</code> header, and the token needs the <code>data.records:write</code> scope with the base added to it as a resource. A personal access token suits an integration you run for yourself or one client, and Airtable says such a token acts as your user account. For a product where each foundation grants your service access to their own base, Airtable recommends OAuth access tokens instead. <code>getVerifiedSession()</code> stands in for your own server-side authentication check, and <code>getAirtableGrant()</code> for wherever you keep that foundation's base id, table id and token.</p>
<p>The official <code>airtable</code> package creates, updates, replaces and destroys records. It has no upsert, in its source or its changelog, so this route calls the endpoint with <code>fetch</code> and posts one JSON body. Its README also warns against putting the key on a web page, which is the same reason the browser above talks only to your own route.</p>
<p>Batching handles up to ten records a request, which is why <code>BATCH</code> is 10. The API allows five requests a second per base, and going over returns a 429 with a 30 second wait before anything succeeds. A 250 millisecond sleep between batches holds four requests a second, inside the published limit with room for a slow response. A thousand rows is a hundred requests, so the sleeps alone add twenty five seconds, well inside the 300 second default duration of a Vercel function. The same chain ending in a Postgres table is in <a href="https://updog.tech/blog/import-csv-into-supabase/">how to import CSV into Supabase</a>, where the ceiling is a statement timeout.</p>
<p>Free and Team plans carry a monthly call cap on top of that, counted per workspace. Free allows 1,000 API calls a month, then blocks the rest of the month once a one-time grace period runs out. Team allows 100,000, after which calls slow to two requests a second until the month resets.</p>
<h2 id="a-value-the-field-has-never-held">A value the field has never held</h2>
<p>A single select accepts a string, and a multiple select accepts an array of strings. Airtable's field model puts the condition plainly, "if the choice string does not exactly match an existing option, the request will fail with an <code>INVALID_MULTIPLE_CHOICE_OPTIONS</code> error unless the <code>typecast</code> parameter is enabled". Airtable's troubleshooting page describes that 422 as a select field option that does not yet exist in the field arriving in the request body.</p>
<p><code>typecast</code> changes what happens next. Airtable calls it "best-effort automatic data conversion from string values", disabled by default "to ensure data integrity", and the field model adds that an enabled <code>typecast</code> creates a new choice when nothing matches exactly.</p>
<pre><code class="language-json">{
  "typecast": true,
  "performUpsert": { "fieldsToMergeOn": ["Application ref"] },
  "records": [{ "fields": { "Decision": "awarded" } }]
}</code></pre>
<p>That body writes an option called <code>awarded</code> into the <code>Decision</code> field of a base the foundation's team works in every day. Their views, their filters and their reports now carry two words for one outcome. The option stays after the import. Leaving <code>typecast</code> out of the request is what stops the API from editing the field, and that works because the option list was settled upstream. The closed <code>select</code> editor and the <code>oneOf</code> validator hold every decision inside <code>Approved</code>, <code>Declined</code> and <code>Under review</code> while the person can still see the row it came from.</p>
<h2 id="upsert-on-a-merge-field">Upsert on a merge field</h2>
<p><code>performUpsert</code> turns the update endpoint into an upsert. <code>fieldsToMergeOn</code> is used as an external id to match records for updates, and a record that matches nothing is created. The array takes one to three field names or ids, and Airtable rules out computed fields, leaving number, text, long text, single select, multiple select and date. <code>Application ref</code> is single line text, so it qualifies.</p>
<p>A <code>PATCH</code> updates only the fields in the request, where a <code>PUT</code> clears every cell value left out. When several existing records match one incoming record, the request fails, which makes a clean merge field worth more than a clever one. The response comes back with <code>createdRecords</code> and <code>updatedRecords</code> arrays, so the route can report which half of the chunk was new.</p>
<p>Chunks that already landed stay landed. Sending one again matches the same records on <code>Application ref</code> and rewrites them with the same values, so a retry after a failed chunk costs a rewrite of what already exists.</p>
<h2 id="field-names-and-field-ids">Field names and field ids</h2>
<p>The request body keys cell values by either field name or field id, and both have a way to break. A field id is tied to a specific field instance, so a field somebody deletes and recreates with the same name, type and position comes back with a new id, and the request answers <code>UNKNOWN_FIELD_NAME</code> with a 422. A field name breaks the day somebody renames the field in the base.</p>
<p>Airtable's own troubleshooting page picks a side, "where possible, prefer referencing fields by name rather than by ID in third-party integrations, since field names are more stable across day-to-day edits". The route above follows that. Reading the base schema before each import covers the other half, because a name that has moved shows up in the response before a single record is written.</p>
<h2 id="what-airtables-own-import-already-does">What Airtable's own import already does</h2>
<p>Updog Importer integrates with nobody. There is no Airtable connector, no destination list, no webhook and no server of ours. <code>onComplete</code> gives your code an object, and the route between it and the base is yours to write.</p>
<p>Airtable already ships its own import for the other case. The native upload takes a CSV up to 100MB into the base. The CSV import extension runs on all paid plans, matches columns to fields by name, and merges on a field the base owner picks, comparing the table against the file and updating the values it finds. It stops at 25,000 rows and 5MB, and its Create missing select options toggle needs Owner or Creator permissions on the base. When the file belongs to whoever owns the base, those are the shorter paths. The whole chain above exists for an export owned by the foundation, arriving in a browser session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> lays out which jobs suit each of the two models.</p>
<h2 id="the-dropdown-nobody-widened">The dropdown nobody widened</h2>
<p>You read a base schema, wrote eight columns with two closed option lists, added a handler that chunks and throws, and stood up one route that holds a token and paces itself. The export never leaves the machine that opened it. The rows travel from your own front end to your own route, and from there into Airtable, and the only party you added to the chain is yourself.</p>
<p>The foundation's team opens the base after that import and finds <code>Approved</code> where they left it. Nothing new appeared in the dropdown, because nothing in the chain was allowed to invent it.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Snowflake</title><link>https://updog.tech/blog/import-csv-into-snowflake/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-snowflake/</guid><pubDate>Thu, 16 Jul 2026 00:00:00 GMT</pubDate><description>Read a messy trial balance CSV in the browser, post the clean rows to your own Express route, and merge them into a Snowflake table from a staging table.</description><content:encoded><![CDATA[<p>A trial balance is every account in one client's ledger for one period, with a debit or a credit against each account. The two columns agree to the cent, and an audit platform that loads one into Snowflake has to keep that true. The file comes out of the client's accounting system, which the audit firm neither runs nor controls.</p>
<p>One month of one European subsidiary arrives looking like this.</p>
<p><code>alpen-handel-2026-06.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Account No</td><td class="sheet__cell">Account Name</td><td class="sheet__cell">Period</td><td class="sheet__cell">Debit</td><td class="sheet__cell">Credit</td><td class="sheet__cell">Currency</td><td class="sheet__cell">Entity</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">1010</td><td class="sheet__cell">Cash at bank</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">1.284.900,00</td><td class="sheet__cell">-</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">1400</td><td class="sheet__cell">Trade receivables</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">842.317,55</td><td class="sheet__cell">-</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">2100</td><td class="sheet__cell">Trade payables</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">-</td><td class="sheet__cell">(97,881.64)</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">4000</td><td class="sheet__cell">Revenue</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">-</td><td class="sheet__cell">(2.126.773,11)</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">6200</td><td class="sheet__cell">Office rent</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">96 000,00</td><td class="sheet__cell">-</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">7</th><td class="sheet__cell">7300</td><td class="sheet__cell">Bank charges</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">EUR 1.437,20</td><td class="sheet__cell">-</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">207 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">215</th><td class="sheet__cell">9900</td><td class="sheet__cell">Retained earnings</td><td class="sheet__cell">2026-06</td><td class="sheet__cell">-</td><td class="sheet__cell">(412.660,90)</td><td class="sheet__cell">EUR</td><td class="sheet__cell">Alpen Handel GmbH</td></tr></tbody></table>
<p>Seven headers, and the two amount columns hold six ways of writing a number. Two debits read <code>1.284.900,00</code>, with the dot grouping thousands and the comma marking the decimal. One credit reads <code>(2.126.773,11)</code>, the same convention inside accounting parentheses. The other credit reads <code>(97,881.64)</code>, with those two separators swapped. One debit groups with a space, <code>96 000,00</code>. One writes its currency in letters, <code>EUR 1.437,20</code>, beside a <code>Currency</code> column that already says EUR. A dash stands for a zero balance on every line carrying no amount.</p>
<p>That trial balance reaches the importer when the person drops it into your audit platform. Updog Importer stays in the browser, matches those seven headers to your fields, and puts the whole ledger on screen. Your <code>onComplete</code> handler receives the rows, checks that the two totals agree, and posts them in chunks to a route you own. The route holds the Snowflake key, writes the chunk into a staging table, and runs one <code>MERGE</code>.</p>
<p>We run no server between that browser and your Snowflake account.</p>
<h2 id="step-1-create-the-target-table-and-its-staging-table">Step 1. Create the target table and its staging table</h2>
<p>Two tables, because the write happens in two moves.</p>
<pre><code class="language-sql">create table ledger.trial_balance (
  engagement_id varchar       not null,
  period        varchar(7)    not null,
  account_no    varchar(10)   not null,
  account_name  varchar       not null,
  debit         number(18, 2),
  credit        number(18, 2),
  currency      varchar(3)    not null,
  entity        varchar       not null,
  loaded_at     timestamp_ntz not null,
  constraint trial_balance_pk primary key (engagement_id, period, account_no)
);

create transient table ledger.trial_balance_stage (
  batch_id      varchar       not null,
  engagement_id varchar       not null,
  period        varchar(7)    not null,
  account_no    varchar(10)   not null,
  account_name  varchar       not null,
  debit         number(18, 2),
  credit        number(18, 2),
  currency      varchar(3)    not null,
  entity        varchar       not null,
  loaded_at     timestamp_ntz not null
);</code></pre>
<p>The primary key names the identity of one line, which takes an engagement, a period and an account number together. A standard Snowflake table leaves that constraint unenforced, along with <code>FOREIGN KEY</code> and <code>UNIQUE</code>, and enforces <code>NOT NULL</code> and <code>CHECK</code>. Enforcing a primary key is reserved for hybrid tables. So a second import of the same file lands a second copy of every row, and the table itself stays quiet about it. The <code>MERGE</code> in step 6 is what closes that hole.</p>
<p>The staging table is transient, which means it carries no Fail-safe period and no Fail-safe cost. Snowflake describes a transient table as built for data that outlives a session and needs less protection than a permanent table. A batch of rows waiting for a merge is exactly that.</p>
<h2 id="step-2-describe-the-ledger-to-updog-importer">Step 2. Describe the ledger to Updog Importer</h2>
<p>The <code>columns</code> array is your table written for the person reading the file. Each entry sets a title they see, an editor that decides how a cell is typed, and validators that mark what fails.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const CURRENCIES = ["EUR", "CHF", "GBP"];

const amount = (value: unknown) => {
  const text = String(value).trim();
  if (text === "" || text === "-") return "";
  return text.startsWith("-") ? text.slice(1) : text;
};

export const columns: DataEditorColumn[] = [
  {
    id: "accountNo",
    title: "Account no",
    size: 120,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^\\d{4}$" },
      { type: "unique" },
    ],
  },
  {
    id: "accountName",
    title: "Account name",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "period",
    title: "Period",
    size: 110,
    validators: [
      { type: "required" },
      { type: "regex", pattern: "^\\d{4}-\\d{2}$" },
    ],
  },
  {
    id: "debit",
    title: "Debit",
    size: 150,
    editor: { type: "number" },
    transformer: amount,
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
    dependentFields: ["credit"],
  },
  {
    id: "credit",
    title: "Credit",
    size: 150,
    editor: { type: "number" },
    transformer: amount,
    validators: [
      { type: "number", min: 0, decimalPlaces: 2 },
      {
        type: "function",
        fn: (value, row) =>
          !value &#x26;&#x26; !row.debit
            ? { level: "error", message: "Every line carries a debit or a credit" }
            : null,
      },
    ],
  },
  {
    id: "currency",
    title: "Currency",
    size: 110,
    validators: [{ type: "required" }, { type: "oneOf", values: CURRENCIES }],
  },
  {
    id: "entity",
    title: "Entity",
    size: 200,
    validators: [{ type: "required" }],
  },
];</code></pre>
<p><code>accountNo</code> carries <code>unique</code>, which flags a second line for the same account. That flag is load-bearing. Two source rows for a key the target already holds reach Snowflake's nondeterministic case, and <code>ERROR_ON_NONDETERMINISTIC_MERGE</code> defaults to TRUE, so the statement returns an error. On the first load of that key the pair takes the <code>WHEN NOT MATCHED</code> branch, which Snowflake documents as deterministic, so both rows land and the duplicate survives. The <code>function</code> validator on <code>credit</code> flags a line carrying neither amount, and <code>dependentFields</code> re-runs it whenever the debit beside it changes.</p>
<p>The mount ties that schema to the wizard and teaches matching the words accountants already use.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;TrialBalanceRow>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="accountNo"
  blockSubmitOnError
  synonyms={{
    columns: {
      accountNo: ["account no", "gl code", "nominal code"],
      accountName: ["account name", "gl description", "narrative"],
    },
  }}
  onComplete={onComplete}
/></code></pre>
<p>Column synonyms map <code>GL Code</code> and <code>Nominal Code</code> onto <code>accountNo</code>, so the next firm's export lands without a hand mapping. <code>blockSubmitOnError</code> keeps the submit button disabled while any cell is flagged, which is how a duplicate account number stays out of the staging table. <code>primaryKey</code> is <code>accountNo</code> on its own, because the engagement and the period are chosen in your app before the importer opens. <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">How to import a CSV file into a React app</a> has the modal state and the install this snippet leaves out.</p>
<p>The front-end snippets are React. The web component build takes the same props, so the same schema and the same handler work in Vue, Angular or Svelte.</p>
<h2 id="step-3-read-the-numbers-the-file-carries">Step 3. Read the numbers the file carries</h2>
<p>Updog picks one number format for a file, and it picks it from the file. A value holding both a dot and a comma settles the question on its own, because the last separator is the decimal. <code>1.284.900,00</code> puts the comma last, so the whole file reads as European. The scan covers the headers mapped to number columns alone, so account codes and periods cast no vote.</p>
<p>From that verdict every amount is rewritten. <code>1.284.900,00</code> becomes <code>1284900.00</code>. <code>96 000,00</code> becomes <code>96000.00</code>, since a space grouping in strict three-digit blocks collapses. <code>(2.126.773,11)</code> becomes <code>-2126773.11</code>, since accounting parentheses peel off and set the sign. Currency symbols and percent signs peel off the same way.</p>
<p>Two shapes survive untouched, by design. <code>EUR 1.437,20</code> keeps its letters, because stripping letters would turn an identifier like <code>abc123</code> into <code>123</code>. The dash keeps itself, because a bare sign leaves nothing numeric behind. Both stay exactly as written, and the <code>number</code> validator flags the cell holding letters.</p>
<p>The <code>transformer</code> on both amount columns runs after that rewrite. It receives <code>-2126773.11</code> and drops the sign, because in this export the parentheses mark a credit. It receives the dash and returns an empty string. The <code>number</code> rule passes an empty value, and the <code>function</code> rule beside it is what flags a line carrying neither amount. So the grid opens with one red cell, <code>EUR 1.437,20</code>, and the person types <code>1437.20</code> over it.</p>
<p>One value gets through looking fine. <code>(97,881.64)</code> was written in the convention the file lost. Under the European verdict its dot disappears and its comma becomes the decimal point, which gives <code>-97.88164</code>. That is a finite number, so it is kept, and <code>number</code> passes it. A trade payable of ninety-seven euros now sits in a column of six-figure amounts. <a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> covers more values that parse and still lie.</p>
<h2 id="step-4-check-the-balance-before-the-rows-leave-the-browser">Step 4. Check the balance before the rows leave the browser</h2>
<p>An amount that parses and still lies is what the balance check exists for. Updog Importer groups the submitted rows by source and passes them to your handler, every ledger line tagged <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. A person can upload several files in one pass, and each file arrives as its own source entry. The handler flattens them before it sums.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 1000;

const total = (rows: TrialBalanceRow[], field: "debit" | "credit") =>
  rows.reduce((sum, row) => sum + Number(row[field] || 0), 0);

const onComplete = useCallback(
  async (result: DataEditorResult&#x3C;TrialBalanceRow>) => {
    const rows = result.sources
      .flatMap((source) => source.rows)
      .map((entry) => entry.row);

    const debits = total(rows, "debit");
    const credits = total(rows, "credit");
    if (Math.abs(debits - credits) > 0.005) {
      throw new Error(
        "Debits reach " + debits.toFixed(2) +
          " and credits reach " + credits.toFixed(2),
      );
    }

    for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
      const response = await fetch("/api/trial-balance/import", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          engagementId,
          period,
          rows: rows.slice(start, start + CHUNK_SIZE),
        }),
      });

      if (!response.ok) {
        const failure = await response.json();
        throw new Error(failure.message);
      }
    }
  },
  [engagementId, period],
);</code></pre>
<p>The two totals are compared before the first request goes out. Debits reach 2,224,654.75. Credits reach 2,126,870.99, which is 97,783.76 short, and that difference is the mis-parsed payable to the cent. The handler throws with both numbers, and the editor keeps every row on the screen.</p>
<p><strong>Throw when the write fails.</strong> Updog awaits your handler and clears the editor the moment it resolves. A handler that keeps the error to itself reads like a merge that landed, and those ledger lines leave the screen unwritten. Throwing keeps every row, every mapping and every fix in place, so the person presses submit again on data they can still see. Once the promise resolves, the editor drops its rows, its sources, its history and its learned synonyms. Anything on the result you want to keep gets copied inside the handler first.</p>
<p>A thousand rows a request is a conservative choice of ours, and two published Snowflake numbers sit well above it. One row of this schema serializes to 147 bytes of JSON.</p>
<pre><code class="language-json">{"accountNo":"1010","accountName":"Cash at bank","period":"2026-06","debit":"1284900.00","credit":"","currency":"EUR","entity":"Alpen Handel GmbH"}</code></pre>
<p>A thousand of those reach 147,000 bytes. Snowflake recommends holding query text to 1 MB a statement, and says that figure covers a whole batch of bound data. A single <code>VALUES</code> clause caps at 200,000 rows. Both ceilings are far away, so the number is picked for the person watching a spinner. The confirm dialog holds the whole round trip open until the last chunk lands.</p>
<h2 id="step-5-write-the-chunk-from-your-own-route">Step 5. Write the chunk from your own route</h2>
<p>The route is where the Snowflake key lives and where the browser stops.</p>
<pre><code class="language-ts">import crypto from "node:crypto";
import express from "express";
import snowflake from "snowflake-sdk";

const pool = snowflake.createPool(
  {
    account: process.env.SNOWFLAKE_ACCOUNT,
    username: process.env.SNOWFLAKE_USER,
    role: "IMPORT_WRITER",
    warehouse: "IMPORT_WH",
    database: "AUDIT",
    schema: "LEDGER",
    authenticator: "SNOWFLAKE_JWT",
    privateKeyPath: process.env.SNOWFLAKE_KEY_PATH,
    privateKeyPass: process.env.SNOWFLAKE_KEY_PASS,
  },
  { max: 10, min: 0 },
);

const run = (conn, sqlText, binds) =>
  new Promise((resolve, reject) => {
    conn.execute({
      sqlText,
      binds,
      complete: (err, stmt, rows) => (err ? reject(err) : resolve(rows)),
    });
  });

const app = express();
app.use(express.json({ limit: "5mb" }));

app.post("/api/trial-balance/import", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const { engagementId, period, rows } = request.body;
  const engagement = await loadEngagement(engagementId, session.firmId);
  if (!engagement) return response.status(403).json({ message: "No access" });

  const stray = rows.find((row) => row.period !== period);
  if (stray) {
    return response.status(400).json({
      message: "Account " + stray.accountNo + " carries period " + stray.period,
    });
  }

  const batchId = crypto.randomUUID();
  const loadedAt = new Date().toISOString();
  const binds = rows.map((row) => [
    batchId,
    engagementId,
    period,
    row.accountNo,
    row.accountName,
    row.debit === "" ? null : Number(row.debit),
    row.credit === "" ? null : Number(row.credit),
    row.currency,
    row.entity,
    loadedAt,
  ]);

  try {
    await pool.use(async (conn) => {
      await run(conn, STAGE_INSERT, binds);
      await run(conn, MERGE_BATCH, [batchId]);
      await run(conn, STAGE_CLEAR, [batchId]);
    });
  } catch (error) {
    return response.status(502).json({ message: error.message });
  }

  return response.json({ merged: rows.length });
});</code></pre>
<p><code>getVerifiedSession</code> and <code>loadEngagement</code> stand in for your own checks. The engagement comes off the session and the request body, and never off a row. So the whole chunk lands under one engagement this firm can open. Every row's period is compared against the period the app chose, and a mismatch fails the chunk with the account number that caused it.</p>
<p>The connection authenticates with a key pair. Snowflake documents key pairs as an alternative to basic authentication, asks for a 2048-bit RSA key as a minimum, and registers the public half through <code>ALTER USER example_user ADD KEY PAIR my_key PUBLIC_KEY='...'</code>, which carries a name, an optional role restriction and an optional expiry. Setting the user's <code>RSA_PUBLIC_KEY</code> property is the older path and carries none of the three. The Node.js driver wants <code>authenticator</code> set to <code>SNOWFLAKE_JWT</code> and either the key itself or a path to it. The private key stays on your server.</p>
<p>The JSON body parser Express bundles defaults to a 100kb limit and answers a larger body with 413 and <code>entity.too.large</code>, so this route raises it on purpose. A thousand rows of 147 bytes leave room to spare inside 5 MB.</p>
<h2 id="step-6-merge-the-batch-into-the-trial-balance">Step 6. Merge the batch into the trial balance</h2>
<p>Three statements do the write, and the middle one is the reason for the other two.</p>
<pre><code class="language-sql">-- STAGE_INSERT
insert into ledger.trial_balance_stage
  (batch_id, engagement_id, period, account_no, account_name,
   debit, credit, currency, entity, loaded_at)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

-- MERGE_BATCH
merge into ledger.trial_balance as t
using (
  select * from ledger.trial_balance_stage where batch_id = ?
) as s
  on t.engagement_id = s.engagement_id
 and t.period = s.period
 and t.account_no = s.account_no
when matched then update set
  t.account_name = s.account_name,
  t.debit        = s.debit,
  t.credit       = s.credit,
  t.currency     = s.currency,
  t.entity       = s.entity,
  t.loaded_at    = s.loaded_at
when not matched then insert
  (engagement_id, period, account_no, account_name,
   debit, credit, currency, entity, loaded_at)
  values
  (s.engagement_id, s.period, s.account_no, s.account_name,
   s.debit, s.credit, s.currency, s.entity, s.loaded_at);

-- STAGE_CLEAR
delete from ledger.trial_balance_stage where batch_id = ?;</code></pre>
<p>The insert is one statement carrying an array of rows, which is the shape the Node.js driver documents for a bulk insertion. Each chunk gets its own batch id, so the <code>MERGE</code> reads only the rows this request wrote. <code>WHEN MATCHED</code> updates a line already sitting under this engagement, period and account. <code>WHEN NOT MATCHED</code> inserts the rest. Send the same file again and the same six rows are rewritten, so the row count stays at six and the later file wins. That is the behaviour the unenforced primary key leaves to you.</p>
<p>The delete afterwards drops the batch from the staging table. Rows left behind by a request that failed halfway carry a different batch id, so no later merge reads them.</p>
<p><strong>A warehouse has to be running before any of this executes.</strong> Snowflake requires one for queries and for every DML operation, loading included. Auto-resume defaults to TRUE, so the first statement starts it, and auto-suspend defaults to 600 seconds. Billing runs per second with a 60-second minimum each time the warehouse starts.</p>
<p>Both settings and the ceiling on a statement sit on the warehouse this route uses.</p>
<pre><code class="language-sql">alter warehouse import_wh set
  auto_resume = true,
  auto_suspend = 60,
  statement_timeout_in_seconds = 120;</code></pre>
<p><code>STATEMENT_TIMEOUT_IN_SECONDS</code> defaults to 172800, which is two days, so it caps nothing a person would sit through. Setting it to 120 turns a hung statement into an error the route can answer with. The person is still watching when that answer arrives. Auto-suspend at 60 seconds gives this warehouse a shorter idle life than the default ten minutes. It wakes for one import and goes back to sleep.</p>
<h2 id="step-7-send-the-failure-back-up-the-chain">Step 7. Send the failure back up the chain</h2>
<p>The Node.js driver reports a failure through the complete callback. The <code>run</code> helper in step 5 turns that callback into a rejected promise, so one <code>try</code> covers all three statements. The message reaches the browser as JSON, the handler throws it, and the grid stays exactly as it was.</p>
<p>Chunks that already merged stay merged. A retry re-sends every chunk, and the <code>MERGE</code> writes the same values over the rows that landed, so a repeat costs a rewrite of what already exists.</p>
<p>A duplicate account number inside one chunk is the failure the grid heads off. Snowflake returns an error when one target row matches two source rows, on the default <code>ERROR_ON_NONDETERMINISTIC_MERGE</code>. The <code>unique</code> validator on <code>accountNo</code> and <code>blockSubmitOnError</code> together keep that chunk from being built at all.</p>
<h2 id="the-row-count-that-picks-the-path">The row count that picks the path</h2>
<p>Updog Importer integrates with nobody. There is no Snowflake connector, no destination list, no webhook and no server of ours. Updog calls <code>onComplete</code> with one result object, and everything between it and the <code>MERGE</code> is work you own.</p>
<p>Snowflake already ships its own import for the other case. The Load Data wizard in Snowsight takes a file up to 250 MB, and up to 250 files at a time. Its documentation points larger loads at the Snowflake CLI or SnowSQL. <code>PUT</code> uploads a file from a local file system onto an internal stage, and <code>COPY INTO</code> loads that stage into a table. Snowflake asks for staged files of roughly 100 to 250 MB compressed. Both paths start from a Snowflake seat. <code>PUT</code> also needs the file to sit on the machine running the driver, and rows arriving as a JSON request body are no such file. Taking that route means writing them to disk first.</p>
<p>Row count decides between the two. A thousand trial balance lines fit in one statement well inside Snowflake's 1 MB recommendation. A hundred million rows of transaction detail belong in a staged file and a <code>COPY INTO</code>. That path also skips a file it has already loaded, for the 64 days its load metadata lives. A file your own systems produced takes the shorter road through Snowsight or a stage. Every step above serves a trial balance the client produced, opened by a browser under a session your own app started. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> compares the two models job by job.</p>
<h2 id="the-period-sent-twice">The period sent twice</h2>
<p>You wrote two tables, a schema of seven columns, a handler that checks a balance and chunks, and a route that holds one key pair. The trial balance never leaves the machine the person opened it on. The rows travel from your own front end to your own route, into a staging table, and out of it through one <code>MERGE</code>. The only party added to the chain is you. The same middle serves a plain <a href="https://updog.tech/js-csv-importer/">JavaScript CSV importer</a> page, since the web component takes the props the React component takes.</p>
<p>If the client sends that period again, the second file corrects the first.</p>]]></content:encoded></item>
<item><title>Build vs Buy a CSV Importer When AI Writes the Code</title><link>https://updog.tech/blog/build-vs-buy-csv-importer/</link><guid isPermaLink="true">https://updog.tech/blog/build-vs-buy-csv-importer/</guid><pubDate>Wed, 15 Jul 2026 00:00:00 GMT</pubDate><description>Teams are building CSV importers in-house with AI. The real math on an engineer month against a $100 subscription, and what the first demo leaves out.</description><content:encoded><![CDATA[<p>The deadline I was given to build a data importer from scratch was two months. I had built import screens before, I had a vision for how this one should work, and I had a $100 a month Claude subscription, and that felt like enough.</p>
<p>This is a normal way to start a project now. Teams that would have bought a tool three years ago are building it in-house, and the reasoning sounds the same everywhere. The engineers already have Claude Code or Codex, a first demo appears within days, and a vendor subscription feels like paying for something the team could make themselves. Hand an engineer an AI assistant and a spec, and wish them luck. I am not going to mock that reasoning, because I was that engineer, and part of it is true.</p>
<h2 id="the-first-version-is-the-cheap-part">The first version is the cheap part</h2>
<p>The build side of build vs buy has changed. A file input, a parser, and a table on the screen take several hours with an AI assistant, where they used to take a sprint. A column mapping screen follows in a day or two, and watching it all come together feels like proof that buying is obsolete.</p>
<p>The companies that sell importers have published cost studies about this decision for years, and I am not going to lean on them. They were written before AI assistants, and when I was the engineer with the deadline I would not have believed them either. The math below uses the cheapest assumptions I can defend, and the cheap version makes the argument on its own.</p>
<h2 id="what-an-engineer-month-costs">What an engineer month costs</h2>
<p>An engineer month costs about $9,700. Price an engineer at $60 an hour, which is still below the fully loaded cost of a senior hire in much of the US, and count a month of focused work as 160 hours. That comes to $9,600 for the time, plus $100 for the AI subscription.</p>
<h2 id="what-the-subscription-costs">What the subscription costs</h2>
<p>A Team account pays $100 a month for any number of domains. Updog is free in development and free in production up to 100,000 rows a month, and Team has no row limit.</p>
<h2 id="how-long-one-engineer-month-pays-for">How long one engineer month pays for</h2>
<p>One engineer month buys more than eight years of that subscription, and my two month deadline was worth more than sixteen. The exact numbers move with the team and the market, and pricing the engineer at a higher rate only stretches the years further.</p>
<p>I would understand the debate if the alternative were expensive. Some import tools cost hundreds of dollars a month and some are priced through a sales call, as the pricing section of <a href="https://updog.tech/blog/best-csv-importer-for-react/">my roundup of CSV importers</a> shows, and against those the build case is a real exercise where you model volumes, compare a year of fees to a quarter of engineering, and can end up deciding to build. Against $100 a month the exercise collapses before the spreadsheet is open.</p>
<h2 id="what-the-two-months-do-not-include">What the two months do not include</h2>
<p>The math above assumes the build finishes on time, and this is where my own two months fell apart. That early version reads clean files. Real files arrive from German Excel with semicolons for delimiters, from exports with a title row above the headers, and from spreadsheets where the dates flipped between 3/4 and 4/3 depending on who saved them last. I collected the full list in <a href="https://updog.tech/blog/common-csv-import-errors/">a separate post about common CSV import errors</a>, and the honest summary is that the supply of broken files does not run out.</p>
<p>Past parsing, the person importing the file needs a way to fix what the validation finds, and the list of what that takes keeps growing. Add an editor where the data can be fixed in place. Add filters that narrow a big file down to the rows that need attention. Add search and replace for the mistakes that repeat across rows, and undo for the fixes that go wrong. Add a way to fix many rows at once, the same way a spreadsheet formula fills a whole column instead of touching each cell by hand. Add clipboard support and cell selection, because the person has used Excel or Google Sheets for years and expects the same here. Add keyboard navigation. Add accessibility, so a screen reader can describe what a cell holds. Add right-to-left rendering, because some of the languages a real product supports are read that way, and a good editor has to know how to draw that too. Add performance that holds at 200,000 rows without the browser tab freezing. None of this is in the first demo, and all of it is the product.</p>
<h2 id="the-build-is-never-finished">The build is never finished</h2>
<p>Say the team ships anyway, late but working. The importer now has an owner, and the owner is the team. Every broken file a user uploads becomes a ticket, and every request that sounded out of scope lands on the same backlog as the product itself, whether that is Excel support, larger files, or a second import flow for a second data type. AI made the first version cheap to write, but it did not make the years after it cheap to own, and every sprint the importer takes is a sprint the product does not get.</p>
<h2 id="when-building-is-the-right-call">When building is the right call</h2>
<p>The math is not one sided, and pretending it is would waste your time.</p>
<p>If your users are one known partner sending one known file shape, you do not need an import product yet. An open source parser and a hundred lines of glue is the right build for that one shape, and AI will write most of it for you.</p>
<p>If your import is an ongoing pipeline with scheduled jobs, SFTP drops, or recurring feeds, that is server work, and a browser importer is the wrong shape for it, whether you build it or buy it. There are server side platforms made for that world, and that is not the world Updog is built for.</p>
<p>And if data import is the product you sell, the thing your users choose you for, then build it, own every line of it, and take longer than two months.</p>
<h2 id="the-case-where-building-was-right">The case where building was right</h2>
<p>That last case is mine. My two months ran out with a version that handled clean files and a growing list of real ones it could not, and I kept building long past the deadline. The only reason that made sense is that the importer had stopped being a side task and had become the product itself, and that product is Updog.</p>
<p>You are probably not in that case. If import is one step in your product, buy that step and spend the two months on the thing your users pay you for. The first version was never the expensive part. The years after it are, and at $100 a month those are the years I would rather own for you.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into MySQL</title><link>https://updog.tech/blog/import-csv-into-mysql/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-mysql/</guid><pubDate>Tue, 14 Jul 2026 00:00:00 GMT</pubDate><description>Detect the encoding, map and validate a messy CSV in the browser, then upsert the clean rows into MySQL with ON DUPLICATE KEY UPDATE.</description><content:encoded><![CDATA[<p>MySQL's own documentation covers <code>LOAD DATA</code>, <code>LOAD DATA LOCAL INFILE</code>, <code>mysqlimport</code> and the Workbench Table Data Import Wizard. <code>LOAD DATA</code> reads a CSV the server itself can reach, and it wants the <code>FILE</code> privilege. The <code>LOCAL</code> form reads a file on the client machine, and <code>local_infile</code> is disabled by default on both ends. <code>mysqlimport</code> wraps the same statement on the command line. The wizard takes CSV or JSON and asks the operator for the encoding. Every one of them starts from a seat holding database credentials. Your customer sits outside that seat, holding a menu export from the point-of-sale system they are leaving.</p>
<p>Their export arrives looking like this.</p>
<p><code>menu-export.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">PLU</td><td class="sheet__cell">Item</td><td class="sheet__cell">Menu Group</td><td class="sheet__cell">Price</td><td class="sheet__cell">Allergens</td><td class="sheet__cell">Station</td><td class="sheet__cell">Active</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">1042</td><td class="sheet__cell">Crème Brûlée</td><td class="sheet__cell">DESSERTS</td><td class="sheet__cell">8,50</td><td class="sheet__cell">milk, eggs</td><td class="sheet__cell">Pastry</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">1043</td><td class="sheet__cell">Creme Brulee</td><td class="sheet__cell">DESSERTS</td><td class="sheet__cell">8,50</td><td class="sheet__cell">milk, eggs</td><td class="sheet__cell">Pastry</td><td class="sheet__cell">N</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">1044</td><td class="sheet__cell">Jalapeño Poppers</td><td class="sheet__cell">App</td><td class="sheet__cell">7,25</td><td class="sheet__cell">milk, gluten</td><td class="sheet__cell">Fryer</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">1051</td><td class="sheet__cell">Sea Bass</td><td class="sheet__cell">Main</td><td class="sheet__cell">MP</td><td class="sheet__cell">fish</td><td class="sheet__cell">Grill</td><td class="sheet__cell">Y</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">1052</td><td class="sheet__cell">Elderflower Soda</td><td class="sheet__cell">Bev</td><td class="sheet__cell">4,00</td><td class="sheet__cell"></td><td class="sheet__cell">Bar</td><td class="sheet__cell">Y</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">142 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">149</th><td class="sheet__cell">1236</td><td class="sheet__cell">House Lemonade</td><td class="sheet__cell">Bev</td><td class="sheet__cell">3,75</td><td class="sheet__cell"></td><td class="sheet__cell">Bar</td><td class="sheet__cell">Y</td></tr></tbody></table>
<p>Seven headers sit between semicolons, and the till wrote the file in Windows-1252. <code>Crème Brûlée</code> carries three bytes a strict UTF-8 reader rejects. Two rows name the same dessert, one with accents and one without. The prices use a comma for the decimal point, and one of them reads <code>MP</code> for market price. The menu group column says <code>DESSERTS</code>, <code>App</code>, <code>Main</code> and <code>Bev</code>.</p>
<p>The franchisee opens your app and hands the menu export to the importer. Updog Importer decodes it in the browser, matches the headers to your schema, and puts every value in front of them. Your <code>onComplete</code> handler receives the rows. The handler cuts them into chunks and sends each chunk to a route you own. The route holds the MySQL credentials and runs one <code>INSERT ... ON DUPLICATE KEY UPDATE</code>. MySQL writes the table.</p>
<p>The chain reaches MySQL with no Updog server anywhere in it.</p>
<h2 id="the-table-and-its-unique-key">The table and its unique key</h2>
<p>Pick the unique key before picking the upsert. <code>ON DUPLICATE KEY UPDATE</code> fires when a row would cause a duplicate value in a <code>UNIQUE</code> index or a <code>PRIMARY KEY</code>, so that key decides which rows merge and which arrive new.</p>
<pre><code class="language-sql">create table menu_item (
  id bigint unsigned not null auto_increment primary key,
  location_id bigint unsigned not null,
  plu varchar(16) not null,
  item_name varchar(120) not null,
  category varchar(32) not null,
  price decimal(8, 2) null,
  allergens varchar(255) not null default '',
  station varchar(32) not null,
  active tinyint(1) not null default 1,
  updated_at datetime not null default current_timestamp
    on update current_timestamp,
  unique key uniq_location_plu (location_id, plu)
) engine = innodb default charset = utf8mb4 collate = utf8mb4_0900_ai_ci;</code></pre>
<p>The key sits on <code>location_id</code> and <code>plu</code>, two values made of digits. Naming the dish instead would have cost a row. MySQL's default collation is <code>utf8mb4_0900_ai_ci</code>, and both suffixes are load-bearing. <code>_ci</code> means case-insensitive and <code>_ai</code> means accent-insensitive. MySQL's own manual runs the worked example under an accent-insensitive collation, inserting <code>Bar</code> and <code>Bär</code> into one table and returning both from a search for <code>Bär</code>. A unique index requires every value in it to be distinct, so <code>Creme Brulee</code> and <code>Crème Brûlée</code> would have been one key, and the second write would have updated the first row.</p>
<p>One unique key is also the shape the clause wants. The manual says to avoid <code>ON DUPLICATE KEY UPDATE</code> on tables with multiple unique indexes, and a key made of digits keeps that rule easy to hold.</p>
<p><code>default charset = utf8mb4</code> decides what the column can store. In MySQL 9.7 the name <code>utf8</code> is still the deprecated alias for <code>utf8mb3</code>, which takes up to three bytes a character and covers the Basic Multilingual Plane alone. A character outside that plane does not fit a <code>utf8mb3</code> column, and MySQL's error 1366 reads <code>Incorrect string value</code>. The manual calls <code>utf8mb4</code> the recommended character set and says every new application should use it.</p>
<h2 id="the-columns-the-person-sees">The columns the person sees</h2>
<p>The <code>columns</code> array carries your <code>menu_item</code> table in the words the franchisee reads. Each entry holds a <code>title</code> for the header, an editor that decides how a cell gets typed, and validators that mark failures.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const GROUPS = ["Starters", "Mains", "Sides", "Desserts", "Drinks"];

export const columns: DataEditorColumn[] = [
  {
    id: "plu",
    title: "PLU",
    size: 100,
    transformer: (value) => String(value).trim(),
    validators: [{ type: "required" }, { type: "unique" }],
  },
  {
    id: "itemName",
    title: "Item name",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "category",
    title: "Menu group",
    size: 150,
    editor: { type: "select", options: GROUPS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: GROUPS }],
  },
  {
    id: "price",
    title: "Price",
    size: 110,
    editor: { type: "number" },
    validators: [{ type: "number", min: 0, decimalPlaces: 2 }],
  },
  { id: "allergens", title: "Allergens", size: 180 },
  { id: "station", title: "Station", size: 130 },
  {
    id: "active",
    title: "Active",
    size: 100,
    editor: { type: "select", options: ["Yes", "No"], enableCustomValue: false },
    validators: [{ type: "oneOf", values: ["Yes", "No"] }],
  },
];</code></pre>
<p>The <code>number</code> editor turns <code>8,50</code> into <code>8.50</code>. Number columns vote on the file's format before any value is rewritten, and four comma decimals against no dot decimals settle this file as European. <code>MP</code> survives that pass untouched, because stripping letters would corrupt a code like <code>abc123</code>, and the <code>number</code> validator flags the cell for the person to fix. The <code>select</code> editor with <code>enableCustomValue</code> off holds the menu group to five options and sends everything else to the value matching step. <code>{ type: "unique" }</code> on <code>plu</code> mirrors the unique key in the table, so a repeated PLU is flagged in the browser before MySQL ever sees it.</p>
<p>The <code>synonyms</code> prop hands matching the words your franchisees already use, and the mount below puts every prop in one place.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;MenuItem>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="plu"
  synonyms={{
    columns: { plu: ["item code", "menu id"], category: ["course", "section"] },
    values: { Starters: ["app", "appetizer"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p>Every header in this file matches on its own, so the column synonyms are there for the next till, which calls the same field <code>Item Code</code> or <code>Course</code>. <code>DESSERTS</code> lands on <code>Desserts</code> exactly, once matching lowercases it. <code>Main</code> scores as a string contained in <code>Mains</code>. <code>Y</code> and <code>N</code> reach <code>Yes</code> and <code>No</code> from the built-in table with no configuration at all. <code>App</code> scores nothing against <code>Starters</code>, which is why it comes from <code>synonyms</code>. <code>Bev</code> reaches nothing, so the person maps it by hand, and that pair comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> walks that pair from the grid into the next menu file.</p>
<p><code>primaryKey</code> decides how an imported row meets a row already in the grid. Inside one import the location is fixed, so the PLU alone identifies a menu item on the browser side. Values are compared after surrounding whitespace is trimmed. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<p>Every snippet here is React. The web component build takes the same props, so a Vue, Angular or Svelte front end declares the same columns and the same handler.</p>
<h2 id="encoding-before-the-write">Encoding before the write</h2>
<p>None of that matters while the file is still bytes. Updog decodes it first, inside the parse worker, before a single header is read.</p>
<p>The first bytes settle the easy cases. A byte order mark names UTF-8 or UTF-16 outright, and the decoder strips it. With no mark, a strict UTF-8 decode runs over the first 64KB. A file that survives that pass is checked again with a fatal decode of the whole file, so legacy bytes hiding behind an ASCII-clean opening cannot slip through. A file that fails goes to chardet, which reads the byte statistics and names a character set. When chardet has no guess at all, Windows-1252 takes the file, because it decodes every byte sequence and never throws.</p>
<p>The first data row of the menu export reads two ways, depending on whether detection ran.</p>
<pre><code class="language-plaintext">no detection      1042;Cr�me Br�l�e;DESSERTS;8,50
after detection   1042;Crème Brûlée;DESSERTS;8,50</code></pre>
<p>Byte <code>0xE8</code> opens a three-byte UTF-8 sequence that never arrives, so a reader with no detection writes the replacement character in its place. The name reaches your handler intact instead, as UTF-8, whatever byte table the till used.</p>
<p>Every cell is cleaned after the decode. Zero-width characters come out, a non-breaking space becomes an ordinary space, and the text is normalised to NFC. That last one earns its place here, because Unicode writes <code>è</code> two ways and MySQL has no normalisation of its own. It stores the bytes it was handed, so the same name written both ways sits in the column as two different strings. The delimiter is a vote as well. Comma, semicolon, tab and pipe are each counted outside quotes across the first ten lines, and the candidate with the steadiest count wins. A candidate that misses a line entirely is out, which is what happens to the comma here, since the header line holds none while <code>milk, eggs</code> holds one. <a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors</a> walks the rest of that list.</p>
<p>By the time the grid opens, the file is text in one encoding with one delimiter, and every cell has been trimmed and normalised. What travels next is the shape your handler reads.</p>
<h2 id="the-chunked-post-to-your-own-route">The chunked post to your own route</h2>
<p>The franchisee presses submit, and Updog Importer hands your handler every menu row grouped by source, carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. A franchisee can drop three menu exports in one import, and each file lands as its own source entry, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 500;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;MenuItem>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/menu-items/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>Five hundred is a conservative choice of ours, sitting inside two ceilings that are published. The first is the body your own route accepts. Fastify caps a request body at 1,048,576 bytes by default and answers a larger one with <code>FST_ERR_CTP_BODY_TOO_LARGE</code>. One menu row of these seven fields serializes to about 140 bytes.</p>
<pre><code class="language-json">{"plu":"1042","itemName":"Crème Brûlée","category":"Desserts","price":"8.50","allergens":"milk, eggs","station":"Pastry","active":"Yes"}</code></pre>
<p>Five hundred of those reach roughly 70KB, and 1 MiB holds around 7,400 of them. Run that division against your own widest row before raising the number. A menu carrying a long description per dish changes the answer.</p>
<p>The second ceiling is the packet. One statement travels to MySQL as one packet, the server default for <code>max_allowed_packet</code> is 64MB, and the largest packet the protocol carries is 1GB. Both the client and the server hold their own copy of that variable, so raising it means raising it twice. At 500 menu rows the statement sits three orders of magnitude inside the default, which makes the body limit the ceiling that binds here. Widen the row or lower the packet limit and the two swap places.</p>
<p><strong>A failed chunk has to throw.</strong> Updog holds the editor open only while your handler runs, and empties it the moment the promise resolves. A handler that catches its own failure and returns reads as success, and the menu rows leave the screen unsaved. A spinner covers the confirm dialog until the last chunk answers, which is the other reason chunks stay small. Throwing leaves every menu row, every mapping and every correction on the screen, so the franchisee submits again on data still in front of them.</p>
<p>Copy anything off the result you plan to keep while the handler is still running. The editor releases its rows, its sources, its history and its learned synonyms as soon as the promise resolves.</p>
<p>The <code>isValid</code> filter in that snippet costs this menu a row. A failed validator marks the cell and lets the person submit anyway, so the row holding <code>MP</code> reaches your handler and the filter drops it on the floor. Pass <code>blockSubmitOnError</code> to the editor and submit stays locked until every menu row passes. Keeping the filter open works too, once you split the rows by <code>isValid</code> and post the failures somewhere your support team can read them.</p>
<h2 id="the-write-from-your-own-server">The write from your own server</h2>
<p>The statement is one <code>INSERT</code> carrying every row in the chunk.</p>
<pre><code class="language-sql">insert into menu_item
  (location_id, plu, item_name, category, price, allergens, station, active)
values
  (?, ?, ?, ?, ?, ?, ?, ?),
  (?, ?, ?, ?, ?, ?, ?, ?)
as new
on duplicate key update
  item_name = new.item_name,
  category  = new.category,
  price     = new.price,
  allergens = new.allergens,
  station   = new.station,
  active    = new.active;</code></pre>
<p><code>AS new</code> names the row being inserted, so the update half can read its values. That alias arrived in MySQL 8.0.19 and replaced the <code>VALUES()</code> function, which has been deprecated since 8.0.20 and is subject to removal. Affected rows counts 1 for a row inserted, 2 for a row updated, and 0 for a row set to the values it already held, so the total is a write count rather than a row count.</p>
<p>The browser goes no further than your route, and the MySQL credentials wait on the other side of it.</p>
<pre><code class="language-ts">import Fastify from "fastify";
import mysql from "mysql2/promise";
import type { ResultSetHeader } from "mysql2/promise";

const pool = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  charset: "utf8mb4",
  connectionLimit: 10,
});

const app = Fastify();

app.post("/api/menu-items/import", async (request, reply) => {
  const session = await getVerifiedSession(request);
  if (!session) return reply.code(401).send({ message: "Not signed in" });

  const { rows } = request.body as { rows: MenuItem[] };
  const values = rows.map((row) => [
    session.locationId,
    row.plu,
    row.itemName,
    row.category,
    row.price === "" ? null : Number(row.price),
    row.allergens,
    row.station,
    row.active === "Yes" ? 1 : 0,
  ]);

  try {
    const [result] = await pool.query&#x3C;ResultSetHeader>(
      buildUpsert(values.length),
      values.flat(),
    );
    return { affectedRows: result.affectedRows };
  } catch (cause) {
    const error = cause as { code?: string; errno?: number; message: string };
    const status = error.code === "ER_DUP_ENTRY" ? 409 : 400;
    return reply
      .code(status)
      .send({ message: error.message, code: error.code, errno: error.errno });
  }
});</code></pre>
<p><code>buildUpsert</code> returns the statement above with one placeholder group per row in the chunk. <code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>location_id</code> comes off that session and never off the request body, because a franchisee who can post rows can also post a different location id.</p>
<p><code>charset</code> names the connection character set explicitly. The driver already opens <code>utf8mb4_unicode_ci</code> when the option is absent, and writing it out keeps the connection and the column describing the same thing. The column charset is the one that decides what gets stored.</p>
<p><code>price</code> arrives as the string <code>8.50</code>, and converting it before it enters the parameter list keeps the payload matching a <code>decimal</code> column. <code>active</code> arrives as <code>Yes</code> or <code>No</code> from the select column and becomes 1 or 0.</p>
<h2 id="duplicate-keys-and-failed-chunks">Duplicate keys and failed chunks</h2>
<p><code>mysql2</code> rejects the promise on a server error, and the error carries <code>code</code> as a string alongside <code>errno</code> as a number. A duplicate on a unique index the clause did not resolve comes back as <code>ER_DUP_ENTRY</code>, error 1062, <code>Duplicate entry</code>. A statement bigger than the packet limit comes back as <code>ER_NET_PACKET_TOO_LARGE</code>, error 1153, and MySQL closes the connection behind it. A character the column cannot hold comes back as error 1366, <code>Incorrect string value</code>.</p>
<p>Pass <code>code</code> and <code>message</code> back to the browser. The handler throws on the first response that is not <code>ok</code>, and the editor keeps everything the person did.</p>
<p>Chunks that already landed stay landed. Running the same chunk again writes the same values a second time, so a retry after a failure costs a rewrite of rows that already exist. Those rows report 0 affected, which is how the second run says it changed nothing.</p>
<h2 id="mysqls-own-import-paths">MySQL's own import paths</h2>
<p>Updog Importer integrates with nobody. There is no MySQL connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route between it and MySQL is yours to write.</p>
<p>MySQL already ships an import for the other case. <code>LOAD DATA</code> needs the <code>FILE</code> privilege, and <code>secure_file_priv</code> decides which directory the server will read from, so the file has to reach the database host first. <code>LOAD DATA LOCAL INFILE</code> reads from the client machine and needs <code>local_infile</code> enabled on the server and requested by the client. MySQL disables it by default, since a patched server could ask a client for any file that client can read. <code>mysqlimport</code> is a command-line wrapper around the same statement, it takes the table name from the file name, and without <code>--replace</code> or <code>--ignore</code> a duplicate key aborts it and the rest of the file is ignored. MySQL Workbench reads CSV and JSON through its Table Data Import Wizard, with an encoding field the operator picks by hand.</p>
<p>Every one of those is the shorter path when the file belongs to the developer. Everything above exists for the menu export that belongs to a franchisee, arriving through a browser, in a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> lays out which of the two a job wants.</p>
<h2 id="the-finished-chain">The finished chain</h2>
<p>The franchisee's file never left their laptop. The rows travelled from your own front end to your own route, and from there into MySQL, and the only party added to the chain is yourself. The table declares <code>utf8mb4</code>, one unique key made of digits, and a collation you picked on purpose.</p>
<p>If the column declares <code>utf8mb4</code> and the unique key names the identity your schema already uses, the rows the person cleaned in the browser reach MySQL as the same rows they saw on the screen.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into ClickHouse</title><link>https://updog.tech/blog/import-csv-into-clickhouse/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-clickhouse/</guid><pubDate>Mon, 13 Jul 2026 00:00:00 GMT</pubDate><description>Match an agency's spend export in the browser, check its campaign ids against your warehouse, and land every change into a ReplacingMergeTree as one append.</description><content:encoded><![CDATA[<p>ClickHouse documents several ways to move a CSV into a table. The command line client takes a file on its standard input with <code>FORMAT CSVWithNames</code>. A SQL statement reads one from disk with <code>INSERT INTO sometable FROM INFILE 'data.csv' FORMAT CSV</code>. The <code>file()</code> table function queries a CSV where it sits and infers its types. The Cloud console takes a JSON, CSV or TSV file through the browser, and ClickPipes pulls from S3, GCS, Postgres and Kafka. Every one of those starts from a seat that already holds the credentials. Your customer sits outside that seat, holding a spend export a media agency sent them.</p>
<h2 id="what-clickhouse-checks-when-a-row-lands">What ClickHouse checks when a row lands</h2>
<p>ClickHouse checks almost nothing on the way in, and it says so. The deduplication guide states that ClickHouse does not check for an existing primary key before inserting a row. Its own comparison with BigQuery states that ClickHouse does not enforce uniqueness for a table's primary key column values, and that ClickHouse currently does not support foreign key constraints. So a repeated line lands twice, and a campaign id nobody recognises lands once.</p>
<p>One thing is checked. A <code>CONSTRAINT ... CHECK</code> declared on the table is checked for every row of an <code>INSERT</code>, and a violated one raises an exception naming the constraint and the expression. That exception fails the statement, so it guards the table without telling anybody which line of the file caused it.</p>
<p>Everything else has to happen before the insert. In <a href="https://updog.tech/blog/import-csv-into-bigquery/">how to import CSV into BigQuery</a> a single <code>MERGE</code> settles which row is new and which row is a correction. Here the two places left are the browser and the table engine.</p>
<h2 id="the-file-that-arrives">The file that arrives</h2>
<p>The agency exports the month from its own planning tool, and it looks like this.</p>
<p><code>agency-september.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Date</td><td class="sheet__cell">Channel</td><td class="sheet__cell">Campaign ID</td><td class="sheet__cell">Campaign</td><td class="sheet__cell">Spend</td><td class="sheet__cell">Impr.</td><td class="sheet__cell">Clicks</td><td class="sheet__cell">Ccy</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">01/09/2026</td><td class="sheet__cell">Meta</td><td class="sheet__cell">CMP-4471</td><td class="sheet__cell">Back to school</td><td class="sheet__cell">1.240,50</td><td class="sheet__cell">84 213</td><td class="sheet__cell">1 902</td><td class="sheet__cell">EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">01/09/2026</td><td class="sheet__cell">Meta</td><td class="sheet__cell">CMP-4471</td><td class="sheet__cell">Back to school</td><td class="sheet__cell">1.240,50</td><td class="sheet__cell">84 213</td><td class="sheet__cell">1 902</td><td class="sheet__cell">EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">02/09/2026</td><td class="sheet__cell">meta ads</td><td class="sheet__cell">CMP-4489</td><td class="sheet__cell">Autumn drop</td><td class="sheet__cell">980,00</td><td class="sheet__cell">51 004</td><td class="sheet__cell">743</td><td class="sheet__cell">EUR</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">15/09/2026</td><td class="sheet__cell">OOH</td><td class="sheet__cell">CMP-5102</td><td class="sheet__cell">Station takeover</td><td class="sheet__cell">12.000,00</td><td class="sheet__cell">0</td><td class="sheet__cell">0</td><td class="sheet__cell">EUR</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">407 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">413</th><td class="sheet__cell">30/09/2026</td><td class="sheet__cell">Google Ads</td><td class="sheet__cell">CMP-5230</td><td class="sheet__cell">Brand always-on</td><td class="sheet__cell">2.415,80</td><td class="sheet__cell">118 902</td><td class="sheet__cell">3 044</td><td class="sheet__cell">EUR</td></tr></tbody></table>
<p>Two headers are shortened. <code>Impr.</code> means impressions and <code>Ccy</code> means the currency code. The first two lines are the same line twice. The money carries a dot for thousands and a comma for decimals. The counts carry spaces for thousands. The dates run day first, and the first two of them could be read either way. The channel column says <code>Meta</code> on one line and <code>meta ads</code> on the next, and <code>OOH</code> further down.</p>
<p>The person drops that file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, checks the campaign ids against the warehouse, and puts every value in front of them beside the spend you already hold. Your <code>onComplete</code> handler receives each row with a verdict on it. The handler posts the rows to a route you own, and that route inserts them.</p>
<p>No Updog server stands between the browser and ClickHouse.</p>
<h2 id="the-table-the-rows-land-in">The table the rows land in</h2>
<p>One table holds the spend, and the engine decides what a second import means.</p>
<pre><code class="language-sql">create table analytics.ad_spend
(
  account_id    String,
  spend_date    Date,
  channel       LowCardinality(String),
  campaign_id   String,
  campaign_name String,
  spend         Decimal(12, 2),
  impressions   UInt32,
  clicks        UInt32,
  currency      LowCardinality(String),
  source_file   String,
  version       DateTime64(3) default now64(3),
  is_deleted    UInt8 default 0,
  constraint spend_not_negative check spend >= 0
)
engine = ReplacingMergeTree(version, is_deleted)
partition by toYYYYMM(spend_date)
order by (account_id, spend_date, channel, campaign_id);</code></pre>
<p><code>ReplacingMergeTree</code> removes duplicate entries with the same sorting key value, and uniqueness of rows comes from the <code>ORDER BY</code> section. The <code>PRIMARY KEY</code> clause has no say in it. With a version column named, the row carrying the maximum version survives. So an update is an insert of the same four key columns with a fresh <code>version</code>, and <code>now64(3)</code> fills that column at insert time because the browser has no business stamping it.</p>
<p><code>is_deleted</code> is the other half. ClickHouse describes it as the column that says whether a row is the state or is to be deleted, <code>1</code> for deleted and <code>0</code> for state, typed <code>UInt8</code>. It can only be enabled when a version column is used. So a delete arrives as a row like any other.</p>
<p>The rest of the table is ordinary warehouse work. <code>channel</code> and <code>currency</code> take <code>LowCardinality</code>, which ClickHouse suggests for a cardinality under ten thousand. <code>spend_date</code> is a <code>Date</code>, two bytes, covering 1970-01-01 to 2149-06-06. The <code>CHECK</code> constraint refuses a negative spend, and the schema in the browser refuses it first.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array is the same table written for the person looking at the file.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const CHANNELS = ["Meta", "Google Ads", "TikTok", "Out of home"];
const CURRENCIES = ["EUR", "GBP", "USD"];

export const columns: DataEditorColumn[] = [
  {
    id: "spendDate",
    title: "Spend date",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "channel",
    title: "Channel",
    size: 150,
    editor: { type: "select", options: CHANNELS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: CHANNELS }],
  },
  {
    id: "campaignName",
    title: "Campaign name",
    size: 200,
    transformer: (value) => String(value).trim(),
  },
  {
    id: "spend",
    title: "Spend",
    size: 120,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "impressions",
    title: "Impressions",
    size: 130,
    editor: { type: "number" },
    validators: [{ type: "number", decimalPlaces: 0 }],
  },
  {
    id: "clicks",
    title: "Clicks",
    size: 110,
    editor: { type: "number" },
    validators: [{ type: "number", decimalPlaces: 0 }],
  },
  {
    id: "currency",
    title: "Currency",
    size: 120,
    editor: { type: "select", options: CURRENCIES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: CURRENCIES }],
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>number</code> editor reads <code>1.240,50</code> as 1240.50, because a value carrying both separators is proof on its own, the last one being the decimal. That single value settles the punctuation for the whole file. Space grouping needs no verdict at all, so <code>84 213</code> loses its space and lands as 84213. The <code>date</code> editor turns <code>15/09/2026</code> into <code>2026-09-15</code>, and since 15 is above 12 the file settles day first, so the two rows that could have gone either way land as <code>2026-09-01</code> and <code>2026-09-02</code>. A file where every date part stays at or below 12 settles on the runtime locale instead, which is the case worth sending your customer a template for.</p>
<p>The <code>select</code> editors hold the channel and the currency to a fixed list, and a value nobody maps is dropped from the row.</p>
<h2 id="the-check-against-the-campaigns-you-already-hold">The check against the campaigns you already hold</h2>
<p>A campaign id is a reference to another table, and ClickHouse holds no foreign keys. So the check runs while the person is still looking at the file.</p>
<pre><code class="language-ts">{
  id: "campaignId",
  title: "Campaign id",
  size: 150,
  validators: [
    { type: "required" },
    { type: "regex", pattern: "^CMP-\\d{4}$" },
    {
      type: "asyncFunction",
      fn: async (cells, onChunk, signal) => {
        for (let offset = 0; offset &#x3C; cells.length; offset += 500) {
          if (signal.aborted) return;
          const batch = cells.slice(offset, offset + 500);

          const response = await fetch("/api/spend/campaigns/known", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              ids: batch.map((cell) => String(cell.value)),
            }),
          });
          const known = new Set&#x3C;string>(await response.json());

          onChunk(
            batch.flatMap((cell, index) =>
              known.has(String(cell.value))
                ? []
                : [{
                    index: offset + index,
                    error: {
                      level: "error",
                      message: "No campaign with this id",
                    },
                  }],
            ),
          );
        }
      },
    },
  ],
}</code></pre>
<p><code>asyncFunction</code> receives every affected cell for the column in one call, each with its own row for context, and reports failures by index. Batching is yours, which is why the loop splits the work into five hundred ids a request and streams verdicts back through <code>onChunk</code> as they arrive. Opening a file triggers a full check of the column, so the first sweep carries one cell per row and later sweeps carry only what changed. Async validators run after every sync validator, whatever their position in the array, so the regex rejects a malformed id before the warehouse is asked about it.</p>
<p>The endpoint answers out of ClickHouse itself.</p>
<pre><code class="language-ts">import { createClient } from "@clickhouse/client";

export const clickhouse = createClient({
  url: process.env.CLICKHOUSE_URL,
  username: process.env.CLICKHOUSE_USER,
  password: process.env.CLICKHOUSE_PASSWORD,
});

const KNOWN_CAMPAIGNS =
  "select campaign_id from analytics.dim_campaign " +
  "where account_id = {account: String} " +
  "and campaign_id in {ids: Array(String)}";

app.post("/api/spend/campaigns/known", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const ids = request.body.ids.slice(0, 500).map(String);
  const result = await clickhouse.query({
    query: KNOWN_CAMPAIGNS,
    query_params: { account: session.accountId, ids },
    format: "JSONEachRow",
  });

  const rows = await result.json&#x3C;{ campaign_id: string }>();
  response.json(rows.map((row) => row.campaign_id));
});

const CURRENT_SPEND =
  "select spend_date as spendDate, channel, " +
  "campaign_id as campaignId, campaign_name as campaignName, " +
  "spend, impressions, clicks, currency " +
  "from analytics.ad_spend final " +
  "where account_id = {account: String} " +
  "and is_deleted = 0 " +
  "and spend_date >= {from: Date} " +
  "order by spend_date, channel, campaign_id";

app.get("/api/spend/current", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const result = await clickhouse.query({
    query: CURRENT_SPEND,
    query_params: { account: session.accountId, from: "2026-09-01" },
    format: "JSONEachRow",
  });

  response.json({ rows: await result.json() });
});</code></pre>
<p><code>query_params</code> keeps the ids out of the SQL text, and the account comes off the session on your server. The second route is what fills the editor when it opens. It reads with <code>FINAL</code>, which is how ClickHouse asks for the deduplicated view at query time. It also filters <code>is_deleted = 0</code>, since a delete row survives the merge until a cleanup pass removes it. The select aliases the warehouse's snake_case to the column ids, because <code>loadData</code> matches a row to a column by id.</p>
<p><code>CMP-5102</code> comes back unknown, so the person sees the error on the row and either fixes the id or removes the line. That is the check a database with foreign keys would have run for you, moved to the one moment somebody is still there to answer it.</p>
<h2 id="the-mount">The mount</h2>
<p>The props tie the file, the schema and the warehouse together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Spend>
  apiKey="your-license-key"
  open={open}
  onClose={closeEditor}
  columns={columns}
  primaryKey={["spendDate", "channel", "campaignId"]}
  enableDeleteRow="all"
  blockSubmitOnError
  synonyms={{
    columns: { currency: ["ccy", "curr", "currency code"] },
    values: { "Out of home": ["ooh", "outdoor", "billboard"] },
  }}
  loadData={async (onChunk) => {
    const response = await fetch("/api/spend/current");
    const body = await response.json();
    if (!response.ok) throw new Error(body.message);
    onChunk(body.rows, { source: "ClickHouse", done: true });
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>Ccy</code> reaches <code>currency</code> through the <code>synonyms</code> table and through nothing else. Fuzzy matching scores it at zero. Three characters fall under the four-character floor the contains tier needs, <code>ccy</code> shares no whole word with <code>currency</code>, and the length gap of five exceeds the two edits allowed at that length. A match needs sixty. The same table carries <code>ooh</code> on the value side, where <code>Out of home</code> stands too far away to be reached alone. <code>meta ads</code> needs no help, since <code>meta</code> sits inside it and the contains tier scores eighty. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time.</p>
<p><code>primaryKey</code> takes three columns, because one campaign spends on one channel on one day. The warehouse key has a fourth part, and <code>account_id</code> never reaches the browser at all. <code>enableDeleteRow="all"</code> lets the person drop a line the agency invoiced by mistake, and <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, the unknown campaign id included.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. The flags are independent, so one row can be new, changed and deleted at once. Rows that merged onto warehouse rows arrive under the ClickHouse source as changed. Rows the file added arrive under the file's own name as new. A warehouse row nobody touched never appears.</p>
<pre><code class="language-tsx">import type { DataEditorResult, ResultRow } from "@updog/data-editor";

const CHUNK_SIZE = 50_000;

const toRow = (entry: ResultRow&#x3C;Spend>, sourceFile: string) => {
  if (entry.isDeleted &#x26;&#x26; entry.isNew) return [];
  return [{
    spend_date: entry.row.spendDate,
    channel: entry.row.channel,
    campaign_id: entry.row.campaignId,
    campaign_name: entry.row.campaignName,
    spend: entry.row.spend,
    impressions: entry.row.impressions,
    clicks: entry.row.clicks,
    currency: entry.row.currency,
    source_file: sourceFile,
    is_deleted: entry.isDeleted ? 1 : 0,
  }];
};

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Spend>) => {
  const rows = result.sources.flatMap((source) => {
    return source.rows.flatMap((entry) => toRow(entry, source.sourceName));
  });

  const batchId = crypto.randomUUID();

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const written = await fetch("/api/spend/rows", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        batchId,
        offset: start,
        rows: rows.slice(start, start + CHUNK_SIZE),
      }),
    });
    if (!written.ok) throw new Error((await written.json()).message);
  }
}, []);</code></pre>
<p>Three flags become one column. An insert and an update are the same payload, since the engine settles which version wins, and a delete is the same payload with <code>is_deleted</code> set to 1. A row the person added and then deleted goes nowhere.</p>
<p>The chunk size comes from ClickHouse's own guidance, which asks for batches of at least a thousand rows and ideally between ten thousand and a hundred thousand. Fewer and larger inserts write fewer parts, and many small ones end in the <code>TOO_MANY_PARTS</code> error. Fifty thousand sits inside that band and stays well under <code>max_insert_block_size</code>, which is around a million rows and is the point where a single insert stops being one block. An insert of one block into one partition of a MergeTree table is transactional, and this table partitions by month, so a chunk covering two months commits per partition.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished import, and the month clears the grid unwritten. A thrown error keeps the grid as it stands, with every match and hand correction on it. The person submits again on rows that never left the screen.</p>
<p>The whole loop runs behind a spinner in the confirm dialog. Anything on the result worth keeping gets copied inside the handler, since the editor drops its rows, its sources, its history and its learned synonyms once the promise resolves.</p>
<h2 id="the-route-that-inserts">The route that inserts</h2>
<p>The route holds the credentials, and the browser stops there.</p>
<pre><code class="language-ts">import { ClickHouseError } from "@clickhouse/client";

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;

app.post("/api/spend/rows", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });
  if (!UUID.test(request.body.batchId)) {
    return response.status(400).json({ message: "Bad batch id" });
  }

  const values = request.body.rows.map((row) => ({
    ...row,
    account_id: session.accountId,
  }));

  try {
    await clickhouse.insert({
      table: "analytics.ad_spend",
      values,
      format: "JSONEachRow",
      clickhouse_settings: {
        insert_deduplication_token:
          request.body.batchId + ":" + request.body.offset,
      },
    });
  } catch (error) {
    if (error instanceof ClickHouseError) {
      request.log.error({ code: error.code, type: error.type });
      return response.status(502).json({ message: error.type ?? "Insert failed" });
    }
    throw error;
  }

  response.json({ written: values.length });
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>account_id</code> comes off that session and never off the request body, so a guessed batch id reaches no other tenant's rows. The client posts <code>JSONEachRow</code> over HTTP, and the columns nobody sent take their declared defaults, which is how <code>version</code> fills itself.</p>
<p><code>insert_deduplication_token</code> is what makes a repeated POST safe. ClickHouse identifies a repeated insert by a hash of the block, and a supplied token takes priority over that hash, so one chunk arriving twice under the same batch id lands once. The token is tracked per partition, so a chunk spanning two months carries it into both. A fresh submit mints a fresh batch id, and there the version column settles the repeat. Deduplication is on by default for the <code>ReplicatedMergeTree</code> family, inside a window of ten thousand blocks or one hour. A single-node MergeTree table starts with <code>non_replicated_deduplication_window</code> at 0, so a self-managed reader sets it before leaning on any of this.</p>
<h2 id="what-the-merge-promises">What the merge promises</h2>
<p>Deduplication happens during a merge, and merges run in the background at an unknown time. Until one runs, the table holds every row that was inserted. The agency's file carried the same line twice, and Updog leaves both on screen because two rows from one file never merge into each other, so both land in ClickHouse.</p>
<p>A plain <code>SELECT</code> over that table counts the spend twice. <code>FINAL</code> is the answer ClickHouse documents for it, since background merges alone cannot promise a deduplicated read, and the read route above carries it. <code>FINAL</code> merges at query time and reads the primary key columns on top of the ones you asked for, so it runs slower than the same query without it, which is the moment to reach for an aggregating view or an <code>argMax</code> over the version column.</p>
<p>When the agency sends a corrected September, the same three key columns arrive with a fresh <code>now64(3)</code>, and the newer version wins from the moment it lands.</p>
<h2 id="when-an-insert-fails">When an insert fails</h2>
<p>The client throws a <code>ClickHouseError</code> carrying a <code>code</code> and a <code>type</code> parsed out of the server's message. <code>TOO_MANY_PARTS</code> is 252 and means the inserts are too small or too frequent. <code>VIOLATED_CONSTRAINT</code> is 469 and names the <code>CHECK</code> that refused the row. <code>TYPE_MISMATCH</code> is 53 and means a value reached a column that cannot hold it.</p>
<p>There is no per-row failure list. The insert fails as a block, and the message names the constraint or the parse position. A file-shaped load can be told to tolerate some of that through <code>input_format_allow_errors_num</code> and <code>input_format_allow_errors_ratio</code>, both of which sit at 0 by default and skip a failing row while the counter stays under the limit. This import takes the other route, where the person sees the bad row on screen while the file is still theirs to fix.</p>
<h2 id="the-routes-nobody-ships-for-you">The routes nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no ClickHouse connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the routes in the middle are work you do.</p>
<p>ClickHouse already ships its own ways in for the other case. The command line client streams a file straight into a table. <code>FROM INFILE</code> reads one from disk. The <code>file()</code> table function queries a CSV where it sits and guesses its types, and <code>DESCRIBE</code> shows the guess before anything is loaded. The Cloud console takes a JSON, CSV or TSV file, and ClickPipes keeps object storage and Postgres flowing in. For an export your own team downloaded, those tools are the shorter way in. Everything above exists for the export an agency sent, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-export">The pieces you wrote and the next export</h2>
<p>You wrote one table, a schema with eight columns, an async check against the campaigns you already hold, a read route, a handler that turns three flags into one column, and one insert route. The file stays on the machine that opened it. The rows travel from your own front end to your own route and into ClickHouse, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The agency will send October, and half of it will be September again with two lines corrected. That time the mappings are already stored, the editor opens on the spend that landed last time, and the version column decides the rest.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into BigQuery</title><link>https://updog.tech/blog/import-csv-into-bigquery/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-bigquery/</guid><pubDate>Fri, 10 Jul 2026 00:00:00 GMT</pubDate><description>Match several meter reading files in the browser, stage them from your own Node endpoint, and land them in BigQuery with one partition-aware MERGE.</description><content:encoded><![CDATA[<p>BigQuery documents several ways to move a CSV into a table. The Cloud console takes an upload, and a local file there cannot pass 100 MB. The <code>bq load</code> command runs the same job from a terminal. A load job from Cloud Storage carries up to 15 TB across as many as ten million files. The Storage Write API streams rows in as they happen. Every one of those starts from a seat that already holds the project's IAM. Your customer sits outside that seat, holding a folder of meter readings a property manager exported, one file per building.</p>
<p>Two of those files arrive looking like this.</p>
<p><code>riverside-court-march.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">meter_serial</td><td class="sheet__cell">site</td><td class="sheet__cell">read_date</td><td class="sheet__cell">register</td><td class="sheet__cell">reading_kwh</td><td class="sheet__cell">tariff</td><td class="sheet__cell">read_type</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">E14K0392117</td><td class="sheet__cell">Riverside Court</td><td class="sheet__cell">2026-03-01</td><td class="sheet__cell">R1</td><td class="sheet__cell">12345.6</td><td class="sheet__cell">Day</td><td class="sheet__cell">Actual</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">E14K0392117</td><td class="sheet__cell">Riverside Court</td><td class="sheet__cell">2026-03-01</td><td class="sheet__cell">R2</td><td class="sheet__cell">4180.2</td><td class="sheet__cell">Night</td><td class="sheet__cell">Actual</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">E14K0392208</td><td class="sheet__cell">Riverside Court</td><td class="sheet__cell">2026-03-01</td><td class="sheet__cell">R1</td><td class="sheet__cell">9874.0</td><td class="sheet__cell">Peak</td><td class="sheet__cell">Estimated</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">180 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">185</th><td class="sheet__cell">E14K0397740</td><td class="sheet__cell">Riverside Court</td><td class="sheet__cell">2026-03-01</td><td class="sheet__cell">R2</td><td class="sheet__cell">3618.9</td><td class="sheet__cell">Night</td><td class="sheet__cell">Actual</td></tr></tbody></table>
<p>The second building runs on different software, and its export shows it.</p>
<p><code>harbour-view-march.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">msn</td><td class="sheet__cell">site</td><td class="sheet__cell">read_date</td><td class="sheet__cell">register</td><td class="sheet__cell">reading_kwh</td><td class="sheet__cell">tariff</td><td class="sheet__cell">read_type</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">K21M0044831</td><td class="sheet__cell">Harbour View</td><td class="sheet__cell">01.03.2026</td><td class="sheet__cell">R1</td><td class="sheet__cell">12 345,6</td><td class="sheet__cell">DAY</td><td class="sheet__cell">Actual</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">K21M0044902</td><td class="sheet__cell">Harbour View</td><td class="sheet__cell">13.03.2026</td><td class="sheet__cell">R1</td><td class="sheet__cell">8 902,4</td><td class="sheet__cell">Peak</td><td class="sheet__cell">Actual</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">129 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">133</th><td class="sheet__cell">K21M0049518</td><td class="sheet__cell">Harbour View</td><td class="sheet__cell">27.03.2026</td><td class="sheet__cell">R2</td><td class="sheet__cell">4 217,8</td><td class="sheet__cell">Night</td><td class="sheet__cell">Actual</td></tr></tbody></table>
<p>One header disagrees, and it is the one that identifies the meter. <code>msn</code> is a short form for a meter serial number, and no built-in synonym covers it. The readings disagree about punctuation. One file writes <code>12345.6</code> and the other writes <code>12 345,6</code>, with a space for grouping and a comma for the decimal. The dates disagree about order. One file writes <code>2026-03-01</code> and the other writes <code>01.03.2026</code>. The tariff column says <code>Day</code> in one file and <code>DAY</code> in the other.</p>
<p>The person drops both files into the importer inside your app. Updog Importer reads them in the browser, matches each file's headers to your schema, and puts every value in front of them. Your <code>onComplete</code> handler receives the rows grouped by the file they came from. The handler posts them to a route you own. The route stages the batch with a load job and runs one <code>MERGE</code>. BigQuery writes the target table.</p>
<p>No Updog server stands between the browser and BigQuery.</p>
<h2 id="the-tables-the-rows-have-to-reach">The tables the rows have to reach</h2>
<p>Two tables carry the whole design, and the second one is temporary.</p>
<pre><code class="language-sql">CREATE TABLE analytics.meter_readings (
  account_id   STRING    NOT NULL,
  meter_serial STRING    NOT NULL,
  site         STRING    NOT NULL,
  read_date    DATE      NOT NULL,
  register     STRING    NOT NULL,
  reading_kwh  NUMERIC,
  tariff       STRING,
  read_type    STRING,
  source_file  STRING,
  updated_at   TIMESTAMP NOT NULL
)
PARTITION BY read_date
CLUSTER BY account_id, site, meter_serial;

CREATE TABLE staging.meter_readings_inbox (
  batch_id     STRING    NOT NULL,
  account_id   STRING    NOT NULL,
  source_file  STRING    NOT NULL,
  meter_serial STRING,
  site         STRING,
  read_date    DATE,
  register     STRING,
  reading_kwh  NUMERIC,
  tariff       STRING,
  read_type    STRING,
  loaded_at    TIMESTAMP NOT NULL
)
PARTITION BY DATE(loaded_at)
OPTIONS (partition_expiration_days = 3);</code></pre>
<p><code>read_date</code> is the partition column, because every question anybody asks of meter readings names a period. BigQuery partitions a <code>DATE</code> column daily, monthly or yearly, and one table takes one partition column. <code>CLUSTER BY</code> sorts the storage blocks inside each partition, and BigQuery caps that list at four columns. The staging table partitions on load time and carries <code>partition_expiration_days = 3</code>, so a batch nobody merged drops itself. Partitions do not expire by default.</p>
<h2 id="the-schema-in-updog-importer">The schema in Updog Importer</h2>
<p>The <code>columns</code> array is the same shape written for the person looking at the file.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const TARIFFS = ["Day rate", "Night rate", "Peak rate"];
const READ_TYPES = ["Actual", "Estimated", "Customer"];

export const columns: DataEditorColumn[] = [
  {
    id: "meterSerial",
    title: "Meter serial",
    size: 150,
    transformer: (value) => String(value).trim(),
    validators: [{ type: "required" }],
  },
  {
    id: "site",
    title: "Site",
    size: 180,
    validators: [{ type: "required" }],
  },
  {
    id: "readDate",
    title: "Read date",
    size: 130,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "register",
    title: "Register",
    size: 100,
    validators: [{ type: "required" }],
  },
  {
    id: "readingKwh",
    title: "Reading kWh",
    size: 140,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 3 },
    ],
  },
  {
    id: "tariff",
    title: "Tariff",
    size: 140,
    editor: { type: "select", options: TARIFFS, enableCustomValue: false },
    validators: [{ type: "oneOf", values: TARIFFS }],
  },
  {
    id: "readType",
    title: "Read type",
    size: 140,
    editor: { type: "select", options: READ_TYPES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: READ_TYPES }],
  },
];</code></pre>
<p>Each editor earns its place against what arrives. The <code>date</code> editor turns <code>01.03.2026</code> into <code>2026-03-01</code>, the format BigQuery requires for a <code>DATE</code> column in loaded JSON. The <code>number</code> editor collapses the space grouping and swaps the comma for a dot, so <code>12 345,6</code> lands as <code>12345.6</code>. Both editors read the locale off the file itself, and each file in one import gets its own verdict. The date scan settles on the first value carrying a part above 12, which is the <code>13.03.2026</code> in the second file. The number scan settles on a vote, where a value with one separator and one or two trailing digits counts once. Neither file's punctuation reaches the other.</p>
<p>The <code>select</code> editors with <code>enableCustomValue</code> off hold both list columns to their options. Anything outside the list travels to the value matching step, and a value nobody maps is dropped from the row.</p>
<p>The <code>synonyms</code> prop teaches matching the words your customers already use, and the mount ties the rest together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Reading>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey={["meterSerial", "readDate", "register"]}
  synonyms={{
    columns: {
      meterSerial: ["msn", "meter serial number", "meter point"],
      readingKwh: ["kwh", "consumption", "units"],
    },
  }}
  blockSubmitOnError
  onComplete={onComplete}
/></code></pre>
<p><code>msn</code> reaches <code>meterSerial</code> through that table and through nothing else. Fuzzy matching scores it at zero. The string appears inside neither <code>meterSerial</code> nor <code>Meter serial</code>, shares no word with either, and stands nine edits away where the spelling tier allows three. A match needs sixty. The <code>kwh</code> and <code>consumption</code> entries sit there for the next property manager. The tariff values need no help. <code>Night</code> and <code>Peak</code> sit inside <code>Night rate</code> and <code>Peak rate</code>. <code>Day</code> and <code>DAY</code> both flatten to <code>day</code> and reach <code>Day rate</code> on the word they share. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time.</p>
<p><code>primaryKey</code> takes three columns here, because one meter reports several registers on the same day. An imported row merges into an existing row only when all three match. A row with an empty part merges with nothing and arrives as new. That prop settles identity inside the browser. The <code>MERGE</code> further down settles it against the warehouse, and the two have to name the same columns.</p>
<p>Every snippet here is React. Those props reach Vue, Angular and Svelte through the web component build. The meter schema and the handler travel there unchanged. The install and the modal wiring beneath this mount live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="the-result-on-submit">The result on submit</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source. An import contributes one entry per file, plus one per sheet when a workbook holds several. A whole file takes the file name, and a sheet takes the file name and the sheet name together.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const BATCH_SIZE = 500;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Reading>) => {
  const rows = result.sources.flatMap((source) =>
    source.rows
      .filter((entry) => !entry.isDeleted)
      .map((entry) => ({ ...entry.row, sourceFile: source.sourceName })),
  );

  let batchId;

  for (let start = 0; start &#x3C; rows.length; start += BATCH_SIZE) {
    const response = await fetch("/api/readings/stage", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        batchId,
        rows: rows.slice(start, start + BATCH_SIZE),
      }),
    });

    const body = await response.json();
    if (!response.ok) throw new Error(body.message);
    batchId = body.batchId;
  }

  const merged = await fetch("/api/readings/merge", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ batchId }),
  });

  const outcome = await merged.json();
  if (!merged.ok) throw new Error(outcome.message);
}, []);</code></pre>
<p>Every staged row now carries the export it arrived in. When one building's readings turn out wrong, the file that carried them has a name inside the warehouse.</p>
<p>Google's quotas page caps a streaming request at 50,000 rows and adds that a maximum of 500 rows is recommended. Nothing equivalent is published for a load job, so 500 carries over here and keeps each POST small. A different destination publishes different numbers, and <a href="https://updog.tech/blog/import-csv-into-supabase/">how to import CSV into Supabase</a> derives its chunk from a request body cap and a role statement timeout. <code>blockSubmitOnError</code> keeps submit disabled while any row carries an error, so the handler never has to sort clean rows from broken ones.</p>
<p><strong>Throw when a route answers with a failure.</strong> Updog holds submit until your promise resolves, then empties the editor. A handler that traps the error and returns counts as a finished load, and the readings clear the grid unwritten. A thrown error keeps the grid as it stands, with every reading, match and hand correction on it. The person submits again on the readings that never left the screen.</p>
<p>The staging posts and the merge all run behind a spinner in the confirm dialog. That is the second reason a batch stays small. Anything on the result worth keeping gets copied inside the handler. Once the promise resolves the editor drops its rows, its sources, its history and its learned synonyms.</p>
<h2 id="the-fork-in-the-write-path">The fork in the write path</h2>
<p>BigQuery takes rows two ways, and its published limits decide which one a correcting import needs.</p>
<p><strong>Streaming puts rows in front of a query straight away.</strong> The Node client's <code>table.insert()</code> posts to the Storage Write API (REST). Google renamed that path from <code>tabledata.insertAll</code> and still fully supports it. Rows are readable the moment BigQuery acknowledges the request. The request caps at 10 MB and 50,000 rows, and a single row caps at 10 MB. The bill runs $0.01 per 200 mebibytes with a 1 KB minimum per row, and a meter reading row sits far under 1 KB. The client also fills an <code>insertId</code> on every row, and Google calls leaving it out the recommended way to insert data. Set <code>createInsertId</code> to false and the client stops adding one.</p>
<p><strong>Streamed rows are locked against DML for thirty minutes.</strong> BigQuery's own page states it plainly. Rows written through the Storage Write API (REST) cannot be modified by <code>UPDATE</code>, <code>DELETE</code>, <code>MERGE</code> or <code>TRUNCATE</code> inside the last 30 minutes of their write. Rows written through the Storage Write API (gRPC) are exempt on the same page, and that path ships as a separate client package. So an import whose whole job is correcting readings already stored waits half an hour, or it stages the batch and merges.</p>
<p><strong>A load job carries no such buffer.</strong> It costs nothing on the shared slot pool, and its result is atomic across the whole payload. BigQuery allows 1,500 load jobs per table per day. Five hundred rows a request leaves room for 750,000 readings a day into one staging table, which is arithmetic worth redoing against your own volume.</p>
<p><strong>Google points a new project at the gRPC Storage Write API.</strong> Its page names lower pricing and exactly-once delivery semantics. That path costs $0.025 per gibibyte with the first 2 TiB each month free. It also wants protocol buffers, a long-lived connection and a second client package. Reach for it when rows arrive all day from a service you run.</p>
<p>So the path below stages a batch with a load job, then moves it across with one <code>MERGE</code>.</p>
<h2 id="the-load-job-that-stages-a-batch">The load job that stages a batch</h2>
<p>The route holds the credential, and the browser stops there.</p>
<pre><code class="language-ts">import { BigQuery } from "@google-cloud/bigquery";
import { Readable } from "node:stream";
import { randomUUID } from "node:crypto";

const bigquery = new BigQuery();
const inbox = bigquery.dataset("staging").table("meter_readings_inbox");

const SCHEMA = {
  fields: [
    { name: "batch_id", type: "STRING", mode: "REQUIRED" },
    { name: "account_id", type: "STRING", mode: "REQUIRED" },
    { name: "source_file", type: "STRING", mode: "REQUIRED" },
    { name: "meter_serial", type: "STRING" },
    { name: "site", type: "STRING" },
    { name: "read_date", type: "DATE" },
    { name: "register", type: "STRING" },
    { name: "reading_kwh", type: "NUMERIC" },
    { name: "tariff", type: "STRING" },
    { name: "read_type", type: "STRING" },
    { name: "loaded_at", type: "TIMESTAMP", mode: "REQUIRED" },
  ],
};

app.post("/api/readings/stage", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) return response.status(401).json({ message: "Not signed in" });

  const batchId = request.body.batchId ?? randomUUID();
  const loadedAt = new Date().toISOString();

  const ndjson = request.body.rows
    .map((row) =>
      JSON.stringify({
        batch_id: batchId,
        account_id: session.accountId,
        source_file: row.sourceFile,
        meter_serial: row.meterSerial,
        site: row.site,
        read_date: row.readDate,
        register: row.register,
        reading_kwh: row.readingKwh === "" ? null : row.readingKwh,
        tariff: row.tariff ?? null,
        read_type: row.readType ?? null,
        loaded_at: loadedAt,
      }),
    )
    .join("\n");

  await new Promise((resolve, reject) => {
    Readable.from([ndjson])
      .pipe(
        inbox.createWriteStream({
          sourceFormat: "NEWLINE_DELIMITED_JSON",
          schema: SCHEMA,
          writeDisposition: "WRITE_APPEND",
        }),
      )
      .on("error", reject)
      .on("complete", resolve);
  });

  response.json({ batchId, staged: request.body.rows.length });
});</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>account_id</code> comes off that session and never off the request body, so a stolen batch id merges nothing. The reading arrives as the string <code>12345.6</code> and stays a string. Google's streaming page requires a <code>NUMERIC</code> value in a row to sit inside double quotation marks, and keeping the string on the load path costs nothing. <code>read_date</code> arrives as <code>2026-03-01</code> and needs nothing. A select value nobody mapped never reaches the row at all, so <code>tariff</code> and <code>read_type</code> fall back to null here.</p>
<p>The credential is the service account attached to the service. It needs <code>roles/bigquery.dataEditor</code> on both datasets, plus <code>roles/bigquery.jobUser</code> on the project to run the jobs. For a Cloud Run service, Google recommends a user-managed service account as that identity over the Compute Engine default. Google writes that the best way to mitigate the threats around downloadable keys is "to avoid user-managed service account keys and to use other methods to authenticate service accounts whenever possible". The same page calls a key "an exception rather than the norm". An attached identity needs no key file at all.</p>
<h2 id="one-merge-into-the-partitioned-target">One MERGE into the partitioned target</h2>
<p>One statement moves the batch across, and it has to survive the same export arriving twice.</p>
<pre><code class="language-sql">MERGE analytics.meter_readings AS t
USING (
  SELECT * EXCEPT (rn)
  FROM (
    SELECT
      account_id, meter_serial, site, read_date, register,
      reading_kwh, tariff, read_type, source_file,
      ROW_NUMBER() OVER (
        PARTITION BY meter_serial, read_date, register
        ORDER BY loaded_at DESC
      ) AS rn
    FROM staging.meter_readings_inbox
    WHERE batch_id = @batch_id
      AND account_id = @account_id
  )
  WHERE rn = 1
) AS s
ON  t.account_id   = s.account_id
AND t.meter_serial = s.meter_serial
AND t.read_date    = s.read_date
AND t.register     = s.register
AND t.read_date BETWEEN @from_date AND @to_date
WHEN MATCHED THEN UPDATE SET
  site        = s.site,
  reading_kwh = s.reading_kwh,
  tariff      = s.tariff,
  read_type   = s.read_type,
  source_file = s.source_file,
  updated_at  = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN INSERT (
  account_id, meter_serial, site, read_date, register,
  reading_kwh, tariff, read_type, source_file, updated_at
)
VALUES (
  s.account_id, s.meter_serial, s.site, s.read_date, s.register,
  s.reading_kwh, s.tariff, s.read_type, s.source_file, CURRENT_TIMESTAMP()
);</code></pre>
<p><code>MERGE</code> combines insert, update and delete into one statement and runs them atomically. The <code>USING</code> subquery deduplicates first. A target row that joins with more than one source row fails the whole statement with <code>UPDATE/MERGE must match at most one source row for each target row</code>. <code>ROW_NUMBER()</code> keeps the newest reading per meter, date and register. March sent twice writes March once, and a corrected reading overwrites the one already stored.</p>
<p>The route reads the batch's own date range with one small query first, so <code>@from_date</code> and <code>@to_date</code> arrive as parameters. That predicate sits in the merge condition on purpose. Google documents three places a partition filter limits which partitions get scanned, and the merge condition is one of them. The optimizer might or might not push it down, depending on the join type, so read the execution plan against your own table.</p>
<p>BigQuery runs two concurrent mutating DML statements per table, queues twenty more, and fails anything past that. One <code>MERGE</code> for the whole import stays clear of that ceiling. One <code>MERGE</code> per file walks toward it.</p>
<h2 id="the-cost-of-a-partitioned-target">The cost of a partitioned target</h2>
<p>Partitioning changes what that statement costs every time it runs. On on-demand billing, a <code>MERGE</code> carrying an <code>UPDATE</code> clause against an unpartitioned table is billed for the bytes the statement reads plus the size of the whole table before the change. On a partitioned table the second half shrinks to the total size of the partitions the statement updates. A month of readings merged into three years of history is billed against the partitions that month lands in.</p>
<p>Clustering by <code>account_id</code>, <code>site</code> and <code>meter_serial</code> sorts the blocks inside each partition, so a query about one building reads the blocks holding that building. BigQuery stops giving an exact cost estimate before a clustered query runs, because the number of blocks stays unknown until it does. Google's own pricing page says to use partitioning and clustering wherever possible. Set <code>require_partition_filter</code> on the target and queries against the table have to carry a filter on <code>read_date</code>.</p>
<p>On-demand queries cost $6.25 per tebibyte after the first tebibyte each month, with a 10 MB minimum for every table a query touches. Google prices each region on its own row, so read the one your dataset sits in. Pruning is what keeps the tebibytes counted against a month.</p>
<h2 id="the-routes-nobody-ships-for-you">The routes nobody ships for you</h2>
<p>Updog Importer integrates with nobody. There is no BigQuery connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the two routes in the middle are work you do.</p>
<p>BigQuery already ships its own way in for the other case. The Cloud console takes a local file up to 100 MB, one file at a time, with no wildcards. The <code>bq load</code> command runs from a terminal. A load job from Cloud Storage carries 15 TB across ten million files on the default quota, and costs nothing on the shared slot pool. Every one of those needs a Google Cloud seat with the project's IAM behind it. For an export your own team downloaded, those tools are the shorter way in. Everything above exists for the export a property manager sent, opened in a browser inside a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> names the jobs each of the two models fits.</p>
<h2 id="the-pieces-you-wrote-and-the-next-export">The pieces you wrote and the next export</h2>
<p>You wrote two tables, a schema with seven columns, a handler that batches, a route that stages, and one <code>MERGE</code>. The files stay on the machines that opened them. The rows travel from your own front end to your own routes, and from there into BigQuery, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/react-csv-importer/">React CSV importer</a> modal or at the web component and the middle stays the same.</p>
<p>The property manager will send March again later, with two corrections and one meter that was estimated the first time. That time the mappings are already stored, the dates already parse, and the <code>MERGE</code> writes two readings where a second copy of the month would have gone.</p>]]></content:encoded></item>
<item><title>A Filter Panel That Narrows a Million Rows in the Browser</title><link>https://updog.tech/blog/filter-panel-performance/</link><guid isPermaLink="true">https://updog.tech/blog/filter-panel-performance/</guid><pubDate>Thu, 09 Jul 2026 00:00:00 GMT</pubDate><description>Bitmask-packed row state, a worker-side mirror instead of row objects, and a filter pipeline ordered by cost, across a million rows.</description><content:encoded><![CDATA[<p>I wrote before about how Updog's canvas grid renders a million rows without slowing down. That post ended on the real point underneath it. Rendering a million rows is not the same as working with them. A person importing a file does not want to scroll through a million rows looking for the dozen that need attention. They want the grid to hand those dozen rows over.</p>
<p>Updog is a browser CSV importer and spreadsheet editor, so those two problems, rendering the rows and letting a person work through them, sit inside the same product. The <a href="https://updog.tech/blog/browser-first-csv-import/">first post about Updog's browser-first approach</a> already made this promise. Exact filters, validation states, error views, search, column transforms, and bulk actions are what make a large import manageable. I touched on the filter worker again in the <a href="https://updog.tech/blog/canvas-grid-performance/">canvas grid post</a>, cheapest checks first, row data mirrored into typed arrays, only matching row IDs returned. This post picks up the rest of that story. It covers what the panel looks like, why the order of its checks matters, and what a person pays in milliseconds when they use it.</p>
<h2 id="why-filtering-lives-on-the-surface">Why filtering lives on the surface</h2>
<p>Spreadsheets filter one column at a time. Open the header, click the dropdown, pick a value, and repeat for the next column. On a wide sheet half the columns sit scrolled out of view, so finding the right header is its own small hunt before the click happens. Once a few filters are on, there is no single place that shows which ones are active, only a scroll back through each header to check. On a file where several things need checking at once, that becomes a bit inconvenient. Updog keeps filtering on the surface instead, in its own panel next to the grid, where search, error status, change status, and per-column filters sit next to each other and a person combines them rather than opening one menu after another.</p>
<p>Say the review needs every row where the country is Canada, the role is Support, and the email field has an error. Column by column, that means three separate menus and three things to remember. In the panel, it is three clicks, and the grid narrows right away.</p>
<p>None of this exists because manual cleanup is fun. Column matching, value matching, and validation catch most of what a file gets wrong, but not everything, and the leftover rows are why manual import exists as its own kind of work. A person still has to look at some of them and decide. Updog cannot make that step disappear. It can make it hurt less.</p>
<h2 id="cheapest-checks-first-text-search-last">Cheapest checks first, text search last</h2>
<p>Every filter a person turns on runs against the same rows in a single pass, but the checks do not cost the same. Checking whether a row belongs to a hidden data source is one Set lookup. Checking whether a row's text contains a search term means scanning every character of every field in that row. Updog's filter engine orders its checks by cost, starting with source visibility, then change status, then validation status, then empty cells, then per-column values, then numeric and date ranges, and text search last.</p>
<p>The order changes what a person feels when they use the panel. Turn on a text search after two filters that already narrow the data down to a couple thousand rows, and the extra cost is close to nothing, because the substring check only runs on the rows that already passed the cheaper filters. Turn on that same search with nothing else active, and it has to scan the full dataset, since there is nothing cheaper to filter with first. In one measured run against close to a million rows, adding a search term on top of two already-narrow filters added no measurable time at all.</p>
<h2 id="what-keeps-a-million-rows-fast-to-search">What keeps a million rows fast to search</h2>
<p>The panel's speed also comes down to what the filter engine keeps in memory and how it updates it. Filtering runs in a dedicated Web Worker, off the main thread, so typing in the search box never competes with the browser for the frame the grid is trying to paint. The worker holds the dataset as flat, parallel arrays rather than row objects.</p>
<pre><code class="language-ts">let rowIds: TRowId[] = [];
let rowTexts: string[] = [];      // NUL-delimited, formatted, for display and search
let rowRawTexts: string[] = [];   // NUL-delimited, unformatted, for number and date compares
let errorBitmask: Uint32Array = new Uint32Array(0);
let editedBitmask: Uint32Array = new Uint32Array(0);
let newFlags: Uint8Array = new Uint8Array(0);
let deletedFlags: Uint8Array = new Uint8Array(0);
let sourceIds: string[] = [];
let rowIndexMap: (number | undefined)[] = [];   // rowId -> array index, O(1) lookup</code></pre>
<p>Cell values live as one delimited string per row rather than an object with a key for every field. A row's error and edited state live as bits inside a <code>Uint32Array</code>, thirty-two columns packed into each word.</p>
<pre><code class="language-ts">const columnMask = new Uint32Array(this._wordsPerRow);
if (filterColumns) {
  for (const col of filterColumns) {
    const idx = this.fieldOrder.indexOf(col);
    if (idx >= 0) {
      const w = idx >>> 5;
      if (w &#x3C; this._wordsPerRow) columnMask[w] |= 1 &#x3C;&#x3C; (idx &#x26; 31);
    }
  }
} else {
  columnMask.fill(0xffffffff);
}</code></pre>
<p>Checking whether a row has an error in a column the person is filtering on becomes one bitwise AND instead of a loop over every field. On a sheet with forty columns, that is eight bytes of state per row for full error tracking.</p>
<p>None of it gets rebuilt on every keystroke. Editing a single cell sends the worker one small message carrying only that row's new text.</p>
<pre><code class="language-ts">case "UPDATE_TEXT": {
  const idx = rowIndexMap[msg.rowId];
  if (idx !== undefined) {
    rowTexts[idx] = msg.rowText;
    rowRawTexts[idx] = msg.rowRawText;
  }
  break;
}</code></pre>
<p>The worker updates one entry in a lookup table and moves on. The cost of an edit stays flat no matter how many rows sit behind it.</p>
<p>The last piece is what happens when a person types faster than the worker can answer. Every filter request carries a number that increases each time one goes out. If a newer request leaves before an older one comes back, Updog throws the old reply away instead of showing a result that no longer matches what the person typed.</p>
<pre><code class="language-ts">private onFilterResult(
  filteredIds: TRowId[] | null,
  baseFilteredIds: TRowId[] | null,
  generation: number,
): void {
  if (generation !== this._filterGeneration) return;
  // ...apply filteredIds, notify subscribers
}</code></pre>
<p>That single check is what keeps fast typing in the search box from flashing a stale result on screen before the real one arrives.</p>
<h2 id="several-ways-to-narrow-the-data-at-once">Several ways to narrow the data at once</h2>
<p>The panel covers more ground than a single filter usually does. Search matches whole words or an exact cell, with an option to scope it to specific columns. A checkbox for rows with errors expands into the individual error messages behind it, so a person can isolate the one validation rule failing on four hundred rows without wading through every other kind of error at the same time. Separate checkboxes cover new rows, edited rows, empty cells, and rows a merge left in the wrong place. Per-column filters add select, number-range, and date-range controls wherever you define one on a column.</p>
<pre><code class="language-ts">{
  id: "salary",
  title: "Salary",
  editor: { type: "number" },
  filter: { type: "number-range", label: "Salary" },
},
{
  id: "role",
  title: "Role",
  editor: { type: "select", options: ["Admin", "Editor", "Viewer"] },
  filter: { type: "select", label: "Role", multiple: true },
},</code></pre>
<p>That configuration lives in the same schema you already write for Updog's CSV importer SDK, next to validators and editors, with nothing extra to wire up. Every filter type, whatever it checks, feeds into the same ordered pipeline described above. There is no special case for one kind of filter at the engine's boundary, which is part of why adding a new way to narrow the data never costs a second pass over the rows.</p>
<h2 id="what-it-costs-in-milliseconds">What it costs in milliseconds</h2>
<p>Numbers matter more than a description of the design, so here they are. The playground run behind these numbers held exactly a million rows across fifteen columns, with a filter defined on every non-text column. Against that dataset, a single filter interaction, a search term, an error toggle, a column filter, or a combination of them, round-tripped in 30 to 250 milliseconds. The slowest single case was a search with no matches at all, at just under 240 milliseconds, still nowhere near a wait a person would notice.</p>
<p>That is one measured session, worth treating as an honest sample rather than a guarantee. Sorting the full dataset is a separate operation from filtering and cost closer to 760 milliseconds in the same session, since it has to place every row in order rather than check each one against a condition once. Text columns add a further cost on top of that. Updog sorts them through <code>Intl.Collator</code>, the browser API that places accented letters, an umlaut among them, in the position a person reading that language expects, and each comparison during the sort costs more than a plain less-than check. Number and date columns skip the collator and compare values directly, which is part of why a text column takes longer to sort than a numeric one at the same row count. Filtering and sorting do different work, and this post is about the one that runs on every keystroke.</p>
<p>None of it matters at a few thousand rows. A plain array filter, no worker, no bitmask, runs fine at that size, and a dedicated panel is more interface than a small file needs. It starts to earn its cost once a real file pushes past a hundred thousand rows and a person needs a way to work through it that does not mean scrolling by hand.</p>
<p>The canvas grid post ended with rendering solved. The harder question was always what a person does once a million rows sit on screen. This is that answer. A panel with every way to narrow the data in one place, still fast enough that finding the dozen rows that matter feels instant, whether you are evaluating Updog as an embedded CSV importer or already have it running in production.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into MongoDB</title><link>https://updog.tech/blog/import-csv-into-mongodb/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-mongodb/</guid><pubDate>Tue, 07 Jul 2026 00:00:00 GMT</pubDate><description>Map and validate a messy CSV in the browser, post the clean rows to your own route, and write them into MongoDB with an unordered bulkWrite.</description><content:encoded><![CDATA[<p>A bulk write into MongoDB is one list of operations, sent to one collection, where every operation carries its own outcome. The <code>ordered</code> option decides what the first failure costs the rest of the list. MongoDB documents the default plainly, "If an error occurs, subsequent operations are not executed." Turn it off and the rule changes to "All operations without errors are completed even if some operations fail." One setting separates an import where one bad row stops nine hundred good ones from an import where it stops itself.</p>
<p>A freight visibility platform receives its shipment manifests from carriers. One carrier's export arrives looking like this.</p>
<p><code>carrier-manifest-march.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th><th class="sheet__column" scope="col">H</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">House Bill</td><td class="sheet__cell">Origin</td><td class="sheet__cell">Dest</td><td class="sheet__cell">Pieces</td><td class="sheet__cell">Gross Wt</td><td class="sheet__cell">Ship Date</td><td class="sheet__cell">Service Level</td><td class="sheet__cell">Status</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">HBL-4471902</td><td class="sheet__cell">SGSIN</td><td class="sheet__cell">NLRTM</td><td class="sheet__cell">14</td><td class="sheet__cell">1,240 kg</td><td class="sheet__cell">04/03/2026</td><td class="sheet__cell">Ocean LCL</td><td class="sheet__cell">IN TRANSIT</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">HBL-4471903</td><td class="sheet__cell">SGSIN</td><td class="sheet__cell">NLRTM</td><td class="sheet__cell">6</td><td class="sheet__cell">985</td><td class="sheet__cell">17/03/2026</td><td class="sheet__cell">Ocean LCL</td><td class="sheet__cell">intransit</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">HBL-4471902</td><td class="sheet__cell">SGSIN</td><td class="sheet__cell">NLRTM</td><td class="sheet__cell">16</td><td class="sheet__cell">1 380</td><td class="sheet__cell">04/03/2026</td><td class="sheet__cell">Ocean LCL</td><td class="sheet__cell">In-Transit</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">HBL-4471908</td><td class="sheet__cell">CNSHA</td><td class="sheet__cell">DEHAM</td><td class="sheet__cell">32</td><td class="sheet__cell">2 840</td><td class="sheet__cell">23 Mar 2026</td><td class="sheet__cell">Air Express</td><td class="sheet__cell">CUSTOMS HOLD - CLEARANCE</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">6</th><td class="sheet__cell">HBL-4471911</td><td class="sheet__cell">VNSGN</td><td class="sheet__cell">USLAX</td><td class="sheet__cell">9</td><td class="sheet__cell">610</td><td class="sheet__cell">28/03/2026</td><td class="sheet__cell">Air Express</td><td class="sheet__cell">POD</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="8"><span class="sheet__break-text">934 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">941</th><td class="sheet__cell">HBL-4472843</td><td class="sheet__cell">VNSGN</td><td class="sheet__cell">USLAX</td><td class="sheet__cell">11</td><td class="sheet__cell">742</td><td class="sheet__cell">31/03/2026</td><td class="sheet__cell">Ocean LCL</td><td class="sheet__cell">POD</td></tr></tbody></table>
<p>Eight headers, and none of them carry the names your documents use. <code>Dest</code> is short for the field you call <code>destination</code>, and <code>Gross Wt</code> is short for <code>grossWeight</code>. One weight reads <code>1,240 kg</code> with the unit sitting inside the cell, and the next reads <code>1 380</code> with a space where a comma would go. Ship dates arrive as <code>04/03/2026</code>, <code>17/03/2026</code> and <code>23 Mar 2026</code>. The status column says <code>IN TRANSIT</code>, <code>intransit</code>, <code>In-Transit</code>, <code>CUSTOMS HOLD - CLEARANCE</code> and <code>POD</code>. House bill <code>HBL-4471902</code> appears twice, once with 14 pieces and once with 16. The carrier amended the manifest and exported both versions.</p>
<p>A person on the operations desk drops that manifest into the importer inside your app. Updog Importer parses it in the browser, maps the eight headers onto your schema, and shows them every value. Your <code>onComplete</code> handler receives the rows. The handler cuts the rows into chunks and posts each chunk to a route you own. The route holds the connection string and calls <code>bulkWrite</code>. MongoDB writes the collection.</p>
<p>No server of ours stands between that manifest and the collection.</p>
<h2 id="step-1-create-the-collection-and-its-unique-index">Step 1. Create the collection and its unique index</h2>
<p>Start from the document the rows have to become. MongoDB creates the collection on the first write, so the shape lives in your code rather than in a migration.</p>
<pre><code class="language-js">{
  _id: ObjectId("66f0c0a1e4b0a1d2f3c4b5a6"),
  tenantId: "acme-freight",
  houseBill: "HBL-4471902",
  origin: "SGSIN",
  destination: "NLRTM",
  pieces: 16,
  grossWeightKg: 1380,
  shipDate: ISODate("2026-03-04T00:00:00Z"),
  serviceLevel: "Ocean LCL",
  status: "In transit",
  createdAt: ISODate("2026-03-05T09:12:44Z"),
  updatedAt: ISODate("2026-03-05T09:12:44Z")
}</code></pre>
<p>Every field there is typed the way MongoDB stores it. <code>pieces</code> and <code>grossWeightKg</code> are numbers, <code>shipDate</code> is a date, and the unit lives in the field name so no cell has to carry it. That last decision is what turns <code>1,240 kg</code> from a value into a problem the person fixes before submit.</p>
<p>Two of your customers can both ship house bill <code>HBL-4471902</code>, so identity takes two fields together.</p>
<pre><code class="language-js">await shipments.createIndex(
  { tenantId: 1, houseBill: 1 },
  { unique: true, name: "tenant_house_bill" },
);</code></pre>
<p>MongoDB says a unique index means "the collection will not accept insertion or update of documents where the index key value matches an existing value in the index." A write that breaks it comes back with error code <code>11000</code>, named <code>DuplicateKey</code> in MongoDB's own source. The message opens <code>E11000 duplicate key error collection</code>. The index also makes the upsert in step 5 safe. <code>db.collection.updateOne</code> asks for exactly that, "To avoid multiple upserts, ensure that the <code>filter</code> field(s) are uniquely indexed."</p>
<h2 id="step-2-describe-the-document-as-flat-columns">Step 2. Describe the document as flat columns</h2>
<p>The <code>columns</code> array is that document written for the person looking at the file. Each entry gives them a <code>title</code> to read, a cell editor to type into, and validators that flag a bad value.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const STATUSES = ["In transit", "Customs hold", "Out for delivery", "Delivered"];

export const columns: DataEditorColumn[] = [
  {
    id: "houseBill",
    title: "House bill",
    size: 150,
    transformer: (value) => String(value).trim().toUpperCase(),
    validators: [
      { type: "required" },
      { type: "unique" },
    ],
  },
  { id: "origin", title: "Origin", size: 100, validators: [{ type: "required" }] },
  { id: "destination", title: "Destination", size: 120 },
  {
    id: "pieces",
    title: "Pieces",
    size: 90,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 1, decimalPlaces: 0 },
    ],
  },
  {
    id: "grossWeight",
    title: "Gross weight",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 1 },
    ],
  },
  {
    id: "shipDate",
    title: "Ship date",
    size: 130,
    editor: { type: "date" },
    validators: [{ type: "date" }],
  },
  { id: "serviceLevel", title: "Service level", size: 130 },
  {
    id: "status",
    title: "Status",
    size: 150,
    editor: { type: "select", options: STATUSES, enableCustomValue: false },
    validators: [{ type: "oneOf", values: STATUSES }],
  },
];</code></pre>
<p>Every editor in that array answers a column in the carrier's export. The <code>date</code> editor reads <code>17/03/2026</code> and sees a first part above 12, which settles the whole file as day first. So <code>04/03/2026</code> lands as <code>2026-03-04</code>, and <code>23 Mar 2026</code> lands as <code>2026-03-23</code>. The <code>number</code> editor collapses the space grouping in <code>1 380</code> to <code>1380</code>. It leaves <code>1,240 kg</code> alone, because stripping letters would turn an id like <code>abc123</code> into <code>123</code>. The <code>number</code> validator flags that cell instead. The <code>select</code> editor with <code>enableCustomValue</code> off holds the status column to four options and sends everything else to value matching.</p>
<p>The <code>synonyms</code> prop teaches matching the words your carriers already use, and the mount ties the whole thing together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Shipment>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="houseBill"
  blockSubmitOnError
  synonyms={{
    columns: { houseBill: ["hbl", "hawb", "master bill"] },
    values: { Delivered: ["pod", "proof of delivery"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>Dest</code> and <code>Gross Wt</code> both match with no synonym. Matching lowercases a header and drops spaces, underscores, hyphens and dots before it scores. So <code>destination</code> containing <code>dest</code> is enough, and <code>Gross Wt</code> shares the word <code>gross</code> with <code>grossWeight</code>. The column synonyms cover the next carrier, whose header says <code>HBL</code> or <code>HAWB</code>.</p>
<p>On the value side, the three spellings of in transit reduce to one string under that same normalizing, so all three land on the option exactly. <code>CUSTOMS HOLD - CLEARANCE</code> reduces to a string containing <code>customshold</code>, which matches on containment, two tiers under an exact hit. <code>POD</code> is the one value no tier reaches, since three letters share nothing with <code>Delivered</code>. That is the gap the value synonym fills. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to feed back next time. The package install and the modal wiring under this snippet live in <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<p>Every snippet here is React. The same props reach the web component build, so a Vue, Angular or Svelte freight app writes this schema and this handler unchanged.</p>
<h2 id="step-3-catch-the-repeats-before-submit">Step 3. Catch the repeats before submit</h2>
<p><code>{ type: "unique" }</code> on <code>houseBill</code> is the rule that finds <code>HBL-4471902</code> twice. Uniqueness is relational, so Updog checks the value against every other row in that column. Both copies get flagged. Empty cells are never indexed, so a blank house bill collides with nothing. The check runs last on the column, whatever position it holds in the array. A cell that fails <code>required</code> reports that error and never a confusing one about duplicates.</p>
<p>The <code>transformer</code> on the same column trims and uppercases before the value enters the store, so <code>hbl-4471902 </code> and <code>HBL-4471902</code> count as one house bill.</p>
<p>The person sees both rows marked in the grid, compares 14 pieces against 16, keeps the amended row and deletes the other. <code>blockSubmitOnError</code> holds the submit button disabled until they do. Catching it here is what buys that comparison. An <code>E11000</code> arriving from the server names an index and a key, and it cannot say which of the two rows the carrier meant. The one person who can answer that is watching a spinner by then. <a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors and how to prevent them</a> covers what else the grid is flagging while they work.</p>
<p><code>primaryKey</code> handles the other half of the problem. It merges an imported row into a row that came from somewhere else, so the same manifest arriving a second time folds into the shipment already on the screen. Values are compared after surrounding whitespace is trimmed, and a row with an empty key merges with nothing and arrives as new. Rows inside one file stay separate. That is why the <code>unique</code> validator is the rule that catches a repeat the carrier sent twice in one export.</p>
<h2 id="step-4-post-the-result-in-chunks">Step 4. Post the result in chunks</h2>
<p>Pressing submit sends every row to your handler grouped by source, each one flagged <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. One person can drop three manifests in a single import, and each file arrives as its own source entry, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 1000;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Shipment>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/shipments/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>MongoDB publishes two numbers a bulk write has to respect, and a chunk of a thousand manifest rows sits far inside both. No document may exceed 16 mebibytes. The limits page says that maximum keeps a single document from using an excessive amount of RAM or bandwidth. One group of operations carries at most 100,000, and the driver divides a longer list before it leaves your server.</p>
<p>The reason MongoDB gives for that second number is what decides the chunk size here. "This limit prevents issues with oversized error messages." A batch whose error report grows too large loses those messages. MongoDB "truncates all remaining error messages to the empty string", and the trigger sits at two messages totalling more than 1MB. Step 6 reads those messages back to the person, so a chunk small enough to keep them intact beats a chunk sized for throughput. MongoDB adds that the sizes and the grouping are internal details subject to change, so hold the number conservative.</p>
<p>The person waiting sets the other bound. The confirm dialog stays open with a spinner on the button for the whole round trip. So 40,000 rows in one request is one long freeze on their screen. A thousand rows a request keeps each hop short and gives the loop somewhere to stop.</p>
<p><strong>Let a failed chunk throw.</strong> Updog Importer awaits your handler and empties the editor as soon as that promise resolves. A handler that swallows its own error and returns counts as a success, and the grid clears with those shipments never written. A thrown error holds the rows, the header mapping and every correction on screen, so the person presses submit again on a manifest they can still see. Whatever you want off that result gets copied while the handler still runs. Once the promise resolves, the editor lets go of its rows, its sources, its history and its learned synonyms.</p>
<h2 id="step-5-write-the-chunk-with-an-unordered-bulk-write">Step 5. Write the chunk with an unordered bulk write</h2>
<p>Your route holds the MongoDB connection string, and the browser reaches no further than it.</p>
<pre><code class="language-ts">import { MongoClient } from "mongodb";
import { NextResponse } from "next/server";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("MONGODB_URI is missing");

const client = new MongoClient(uri);
const shipments = client.db("freight").collection("shipments");

export async function POST(request: Request) {
  const session = await getVerifiedSession();
  if (!session) {
    return NextResponse.json({ message: "Not signed in" }, { status: 401 });
  }

  const { rows } = await request.json();
  const operations = rows.map((row) => ({
    updateOne: {
      filter: { tenantId: session.tenantId, houseBill: row.houseBill },
      update: {
        $set: {
          origin: row.origin,
          destination: row.destination,
          pieces: Number(row.pieces),
          grossWeightKg: Number(row.grossWeight),
          shipDate: new Date(row.shipDate),
          serviceLevel: row.serviceLevel,
          status: row.status,
          updatedAt: new Date(),
        },
        $setOnInsert: { createdAt: new Date() },
      },
      upsert: true,
    },
  }));

  const result = await shipments.bulkWrite(operations, { ordered: false });

  return NextResponse.json({
    matched: result.matchedCount,
    upserted: result.upsertedCount,
  });
}</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. <code>tenantId</code> comes off that session and never off the request body, because the browser sends rows and the server decides who they belong to.</p>
<p><code>updateOne</code> with <code>upsert: true</code> is what makes a repeated import safe. MongoDB states the behaviour directly. "If <code>upsert: true</code> and no documents match the <code>filter</code>, <code>db.collection.updateOne()</code> creates a new document based on the <code>filter</code> criteria and <code>update</code> modifications." So the tenant and the house bill land in a new document on their own. <code>$setOnInsert</code> carries the fields that belong to a first arrival, and it does nothing when the write turns out to be an update. That is what keeps <code>createdAt</code> honest across repeated imports of the same manifest.</p>
<p><code>replaceOne</code> would also take an <code>upsert</code>, and it would cost you every field the file does not carry. Its replacement document cannot contain update operators, so a <code>flaggedForReview</code> your app wrote earlier is gone the next time the carrier exports. <code>$set</code> touches the fields the manifest carries and leaves the rest of the document alone.</p>
<p><code>ordered: false</code> is the setting the whole route exists for. Under the default, one rejected operation stops every operation queued behind it, and a chunk of a thousand can land hundreds of rows short over one bad house bill. Unordered, every operation without an error of its own completes, with write concern errors and transactions as the documented exceptions. The driver handles the grouping itself, and the count-based split starts above 100,000.</p>
<h2 id="step-6-read-the-write-errors-and-name-the-rows">Step 6. Read the write errors and name the rows</h2>
<p>A bulk write that rejects anything throws, so the return value never arrives. Wrap the one call.</p>
<pre><code class="language-ts">import { MongoBulkWriteError } from "mongodb";

try {
  const result = await shipments.bulkWrite(operations, { ordered: false });

  return NextResponse.json({
    matched: result.matchedCount,
    upserted: result.upsertedCount,
  });
} catch (error) {
  if (!(error instanceof MongoBulkWriteError)) throw error;

  const writeErrors = Array.isArray(error.writeErrors)
    ? error.writeErrors
    : [error.writeErrors];

  const rejected = writeErrors.map((entry) => ({
    houseBill: rows[entry.index].houseBill,
    code: entry.code,
    reason: entry.errmsg,
  }));

  return NextResponse.json(
    {
      message: rejected.length + " shipments were rejected",
      upserted: error.result.upsertedCount,
      rejected,
    },
    { status: 409 },
  );
}</code></pre>
<p><code>MongoBulkWriteError</code> carries a <code>writeErrors</code> array. Each entry holds an <code>index</code> the driver documents as the original bulk operation index. You built one operation per row in file order, so that number is the position of the row the browser posted. Look it up in <code>rows</code> and the failure stops being a stack trace and becomes a house bill the person recognizes. <code>error.result</code> carries the counts for everything that did land, so a partial success reports as one. That list travels back in the response, and the handler from step 4 decides what the person sees before it throws.</p>
<p>The driver types <code>writeErrors</code> as one error or many, so it gets normalized before anything iterates it. A bulk write can also fail before any operation runs, on a dropped connection or a rejected command, so anything that is not a <code>MongoBulkWriteError</code> gets rethrown. Each entry carries its own <code>code</code>, and the route passes it along, because a duplicate key is one failure among the codes MongoDB defines.</p>
<p>With the repeats caught in the grid, <code>11000</code> reaches this route from the cases the browser could not see. A second unique index on the collection does it, and so does another import running against the same tenant at the same moment.</p>
<p>Chunks that already landed stay landed. An upsert against the same filter writes the same values a second time, so a retry after a failed chunk costs a rewrite of what already exists.</p>
<h2 id="the-work-updog-hands-back">The work Updog hands back</h2>
<p>Updog Importer integrates with nobody. There is no MongoDB connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object of rows, and the route between it and the collection is yours to write.</p>
<p>MongoDB already ships its own import for the other case, and each path assumes a seat. <code>mongoimport</code> runs "from the system command line, not the <code>mongo</code> shell", against a connection string held by whoever runs it. It "continues an operation when it encounters duplicate key and document validation errors" until you pass <code>--stopOnError</code>. Compass reads a JSON or a CSV file from someone connected to the deployment, and its own documentation names the stopping rule. "The import operation will not continue after encountering an error in either case." Atlas sends the same job back to that GUI, "To load data from a JSON or a CSV file into an Atlas cluster, use the Compass GUI."</p>
<p>Every one of those starts from the seat of somebody who holds the database credentials. When the file is yours, they are the shorter paths. Everything above exists for the file that belongs to a carrier, arriving through a browser, in a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> works through where the browser belongs and where the credentials do.</p>
<h2 id="the-manifest-that-arrives-amended">The manifest that arrives amended</h2>
<p>You wrote a collection with a unique index, a schema with eight columns, a handler that chunks, and a route that holds one connection string. The manifest never leaves the machine that opened it. The rows travel from your own front end to your own route, and from there into MongoDB, and the only party you added to the chain is yourself. Move the same setup onto a <a href="https://updog.tech/nextjs-csv-importer/">Next.js CSV importer</a> page or a plain React modal, and everything between the drop zone and <code>bulkWrite</code> holds.</p>
<p>The carrier who sent that manifest will send an amended one later. That time the duplicate is caught on the screen in front of a person who knows which version is right, and <code>E11000</code> never has to explain it afterwards.</p>]]></content:encoded></item>
<item><title>A Canvas Grid That Renders a Million Rows in the Browser</title><link>https://updog.tech/blog/canvas-grid-performance/</link><guid isPermaLink="true">https://updog.tech/blog/canvas-grid-performance/</guid><pubDate>Mon, 06 Jul 2026 00:00:00 GMT</pubDate><description>How Updog's data editor renders a million rows in the browser: a canvas engine, scrolling past browser pixel limits, zero overscan, and frame skipping.</description><content:encoded><![CDATA[<p>Somewhere early in building Updog's data editor, I ran into the wall every table library eventually hits. Render rows and cells as ordinary HTML elements, and it works well, right up until the row count climbs past some tens of thousands. Past that, scrolling starts to stutter, memory climbs, and the browser tab spends its effort holding a page open instead of running a spreadsheet. I needed an editor that stayed smooth at a million rows, inside a browser tab, with no server doing the heavy lifting. That ceiling is why Updog's grid draws its own rows and cells on a canvas instead of building them out of HTML.</p>
<p>I already wrote about why <a href="https://updog.tech/blog/browser-first-csv-import/">one million rows is the practical ceiling</a> Updog is built around, and why the browser can carry more of that weight than it usually gets credit for. Underneath that claim is a set of specific decisions inside the grid engine, the ones that let a million rows scroll as smoothly as a hundred.</p>
<h2 id="why-a-normal-table-stops-at-some-point">Why a normal table stops at some point</h2>
<p>Every serious web data grid virtualizes, rendering only the rows on screen instead of the whole dataset as DOM nodes. <a href="https://www.ag-grid.com/javascript-data-grid/dom-virtualisation/">AG Grid's own documentation</a> puts it plainly: "The grid only renders what you see on the screen." AG Grid still renders a buffer by default, 10 rows above and below what is visible, plus a hard cap of 500 rows at once. The <a href="https://tanstack.com/table/latest/docs/guide/pagination">wider TanStack Table docs</a> are candid that the stack is "designed to scale up to 10s of thousands of rows with decent performance."</p>
<p>None of this is a mark against those tools. It is what happens when the unit of rendering is a DOM element, which carries layout and paint cost that a canvas pixel does not. Updog's grid moves drawing off the DOM entirely, painting rows and cells with the 2D canvas API so the browser manages one element instead of a million. Row count has not stopped mattering, a million rows still sit in the tab's memory and that cost is real, but the render cost per frame no longer scales with dataset size. It scales with viewport size instead, and the rest of the engine is built around making one full repaint of that viewport cheap.</p>
<h2 id="scrolling-past-a-browsers-pixel-limit">Scrolling past a browser's pixel limit</h2>
<p>Canvas creates a problem of its own immediately. Something still has to scroll, and a canvas element has no scroll behavior built in. Updog's grid solves that with two invisible, empty divs, one for vertical scroll and one for horizontal, given native overflow-scroll. Wheel events and scrollbar drags both move the same track, and the canvas repaints in response.</p>
<p>At a million rows and a fixed row height of 34 pixels, that content is 34 million pixels tall, past what browsers allow. Chrome and Safari cap element height around 33.5 million pixels, a fixed-point integer limit in their layout engines, and Firefox's cap sits lower, around 17.9 million pixels. Updog's grid keeps the invisible vertical sizer under a 10 million pixel ceiling, safely below both, shrinking it by a whole number factor as row count grows, and remaps scroll position between that physical space and the full virtual height.</p>
<pre><code class="language-ts">/** Browsers cap element heights around 33.5M px (Chrome/Safari) or 17.9M px (Firefox); stay well below both. */
const MAX_SCROLL_HEIGHT = 10_000_000;

function computeMultiplier(rowCount: number): number {
  const totalContent = rowCount * CELL_HEIGHT;
  return Math.max(1, Math.ceil(totalContent / MAX_SCROLL_HEIGHT));
}

export function toVirtualScrollTop(
  scrollTop: number,
  viewportHeight: number,
  rowCount: number,
): number {
  const multiplier = computeMultiplier(rowCount);
  if (multiplier === 1) {
    return scrollTop;
  }
  const sizerHeight = getSizerHeight(rowCount);
  const maxBrowser = Math.max(1, sizerHeight - viewportHeight);
  const maxVirtual = Math.max(1, rowCount * CELL_HEIGHT - viewportHeight);
  return (scrollTop / maxBrowser) * maxVirtual;
}</code></pre>
<p>The mapping is exact at both ends, so scrolling all the way down lands precisely on the last of a million rows, not somewhere close to it. The person dragging a scrollbar is moving a normal, short track, and the grid does the arithmetic that turns it into a position across 34 million virtual pixels.</p>
<h2 id="no-buffer-rows-on-purpose">No buffer rows, on purpose</h2>
<p>I had tested DOM-based tables before building this one, including a custom grid of my own, with overscan and a row buffer both in place. On large datasets, that was still not enough. Blank rows flashed through while they waited to load, then filled in a moment later. The flash is brief, but it is visible on a fast scroll, and I wanted a version where it did not exist at all. That felt like the right problem to take on.</p>
<p>Updog's grid renders no extra rows above or below the visible window. The visible range comes directly from scroll position and a fixed row height, and the paint loop draws exactly that range.</p>
<pre><code class="language-ts">this._rowRange.start = Math.max(0, Math.floor(this.scrollTop / CELL_HEIGHT));
this._rowRange.end = Math.min(totalRows,
  Math.ceil((this.scrollTop + this.viewportHeight - HEADER_HEIGHT) / CELL_HEIGHT));</code></pre>
<p>Columns are variable width, so finding which one sits under a given position runs a binary search over cumulative widths instead of arithmetic, but either way the loop only touches what is on screen. Removing the buffer is not a separate trick, it falls out once a full repaint is cheap enough that there is nothing left to hide. The next two sections show what makes that true.</p>
<h2 id="redrawing-everything">Redrawing everything</h2>
<p>Most rendering systems built for scale track which regions changed and repaint only those. Updog's grid does not. Every frame that repaints clears the canvas and redraws the entire viewport in the same fixed order, cell backgrounds, gridlines, selection, overlays, pinned columns, marker column, header, corner, and resize guide.</p>
<p>What it does track is whether a frame needs to happen at all. A version counter covers everything that can invalidate the canvas, the data store, selection, the cell being edited, clipboard, fill handle, columns, scroll, theme, viewport size, and painting only runs if one of them changed.</p>
<pre><code class="language-ts">const versionsUnchanged =
  cur.store === prev.store &#x26;&#x26;
  cur.selection === prev.selection &#x26;&#x26;
  cur.editing === prev.editing &#x26;&#x26;
  cur.clipboard === prev.clipboard &#x26;&#x26;
  cur.fill === prev.fill &#x26;&#x26;
  cur.columns === prev.columns &#x26;&#x26;
  cur.scrollLeft === prev.scrollLeft &#x26;&#x26;
  cur.scrollTop === prev.scrollTop &#x26;&#x26;
  // ... viewport size, find/replace, theme version, resize guide
if (versionsUnchanged) {
  return;
}</code></pre>
<p>When nothing moved, the grid skips the frame. When something did, one requestAnimationFrame call runs the full repaint, requested exactly once per change, so an idle grid uses no CPU at all.</p>
<pre><code class="language-ts">const markDirty = useCallback(() => {
  if (!dirtyRef.current) {
    dirtyRef.current = true;
    rafIdRef.current = requestAnimationFrame(paint);
  }
}, [paint]);</code></pre>
<p>Clearing the canvas is the first of ten ordered drawing passes, an opaque fill over the viewport before everything else is drawn on top.</p>
<pre><code class="language-ts">ctx.fillStyle = theme.cellBgIdle;
fillRectSnapped(ctx, 0, 0, vpW, vpH);</code></pre>
<p>Comparing those version numbers costs almost nothing. Painting the full viewport is the expensive part, and keeping that cheap is what the next section covers.</p>
<h2 id="making-every-frame-cheap-to-draw">Making every frame cheap to draw</h2>
<p>The canvas context itself is set up cheap from the start, created with <code>alpha: false</code> so the browser never composites against whatever sits behind it, plus <code>desynchronized</code> mode where the browser supports it.</p>
<pre><code class="language-ts">const ctx =
  canvas.getContext("2d", { alpha: false, desynchronized: useDesync });</code></pre>
<p>The bigger cost is text. <code>measureText</code> and <code>fillText</code> do not scale cleanly to a large number of strings, a complaint old enough that a Firefox bug was filed on it back in 2009, and a cell grid draws a string in almost every visible cell.</p>
<p>Every <code>measureText</code> call goes through a cache with no exceptions, holding full-string widths and per-character widths that barely change once loaded for a font. Eviction is generational rather than tracked by recency. Once the cache passes 10,000 entries, the whole map demotes at once and a fresh one takes over, with old entries promoted back up on a hit, costing one comparison per lookup instead of recency bookkeeping.</p>
<pre><code class="language-ts">/**
 * Cache for ctx.measureText() results — the single most expensive call in canvas text rendering.
 * Two-level cache: full string widths (generation-based eviction at 10k cap)
 * and individual character widths (never evicted, ~96 entries per font).
 */
const prev = this._prevCache.get(key);
if (prev !== undefined) {
  this._cache.set(key, prev);   // promote on prev-generation hit
  return prev;
}
ctx.font = font;
const width = ctx.measureText(text).width;
if (this._cache.size >= this._maxSize) {
  this._prevCache = this._cache; // demote whole map, O(1) eviction
  this._cache = new Map();
}</code></pre>
<p>Truncating an overflowing value reuses the same cache, a forward scan of cached character widths until the running total passes the available space, then an ellipsis appended to the slice that fits. Not a binary search, but every width it touches was already cached.</p>
<pre><code class="language-ts">let cumWidth = 0;
let truncateAt = 0;
for (let i = 0; i &#x3C; text.length; i++) {
  cumWidth += cache.measureChar(ctx, text, i, font);
  if (cumWidth > available) {
    break;
  }
  truncateAt = i + 1;
}
ctx.fillText(text.slice(0, truncateAt) + ELLIPSIS, sx, sy);</code></pre>
<p>Formatted values, the string a number or date turns into on screen, get the same generational cache, thrown out wholesale whenever the data changes. A date column shows why it matters. Building an <code>Intl.DateTimeFormat</code> instance is expensive, calling it once built is cheap, so the grid builds one per format and reuses it for every cell in that column.</p>
<p>The rest of a frame's cost comes down to draw-call count. Cells sharing a background are filled together under one <code>fillStyle</code> assignment, and every gridline in the viewport, horizontal and vertical, is added to a single path and stroked once.</p>
<pre><code class="language-ts">ctx.beginPath();
// Horizontal lines
for (let r = rowRange.start; r &#x3C;= rowRange.end; r++) { /* moveTo/lineTo */ }
// Vertical lines
for (let c = colRange.start; c &#x3C;= colRange.end; c++) { /* moveTo/lineTo */ }
ctx.stroke();</code></pre>
<p>Text is the honest exception. Every non-empty cell gets its own <code>fillText</code> call, with font and color reassigned inside that loop, since a cell's color can differ from its neighbor's in a way a shared fill never has to account for.</p>
<pre><code class="language-ts">ctx.font = theme.font;
ctx.fillStyle = isCut ? theme.cellContentCut : theme.cellContentIdle;</code></pre>
<p>Theme colors come from one <code>getComputedStyle</code> call, read once into a plain object rather than looked up per cell. A <code>MutationObserver</code> bumps the theme version on a dark mode change, one more counter the frame-skip check above already watches.</p>
<h2 id="keeping-the-main-thread-free-while-the-grid-works">Keeping the main thread free while the grid works</h2>
<p>None of this matters if loading or filtering a million rows freezes the tab first. Updog moves the heavy, one-shot work off the main thread and keeps only what needs to be there.</p>
<table class="thread-table"><thead><tr><th scope="col">Work</th><th scope="col">Thread</th></tr></thead><tbody><tr><th scope="row">CSV/JSON parse, CSV/TSV/JSON/XML export</th><td>Text worker (PapaParse lives here)</td></tr><tr><th scope="row">XLSX/XLS/XLSB/ODS parse and export</th><td>Sheet worker, lazily loaded (SheetJS)</td></tr><tr><th scope="row">Filtering and sorting</th><td>Filter worker</td></tr><tr><th scope="row">Validation</th><td>Main thread, cooperatively chunked</td></tr><tr><th scope="row">Formatting</th><td>Main thread; the filter worker receives pre-formatted strings</td></tr></tbody></table>
<p>The filter worker does the most unusual thing on that list, it is never handed row objects. The main thread mirrors data into it as parallel arrays instead, row IDs, pre-formatted cell text joined by a null character, raw text for numeric and date comparisons, and a per-row status flag in a typed array, kept in sync through messages like APPEND, INSERT, DELETE, and UPDATE_TEXT. A filter or sort runs entirely inside the worker, cheapest checks first, source visibility, then status, then empty cells, before the costlier column-value, range, and text-search comparisons, and returns only matching row IDs, never the rows themselves.</p>
<p>Validation stays on the main thread on purpose, since it updates the same store the grid reads without a worker round trip, but it never blocks a frame for a full million rows at once. It runs in chunks, yielding between them with a MessageChannel message instead of <code>setTimeout(0)</code>, to dodge the browser's roughly four millisecond floor on nested <code>setTimeout</code> calls.</p>
<p>The file itself is never copied to the main thread to get parsed, it is handed to the parsing worker by reference, and the result comes back as one message rather than a stream. XLSX has no main-thread fallback at all, that format needs a worker.</p>
<h2 id="accessibility-without-a-million-dom-nodes">Accessibility without a million DOM nodes</h2>
<p>Drawing the grid on canvas solves the row-count problem, but it opens an accessibility one immediately. A canvas has no structure a screen reader can read at all. Updog's answer is a second, offscreen table that exists only for assistive technology, built with the same grid semantics a real HTML table would carry. Here is what that table renders in the browser, trimmed to three columns with mock data.</p>
<pre><code class="language-html">&#x3C;div class="updog-grid-a11y">
  &#x3C;table role="grid" aria-rowcount="1001" aria-colcount="3" aria-label="Data editor">
    &#x3C;thead>
      &#x3C;tr aria-rowindex="1">
        &#x3C;th role="columnheader" aria-colindex="1">First Name&#x3C;/th>
        &#x3C;th role="columnheader" aria-colindex="2">Last Name&#x3C;/th>
        &#x3C;th role="columnheader" aria-colindex="3">Email&#x3C;/th>
      &#x3C;/tr>
    &#x3C;/thead>
    &#x3C;tbody>
      &#x3C;tr aria-rowindex="2">
        &#x3C;td role="gridcell" aria-colindex="1">Richard&#x3C;/td>
        &#x3C;td role="gridcell" aria-colindex="2">Young&#x3C;/td>
        &#x3C;td role="gridcell" aria-colindex="3">richard.young@example.com&#x3C;/td>
      &#x3C;/tr>
      &#x3C;tr aria-rowindex="3">
        &#x3C;td role="gridcell" aria-colindex="1">Joseph&#x3C;/td>
        &#x3C;td role="gridcell" aria-colindex="2">Anderson&#x3C;/td>
        &#x3C;td role="gridcell" aria-colindex="3">joseph.anderson@example.com&#x3C;/td>
      &#x3C;/tr>
    &#x3C;/tbody>
  &#x3C;/table>
  &#x3C;div aria-live="polite" aria-atomic="true" class="updog-grid-a11y__live">&#x3C;/div>
&#x3C;/div></code></pre>
<p>That table is virtualized the same way the canvas is, only the visible row window renders into it, synced on a short debounce as the person scrolls, so accessibility support does not bring back a million real DOM nodes. Navigation and selection changes are announced through a live region, reading out the row, column, and value, in English and Arabic both.</p>
<h2 id="where-canvas-earns-its-cost">Where canvas earns its cost</h2>
<p>None of this is free to build, and canvas is not the right call for every table. A settings page with forty rows needs a table element, not a rendering engine, since a table is simpler, accessible by default, and easier for the next developer to reason about. Canvas earns its cost for the shape of problem Updog exists to solve, a spreadsheet-like editor that stays responsive at row counts a normal DOM table was never built to hold, in a browser tab with no server behind it.</p>
<p>That is not a claim that other data grids are doing it wrong. Most solve a wider problem than Updog does, with more configuration surface and years more track record. Updog's grid is narrower on purpose. It is read-heavy and edit-heavy, holds up to around a million rows, and is built for importing and correcting a real file rather than every shape a data grid can take.</p>
<p>The recording below is one unedited take, scrolling a million generated rows with Chrome's own FPS meter visible in the corner of the frame. The screenshot after it is Chrome's memory tooling reading the JS heap on the main thread and inside the filter worker, taken after importing and filtering that same million rows and letting the browser's garbage collector settle. Both are here so the numbers are something a reader can go verify by installing <a href="https://www.npmjs.com/package/@updog/data-editor">the package</a> and trying it, not something to take on faith from a spec sheet.</p>
<figure class="post-figure"><p>Video: <a href="https://updog.tech/_astro/scroll-1m-rows.B3__-8nV.mp4">Scrolling through one million rows in the Updog grid, recorded in one take with Chrome's FPS meter visible</a></p><figcaption>Scrolling a million rows in one unedited take, Chrome's FPS meter visible in the corner.</figcaption></figure>
<figure class="post-figure"><img src="https://updog.tech/_astro/heap-snapshot.icXzNQIF_y2nLy.webp" alt="Chrome DevTools memory panel showing per-VM heap size on the main thread and in the filter worker after importing and filtering one million rows" width="1440" height="902"><figcaption>Chrome's memory panel, main thread and filter worker, after importing and filtering a million rows.</figcaption></figure>
<p>In everyday use, a million-row import is rare. A typical file is a few thousand rows, and at that size the engine has almost nothing to do. But large files do arrive, and when one does, the headroom is already there.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into PostgreSQL</title><link>https://updog.tech/blog/import-csv-into-postgresql/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-postgresql/</guid><pubDate>Fri, 03 Jul 2026 00:00:00 GMT</pubDate><description>Map and validate a messy pay run in the browser, then import the CSV into PostgreSQL with one transaction per chunk through node-postgres.</description><content:encoded><![CDATA[<p>Importing a CSV into PostgreSQL from inside your own app is one statement carrying many rows, aimed at a table whose constraints decide which of them survive. A payroll product meets that statement every time a customer arrives holding a pay run exported from the system they are leaving.</p>
<p>Their export looks like this.</p>
<p><code>pay-run-july.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th><th class="sheet__column" scope="col">F</th><th class="sheet__column" scope="col">G</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Line Ref</td><td class="sheet__cell">Emp No</td><td class="sheet__cell">Period End</td><td class="sheet__cell">Element</td><td class="sheet__cell">Hours</td><td class="sheet__cell">Rate/hr</td><td class="sheet__cell">Cost Ctr</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">PR-4471</td><td class="sheet__cell">E-0148</td><td class="sheet__cell">05/07/2026</td><td class="sheet__cell">BASIC</td><td class="sheet__cell">37.50</td><td class="sheet__cell">18.90</td><td class="sheet__cell">CC-200</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">PR-4472</td><td class="sheet__cell">E-0148</td><td class="sheet__cell">31/07/2026</td><td class="sheet__cell">O/T</td><td class="sheet__cell">6.25</td><td class="sheet__cell">28.35</td><td class="sheet__cell">CC-200</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">PR-4473</td><td class="sheet__cell">E-0209</td><td class="sheet__cell">31/07/2026</td><td class="sheet__cell">Bonus (annual)</td><td class="sheet__cell">n/a</td><td class="sheet__cell">(45.00)</td><td class="sheet__cell">CC-410</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">5</th><td class="sheet__cell">PR-4473</td><td class="sheet__cell">E-0233</td><td class="sheet__cell">31/07/2026</td><td class="sheet__cell">BASIC</td><td class="sheet__cell">37.50</td><td class="sheet__cell">22.10</td><td class="sheet__cell"></td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="7"><span class="sheet__break-text">407 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">413</th><td class="sheet__cell">PR-4882</td><td class="sheet__cell">E-0331</td><td class="sheet__cell">31/07/2026</td><td class="sheet__cell">BASIC</td><td class="sheet__cell">37.50</td><td class="sheet__cell">19.75</td><td class="sheet__cell">CC-310</td></tr></tbody></table>
<p>Seven headers. Three of them carry names your table never uses. Rows 4 and 5 share the line reference <code>PR-4473</code>. One period end reads <code>05/07/2026</code> and the next reads <code>31/07/2026</code>. The hours cell on the bonus line says <code>n/a</code>, and the rate beside it reads <code>(45.00)</code>, which is how the old system wrote a negative. The element column says <code>BASIC</code>, <code>O/T</code> and <code>Bonus (annual)</code>. The cost centre on row 5 is empty.</p>
<p>The person opens the importer inside your app and drops the pay-run export into it. Updog Importer parses the export in the browser, lines its headers up with your fields, and shows them every pay line. Your <code>onComplete</code> handler receives the rows. The handler slices those rows into chunks and posts each chunk to a route you own. The route holds the connection string and sends one <code>INSERT</code> per chunk. PostgreSQL writes the table.</p>
<p>Between that browser and PostgreSQL there is no Updog server.</p>
<h2 id="step-1-create-the-table-and-its-constraints">Step 1. Create the table and its constraints</h2>
<p>Start with the table, because everything the browser checks later is a copy of what this declares.</p>
<pre><code class="language-sql">create table public.pay_run_lines (
  id bigint generated always as identity primary key,
  tenant_id uuid not null,
  line_ref text not null,
  emp_no text not null,
  period_end date not null,
  pay_element text not null,
  hours numeric(6, 2) not null,
  hourly_rate numeric(8, 2) not null,
  cost_centre text not null,
  updated_at timestamptz not null default now(),
  constraint pay_run_lines_ref_key unique (tenant_id, line_ref),
  constraint pay_run_lines_rate_check check (hourly_rate >= 0),
  constraint pay_run_lines_element_check
    check (pay_element in ('Basic', 'Overtime', 'Bonus'))
);</code></pre>
<p>The unique constraint on <code>tenant_id</code> and <code>line_ref</code> is the piece that makes a second import safe. The <code>INSERT</code> documentation is explicit, "For <code>ON CONFLICT DO UPDATE</code>, a <code>conflict_target</code> must be provided", and only non-deferrable constraints and unique indexes are allowed to arbitrate one. Two of your customers can both send a line called <code>PR-4471</code>, so identity here takes the tenant as well. Inside one import the tenant is fixed, so the line reference alone identifies a line on the browser side.</p>
<p>The rest of the table is four kinds of refusal. <code>not null</code> refuses a cost centre that arrives as null. <code>numeric(6, 2)</code> refuses the <code>n/a</code> sitting in the hours cell. <code>check (hourly_rate >= 0)</code> refuses <code>-45.00</code>. The check on <code>pay_element</code> refuses anything outside the three elements your product pays.</p>
<p>The empty cost centre in the file gets past the first of those. An empty cell reaches your handler as an empty string, and <code>not null</code> accepts an empty string, so the browser check on that column reaches further than the table does.</p>
<h2 id="step-2-mirror-those-constraints-in-the-column-schema">Step 2. Mirror those constraints in the column schema</h2>
<p>The <code>columns</code> array is that table written for the person looking at the file. Every entry carries a <code>title</code> the person reads, an editor that shapes typing in a cell, and validators that mark what the table would refuse.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const PAY_ELEMENTS = ["Basic", "Overtime", "Bonus"];

export const columns: DataEditorColumn[] = [
  {
    id: "lineRef",
    title: "Line ref",
    size: 130,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "unique" },
    ],
  },
  {
    id: "empNo",
    title: "Employee number",
    size: 140,
    validators: [{ type: "required" }],
  },
  {
    id: "periodEnd",
    title: "Period end",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
  {
    id: "payElement",
    title: "Pay element",
    size: 150,
    editor: { type: "select", options: PAY_ELEMENTS, enableCustomValue: false },
    validators: [
      { type: "required" },
      { type: "oneOf", values: PAY_ELEMENTS },
    ],
  },
  {
    id: "hours",
    title: "Hours",
    size: 110,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", decimalPlaces: 2 },
    ],
  },
  {
    id: "hourlyRate",
    title: "Hourly rate",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "required" },
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "costCentre",
    title: "Cost centre",
    size: 140,
    validators: [{ type: "required" }],
  },
];</code></pre>
<p>Every validator answers one line of the create table statement above.</p>
<div class="blog-table blog-table--narrow"><table>
<thead>
<tr>
<th>What the table declares</th>
<th>What the column declares</th>
<th>The error it stops</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>not null</code></td>
<td><code>{ type: "required" }</code></td>
<td><code>23502</code> not_null_violation</td>
</tr>
<tr>
<td><code>unique (tenant_id, line_ref)</code></td>
<td><code>{ type: "unique" }</code></td>
<td><code>23505</code> unique_violation</td>
</tr>
<tr>
<td><code>numeric(6, 2)</code></td>
<td><code>{ type: "number", decimalPlaces: 2 }</code></td>
<td><code>22P02</code> invalid_text_representation</td>
</tr>
<tr>
<td><code>check (hourly_rate >= 0)</code></td>
<td><code>{ type: "number", min: 0 }</code></td>
<td><code>23514</code> check_violation</td>
</tr>
<tr>
<td><code>check (pay_element in ...)</code></td>
<td><code>{ type: "oneOf", values }</code></td>
<td><code>23514</code> check_violation</td>
</tr>
</tbody>
</table></div>
<p>Those four codes are PostgreSQL's own, listed in its error appendix under Class 22 for data exceptions and Class 23 for integrity constraint violations. <a href="https://updog.tech/blog/common-csv-import-errors/">Common CSV import errors and how to prevent them</a> covers the wider set a file arrives with.</p>
<p><code>blockSubmitOnError</code> is what makes the mirror hold. Submit stays disabled while any row carries an error, so a row that would raise any of those codes stays on the screen until somebody fixes it. The <code>synonyms</code> prop teaches matching the words the old payroll system used, and the mount ties the whole thing together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;PayRunLine>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="lineRef"
  blockSubmitOnError
  synonyms={{
    columns: { hourlyRate: ["rate/hr", "hourly pay rate", "std rate"] },
    values: { Overtime: ["o/t", "ot", "overtime prem"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p><code>Emp No</code> and <code>Period End</code> reach <code>empNo</code> and <code>periodEnd</code> on an exact match, because matching lowercases a header and drops spaces before it scores. <code>Element</code> reaches <code>payElement</code> because <code>payelement</code> contains <code>element</code>. <code>Cost Ctr</code> reaches <code>costCentre</code> on word overlap, since <code>cost</code> matches and <code>ctr</code> matches nothing. <code>Rate/hr</code> reaches no column at all, because the slash survives normalising, so neither string contains the other and they share no word. That header comes from <code>synonyms</code>. Values score the same way. <code>BASIC</code> lands on <code>Basic</code> exactly, and <code>Bonus (annual)</code> lands on <code>Bonus</code> because it contains it. <code>O/T</code> is three characters, which is under the length the contains tier accepts, so it comes from <code>synonyms</code> too.</p>
<p>A <code>date</code> column normalizes <code>05/07/2026</code> to <code>2026-07-05</code>, because <code>31/07/2026</code> further down the file carries a day past 12 and settles the whole file as day-first. The number columns read the same file as dot-decimal, since <code>37.50</code> and <code>18.90</code> vote that way and nothing votes the other. Those two verdicts are taken separately, so a day-first file with dot decimals stays readable.</p>
<p><code>primaryKey</code> is required, and <code>lineRef</code> points it at the browser half of that conflict target. Every snippet here is React. The web component build carries the same props, so a Vue, Angular or Svelte app writes the same schema and the same handler. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<h2 id="step-3-post-the-result-in-chunks">Step 3. Post the result in chunks</h2>
<p>When the person submits, Updog Importer hands your handler each pay line grouped by source, carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. One person can drop three files in a single import, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 1000;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;PayRunLine>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const chunk = rows.slice(start, start + CHUNK_SIZE);

    const response = await fetch("/api/pay-run/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: chunk }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(
        "Rows " + (start + 1) + " to " + (start + chunk.length) +
          " were not saved. " + failure.message,
      );
    }
  }
}, []);</code></pre>
<p>The chunk size is arithmetic on a published number. PostgreSQL caps a statement at 65,535 query parameters, in the same appendix that caps a table at 1,600 columns. A parameterized query in node-postgres travels through the extended query protocol, whose Bind message carries the parameter count as an Int16. Each row in the statement below writes eight columns, so that statement holds 8,191 rows at the most.</p>
<p>Nobody publishes a batch size for this, so 1,000 is a conservative choice of ours under that ceiling. Two things pull it down. The person waits with the confirm dialog open and a spinner on the button, so a single huge request is a long freeze. A chunk that fails rolls back whole, so the smaller the chunk, the less work a retry repeats. Run the division against your own table before you raise it, because a table of forty columns puts the ceiling at 1,638.</p>
<p><strong>Throw when PostgreSQL refuses a chunk.</strong> Updog waits on your handler and empties the editor the instant the promise resolves. A handler that swallows the failure and returns looks like a clean import, and the grid empties with the pay run unwritten. Throwing holds every pay line, every mapping and every correction on the screen, so the person submits again on data still in front of them. Copy anything you want to keep inside the handler, because the editor drops its rows, its sources and its learned synonyms once the promise resolves.</p>
<p>The <code>isValid</code> filter carries a cost worth naming. A failed validator marks the cell and lets submission continue, so without <code>blockSubmitOnError</code> the flagged rows reach your handler and the filter drops them on the floor. Splitting the rows by <code>isValid</code> and posting the failures to a table your support team reads works too.</p>
<h2 id="step-4-write-one-transaction-per-chunk">Step 4. Write one transaction per chunk</h2>
<p>The connection string lives in that route, and the browser goes no further.</p>
<pre><code class="language-ts">import express from "express";
import { Pool } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const FIELDS = 8;

export const router = express.Router();

router.post("/api/pay-run/import", async (request, response) => {
  const session = await getVerifiedSession(request);
  if (!session) {
    return response.status(401).json({ message: "Not signed in" });
  }

  const rows = request.body.rows;
  const values = [];

  const tuples = rows.map((row, index) => {
    values.push(
      session.tenantId, row.lineRef, row.empNo, row.periodEnd,
      row.payElement, row.hours, row.hourlyRate, row.costCentre,
    );
    const base = index * FIELDS;
    const holders = [];
    for (let n = 1; n &#x3C;= FIELDS; n++) holders.push("$" + (base + n));
    return "(" + holders.join(", ") + ")";
  });

  const text = [
    "insert into pay_run_lines (tenant_id, line_ref, emp_no, period_end,",
    "  pay_element, hours, hourly_rate, cost_centre)",
    "values " + tuples.join(", "),
    "on conflict (tenant_id, line_ref) do update set",
    "  emp_no = excluded.emp_no,",
    "  period_end = excluded.period_end,",
    "  pay_element = excluded.pay_element,",
    "  hours = excluded.hours,",
    "  hourly_rate = excluded.hourly_rate,",
    "  cost_centre = excluded.cost_centre,",
    "  updated_at = now()",
  ].join("\n");

  const client = await pool.connect();
  try {
    await client.query("begin");
    await client.query(text, values);
    await client.query("commit");
    response.json({ written: rows.length });
  } catch (error) {
    await client.query("rollback");
    response.status(400).json(describeFailure(error));
  } finally {
    client.release();
  }
});</code></pre>
<p>One <code>INSERT</code> carries the whole chunk. <code>on conflict (tenant_id, line_ref) do update set</code> turns a second import of the same line into an update, and <code>excluded</code> is Postgres's name for the row that was proposed. The alternative is a loop of single-row inserts, which sends one Parse and one Bind per row and holds the person on the spinner while it runs. A hosted Postgres reaches the same table through its own client library, and <a href="https://updog.tech/blog/import-csv-into-supabase/">how to import CSV into Supabase</a> writes this route with <code>upsert()</code> and a secret key.</p>
<p>The <code>begin</code> and the <code>commit</code> earn nothing while the chunk is one statement. PostgreSQL wraps every lone statement in an implicit <code>BEGIN</code> and <code>COMMIT</code> of its own, and its tutorial says exactly that. The pair starts earning the moment the route makes a second write in the same chunk, an audit row or a header update. Until then it keeps the chunk boundary and the rollback boundary on one line of code.</p>
<p>The client comes from <code>pool.connect()</code> and goes back in a <code>finally</code>. node-postgres is blunt about why, "You must use the same client instance for all statements within a transaction", and <code>pool.query</code> hands out whichever client happens to be idle. <code>getVerifiedSession()</code> stands in for your own server-side check. <code>tenant_id</code> comes off that session and never off the request body, so one customer cannot write rows into another customer's pay run.</p>
<p>A chunk PostgreSQL refuses takes the <code>catch</code> and the <code>rollback</code> before the person hears anything about it.</p>
<h2 id="step-5-carry-the-constraint-error-back-to-its-row">Step 5. Carry the constraint error back to its row</h2>
<p>A rejected chunk comes back as one error object carrying the fields the wire protocol defines.</p>
<pre><code class="language-ts">const FIELD_BY_CONSTRAINT = {
  pay_run_lines_ref_key: "Line ref",
  pay_run_lines_rate_check: "Hourly rate",
  pay_run_lines_element_check: "Pay element",
};

const describeFailure = (error) => ({
  code: error.code,
  field: FIELD_BY_CONSTRAINT[error.constraint] ?? error.column ?? null,
  message: error.message,
  detail: error.detail ?? null,
});</code></pre>
<p><code>23505</code> and <code>23514</code> both name the rule they broke in <code>error.constraint</code>, so a lookup turns <code>pay_run_lines_rate_check</code> into the words <code>Hourly rate</code>. <code>23502</code> leaves that field empty and fills <code>error.column</code> instead, which is why the mapping reads one and then the other. <code>22P02</code> fills neither, because a value that fails to become a <code>numeric</code> never reaches a constraint, so the message carrying <code>invalid input syntax for type numeric</code> is what travels back.</p>
<p><code>error.detail</code> holds the half a person can act on. A unique violation puts <code>Key (tenant_id, line_ref)=(...) already exists.</code> there, and a check violation puts the failing row. Postgres withholds it when the connecting role cannot read every column in the key, so the mapping falls back to the message when it arrives empty. What it does carry is values out of the row the person submitted, going back to the browser they came from.</p>
<p>The conflict target moves the unique code. A line already stored under the same key comes back as an update, and a duplicate that arrives inside one chunk stops the statement with <code>21000</code>, where Postgres answers <code>ON CONFLICT DO UPDATE command cannot affect row a second time</code>. Its hint asks you to ensure that no rows proposed for insertion within the same command have duplicate constrained values, which is the whole job of the <code>unique</code> validator on <code>lineRef</code>. That failure carries no constraint name and no column, so the lookup falls through to the message.</p>
<p>Chunks that already committed stay committed. The same chunk sent again writes the same values through the same conflict target, so a retry after a failure costs a rewrite of what already landed.</p>
<h2 id="the-connector-that-does-not-exist">The connector that does not exist</h2>
<p>Updog Importer integrates with nobody. There is no PostgreSQL connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object of pay lines, and the route that writes them is yours to build.</p>
<p>PostgreSQL already ships its own import paths for the other case. <code>COPY</code> reads a file the server itself can reach, and its documentation allows that to superusers and to roles granted <code>pg_read_server_files</code>. <code>\copy</code> in psql reads a file on the machine running psql, which is the shorter path when the file is yours. The pgAdmin Import/Export dialog does the same work through a form. Each one starts from the seat of somebody holding a database connection, and a bad value fails the whole command by default, since <code>COPY</code> ships <code>ON_ERROR</code> as <code>stop</code>.</p>
<p>Your customer holds none of that. They hold a pay-run export and a login to your app. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> lays out what each model does well.</p>
<h2 id="the-rules-that-run-in-both-places">The rules that run in both places</h2>
<p>You wrote a table whose constraints say what a pay-run line has to be, a schema that repeats each of those rules as a validator, a handler that chunks at 1,000 rows, and a route that opens one transaction per chunk. The pay-run export never leaves the machine that opened it. The rows travel from your own front end to your own route, and from there into PostgreSQL, and the only party added to the chain is yourself.</p>
<p>The error codes in step 5 are there for the rows nobody fixed. The same rules already ran in a grid where the person could see them and type over them, which is the point of writing those rules twice.</p>]]></content:encoded></item>
<item><title>How to Import a CSV File Into a React App With the Updog Importer</title><link>https://updog.tech/blog/how-to-import-csv-into-react-app/</link><guid isPermaLink="true">https://updog.tech/blog/how-to-import-csv-into-react-app/</guid><pubDate>Thu, 02 Jul 2026 00:00:00 GMT</pubDate><description>A step-by-step guide to adding CSV and Excel import to your React app with Updog. Install the SDK, define your schema, set up matching, and get clean rows back.</description><content:encoded><![CDATA[<p>This guide shows you how to add a CSV and Excel importer to a React app. Import needs more than a parser. Read <a href="https://updog.tech/blog/csv-import-is-more-than-parsing/">CSV import is more than parsing a file</a> to see why.</p>
<p>The example is an employee importer with seven columns. A messy file goes in. Clean rows come out. You install the package, describe your data, match the file to your schema, and get the result back.</p>
<h2 id="step-1-install-the-package">Step 1. Install the package</h2>
<pre><code class="language-bash">npm install @updog/data-editor</code></pre>
<p>You can find the package on npm at <a href="https://www.npmjs.com/package/@updog/data-editor">@updog/data-editor</a>. There is also a web component build at <a href="https://www.npmjs.com/package/@updog/data-editor-wc">@updog/data-editor-wc</a>, in case you are not coming from the React ecosystem.</p>
<h2 id="step-2-mount-the-editor">Step 2. Mount the editor</h2>
<p>Render <code>DataEditor</code> and set <code>variant</code> to <code>uploader</code>. This opens the import wizard first. The default <code>editor</code> variant opens the grid first, for cases when you already have data, for example.</p>
<p>Import usually sits behind a button, and modal is the default. Control it with <code>open</code> and <code>onClose</code>.</p>
<pre><code class="language-tsx">import { useCallback, useState } from "react";
import { DataEditor } from "@updog/data-editor";

export function ImportEmployees() {
  const [open, setOpen] = useState(false);

  const openImporter = useCallback(() => {
    setOpen(true);
  }, []);

  const closeImporter = useCallback(() => {
    setOpen(false);
  }, []);

  const onComplete = useCallback((result) => {
    console.log(result);
  }, []);

  return (
    &#x3C;>
      &#x3C;button onClick={openImporter}>Import employees&#x3C;/button>
      &#x3C;DataEditor
        apiKey="your-license-key"
        variant="uploader"
        open={open}
        onClose={closeImporter}
        onComplete={onComplete}
      />
    &#x3C;/>
  );
}</code></pre>
<p>Get the <code>apiKey</code> by signing up at <a href="https://console.updog.tech/">console.updog.tech</a>. After you sign up, you get a default API key right away. Updog is free to use on localhost and on the preview domains from hosts like Vercel and Netlify. In production, the Free plan covers 100,000 rows a month. Above that, Team costs $100 a month for any number of domains.</p>
<p><code>columns</code> and <code>primaryKey</code> are required, and the next steps build both.</p>
<p>If you want to embed the editor in the page instead, set <code>mode</code> to <code>inline</code> and drop <code>open</code> and <code>onClose</code>.</p>
<p>These examples use React, the native package. For Vue, Angular, Svelte, or plain JavaScript, Updog ships as a web component with the same props. See the <a href="https://updog.tech/csv-importer/">CSV importer for any framework</a> page.</p>
<h2 id="step-3-describe-your-data">Step 3. Describe your data</h2>
<p>The <code>columns</code> array describes the shape your app expects. Every uploaded file gets changed to match it. The more detail you add to the schema, the less anyone has to fix by hand later.</p>
<h3 id="start-with-the-columns">Start with the columns</h3>
<p>Each column needs an <code>id</code> that matches the key in your row data. It also needs a <code>title</code>, the text users see. <code>size</code> is optional. Add it in pixels when you want a column wider or narrower.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

export const columns: DataEditorColumn[] = [
  {
    id: "firstName",
    title: "First name",
    size: 150,
  },
  {
    id: "lastName",
    title: "Last name",
    size: 150,
  },
  {
    id: "email",
    title: "Email",
    size: 260,
  },
  {
    id: "startDate",
    title: "Start date",
    size: 140,
  },
  {
    id: "salary",
    title: "Salary",
    size: 120,
  },
  {
    id: "skills",
    title: "Skills",
    size: 220,
  },
  {
    id: "status",
    title: "Status",
    size: 140,
  },
];</code></pre>
<h3 id="choose-an-editor-for-each-column">Choose an editor for each column</h3>
<p>Text is the default, so the name and email columns need nothing. The other columns each need an editor. Use <code>date</code> for the start date, <code>number</code> for salary, <code>multiselect</code> for skills, and <code>select</code> for status. An editor sets what users can type. For <code>select</code> and <code>multiselect</code>, it also tells the import which values to match against a known list.</p>
<pre><code class="language-ts">{
  id: "startDate",
  title: "Start date",
  size: 140,
  editor: {
    type: "date",
  },
},
{
  id: "salary",
  title: "Salary",
  size: 120,
  editor: {
    type: "number",
  },
},
{
  id: "skills",
  title: "Skills",
  size: 220,
  editor: {
    type: "multiselect",
    options: ["React", "TypeScript", "Node", "Design"],
  },
},
{
  id: "status",
  title: "Status",
  size: 140,
  editor: {
    type: "select",
    options: ["Active", "Onboarding", "On leave", "Terminated"],
  },
},</code></pre>
<h3 id="add-the-rules">Add the rules</h3>
<p>Validators run on every edit. A value that fails is highlighted in the grid. Here is the full schema, with editors and validators together.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const STATUSES = ["Active", "Onboarding", "On leave", "Terminated"];

export const columns: DataEditorColumn[] = [
  {
    id: "firstName",
    title: "First name",
    size: 150,
    validators: [
      {
        type: "required",
        message: "First name is required",
      },
    ],
  },
  {
    id: "lastName",
    title: "Last name",
    size: 150,
    validators: [
      {
        type: "required",
        message: "Last name is required",
      },
    ],
  },
  {
    id: "email",
    title: "Email",
    size: 260,
    validators: [
      {
        type: "required",
        message: "Email is required",
      },
      {
        type: "email",
        message: "Enter a valid email address",
      },
      {
        type: "unique",
      },
    ],
  },
  {
    id: "startDate",
    title: "Start date",
    size: 140,
    editor: {
      type: "date",
    },
    validators: [
      {
        type: "date",
        message: "Enter a valid date",
      },
    ],
  },
  {
    id: "salary",
    title: "Salary",
    size: 120,
    editor: {
      type: "number",
    },
    validators: [
      {
        type: "number",
        min: 0,
        decimalPlaces: 0,
        message: "Salary must be zero or greater",
      },
    ],
  },
  {
    id: "skills",
    title: "Skills",
    size: 220,
    editor: {
      type: "multiselect",
      options: ["React", "TypeScript", "Node", "Design"],
    },
  },
  {
    id: "status",
    title: "Status",
    size: 140,
    editor: {
      type: "select",
      options: STATUSES,
    },
    validators: [
      {
        type: "oneOf",
        values: STATUSES,
        message: "Select a status from the list",
      },
    ],
  },
];</code></pre>
<p>Email uses <code>required</code> and <code>email</code>. A <code>unique</code> validator flags a duplicate address in the file. Start date runs a <code>date</code> check. Salary uses a <code>number</code> check that rejects anything below zero. Status uses <code>oneOf</code> against the same list its dropdown offers, which catches a value that slips past matching. A failed rule marks the cell, but it does not block submission by default. Users can still fix it in the grid, and invalid rows still reach you, tagged with the <code>isValid</code> flag. If you want to hold submission until every error is fixed, set <a href="https://docs.updog.tech/api-reference/core-props/#blocksubmitonerror"><code>blockSubmitOnError</code></a>.</p>
<h3 id="fix-common-errors-before-anyone-sees-them">Fix common errors before anyone sees them</h3>
<p>A validator flags a bad value, but a <code>transformer</code> fixes it first. Add one to a column, and Updog runs it on each cell right after the user clicks import on the upload step, before the rows reach the editor grid. This lets you clean up common mistakes before users ever see them, such as trimming stray spaces, lowercasing an email, or dropping a currency symbol. It runs on text, number, and date columns, after Updog normalizes the raw value and before it enters the store. Select and multiselect columns go through value matching instead.</p>
<pre><code class="language-ts">{
  id: "email",
  title: "Email",
  size: 260,
  transformer: (value) => String(value).trim().toLowerCase(),
},</code></pre>
<h3 id="shape-how-columns-show-and-filter">Shape how columns show and filter</h3>
<p>Two more column props work on the grid itself, once the file is loaded. A <code>formatter</code> changes how a value looks without changing what you store. Salary can show with a <code>$</code> in front while the stored value stays untouched. A <code>filter</code> adds a control to the sidebar Filters panel. That means a dropdown for status, a min and max range for salary, and a date range for the start date.</p>
<pre><code class="language-ts">{
  id: "salary",
  title: "Salary",
  size: 120,
  formatter: (value) => (value ? "$" + value : ""),
  filter: {
    type: "number-range",
    label: "Salary",
  },
},</code></pre>
<h2 id="step-4-help-updog-match-the-file">Step 4. Help Updog match the file</h2>
<p>The schema is ready, but the file rarely matches it word for word. Headers and values come in whatever words the file's author chose. Updog runs fuzzy matching first, and it already catches most small differences on its own, like extra spaces, different capitalization, or a common alternate spelling. If your data uses terms Updog cannot guess, like an internal code, an abbreviation, or a word specific to your industry, you add your own dictionary on top of it. Two props do this. <code>synonyms</code> lets you list the exact words you already know users use. The <code>onColumnMatch</code> and <code>onValueMatch</code> callbacks let you match anything else with your own code or your own AI model.</p>
<h3 id="match-the-columns">Match the columns</h3>
<p>The file might say <code>E-mail</code>, <code>Employment Status</code>, and <code>Start Date</code>. Your columns are <code>email</code>, <code>status</code>, and <code>startDate</code>. Built-in matching pairs the obvious ones. Add the headers users often send to the <code>columns</code> table of <code>synonyms</code>, and they map on their own.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  synonyms={{
    columns: {
      email: ["e-mail", "email address", "work email"],
      status: ["employment status", "employee status", "state"],
    },
  }}
  ...
/></code></pre>
<p>For a header no list catches, pass the decision to your own model through <code>onColumnMatch</code>. Updog gives it the file's headers and your columns. You return a map of which goes where.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  onColumnMatch={async (headers, columns) => {
    // headers = ["Emp Email", "Emp Status", ...] from the file
    // columns = your firstName, lastName, email, ... schema
    const map = await askYourModel(headers, columns);
    return map; // { "Emp Email": "email", "Emp Status": "status" }
  }}
  ...
/></code></pre>
<p>See <a href="https://updog.tech/blog/bring-your-own-ai/">bring your own AI to CSV and Excel import</a> for that path and how the data stays private.</p>
<h3 id="match-the-values">Match the values</h3>
<p>The same works inside the status column. A file can send <code>loa</code>, <code>on-leave</code>, and <code>leave</code> for the status <code>On leave</code>. Value aliases go in the <code>values</code> table, keyed by the option, with the array listing what maps to it. The two tables stay apart, so a word learned inside a dropdown never competes for a column.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  synonyms={{
    columns: {
      email: ["e-mail", "email address", "work email"],
      status: ["employment status", "employee status", "state"],
    },
    values: {
      "On leave": ["loa", "on-leave", "leave"],
      Terminated: ["term", "terminated", "left"],
    },
  }}
  ...
/></code></pre>
<p>For values no list covers, <code>onValueMatch</code> is the column callback one level down. Updog hands you the distinct values found in each select column, plus the options you allow. You return the mapping.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  onValueMatch={async (valuesToMatch) => {
    // valuesToMatch = { status: { importedValues: ["loa", "left"], options: ["Active", "On leave", ...] } }
    const map = await askYourModel(valuesToMatch);
    return map; // { status: { loa: "On leave", left: "Terminated" } }
  }}
  ...
/></code></pre>
<p>It can run through your model too, as shown in the <a href="https://updog.tech/blog/bring-your-own-ai/">bring your own AI</a> post.</p>
<h3 id="set-the-primary-key">Set the primary key</h3>
<p><code>primaryKey</code> decides how new rows join the rows you already have. It is a <code>DataEditor</code> prop, like <code>columns</code>. For employees, <code>email</code> fits well. Updog checks each imported row against the loaded rows. A match updates that employee instead of adding a copy. Import the same list twice, and you get one list, not duplicates.</p>
<p>Updog leans on it wherever rows have to line up. In the upload flow, it sets the default on the primary key step, where users can confirm it or choose another column. With AI chat on, it is the key used to match the rows the assistant returns, so a transformation merges into the grid instead of duplicating rows.</p>
<h2 id="step-5-take-back-the-result">Step 5. Take back the result</h2>
<p>On submit, Updog passes the edited data to <code>onComplete</code>, grouped by source. Each row carries four flags. They are <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code>, and <code>isValid</code>. Routing depends on your backend, so Updog leaves that part to you. Filter on the flags, and send each row where it belongs. Pass your row type to <code>DataEditor</code>, and the result is typed throughout.</p>
<pre><code class="language-ts">type Employee = {
  firstName: string;
  lastName: string;
  email: string;
  startDate: string;
  salary: string;
  skills: string[];
  status: string;
};

const onComplete = useCallback(
  async (result: DataEditorResult&#x3C;Employee>) => {
    for (const source of result.sources) {
      const inserts = source.rows.filter(
        (r) => r.isNew &#x26;&#x26; !r.isDeleted &#x26;&#x26; r.isValid,
      );
      const updates = source.rows.filter(
        (r) => !r.isNew &#x26;&#x26; r.isChanged &#x26;&#x26; !r.isDeleted &#x26;&#x26; r.isValid,
      );
      await saveEmployees(inserts, updates);
    }
  },
  [],
);

&#x3C;DataEditor&#x3C;Employee>
  apiKey="your-license-key"
  variant="uploader"
  columns={columns}
  primaryKey="email"
  onComplete={onComplete}
/></code></pre>
<p>A file went in. Typed, validated employees come out, ready to save.</p>
<h2 id="step-6-localize-it">Step 6. Localize it</h2>
<p>Updog translates. Set <code>locale</code>, pass a <code>translations</code> object with the strings you override, and set <code>rtl</code> for right-to-left languages.</p>
<pre><code class="language-tsx">&#x3C;DataEditor
  locale="ar"
  rtl
  translations={arabicTranslations}
  ...
/></code></pre>
<p>You do not translate every string by hand. Copy the defaults object from the <a href="https://docs.updog.tech/localization/#defaults">localization docs</a>, paste it into your AI, and ask it to translate the values. Drop the result into the <code>translations</code> prop.</p>
<h2 id="what-you-built">What you built</h2>
<p>You installed a package, wrote a schema, and added a few props and a result handler. It runs in the browser, so you do not need a server, and nothing leaves the page until you save it. The config you wrote handles the messy files. You handle what happens to the clean, typed rows.</p>]]></content:encoded></item>
<item><title>How to Import CSV Into Supabase</title><link>https://updog.tech/blog/import-csv-into-supabase/</link><guid isPermaLink="true">https://updog.tech/blog/import-csv-into-supabase/</guid><pubDate>Wed, 01 Jul 2026 00:00:00 GMT</pubDate><description>Map and validate a messy CSV in the browser, post the clean rows to your own route in chunks, and upsert them into a Supabase table.</description><content:encoded><![CDATA[<p>Supabase documents four ways to move a CSV into a table. The dashboard importer takes a file up to 100MB. <code>pgloader</code> carries a whole database across. <code>COPY</code> loads a file straight into a table from a direct database connection. The API writes rows from code you control. Every one of them starts from the seat of somebody who holds the project credentials. Your customer sits outside that seat, holding a price list exported from the system they are leaving.</p>
<p>Their export arrives looking like this.</p>
<p><code>price-list.csv</code></p><table class="sheet__grid"><thead><tr><td class="sheet__corner"></td><th class="sheet__column" scope="col">A</th><th class="sheet__column" scope="col">B</th><th class="sheet__column" scope="col">C</th><th class="sheet__column" scope="col">D</th><th class="sheet__column" scope="col">E</th></tr></thead><tbody><tr class="sheet__row sheet__row--header"><th class="sheet__number" scope="row">1</th><td class="sheet__cell">Item Code</td><td class="sheet__cell">Product Name</td><td class="sheet__cell">Cat</td><td class="sheet__cell">Unit Price</td><td class="sheet__cell">Launch</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">2</th><td class="sheet__cell">0041782 </td><td class="sheet__cell">ThinkPad X13 Gen 4</td><td class="sheet__cell">notebooks</td><td class="sheet__cell">$1,299.00</td><td class="sheet__cell">03/04/2026</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">3</th><td class="sheet__cell">0041783</td><td class="sheet__cell">Dell U2723QE</td><td class="sheet__cell">MONITORS</td><td class="sheet__cell">$589.99</td><td class="sheet__cell">17.04.2026</td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">4</th><td class="sheet__cell">0041784</td><td class="sheet__cell">USB-C Dock 90W</td><td class="sheet__cell">PC accessories</td><td class="sheet__cell">USD 149.00</td><td class="sheet__cell">2026-05-02</td></tr><tr class="sheet__break"><td class="sheet__break-gutter"></td><td class="sheet__break-body" colspan="5"><span class="sheet__break-text">1200 rows not shown</span></td></tr><tr class="sheet__row"><th class="sheet__number" scope="row">1205</th><td class="sheet__cell">0042985</td><td class="sheet__cell">Logitech MX Master 3S</td><td class="sheet__cell">PC accessories</td><td class="sheet__cell">89.00</td><td class="sheet__cell">2026-05-14</td></tr></tbody></table>
<p>Five headers, and none of them carry the names your table uses. The item codes carry leading zeros a numeric column would eat, and the first one trails a space. One launch date reads <code>03/04/2026</code> and the next reads <code>17.04.2026</code>. Two prices carry a dollar sign and a thousands comma, and the third writes its currency in letters. The category column says <code>notebooks</code>, <code>MONITORS</code> and <code>PC accessories</code>.</p>
<p>The person drops that file into the importer inside your app. Updog Importer reads it in the browser, matches the headers to your schema, and puts every value in front of them. Your <code>onComplete</code> handler receives the rows. The handler posts them in chunks to a route you own. The route holds the Supabase secret key and calls <code>upsert()</code>. Supabase writes the table.</p>
<p>No Updog server sits anywhere in that chain.</p>
<h2 id="step-1-create-the-table-and-its-conflict-target">Step 1. Create the table and its conflict target</h2>
<p>Start in the SQL editor with the table the rows have to reach.</p>
<pre><code class="language-sql">create table public.products (
  id uuid primary key default gen_random_uuid(),
  tenant_id uuid not null,
  item_code text not null,
  product_name text not null,
  category text not null,
  price numeric(10, 2),
  launch_date date not null,
  updated_at timestamptz not null default now(),
  constraint products_tenant_item_key unique (tenant_id, item_code)
);

alter table public.products enable row level security;</code></pre>
<p><code>item_code</code> stays <code>text</code>, so <code>0041782</code> keeps the zeros a numeric column would eat. The unique constraint on <code>tenant_id</code> and <code>item_code</code> is the piece that makes a repeat import safe. Postgres puts the requirement plainly, "For <code>ON CONFLICT DO UPDATE</code>, a <code>conflict_target</code> must be provided", and the arbiter it infers has to be a non-deferrable unique index or unique constraint. Name a conflict target with nothing like that behind it and Postgres answers "there is no unique or exclusion constraint matching the ON CONFLICT specification".</p>
<p>A table you create in the SQL editor starts with row level security off, and Supabase warns that "a table in an exposed schema without RLS is readable and writable by anyone with your publishable key". The <code>alter</code> line closes that. The route below writes with the secret key, whose <code>service_role</code> carries <code>BYPASSRLS</code>, so the write path keeps working with the door shut.</p>
<p>Identity here takes two columns, because two of your customers can both stock item <code>0041782</code>. Inside one import the tenant is fixed, so the item code alone identifies a product on the browser side.</p>
<h2 id="step-2-describe-the-same-shape-to-updog-importer">Step 2. Describe the same shape to Updog Importer</h2>
<p>The <code>columns</code> array is your table written for the person looking at the file. Each entry sets a <code>title</code> they read, an editor that decides how a cell is typed, and validators that mark what fails.</p>
<pre><code class="language-ts">import type { DataEditorColumn } from "@updog/data-editor";

const CATEGORIES = ["Laptops", "Monitors", "Accessories"];

export const columns: DataEditorColumn[] = [
  {
    id: "itemCode",
    title: "Item code",
    size: 130,
    transformer: (value) => String(value).trim(),
    validators: [
      { type: "required" },
      { type: "unique" },
    ],
  },
  {
    id: "productName",
    title: "Product name",
    size: 220,
    validators: [{ type: "required" }],
  },
  {
    id: "category",
    title: "Category",
    size: 150,
    editor: { type: "select", options: CATEGORIES, enableCustomValue: false },
    validators: [
      { type: "required" },
      { type: "oneOf", values: CATEGORIES },
    ],
  },
  {
    id: "price",
    title: "Unit price",
    size: 130,
    editor: { type: "number" },
    validators: [
      { type: "number", min: 0, decimalPlaces: 2 },
    ],
  },
  {
    id: "launchDate",
    title: "Launch date",
    size: 140,
    editor: { type: "date" },
    validators: [
      { type: "required" },
      { type: "date" },
    ],
  },
];</code></pre>
<p>Every editor earns its place against the incoming file. The <code>date</code> editor turns <code>03/04/2026</code> and <code>17.04.2026</code> into <code>2026-04-03</code> and <code>2026-04-17</code>, which is the shape a Postgres <code>date</code> column accepts as it stands. The <code>number</code> editor strips the dollar sign, the thousands comma and accounting parentheses, so <code>$1,299.00</code> lands as <code>1299.00</code>. The <code>USD 149.00</code> in the third row stays raw on purpose, because stripping letters would corrupt a code like <code>abc123</code>. The <code>number</code> validator flags that cell for the person to fix. The <code>select</code> editor with <code>enableCustomValue</code> off holds the category column to three options and sends everything else to the value matching step.</p>
<p><code>required</code> sits on every column the table declares <code>not null</code>. The other built-in validators all pass an empty cell, so a blank category or a blank launch date would leave the grid clean, reach the route, and take the whole chunk down on a not-null violation. <code>price</code> is nullable in the table, so it stays open and arrives as <code>null</code>.</p>
<p>The <code>synonyms</code> prop teaches matching the words your customers already use, and the mount ties the whole thing together.</p>
<pre><code class="language-tsx">&#x3C;DataEditor&#x3C;Product>
  apiKey="your-license-key"
  variant="uploader"
  open={open}
  onClose={closeImporter}
  columns={columns}
  primaryKey="itemCode"
  synonyms={{
    columns: { itemCode: ["item code", "sku", "article no"] },
    values: { Laptops: ["notebooks", "notebook", "laptop pc"] },
  }}
  onComplete={onComplete}
/></code></pre>
<p>Column synonyms map <code>Item Code</code> onto <code>itemCode</code>, and they cover the <code>SKU</code> and <code>Article No</code> the next supplier sends. Value synonyms map <code>notebooks</code> onto <code>Laptops</code>, a pair no score reaches on its own, since the two words share no letters in the same order. <code>MONITORS</code> and <code>PC accessories</code> land without help, because matching lowercases the value and drops spaces before it scores. Whatever the person fixes by hand comes back on the result as <code>learnedSynonyms</code>, ready to store and feed back next time. <a href="https://updog.tech/blog/remember-csv-import-mappings/">How to remember CSV import mappings between uploads</a> covers that round trip. For the install and the modal wiring underneath this snippet, see <a href="https://updog.tech/blog/how-to-import-csv-into-react-app/">how to import a CSV file into a React app</a>.</p>
<p>Every snippet here is React. The web component build carries the same props, so a Vue, Angular or Svelte app writes the same schema and the same handler.</p>
<h2 id="step-3-point-the-primary-key-at-the-same-identity">Step 3. Point the primary key at the same identity</h2>
<p><code>primaryKey</code> decides how an imported row meets a row already in the grid. Set it to <code>itemCode</code> and a matching row merges, so one item code stays one row. Values are compared after surrounding whitespace is trimmed, so the space trailing the first item code costs nothing. A row with an empty key merges with nothing and arrives as new.</p>
<p>That prop and the <code>onConflict</code> target have to name the same identity. <code>primaryKey</code> sets the <code>isNew</code> flag your handler reads, <code>onConflict</code> decides whether Postgres writes a row or updates one. Point them at different columns and the flags on the result stop describing what the table did.</p>
<h2 id="step-4-post-the-result-in-chunks">Step 4. Post the result in chunks</h2>
<p>On submit, Updog Importer hands your handler every row grouped by source, each one carrying <code>isNew</code>, <code>isChanged</code>, <code>isDeleted</code> and <code>isValid</code>. Rows nobody touched stay out. One person can drop three files in a single import, and each file arrives as its own source entry, so the handler flattens before it slices.</p>
<pre><code class="language-tsx">import type { DataEditorResult } from "@updog/data-editor";

const CHUNK_SIZE = 500;

const onComplete = useCallback(async (result: DataEditorResult&#x3C;Product>) => {
  const rows = result.sources
    .flatMap((source) => source.rows)
    .filter((entry) => entry.isValid &#x26;&#x26; !entry.isDeleted)
    .map((entry) => entry.row);

  for (let start = 0; start &#x3C; rows.length; start += CHUNK_SIZE) {
    const response = await fetch("/api/products/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ rows: rows.slice(start, start + CHUNK_SIZE) }),
    });

    if (!response.ok) {
      const failure = await response.json();
      throw new Error(failure.message);
    }
  }
}, []);</code></pre>
<p>Neither Supabase nor Vercel publishes a batch size, so 500 is a conservative choice of ours, sitting inside two ceilings that are published. The first ceiling is the body your own route accepts. A Vercel function caps the request body at 4.5 MB and answers a larger one with <code>413: FUNCTION_PAYLOAD_TOO_LARGE</code>. One product row of these five fields serializes to 122 bytes.</p>
<pre><code class="language-json">{"itemCode":"0041782","productName":"ThinkPad X13 Gen 4","category":"Laptops","price":"1299.00","launchDate":"2026-04-03"}</code></pre>
<p>Five hundred of those reach 60 KB, and 4.5 MB holds around 38,000. Run that division against your own widest row before you raise the number. A table of forty text columns changes the answer.</p>
<p>The second ceiling is time. Supabase publishes a statement timeout per database role, 3 seconds for <code>anon</code>, 8 seconds for <code>authenticated</code>, and none for <code>service_role</code>, which falls back to the authenticator role's 8 seconds. One <code>upsert</code> of 500 rows is one statement, so the whole chunk lives or dies inside that budget. Raise the ceiling when your rows are wide and your writes are slow.</p>
<pre><code class="language-sql">alter role authenticator set statement_timeout = '30s';
notify pgrst, 'reload config';</code></pre>
<p>The <code>notify</code> line is what makes PostgREST pick the change up, and it is documented alongside the timeouts. Counting bytes against the body cap is arithmetic you can do at your desk. The timeout moves with row width, indexes, triggers and whatever else the database is doing, so that one gets measured against your own table.</p>
<p><strong>Throw when a chunk fails.</strong> Updog awaits your handler and clears the editor the moment it resolves. A handler that catches its own error and returns reads as success, and the grid empties with the rows unsaved. The confirm dialog holds the whole round trip behind a spinner, which is the other reason chunks stay small. Throwing keeps every row, every mapping and every fix on the screen, so the person presses submit again on data they can still see.</p>
<p>Anything on the result you want to keep gets copied inside the handler. After the promise resolves the editor drops its rows, its sources, its history and its learned synonyms.</p>
<p>That <code>isValid</code> filter carries a cost worth naming. A failed validator marks the cell and lets the person submit anyway, so the rows it flagged reach your handler and the filter drops them on the floor. Set <code>blockSubmitOnError</code> on the editor and submit stays disabled until the grid is clean. Keeping the filter open works too, once you split the rows by <code>isValid</code> and post the failures to a table your support team can read.</p>
<h2 id="step-5-write-the-rows-from-your-own-route">Step 5. Write the rows from your own route</h2>
<p>The route is where the secret lives and where the browser stops.</p>
<pre><code class="language-ts">import { createClient } from "@supabase/supabase-js";
import { NextResponse } from "next/server";

const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_SECRET_KEY!,
  { auth: { persistSession: false } },
);

export async function POST(request: Request) {
  const session = await getVerifiedSession();
  if (!session) {
    return NextResponse.json({ message: "Not signed in" }, { status: 401 });
  }

  const { rows } = await request.json();
  const records = rows.map((row) => ({
    tenant_id: session.tenantId,
    item_code: row.itemCode,
    product_name: row.productName,
    category: row.category,
    price: row.price === "" ? null : Number(row.price),
    launch_date: row.launchDate,
    updated_at: new Date().toISOString(),
  }));

  const { error } = await supabase
    .from("products")
    .upsert(records, { onConflict: "tenant_id,item_code" });

  if (error) {
    return NextResponse.json(
      { message: error.message, hint: error.hint, code: error.code },
      { status: 400 },
    );
  }

  return NextResponse.json({ written: records.length });
}</code></pre>
<p><code>getVerifiedSession()</code> stands in for your own server-side authentication check. When Supabase Auth owns the session, reach for <code>getClaims()</code> or <code>getUser()</code>, because Supabase warns that <code>getSession()</code> reads credentials out of storage and gives no guarantee that the token was revalidated.</p>
<p>The secret key holds full access to your project's data through the built-in <code>service_role</code>, which carries the <code>BYPASSRLS</code> attribute. Supabase says "Never use in a browser, even on <code>localhost</code>", and a browser that sends one gets HTTP 401 back, because Supabase matches on the <code>User-Agent</code> header. In August 2026 both namings are live, <code>sb_secret_...</code> on the new keys and <code>service_role</code> on the legacy ones.</p>
<p>Bypassing row level security moves the decision to your code, so <code>tenant_id</code> comes off the session and never off the request body. The rest of the mapping is small. <code>price</code> arrives as the string <code>1299.00</code>, and converting it before it enters the record keeps the payload matching a <code>numeric</code> column. <code>launch_date</code> arrives as <code>2026-04-03</code> and needs nothing.</p>
<p><code>upsert()</code> takes the whole array in one call and returns no rows by default, so leaving <code>.select()</code> off keeps the response small. <code>onConflict</code> goes in as the comma-separated list of unique columns PostgREST expects.</p>
<p>An app whose users already hold Supabase sessions can keep RLS in the write path. Build the client inside the route from the publishable key and the person's own access token, then give the <code>authenticated</code> role the table privileges and the policies this write needs. An upsert takes the insert path or the update path, so it needs an insert policy with a <code>with check</code> expression and an update policy with both <code>using</code> and <code>with check</code>. Supabase adds that an update also needs a matching select policy. All three tie <code>tenant_id</code> to a claim in the token, and no secret sits in the chain at all.</p>
<h2 id="step-6-send-the-failure-back-up-the-chain">Step 6. Send the failure back up the chain</h2>
<p>Supabase Data API queries return a <code>{ data, error }</code> pair by default. Chain <code>.throwOnError()</code> and the promise rejects instead. On the default an unchecked <code>error</code> reads exactly like a successful write.</p>
<p>The error object carries <code>hint</code>, <code>code</code>, <code>details</code> and <code>message</code>. A write that breaks a unique constraint your conflict target does not cover returns <code>23505</code>, which PostgREST maps to HTTP 409 and describes as a uniqueness violation. A malformed body returns <code>PGRST102</code>. Pass <code>message</code> back, and pass <code>hint</code> along whenever Postgres supplies one, because that is where the actionable half lands.</p>
<p>Chunks that already landed stay landed. <code>upsert</code> against the same conflict target writes the same values a second time, so a retry after a failed chunk costs a rewrite of what already exists.</p>
<h2 id="what-updog-leaves-to-you">What Updog leaves to you</h2>
<p>Updog Importer integrates with nobody. There is no Supabase connector, no destination list, no webhook and no server of ours. <code>onComplete</code> hands your code an object, and the route in the middle is work you do.</p>
<p>Supabase already ships its own import for the other case. The dashboard takes a CSV up to 100MB into a new or an existing table, <code>pgloader</code> handles a database migration, and <code>psql</code> loads a local file with <code>\COPY</code> over a direct connection. Its documentation adds that bulk imports through the API are worth avoiding. When the file is yours, those are the shorter paths. Everything above exists for the file that belongs to somebody else, arriving through a browser, in a session your app issued. <a href="https://updog.tech/blog/client-side-vs-server-side-importer/">Client-side and server-side CSV import</a> sets out where each model earns its keep.</p>
<h2 id="what-you-built">What you built</h2>
<p>You wrote a table with a conflict target, a schema with five columns, a handler that chunks, and a route that holds one secret. The file stays on the machine that opened it. The rows travel from your own front end to your own route, and from there into Supabase, and the only party you added to the chain is yourself. Point the same setup at a <a href="https://updog.tech/nextjs-csv-importer/">Next.js CSV importer</a> page or a plain React modal and the middle stays the same.</p>
<p>The person who sent that file will send another one later. That time the mappings are already stored, the dates already parse, and they close the tab on a table that matches yours.</p>]]></content:encoded></item>
<item><title>Make Updog's CSV Importer Match Your Product</title><link>https://updog.tech/blog/style-updog-to-match-your-product/</link><guid isPermaLink="true">https://updog.tech/blog/style-updog-to-match-your-product/</guid><pubDate>Mon, 15 Jun 2026 00:00:00 GMT</pubDate><description>Restyle the importer and spreadsheet editor with plain CSS variables, so column mapping, validation states and the grid match your design system.</description><content:encoded><![CDATA[<p>I built Updog knowing it would live inside someone else's app, a real product that already has its own colors, its own font, its own corners and habits. An embedded importer has to disappear into that design and leave no seam. The person bringing in their data should never notice where your app ends and the editor begins.</p>
<p>That made Updog white-label from the start. There is no branding to strip, and the styling is not locked behind a theme object you pass in or an importer sealed in an iframe your CSS never reaches. Those approaches share one ceiling: the day your design needs something the fixed list does not cover, you stop and wait for it. So the whole look rides on CSS variables and BEM classes, which makes Updog a customizable CSV importer in the plainest sense. The browser already understands both, every element carries them, and you override them the same way you style your own markup. There is no private API. It is plain CSS, and it is available on every plan.</p>
<h2 id="everything-is-a-css-variable">Everything is a CSS variable</h2>
<p>The variables come in layers. At the bottom is a small set of base colors. From those, a wide range of shades is generated. On top sit named tokens, surface, border, and content, that point at the shades. A fourth set, the grid variables, carries those tokens into the spreadsheet, which is drawn on a canvas. You can reach in at any layer, and where you reach in decides how much you control and how much you let the editor decide for you.</p>
<p>This guide covers the full surface in the order I would work through it: base colors, semantic tokens, typography, the spreadsheet grid, and dark mode. The base colors alone give a rough fit. The semantic tokens give an exact match. The reference tables for every token live in the <a href="https://docs.updog.tech/styling/">styling docs</a>; here I explain how the layers fit together.</p>
<h2 id="map-your-design-system-onto-updog">Map your design system onto Updog</h2>
<p>A precise match is a mapping job. Every color and shape in your design system has a home in Updog, and the work is connecting the two. Go in this order, because each step builds on the one before it. Start with your neutrals, since they cover the most pixels. Your page and panel backgrounds map to the surface tokens, from <code>layer0</code> for the base canvas up to <code>layer4</code> for the most raised panel. Your dividers and outlines map to the two border tokens. Your text colors map to the content tokens, with <code>primary</code> as the base color the editor inherits everywhere, so set it first. Set these and most of the foreign feeling is gone.</p>
<p>Then the brand. Your primary action color becomes <code>--updog-brand</code>, and a full range of shades regenerates from it for hovers, links, the selected cell, and the active header. Your four status colors, for errors, success, warnings, and information, map to red, green, yellow, and blue. After that comes your font family. Last, carry the same decisions into the grid variables so the spreadsheet matches the rest. The sections below give the exact variable for each.</p>
<h2 id="the-base-colors">The base colors</h2>
<p>Six colors sit under everything. Set these and the editor builds every shade it needs from them. This is the smallest change that still touches the whole product.</p>
<pre><code class="language-css">:root {
  --updog-brand: #2f6df6;
  --updog-neutral: #6b7280;
  --updog-red: #e5484d;
  --updog-green: #30a46c;
  --updog-yellow: #ffb224;
  --updog-blue: #0091ff;
}</code></pre>
<p><code>--updog-brand</code> drives the primary actions and the highlights. <code>--updog-neutral</code> drives the grays, so the surfaces, the borders, and the muted text all shift with it. The other four are the status colors that tell the person what is happening with their data.</p>
<p>If your surfaces carry a tint instead of a flat white, set one more variable: <code>--updog-ramp-light</code>. The base surface and every light shade lean toward it, so pointing it at a warm off-white warms the whole light theme at once, the surfaces, the subtle fills, and the selected cell together. It is the lever dark mode uses to turn the palette over, and in a light theme you nudge it the same way without inverting anything. For a theme that reads as one tint, these three, <code>--updog-brand</code>, <code>--updog-neutral</code>, and <code>--updog-ramp-light</code>, often do the whole job, and the semantic layer below is optional. Set the named tokens when your surfaces and borders need different hues than a single tint can give.</p>
<h2 id="the-semantic-layer-for-an-exact-match">The semantic layer, for an exact match</h2>
<p>A real design system is rarely a clean tint of one gray. Your surfaces might be cool while your borders are warm, or your text softer than a generated shade would land. When you want the editor to match exactly rather than approximately, set the named tokens yourself instead of leaving them to the neutral.</p>
<pre><code class="language-css">:root {
  /* Surfaces */
  --updog-surface-layer0: #ffffff;
  --updog-surface-layer1: #f7f7f8;
  --updog-surface-layer2: #ededf0;
  --updog-surface-layer3: #e0e0e4;
  --updog-surface-layer4: #cfcfd6;

  /* Borders */
  --updog-border-primary: #e3e3e7;
  --updog-border-secondary: #efeff1;

  /* Content */
  --updog-content-primary: #18181b;
  --updog-content-secondary: #5c5c66;
  --updog-content-tertiary: #8e8e96;
  --updog-content-placeholder: #a8a8b0;
  --updog-content-inverse: #ffffff;

  /* Disabled state */
  --updog-disabled-background: #f1f1f3;
  --updog-disabled-border: #e3e3e7;
  --updog-disabled-content: #b4b4bc;
}</code></pre>
<p>This is the layer that decides whether the editor reads as part of your app or merely near it. The surfaces are your backgrounds, from the flat base to the most raised panel. There are two borders: <code>primary</code> is the line you see almost everywhere, and <code>secondary</code> is the lighter line on dropdowns and a few inner edges. The content tokens are your text, from headings to placeholder hints. The brand and status tokens follow your base colors from the block above, so you do not repeat them here unless you want a specific shade.</p>
<p>The generated shades have names too, like <code>--updog-gray-200</code> or <code>--updog-brand-600</code>, and you can override a single one if a step lands off. Most of the time you set the named tokens instead, which says what you mean rather than patching a number in a ramp. Dark mode is the one case where you work at the shade level, covered below.</p>
<h2 id="typography">Typography</h2>
<p>The font is one variable, and it reaches everywhere. Set <code>--updog-font-family</code> and it applies across the React parts and inside the spreadsheet, where the cell text is drawn on a canvas. The grid reads the same value, so a million rows render in your font with no second setting to keep in sync.</p>
<pre><code class="language-css">:root {
  --updog-font-family: "Inter", system-ui, sans-serif;
}

/* Only if your type scale differs from the defaults */
.updog-text--sm { font-size: 0.875rem; line-height: 1.5; }
.updog-text--md { font-size: 1rem; line-height: 1.5; }
.updog-text--lg { font-size: 1.25rem; line-height: 1.5; }
.updog-button-text--md { font-weight: 500; }</code></pre>
<p>The sizes are defined in <code>rem</code>, so they scale with the root font size of the page the editor sits in. If your app runs at a larger base size, the editor grows with it, and often you do not touch the sizes at all. When your type scale truly differs, the size and weight classes are there to override, as shown above.</p>
<h2 id="the-spreadsheet-editor">The spreadsheet editor</h2>
<p>The spreadsheet is the part people expect to be hard, because it is drawn on a canvas rather than page elements, and a canvas cannot read CSS on its own. So Updog reads your variables for it. When the editor mounts, it picks up every grid color from the page and paints with it, and it repaints when your theme changes. You write CSS, and the canvas obeys it like everything else.</p>
<p>The grid variables default to the same brand, surface, and status tokens you already set, so once the layers above are in place the spreadsheet editor is mostly matched. The block below is the full surface, for when you want to control the cell states directly: the edited cell, the invalid cell, the selection, the headers, and the colored bar that marks new, edited, error, and empty rows down the side of the grid.</p>
<pre><code class="language-css">:root {
  /* Cells */
  --updog-grid-cell-bg-idle: #ffffff;
  --updog-grid-cell-bg-hover: #f7f7f8;
  --updog-grid-cell-bg-dirty: #fff7e6;
  --updog-grid-cell-bg-invalid: #fff0f0;
  --updog-grid-cell-border-idle: #e3e3e7;
  --updog-grid-cell-content-idle: #18181b;
  --updog-grid-cell-content-cut: #5c5c66;
  --updog-grid-cell-placeholder-idle: #a8a8b0;

  /* Selection and focus */
  --updog-grid-selection-bg: #eef4ff;
  --updog-grid-selection-border: #2f6df6;
  --updog-grid-focus-ring-border: #2f6df6;

  /* Column headers */
  --updog-grid-header-bg-idle: #f7f7f8;
  --updog-grid-header-bg-active: #eef4ff;
  --updog-grid-header-bg-selected: #dbe7ff;
  --updog-grid-header-content-idle: #18181b;
  --updog-grid-header-icon-idle: #5c5c66;

  /* Row markers and the row status bar */
  --updog-grid-marker-bg-idle: #f7f7f8;
  --updog-grid-marker-bg-active: #eef4ff;
  --updog-grid-marker-content-idle: #5c5c66;
  --updog-grid-status-bar-bg-new: #b7e0c6;
  --updog-grid-status-bar-bg-edited: #ffe1ad;
  --updog-grid-status-bar-bg-error: #ffc9c9;
  --updog-grid-status-bar-bg-empty: #d4d4d8;

  /* Clipboard, fill handle, find matches, loading skeleton */
  --updog-grid-clipboard-border-copy: #2f6df6;
  --updog-grid-fill-handle-bg: #2f6df6;
  --updog-grid-fill-handle-border: #ffffff;
  --updog-grid-match-bg-default: #eef4ff;
  --updog-grid-match-bg-current: #dbe7ff;
  --updog-grid-skeleton-bg: #ededf0;
  --updog-grid-skeleton-highlight: #f7f7f8;
  --updog-grid-validating-stripe: #f5f9ff;
}</code></pre>
<h2 id="shadows-and-scrollbars">Shadows and scrollbars</h2>
<p>Two smaller surfaces finish the match. The elevation tokens are the shadows under popovers and modals, and the scrollbar tokens style the thin scrollbars inside the editor. Set these to your own and even the edges of the editor belong to your product.</p>
<pre><code class="language-css">:root {
  --elevation-1: 0 1px 2px rgba(0, 0, 0, 0.06), 0 4px 12px rgba(0, 0, 0, 0.08);
  --elevation-2: 0 2px 4px rgba(0, 0, 0, 0.08), 0 8px 24px rgba(0, 0, 0, 0.16);

  --updog-scrollbar-width: 0.375rem;
  --updog-scrollbar-thumb: #cfcfd6;
  --updog-scrollbar-thumb-hover: #b4b4bc;
}</code></pre>
<h2 id="when-a-variable-is-not-enough-target-the-class">When a variable is not enough, target the class</h2>
<p>The variables cover color and type, which is most of what a match needs. When you want something they do not reach, like the corner radius of your buttons, the exact padding of one toolbar, or a single button that should be a pill, every element in Updog carries a stable BEM class you can style directly. The components from the kit use a plain block name, such as <code>.updog-button</code> and <code>.updog-input</code>, with <code>__element</code> parts and <code>--modifier</code> states. The editor's own pieces use a prefixed block, such as <code>.updog__data-editor-footer</code> and <code>.updog__aside-pane</code>. Inspect the element to read its exact class.</p>
<pre><code class="language-css">/* Reach for a class only when no variable covers what you need. */
.updog-button--filled.updog-button--primary {
  border-radius: 9999px;
}

.updog__data-editor-footer {
  padding-inline: 1.5rem;
}</code></pre>
<p>Treat this as the escape hatch, not the main road. The variables are the contract Updog keeps stable across versions. The internal classes can change as the editor grows, so a rule pinned to one is more likely to need a touch later. Override the token when a token exists, and target the class when one does not.</p>
<h2 id="put-the-variables-on-the-root">Put the variables on the root</h2>
<p>Define your variables on <code>:root</code>, not on a wrapper around the editor. Scoping them to your own class works for the editor itself, then breaks in a way that is hard to trace, because of the parts that float. Modals, dropdowns, context menus, and tooltips do not render inside the editor's box. They open in a portal at the end of the page, as siblings of your app rather than children of the editor. A selector scoped to your wrapper never reaches them, so the grid would carry your theme while the sheet picker and the right-click menu fell back to the defaults. Put the variables on <code>:root</code> and they reach the editor, the floating parts, and the canvas all at once.</p>
<p>This is also why the look is identical whether you embed Updog as a React component or as the <code>&#x3C;updog-editor></code> web component. Both render into the normal page rather than hiding behind a shadow root, so the same variables on <code>:root</code> style both the same way. You learn one method and it carries across.</p>
<h2 id="dark-mode-is-yours-to-build">Dark mode is yours to build</h2>
<p>Updog does not ship a dark theme today. What it gives you is the means to build one, by setting variables again under your own dark selector. Flip that class on the page and the editor switches with it, the canvas grid included, because it watches the page for the change and repaints.</p>
<p>Work with the ramps, not the semantic tokens. First, point <code>--updog-ramp-light</code> at your dark base, so the base surface and every low shade you do not tune lean toward it and nothing strays light. Second, set the gray ramp. The surfaces, borders, content, disabled tokens, and the neutral tag all derive from gray shades, so tuning the ramp moves them together. The high grays carry text and must be light; the low grays you tune by hand for surface depth, since a flat mix toward one dark value leaves the panels too close to tell apart. Third, invert the colored ramps, pointing each pale tint at its dark counterpart so the button hovers, tag and tooltip backgrounds, selection, edited and invalid cells, matches, and skeletons all flip together.</p>
<pre><code class="language-css">.dark {
  /* Dark base: surface-layer0 and every untuned low shade lean toward this.
     Leave ramp-dark black so the -950 shades stay dark. */
  --updog-ramp-light: #0f1115;

  /* Gray ramp. Surfaces, borders, content, disabled, and the neutral tag all
     derive from these. The high grays carry text and must be light; the low
     grays are tuned for surface depth. */
  --updog-gray-50: #161a20;
  --updog-gray-100: #1e232b;
  --updog-gray-200: #262c36;
  --updog-gray-300: #2f3641;
  --updog-gray-400: #5c6370;
  --updog-gray-450: #5c6370;
  --updog-gray-500: #6b7280;
  --updog-gray-600: #a8aeb8;
  --updog-gray-950: #e6e8eb;

  /* Invert the colored ramps: subtle fills go dark, accents stay bright */
  --updog-brand-50: var(--updog-brand-950);
  --updog-brand-100: var(--updog-brand-900);
  --updog-red-50: var(--updog-red-950);
  --updog-yellow-50: var(--updog-yellow-950);
  --updog-green-50: var(--updog-green-950);
  --updog-blue-50: var(--updog-blue-950);

  /* Keep the row status bars saturated so the strip stays visible */
  --updog-grid-status-bar-bg-error: var(--updog-red-700);
}</code></pre>
<p>You cannot get dark mode by swapping a base color. The generated shades always run light to dark in the same direction, so a base swap only tints. Inverting the ramps is what turns the polarity around. And you do not rewrite every surface and text color by hand: those derive from the gray ramp, so you tune the ramp once and they follow.</p>
<h2 id="before-you-ship">Before you ship</h2>
<ul>
<li>Put your overrides on <code>:root</code>. Modals, dropdowns, and tooltips render in a portal at the end of the page, so a selector scoped to a wrapper around the editor will miss them.</li>
<li>Load your CSS after the Updog stylesheet. Both sit at the same specificity, so the file that comes later wins, and import order is what decides it.</li>
<li>Inspect before you guess. Read the variable on the element you want to change and override that token. The names map to what you see.</li>
<li>For dark mode, invert the colored ramps instead of swapping a base color, tune the gray ramp rather than each surface, and keep <code>--updog-content-inverse</code> light so the text on brand-colored buttons does not flip.</li>
</ul>
<h2 id="make-it-feel-like-yours">Make it feel like yours</h2>
<p>There is no Updog logo, no badge, and no powered-by line anywhere in the editor. That is on purpose. A white-label importer should leave your users looking at your product, not ours. Updog was always meant to blend into the data import flow you already built, so customer data onboarding feels like part of your app instead of a separate tool. The upload, the column mapping, and the spreadsheet all look like yours, and this guide is how you make that fit exact.</p>]]></content:encoded></item>
<item><title>Common CSV Import Errors and How to Prevent Them</title><link>https://updog.tech/blog/common-csv-import-errors/</link><guid isPermaLink="true">https://updog.tech/blog/common-csv-import-errors/</guid><pubDate>Fri, 12 Jun 2026 00:00:00 GMT</pubDate><description>Missing headers, invalid values, locale formats, encoding damage and silently shifted rows, and what to check before users submit data.</description><content:encoded><![CDATA[<p>Earlier this month I sat down with every CSV import problem I could find: exports from German Excel, spreadsheets with a title across the top, rows with one cell too many, headers that appear twice, a required cell that held a single space. The plan was an audit. Build a file for each problem, run it through Updog, and confirm each one comes out handled.</p>
<p>The pattern that stayed with me is that the worst CSV import errors never show an error. The file imports, the grid looks clean, and one value is wrong in a way nobody notices for weeks. A crash gets reported the same day. A silent wrong value gets trusted.</p>
<p>CSV import errors are rarely parsing errors. In a SaaS product, the person uploading a file needs to match it to your schema, fix the invalid values, review the result, and submit it without getting stuck, and every step has its own ways to fail. Here are the issues from that audit, in the order a real file runs into them, and what an importer can do about each one.</p>
<h2 id="encoding-issues-and-special-characters">Encoding issues and special characters</h2>
<p>The first thing an importer touches is bytes, and the bytes do not announce their encoding. A file saved from an older Windows tool is often Windows-1252. Exports from Japanese or Chinese systems arrive as Shift-JIS or GB18030. Read any of them as UTF-8 and the names break: José turns into Jos� or JosÃ©, depending on which side guessed wrong, and the person cannot understand why a file that looks fine in Excel looks broken in your app.</p>
<p>There is a quieter version of the same problem. Many files begin with a byte order mark, a few invisible bytes that declare the encoding. Leave it in place and it glues itself to the first header, so the column that looks like <code>id</code> on screen is an invisible character followed by <code>id</code> in memory, and it fails to match your <code>id</code> field every time.</p>
<p>The fix is boring and absolute: detect the encoding from the bytes, strip the byte order mark, and convert everything to UTF-8 before a single cell is parsed. Updog does this on every file, because no person should be asked what encoding their export uses.</p>
<h2 id="the-delimiter-is-not-always-a-comma">The delimiter is not always a comma</h2>
<p>Comma-separated values are separated by semicolons surprisingly often. In much of Europe the comma is the decimal mark, so Excel there writes CSV files with semicolons between values. Other tools export tabs or pipes. An importer hard-coded to commas reads a semicolon file as one giant column, and everything downstream fails at once.</p>
<p>Detection is the easy half: count candidate delimiters across the first lines, ignore anything inside quotes, and pick the one that appears consistently. The subtle half is a hint line that some tools write at the top of a file so that Excel will open it with the right delimiter:</p>
<pre><code class="language-plaintext">sep=;
id;name;age
1;Alice;30</code></pre>
<p>The directive is not part of the CSV standard. Excel honors it when opening a file, but parsing libraries generally do not: PapaParse, for example, has <a href="https://github.com/mholt/PapaParse/issues/951">an open issue about it</a>, and the line arrives in your rows as if it were data. On a file without a header row the damage is sharp: the literal text <code>sep=</code> becomes a column header and every value shifts one cell over. Updog drops a first line shaped exactly like <code>sep=</code> plus one character before anything else sees the rows.</p>
<h2 id="missing-or-wrong-column-headers">Missing or wrong column headers</h2>
<p>We picture a CSV as a grid with the column names on the first line. Real files open with a report title, a date, a blank row or two, and the real header three lines down. An importer that trusts row one turns the title into the header, and nothing maps after that.</p>
<p>Finding the header takes a heuristic: score the first rows on signals like all-text cells, uniqueness, and length, and pick the best. The trap inside that heuristic is a title in a single cell. <code>Sales Report</code> is short, unique, and all text, so it scores like a header on every content signal, and an importer that trusts the score takes the title and shifts everything under it. The signal that matters is structural: a real header spans the width of the table, and a title does not. Updog checks that shape before accepting any row, so a one-cell title never wins.</p>
<p>Two more header problems are worth designing for. The same column arrives under different names in every file, <code>First Name</code> in one, <code>fname</code> in the next, <code>Contact First</code> in a third, which is why column mapping with fuzzy matching is a standard step in any serious CSV import flow. And sometimes a header appears twice. A file with two <code>id</code> columns is legal, but an importer that identifies columns by header name lets the second <code>id</code> overwrite the first, and a whole column vanishes. Updog renames repeats to <code>id</code> and <code>id (2)</code>, so both columns survive and the person decides what each one means during mapping. A silent loss becomes a visible question.</p>
<h2 id="rows-that-do-not-line-up-with-the-headers">Rows that do not line up with the headers</h2>
<p>This is the issue I would put at the top of any list, because its worst case is invisible. A ragged row is a data row whose cell count does not match the header. Too many cells usually means an unescaped delimiter inside a value, a last name entered as <code>Van Der, Berg</code> or an address with a comma in it. Too few usually means a value was omitted without an empty placeholder.</p>
<p>The naive importer pads short rows and truncates long ones, silently. Hidden inside that behavior is the shifted row: one missing cell early in the line slides every later value one column over. The email lands in the last name field, the age lands in the email field. Nothing crashes, the row imports, and the data sits under the wrong headers until someone notices.</p>
<p>Here is the uncomfortable part: from the row alone, a shift cannot be repaired. Given four values and five headers, no amount of counting tells you which column is the missing one. Every guess produces a different, plausible row. Import tools deal with this honestly by flagging the mismatched row and asking the person to fix it, and that is the right floor. But one signal sits unused: your schema. Updog tries the possible alignments of a ragged row and keeps only the ones that pass your validators. When exactly one survives, the structure has been recovered and the row imports correctly. When several survive, the row imports with the uncertain cells flagged, so the person answers a small, specific question instead of retyping a line. The strictness of your schema decides how often that works: an email validator pins the email column in place, while a schema of free-text fields gives the aligner little to prove with. Even then, turning an invisible shift into a visible flag is most of the value.</p>
<h2 id="date-and-number-formats-follow-the-locale">Date and number formats follow the locale</h2>
<p><code>03/04/2026</code> is March 4 in New York and April 3 in London, and the file does not say which. Guess per value and you corrupt every date that happens to read both ways. The reliable approach decides per file: one value with a day above twelve settles the order for the whole file, and every date is stored in one canonical shape, ISO <code>2026-04-03</code>, so nothing downstream has to guess again.</p>
<p>Numbers carry the same ambiguity. <code>1.234,56</code> and <code>1,234.56</code> are the same amount written in two locales, so the decimal format also has to be decided once per file, and decided by looking only at the columns mapped to number fields, because dots in text and ID columns will pollute the vote. Real files also dress numbers up: currency symbols, percent signs, accounting parentheses for negatives. <code>$1,234.56</code> in a price column should land as <code>1234.56</code>. An ambiguous decoration like the letter code in <code>100 kr</code> should stay raw and get flagged, because removing letters is guessing.</p>
<p>The rule that survived our audit: normalization belongs to the column type. Stripping <code>€</code> from a value headed into a number field is cleanup. Rewriting <code>1,234</code> inside a free-text column is corruption. The same string is content in one column and costume in another, and only the declared type can tell the importer which.</p>
<h2 id="excel-changed-the-data-before-the-file-existed">Excel changed the data before the file existed</h2>
<p>Some of the most reported CSV import issues happen before the upload. Excel converts what it recognizes at the moment of entry: a product code like <code>3/4</code> becomes a date, a nineteen-digit card number has every digit past the fifteenth turned into a zero, and the zip code <code>00123</code> is usually not text at all but the number <code>123</code> wearing a five-digit display format. Inside the workbook the stored value is <code>123</code>. The zeros were never saved.</p>
<p>An importer has to be honest about this: it cannot recover information the spreadsheet never stored, and inventing the digits back would only manufacture confidence. What it can do is refuse to add damage of its own. Text cells must round-trip byte for byte, so an ID typed as text keeps its zeros. Date cells in an Excel file arrive as date objects, and converting them carelessly produces strings like <code>Thu Jan 15 2026 00:00:00 GMT+0000</code>, where the calendar day can even change with the timezone of the machine; the safe rendering is the plain ISO date, computed in UTC, so January 15 stays January 15 everywhere. And the one piece of guidance worth passing to your users costs nothing: identifiers belong in text cells.</p>
<h2 id="values-that-pass-validation-and-should-not">Values that pass validation and should not</h2>
<p>Required fields missing, invalid email addresses, values outside an allowed set, duplicate rows: this is the visible layer of CSV import validation, and any import tool should check all of it before the data reaches your system. Duplicates deserve both halves of the check: a uniqueness rule inside the file, and a merge key on import, so a row that matches an existing record updates it instead of landing twice. The audit taught me to also distrust the green results.</p>
<p>The sneakiest file in the test set had a required cell holding a single space. A required check that compares against the empty string passes it, and the trap runs deeper than it looks, because a typical cleanup pass rewrites non-breaking spaces into regular spaces and manufactures exactly the value that fools the check. Updog trims whitespace at the point where data enters, so a visually empty cell is stored as a true empty string and the required rule fails honestly. A green check over an empty cell is the same failure as the shifted row: validation telling you everything is fine when it is not.</p>
<h2 id="large-csv-files-are-an-architecture-problem">Large CSV files are an architecture problem</h2>
<p>A large CSV file upload fails differently: the tab freezes, memory runs out, or an arbitrary row limit sends the person away to split their file into pieces. None of those are parsing problems either. They come from reading the whole file into memory at once and rendering every row into the page.</p>
<p>The architecture that holds up is streaming the parse in chunks, moving heavy work like filtering into a worker, and drawing the grid on canvas so the page only pays for the rows on screen. We wrote about that approach in <a href="https://updog.tech/blog/browser-first-csv-import/">how Updog handles a million rows in the browser</a>. The honest part of that number is that it is a ceiling, not a promise of infinity. The point is that a hundred-thousand-row customer file should feel ordinary.</p>
<h2 id="the-error-experience-decides-whether-the-import-finishes">The error experience decides whether the import finishes</h2>
<p>Every issue above ends the same way: some cells need a person's attention. What happens next separates an import that finishes from one that gets abandoned. A message like "import failed on line 8,442" sends the person back to Excel to fix one cell and upload again, and the next attempt fails on line 9,107.</p>
<p>The shape that works is a spreadsheet-like editor inside the CSV import flow itself: every failing cell highlighted, filters that narrow a big file down to the rows that need work, and edits applied in place with validation rerunning as the person types. Updog flags problems instead of blocking on them, because someone fixing row twelve should not be locked out of row thirteen. We wrote a longer piece on why <a href="https://updog.tech/blog/csv-import-is-more-than-parsing/">CSV import is more than parsing a file</a>, and the editor is the heart of that argument.</p>
<h2 id="a-checklist-before-users-submit-data">A checklist before users submit data</h2>
<p>If you are building or buying a CSV importer, this is the list I would test it against, one broken file per line:</p>
<ul>
<li>Detect the encoding from the bytes and strip the byte order mark before parsing.</li>
<li>Detect the delimiter, and drop a first line that reads <code>sep=</code> plus one character.</li>
<li>Find the header row instead of assuming row one, and rename duplicate headers instead of losing a column.</li>
<li>Compare every row's cell count to the header, and never realign a mismatch silently.</li>
<li>Settle date order and decimal format once per file, from the file, and store canonical values.</li>
<li>Normalize numbers and dates only in columns typed for them, and keep text byte for byte.</li>
<li>Trim whitespace at the boundary, so a required field cannot be satisfied by a space.</li>
<li>Validate emails, ranges, allowed values, and duplicates before submission, and show every failure where it can be fixed.</li>
<li>Test with a headerless file, a non-US Excel export, a file with a title row, and a file large enough to hurt.</li>
</ul>
<h2 id="the-audit-never-finishes">The audit never finishes</h2>
<p>Every safeguard in this post earns its place because one specific file, somewhere, does one specific strange thing, and the supply of reasonable files from unreasonable tools does not run out. That is what CSV import issues are like up close. The importer's job is to meet each file calmly: fix what it can prove, flag what it cannot, and never be silently wrong. We keep feeding Updog broken files so that when your users upload theirs, the import is the easiest part of their day.</p>]]></content:encoded></item>
<item><title>Bring Your Own AI to CSV and Excel Import</title><link>https://updog.tech/blog/bring-your-own-ai/</link><guid isPermaLink="true">https://updog.tech/blog/bring-your-own-ai/</guid><pubDate>Tue, 02 Jun 2026 00:00:00 GMT</pubDate><description>Updog ships no model of its own, so your users' data stays private. Bring your own AI for column matching, value matching and data cleaning.</description><content:encoded><![CDATA[<p>Every tool is adding AI right now. Import tools too. Drop in a model, let it guess the columns, let it rewrite the values, ship it. It looks great in a demo.</p>
<p>But import is not a demo. The files people upload are real: customer lists, payroll exports, patient records, transactions. The moment that file goes through a vendor's AI, you have put a third party in the middle of your most sensitive step. And then you have to answer for it. Where did the data go? How long was it kept? Who else saw it? Did any of it train a model? Those are heavy questions to take on from an import widget.</p>
<p>Updog stays out of that. It needed AI, but it did not need to hold your data while the AI runs.</p>
<h2 id="the-model-should-be-yours">The model should be yours</h2>
<p>AI is good at this work: mapping a column called <code>First Name</code> to your <code>firstName</code> field, sorting messy values into the options a column allows, or turning "lowercase all the email addresses" into a real edit. By hand, this takes a while. A model does it in seconds.</p>
<p>The question was never whether Updog should use AI. It was who holds the data when it runs. The answer is you, since you already have it.</p>
<p>Updog does not ship an AI of its own. Look through the SDK and you will not find a model, an API key, or a line of OpenAI, Anthropic, or Gemini code. When AI runs in an Updog import, it runs because your app called your endpoint with your provider. Updog gives you the context, you make the call, and Updog applies what comes back. This is how the SDK is built, not a setting you can forget to turn on.</p>
<p>So Updog works the same with a hosted model, a self-hosted one behind your firewall, or no AI at all. You can use it either way.</p>
<h2 id="three-places-you-can-plug-in-a-model">Three places you can plug in a model</h2>
<p>There are three places where you can plug in AI. Each one is a single callback to your own endpoint, and each passes only what the model needs, never the whole dataset.</p>
<h3 id="column-matching">Column matching</h3>
<p>When someone uploads a file, Updog can ask your code to match the file's headers to your schema. Your callback gets the header names and your column definitions. That is all it gets.</p>
<pre><code class="language-tsx">onColumnMatch={async (headers, columns) => {
  const res = await fetch("/api/match-columns", {
    method: "POST",
    body: JSON.stringify({ headers, columns }),
  });
  return res.json();
}}</code></pre>
<p>Return a map of <code>{ header: columnId }</code>. Anything you skip, or set to <code>null</code>, falls back to Updog's built-in matching: exact match, synonyms, edit distance. The model handles the unclear headers. The obvious ones never needed it. And the point worth repeating: your endpoint sees a list of column names here, never a row of data.</p>
<h3 id="value-matching">Value matching</h3>
<p>After the columns are matched, the values can still be off. The file says <code>Eng</code>, <code>engineering</code>, <code>R&#x26;D</code>. Your Department column expects <code>Engineering</code>. Updog gives your callback the distinct values it found and the options you allow.</p>
<pre><code class="language-tsx">onValueMatch={async (valuesToMatch) => {
  const res = await fetch("/api/match-values", {
    method: "POST",
    body: JSON.stringify({ valuesToMatch }),
  });
  return res.json();
}}</code></pre>
<p>Return <code>{ columnId: { importedValue: option } }</code>. Anything left over falls back to fuzzy matching, and the user checks it before it lands. Again, the data that leaves is small: the unique values in a dropdown and the options you already set, never the rows behind them.</p>
<h3 id="the-data-cleaning-chat">The data-cleaning chat</h3>
<p>An AI button in the footer opens a small assistant over the grid. The user types a fix in plain words: "remove rows with no email," "normalize the phone numbers," "convert dates to ISO." Updog calls your <code>onMessage</code> with context about the data and streams back whatever your model returns.</p>
<p>What matters is what Updog sends and what it gets back. It does not send the whole table. It sends the column schema, the counts, a summary of the errors, and a small sample of rows. Your model does not need a million rows to write a fix. It needs the shape of the data and a few examples.</p>
<pre><code class="language-tsx">chat={{
  async *onMessage(context) {
    yield { type: "status", content: "Thinking..." };

    const res = await fetch("/api/clean", {
      method: "POST",
      body: JSON.stringify({
        message: context.message,
        columns: context.columns,
        errorSummary: context.errorSummary,
        sample: context.sample,
      }),
    }).then((r) => r.json());

    yield { type: "ops", content: res.ops };
    yield { type: "message", content: res.reply };
  },
}}</code></pre>
<p>And it does not send back rewritten data. It sends back a transformation: a small function, written as text, that Updog runs on each row in the browser.</p>
<pre><code class="language-ts">{
  action: "edit",
  fn: "(r) => { r.email = r.email.trim().toLowerCase(); }",
}</code></pre>
<p>Updog runs that function across every row in the current view, locally, and groups the whole change into one undo step. One function can clean a million rows without any of them reaching the model. That is faster than sending data back and forth. And it keeps the data private.</p>
<h2 id="the-human-stays-in-control">The human stays in control</h2>
<p>When the model returns a fix, Updog runs it and the result is right there in the grid. The user sees exactly what changed. If it is wrong, one undo takes the whole thing back. And nothing leaves until they submit the import.</p>
<p>So the roles stay clear. You choose the intelligence behind the import: the model, the prompt, the rules it follows. The user owns what happens to their data. Updog is the connection between the two, and it stays out of the data itself.</p>]]></content:encoded></item>
<item><title>A Different Way to Think About CSV Import</title><link>https://updog.tech/blog/browser-first-csv-import/</link><guid isPermaLink="true">https://updog.tech/blog/browser-first-csv-import/</guid><pubDate>Mon, 18 May 2026 00:00:00 GMT</pubDate><description>The file stays on the machine that opened the page. A free plan, one embedded component, and a smoother import flow for web apps.</description><content:encoded><![CDATA[<p>I started building Updog because I could not find the data import product I wanted to use.</p>
<p>The limits felt artificial. The UX was not good enough. The privacy story was heavier than it needed to be. The pricing became another thing to think about. And after all of that, the import flow still often felt like a small upload widget trying to handle a serious product moment.</p>
<p>CSV import looks simple only from far away. In a real product, the file almost never matches the system. Column names are different. Dates are formatted differently. Required fields are missing. Some values are valid for the user, but not valid for the product. Some rows can be fixed automatically. Some rows need attention.</p>
<p>That was the part that bothered me. The user is trying to bring external data into the product, but the workflow around that moment often becomes heavier than the moment itself. It turns into backend work, privacy questions, pricing rules, and UI compromises before the product has even helped the user prepare the file.</p>
<p>I wanted to try a different shape for that workflow.</p>
<h2 id="the-browser-became-the-product-idea">The browser became the product idea</h2>
<p>The core idea was to make the import step happen in the browser.</p>
<p>Updog is client-side code. When a user uploads a file, the SDK works with that file locally in the browser: parsing it, mapping columns, checking values, and preparing the final structured data for the host application. The raw file data does not get sent to Updog servers, because Updog does not need a server to run the import flow.</p>
<p>The host application still decides what happens after submission. Updog handles the preparation step inside the browser. The file is processed by the SDK locally. It never reaches Updog's servers.</p>
<p>That was the foundation I wanted.</p>
<h2 id="real-files-need-an-honest-benchmark">Real files need an honest benchmark</h2>
<p>A browser-first importer still needs to be honest about browser limits. A browser tab has memory constraints, and large files are expensive. The data needs to live somewhere. So do validation states, edits, filters, selections, and the rest of the working state required to make the import usable.</p>
<p>That is why one million rows became an important benchmark for Updog. The point was not that someone will manually inspect one million rows. Nobody should do that. The point is that real customer files can be large, and the product should have enough headroom to handle them without immediately turning import into a server-side project.</p>
<p>One million rows is a practical ceiling, not an unlimited claim. It says that the browser can go surprisingly far when the product is built around its strengths, but the limit is still real. If the import experience works at that scale, then 50,000 or 100,000 rows should feel normal instead of dangerous.</p>
<h2 id="how-it-works-without-rendering-one-million-rows">How it works without rendering one million rows</h2>
<p>Updog does not render one million HTML rows. That would be the wrong model.</p>
<p>A normal DOM table is useful for normal tables, but it is not the right foundation for a large import experience. When the dataset grows, the interface starts to pay for every wrong rendering decision. Scrolling becomes uneven, rows appear late, and the product begins to feel like it is barely holding together.</p>
<p>Updog uses a canvas-based grid. It draws what the user can see, instead of asking the browser to manage the whole dataset as page elements. Heavier operations, like filtering, can run in a Web Worker, so the main interface can stay responsive while the data is being processed. The browser still holds the data in memory, and that cost is real. The difference is that the UI is built around the browser's strengths instead of fighting them.</p>
<p>The goal is not to make a human scroll through a million rows. The goal is to make the product capable of working with a large file, then give the user tools to narrow the problem. Exact filters, validation states, error views, search, column transforms, and bulk actions are what make large imports manageable. The user should not be fixing every broken value by hand. Most issues should be handled automatically, and the editor exists for the remaining cases where the data still needs human correction.</p>
<h2 id="what-updog-handles">What Updog handles</h2>
<p>Updog is a browser-first JavaScript SDK for importing CSV and other structured files into web apps. It handles the preparation step: mapping columns, checking values, showing issues, narrowing the data that needs attention, and returning structured data back to the host application.</p>
<p>The application stays in control of what happens after submission. It can save the data, call an API, run business logic, or start a backend process. Some data workflows naturally belong there: scheduled jobs, recurring pipelines, warehouse-scale imports, very large migrations, and automated infrastructure flows.</p>
<p>Updog is focused on the user-facing import step inside a web application. The moment when someone brings a file into a product, the product helps prepare it, and clean structured data is submitted into the system. The browser can do a lot when the workflow fits the browser, and Updog is built for that specific workflow.</p>
<h2 id="pricing-should-feel-predictable">Pricing should feel predictable</h2>
<p>Client-side architecture also shaped pricing. The import work runs in the customer's browser, so running Updog costs us nothing more per row. The Free plan counts rows, 100,000 a month in production, and Team counts nothing.</p>
<p>Localhost and preview domains are free and never counted. Team costs $100 a month for any number of domains. All features are included on both plans. Team has no per-import fees, no row fees, and no usage tiers, and no plan carries Updog branding.</p>
<h2 id="the-version-i-wanted-to-exist">The version I wanted to exist</h2>
<p>I wanted CSV import to feel more secure, more usable, more predictable, and less artificially constrained.</p>
<p>That became Updog: a browser-first CSV import SDK where raw files can stay in the browser during preparation, real files have enough headroom to feel safe, users get tools to narrow and fix the data that needs attention, and pricing does not punish usage.</p>
<p>It is a simple idea, but it changes the shape of the product. CSV import does not need to become a heavy infrastructure problem every time a user brings data into a web app. That is the product I wanted to use, so that is the product I started building.</p>]]></content:encoded></item>
</channel>
</rss>
