Node.js / TypeScript: pg
Connects, creates a todo table if it does not exist, inserts a row and counts open rows. The code is the same against the original database and against MachSQL; only the address changes.
The only change
Section titled “The only change”DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/appDATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appNothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- Node.js 26 LTS
- pg 8.23.1
- TypeScript 7.0.2, tsx 4.23.15
npm installexport DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/appnpm startExpected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
// node-postgres (pg) from TypeScript.import pg from "pg";
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });await client.connect();try { await client.query("CREATE TABLE IF NOT EXISTS todo (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, done boolean NOT NULL DEFAULT false)"); const inserted = await client.query<{ id: string }>( "INSERT INTO todo (title) VALUES ($1) RETURNING id", ["write the examples"], ); const open = await client.query<{ n: string }>("SELECT count(*) AS n FROM todo WHERE NOT done"); console.log(`inserted todo ${inserted.rows[0].id}, ${open.rows[0].n} open`);} finally { await client.end();}{ "name": "machsql-example-node-pg", "private": true, "type": "module", "scripts": { "start": "tsx index.ts" }, "dependencies": { "pg": "8.23.1" }, "devDependencies": { "@types/node": "26.6.6", "@types/pg": "8.23.1", "tsx": "4.23.15", "typescript": "7.0.2" }}