npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

psql-tson

v1.0.0

Published

Specialized PostgreSQL to TSON (Token-Structured Object Notation) converter & query generator. Native support for JSONB, Arrays, TIMESTAMPTZ, UUID, ON CONFLICT upserts, and node-postgres (pg) / Supabase / Neon.

Readme

psql-tson 🚀

npm version license bundle size TypeScript

Specialized PostgreSQL to TSON (Token-Structured Object Notation) Converter & Query Generator.

Native support for JSONB, TIMESTAMPTZ, UUID, Bytea, ON CONFLICT Upserting, and drivers like node-postgres (pg), @neondatabase/serverless, @vercel/postgres, and Supabase.

Cuts 50% of prompt input tokens and 50% of AI output generation tokens!


💡 Why psql-tson?

When working with PostgreSQL databases in RAG & AI Agent pipelines:

  • JSONB & Column Key Duplication: Standard JSON duplicates column names ("user_id", "email", "created_at") across every single row.
  • Slow Output Generation: Forcing LLMs to reply in verbose JSON or raw SQL strings inflates API costs by 3x to 4x.
  • PostgreSQL Type Handling: TIMESTAMPTZ, BigInt, JSONB, and UUID columns need clean, token-efficient serialization without data loss.

psql-tson formats PostgreSQL query results into columnar TSON, and safely parses AI responses directly into Parameterized PostgreSQL Queries ($1, $2) with RETURNING * and ON CONFLICT DO UPDATE.


📊 PostgreSQL Token Savings Benchmark

| Query Target | Standard JSON Output | TSON Format | Token Savings | Speedup | | :--- | :--- | :--- | :--- | :--- | | Read Path (Prompt Context) | ~14,500 tokens | ~6,700 tokens | 7,800 tokens saved | 53.7% Less Input Cost ⚡ | | Write Path (LLM Output) | ~5,800 tokens | ~2,350 tokens | 3,450 tokens saved | ~2.2x Faster Generation ⚡ |


📦 Installation

npm install psql-tson
# or
yarn add psql-tson
# or
pnpm add psql-tson

⚡ Quick Start

1. Read Path: PostgreSQL (pg QueryResult) $\rightarrow$ TSON (Prompt Context)

import { psqlToTson } from 'psql-tson';
import { Pool } from 'pg';

const pool = new Pool();

// Query PostgreSQL database
const result = await pool.query('SELECT user_id, first_name, email, role, meta, created_at FROM users WHERE status = $1', ['active']);

// Convert pg.QueryResult directly into compact TSON prompt context
const tsonPrompt = psqlToTson(result, { trackSavings: true });

console.log(tsonPrompt);
/*
user_id: 101, 102
first_name: Abhi, Sarah
email: [email protected], [email protected]
role: Architect, AI Engineer
meta:
  #1: {"level":"Senior","verified":true}
  #2: {"level":"Principal","verified":true}
created_at: 2026-08-27T15:45:00.000Z, 2026-08-27T15:46:12.000Z
*/

2. Write Path: LLM TSON Response $\rightarrow$ Parameterized PostgreSQL INSERT

import { tsonToPsqlInsert } from 'psql-tson';

const llmTsonOutput = `
first_name: Abhi, Sarah
last_name: Asok, Chen
email: [email protected], [email protected]
role: Architect, AI Engineer
`;

// Generate Parameterized Query
const query = tsonToPsqlInsert(llmTsonOutput, {
  tableName: 'users',
  returning: true
});

console.log(query.text);
// INSERT INTO "users" ("first_name", "last_name", "email", "role") VALUES ($1, $2, $3, $4), ($5, $6, $7, $8) RETURNING *;

console.log(query.values);
// ['Abhi', 'Asok', '[email protected]', 'Architect', 'Sarah', 'Chen', '[email protected]', 'AI Engineer']

// Execute safely with pg pool!
const inserted = await pool.query(query.text, query.values);

3. Generate PostgreSQL ON CONFLICT DO UPDATE (Upsert)

import { tsonToPsqlUpsert } from 'psql-tson';

const upsertQuery = tsonToPsqlUpsert(llmTsonOutput, {
  tableName: 'users',
  conflictColumns: ['email']
});

console.log(upsertQuery.text);
// INSERT INTO "users" (...) VALUES (...) ON CONFLICT ("email") DO UPDATE SET "first_name" = EXCLUDED."first_name", "last_name" = EXCLUDED."last_name", "role" = EXCLUDED."role";

4. Interactive Terminal Demo

Run the interactive CLI demonstration:

npm run demo

Check cumulative token savings logged automatically in SAVINGS_TRACKER.json:

import { getGlobalSavingsTracker } from 'psql-tson';

const tracker = getGlobalSavingsTracker();
console.log(tracker.getStats());

🛠️ API Reference

| Function | Direction | Description | | :--- | :--- | :--- | | psqlToTson(pgResult, options?) | PostgreSQL -> TSON | Converts pg.QueryResult or row arrays to TSON prompt strings. | | tsonToPsql(tsonStr, options?) | TSON -> PostgreSQL Rows | Parses TSON strings back into JS PostgreSQL row objects. | | tsonToPsqlInsert(tsonStr, options?) | TSON -> INSERT | Generates parameterized PostgreSQL INSERT statements ($1, $2) with RETURNING *. | | tsonToPsqlUpsert(tsonStr, options) | TSON -> UPSERT | Generates PostgreSQL ON CONFLICT DO UPDATE queries. | | tsonToPsqlWhere(tsonStr, options?) | TSON -> WHERE | Generates PostgreSQL WHERE filter clauses. |


👤 Author & Contact

Developed with ❤️ by Abhi Asok.

For business inquiries, collaboration, or support:


📄 License

MIT © Abhi Asok