Files
b8ea92eccb fix(foundations): write assessments where the read looks, and fail loudly when it can't (#50)
Splitting foundations into a shared registry and per-org assessments (#47)
moved the READ. Every write path still wrote fitScore, priority, themes,
tagline and researchNotes into config_data, which composeFoundation now
strips. So editing research notes returned 200 and changed nothing visible,
and seven ingestion scripts reported rows updated while producing no effect.
A failure with no error to notice.

Write paths now split a Foundation-shaped patch by ANALYSIS_FIELDS — the same
schema-derived list the read uses, so the two cannot disagree about where a
field lives:

  API      POST/PUT/PATCH/import — registry to config_data, analysis to the
           asking org's assessment row.
  Scripts  foundation-upsert, zefix-ingest, pipeline-incremental,
           ingest-triage, pipeline-graduate, bulk-import-batches,
           dedupe-by-uid.

Four of those scripts had no org id at all and updated rows by slug alone.
They take --org now: an assessment has an owner by construction, so the
question can no longer go unanswered.

Three things the split changed that are easy to miss, and are handled:

- bulk-import-batches decides "fill only what is empty" and "raise a fit
  score, never lower it" against current values. Reading config_data alone
  would show them all absent, so every rule protecting existing work would
  pass and overwrite it. It now merges against both halves.
- foundation-upsert read its own row back and parsed it as a Foundation to
  correct priority. That parse can no longer succeed on the blob alone, so
  the correction would have silently stopped running. It reads through the
  shared composition instead.
- dedupe merges two registry rows, but the opinions attached to them belong
  to tenants, possibly several. It now carries every org's assessment onto
  the keeper rather than archiving them with the loser.

Also fixes a production outage found while verifying #47 against its baseline.

Migration 0012 created the assessments table as the migrating role; the app
connects as a lesser one, and a new table grants nobody but its owner. Every
read raised 42501, the repo caught it, logged "DB unreachable", and returned
[]. Production served HTTP 200 everywhere and showed a customer with 1,683
researched foundations that it had none; /api/export/foundations returned a
header row and nothing else. Nothing alerted.

Both halves of that are closed:

- 0014 grants the app role access, deriving the role name from the existing
  grantee on fundraising_foundations so it is correct on any deployment, and
  sets default privileges so the next new table cannot repeat it.
- foundations-repo rethrows SQLSTATE class 42 instead of degrading. Code and
  schema disagreeing is a deploy defect, true again on the next request; only
  a genuinely transient failure falls back to an empty list.

Guarded by tests, both proven to fail under mutation: the scripts' column map
must equal ANALYSIS_FIELDS, and the class-42 rule is pinned against both the
codes it must catch and the ones it must not.

The flat fit_score/priority/research_date/research_depth columns on
fundraising_foundations are still written, from one helper, because the list
endpoint still filters on them — not writing them would recreate the drift
migration 0003's trigger exists to prevent. They go when the columns do.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 17:23:57 -07:00

71 lines
2.2 KiB
TypeScript

/**
* Shared script DB client — pg-backed `sql` tagged template.
*
* Drop-in replacement for the old `neon()` tagged-template client the pipeline
* scripts used before the 2026-06 self-host migration (the Neon HTTP driver
* cannot talk to plain Postgres). Same call-site API:
*
* import { sql } from './lib/db';
* const rows = await sql`SELECT * FROM fundraising_foundations WHERE id = ${id}`;
*
* Connection: DATABASE_URL from .env.local. Against the production box, open a
* tunnel first: ssh -L 15432:127.0.0.1:5432 root@bitbaum (see docs/DEPLOYMENT.md).
*
* `allowExitOnIdle` lets one-shot scripts exit naturally without pool.end().
*/
import { config } from 'dotenv';
config({ path: '.env.local' });
import { Pool } from 'pg';
let pool: Pool | null = null;
function getPool(): Pool {
if (!pool) {
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is not set — configure .env.local (see docs/DEPLOYMENT.md)');
}
pool = new Pool({
connectionString: process.env.DATABASE_URL,
allowExitOnIdle: true,
});
}
return pool;
}
/** Tagged-template query: sql`SELECT ... ${value}` → Promise of rows. */
export async function sql<T = Record<string, unknown>>(
strings: TemplateStringsArray,
...values: unknown[]
): Promise<T[]> {
const text = strings.reduce((acc, part, i) => (i === 0 ? part : `${acc}$${i}${part}`), '');
const { rows } = await getPool().query(text, values);
return rows as T[];
}
/**
* Plain parameterised query, for statements whose column list is built at
* runtime and so cannot be written as a single template literal.
*
* Same pool, same parameter binding as `sql`. The only caller that needs it is
* the assessment upsert, which writes whichever subset of columns a patch
* actually mentions.
*/
export async function query<T = Record<string, unknown>>(
text: string,
values: unknown[] = [],
): Promise<T[]> {
const { rows } = await getPool().query(text, values);
return rows as T[];
}
/** Type of the tagged-template client — for functions that take `sql` as a parameter. */
export type SqlClient = typeof sql;
/** Explicitly close the pool (only needed for long-lived scripts). */
export async function closeDb(): Promise<void> {
await pool?.end();
pool = null;
}