Slonik Utilities

2.0.2 · active · verified Wed Apr 22

Slonik Utilities provides a set of helper functions designed to simplify common data manipulation operations within a PostgreSQL database when using the Slonik client library. It abstracts away the direct construction of parameterized SQL queries for tasks such as `UPDATE`, `UPDATE ... DISTINCT`, and `UPSERT`, allowing developers to express these operations using JavaScript objects. The library is currently at stable version 2.0.2 and receives updates primarily to maintain compatibility with new major versions of Slonik (e.g., supporting Slonik v29). Its key differentiators include enhancing developer productivity by reducing boilerplate SQL, improving type safety through its TypeScript definitions, and mitigating SQL injection risks by leveraging Slonik's tagged template literals internally. It does not replace Slonik but complements it by offering a higher-level, opinionated API for frequent DML patterns.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `slonik-utilities` `update` function to modify records in a PostgreSQL database using a Slonik connection, including basic setup and verification.

import { createPool, sql } from 'slonik';
import { update } from 'slonik-utilities';

const connectionString = process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/database';

async function runExample() {
  const pool = await createPool(connectionString);

  try {
    // Create a dummy table for demonstration
    await pool.query(sql`
      CREATE TABLE IF NOT EXISTS "user" (
        id SERIAL PRIMARY KEY,
        given_name TEXT,
        last_name TEXT
      );
    `);

    // Insert some initial data
    await pool.query(sql`
      INSERT INTO "user" (given_name, last_name) VALUES ('John', 'Doe'), ('Jane', 'Smith');
    `);

    console.log('Initial data inserted.');

    // Use slonik-utilities to update rows matching a condition
    const updateResult = await pool.connect(async (connection) => {
      return await update(
        connection,
        'user',
        {
          givenName: 'Jonathan'
        },
        {
          lastName: 'Doe'
        }
      );
    });

    console.log(`Updated ${updateResult.rowCount} row(s).`);

    // Verify the update
    const updatedUsers = await pool.query(sql`SELECT * FROM "user" WHERE last_name = 'Doe'`);
    console.log('Updated user:', updatedUsers.rows[0]);

  } catch (error) {
    console.error('Error during example execution:', error);
  } finally {
    await pool.end();
  }
}

runExample();

view raw JSON →