Skip to content

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.

DATABASE_URL=postgres://app:${DB_PASSWORD}@old-postgres:5432/app
DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • Node.js 26 LTS
  • pg 8.23.1
  • TypeScript 7.0.2, tsx 4.23.15
Terminal window
npm install
export DATABASE_URL=postgres://app:${DB_PASSWORD}@machsql-host:5432/app
npm start

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

index.ts
// 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();
}
package.json
{
"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"
}
}