<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Spendwise]]></title><description><![CDATA[Build notes from Spendwise, a private offline-first expense tracker for Android: SQLite schema design, integer money and export tooling.]]></description><link>https://getspendwise.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6af9b7704a838c8865a87ac9/1869a861-aa01-4eb2-874d-82e645ea5d7b.png</url><title>Spendwise</title><link>https://getspendwise.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 15:25:55 GMT</lastBuildDate><atom:link href="https://getspendwise.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Money in SQLite: building an offline-first expense tracker with Expo]]></title><description><![CDATA[Schema migrations, integer minor units, one scope predicate, and a hand-written XLSX writer — the decisions behind a local-first ledger on Android.]]></description><link>https://getspendwise.hashnode.dev/money-in-sqlite-building-an-offline-first-expense-tracker-with-expo</link><guid isPermaLink="true">https://getspendwise.hashnode.dev/money-in-sqlite-building-an-offline-first-expense-tracker-with-expo</guid><category><![CDATA[Android]]></category><category><![CDATA[React Native]]></category><category><![CDATA[SQLite]]></category><category><![CDATA[Expo]]></category><dc:creator><![CDATA[Kasim Rangwala]]></dc:creator><pubDate>Sun, 15 Nov 2026 13:59:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af9b7704a838c8865a87ac9/7e770554-c383-4469-a973-08cd1c43b6ea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most expense trackers treat your spending history as a server-side asset. You sign up, the app syncs, and the ledger lives somewhere you cannot see. I wanted the opposite: the ledger is a SQLite file on the phone, and the app is a reader and writer for it.</p>
<p>That constraint changes the design. This post covers the four decisions that mattered most while building Spendwise, a local-first <a href="https://spendwise.download/">expense tracker</a> for Android: how money is stored, how the schema evolves, how reads stay scoped, and how exports work without a spreadsheet dependency.</p>
<h2>1. Money never touches a float</h2>
<p>The single rule that prevents most finance bugs: <strong>money is an integer in minor units</strong>. A coffee is <code>350</code>, not <code>3.5</code>. Currency decimals come from a table, because not every currency has two:</p>
<pre><code class="language-ts">export function parseAmountToMinor(amount: string, currencyCode: CurrencyCode): number {
  if (amount.includes('-')) {
    throw new AppError('VALIDATION_ERROR', 'errors.invalidAmount');
  }
  const decimals = getCurrencyDecimals(currencyCode);
  const value = Number.parseFloat(normalizeAmountInput(amount, decimals));

  if (!Number.isFinite(value) || value &lt; 0) {
    throw new AppError('VALIDATION_ERROR', 'errors.invalidAmount');
  }

  return Math.round(value * 10 ** decimals);
}
</code></pre>
<p><code>Number.parseFloat</code> appears here exactly once, at the boundary where text becomes a number, and the result is immediately rounded to an integer. Every sum, budget comparison and balance after that is integer arithmetic. <code>0.1 + 0.2</code> never enters the ledger.</p>
<p>The other half is input normalization. The decimal keypad follows the device locale, so <code>12,50</code> arrives as often as <code>12.50</code>, and an Arabic or Persian keypad types its own digits and separators. Stripping commas — the obvious fix — turned <code>12,50</code> into <code>1250</code>, a 100× error. The parser caches the locale's grouping and decimal separators from <code>Intl.NumberFormat().formatToParts()</code> and strips only the grouping character.</p>
<p>Rejecting the minus sign before cleaning is deliberate too. A negative amount is not a valid transaction in this app; if the sign is silently dropped, a refund becomes an expense.</p>
<h2>2. Migrations are a list, not a diff</h2>
<p><code>expo-sqlite</code> gives you <code>openDatabaseAsync</code>, <code>execAsync</code> and prepared statements. It does not give you a migration framework. The whole mechanism is a version table and an ordered array:</p>
<pre><code class="language-ts">async function runMigrations(db: SQLite.SQLiteDatabase): Promise&lt;void&gt; {
  await db.execAsync(`
    CREATE TABLE IF NOT EXISTS schema_migrations (
      version INTEGER PRIMARY KEY NOT NULL
    );
  `);

  const row = await db.getFirstAsync&lt;{ version: number }&gt;(
    'SELECT MAX(version) as version FROM schema_migrations',
  );
  const currentVersion = row?.version ?? 0;

  for (const migration of migrations) {
    if (migration.version &gt; currentVersion) {
      await migration.up(db);
      await db.runAsync('INSERT INTO schema_migrations (version) VALUES (?)', migration.version);
    }
  }
}
</code></pre>
<p>Each migration is a module exporting <code>version</code> and <code>up</code>. They are imported and listed in <code>client.ts</code> in order — the list is the source of truth, not the filesystem. That catches the class of bug where a bundled app cannot enumerate its own assets and silently skips a migration.</p>
<p>Two rules keep this safe:</p>
<ul>
<li><strong>Never edit a released migration.</strong> Add a new numbered one. An app on someone's phone already ran the old body; changing it means two users have two different schemas with the same version number.</li>
<li><strong>One database handle.</strong> A module-level singleton with an <code>initPromise</code> guard means concurrent callers during startup wait for the same migration run instead of racing it.</li>
</ul>
<p>The schema is ordinary SQLite: transactions, categories, budgets, recurring rules, people, groups, attachments. Nothing exotic, which is the point — the queries are portable, and the data can be read with any SQLite browser.</p>
<h2>3. Scoping needs one predicate, not one per query</h2>
<p>Once groups exist — a trip, a shared household — every scoped table has a nullable <code>group_id</code>. The app-level context is <code>NULL</code>, meaning "not in a group". The trap follows immediately:</p>
<pre><code class="language-sql">SELECT * FROM transactions WHERE group_id = ?; -- never matches NULL
</code></pre>
<p><code>= NULL</code> is never true in SQL, so a scoped read written with <code>=</code> silently returns nothing for the app-level ledger, and a read that forgets the predicate silently returns every group's rows. Both failures are quiet, which is the worst kind.</p>
<p>The fix is a single helper that every repository uses:</p>
<pre><code class="language-ts">export function scopeFilter(column: string, groupId: GroupScope = null): ScopeFilter {
  return groupId === null
    ? { sql: `${column} IS NULL`, params: [] }
    : { sql: `${column} = ?`, params: [groupId] };
}
</code></pre>
<p>It returns SQL plus the params to bind, in order, so callers compose rather than concatenate. The column name is always a literal written in the repository layer — never user input. Reads take <code>groupId: GroupScope = null</code>, so an existing app-level call keeps its meaning and a group read is opt-in at the call site.</p>
<p>The rule that makes this stick: <strong>no hand-written scope predicates</strong>. If a repository needs one, it calls the helper. Reviewing a diff for <code>group_id</code> used without it is mechanical, which is exactly what you want in the one place a mistake leaks another context's data.</p>
<h2>4. Exports: self-contained PDF, hand-written XLSX</h2>
<p>Two export paths, both built on the same data model.</p>
<p><strong>PDF</strong> goes through <code>expo-print</code>, which renders a self-contained HTML document with the platform's own engine. Every currency symbol the app supports prints correctly without embedding a font, and the file needs no network. The charts are drawn inline in HTML rather than reusing the on-screen <code>react-native-svg</code> charts, because a print document cannot share a native view tree.</p>
<p><strong>XLSX</strong> was the interesting one. An <code>.xlsx</code> is a ZIP of XML parts. A spreadsheet library is roughly a megabyte of dependency for one export button, so the app builds the parts it needs — workbook, styles, one sheet per report table — and writes the ZIP itself with stored (uncompressed) entries.</p>
<p>Two details that decide whether Excel opens the result:</p>
<ul>
<li>Control characters are not legal in XML 1.0. Notes are free text and can carry anything, so they are stripped from every cell rather than trusted.</li>
<li>Money is written as a plain decimal string from the formatter (<code>minorToDisplayAmount</code>), flagged numeric, never as a float computed on the way out. The formatting layer is the only place integer minor units become <code>12.50</code>.</li>
</ul>
<p>The result is a few hundred lines, no native module, and the same content as the PDF.</p>
<h2>What this buys, and what it costs</h2>
<p><strong>Buys:</strong> the app works in airplane mode, the first launch has no signup, and backing up means keeping a file. There is no server to breach and no sync conflict to resolve.</p>
<p><strong>Costs:</strong> multi-device sync is a feature you have to build deliberately, not something the database gives you. Device loss is real unless the user exports or backs up. And every schema change needs a migration that runs correctly on an old database — the cost is paid per release, not once.</p>
<p>For a personal finance app, the trade is worth it. The ledger is the product; it should live where the user can see it.</p>
<p>If you want to see the result, Spendwise is <a href="https://play.google.com/store/apps/details?id=com.gripxtech.spendwise&amp;hl=en_US">free on Google Play</a>. I write about the internals when something is worth sharing; the <a href="https://spendwise.download/blog/why-local-first">local-first article on the site</a> goes deeper on the data model.</p>
<p>Questions about the migration runner or the scope helper are welcome in the comments — especially if you have hit the <code>= NULL</code> bug in your own schema.</p>
]]></content:encoded></item></channel></rss>