{"id":16534,"library":"slonik-utilities","title":"Slonik Utilities","description":"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.","status":"active","version":"2.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/gajus/slonik-utilities","tags":["javascript","postgresql","slonik","utilities","typescript"],"install":[{"cmd":"npm install slonik-utilities","lang":"bash","label":"npm"},{"cmd":"yarn add slonik-utilities","lang":"bash","label":"yarn"},{"cmd":"pnpm add slonik-utilities","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime peer dependency; the utilities operate on Slonik connection instances and types.","package":"slonik","optional":false}],"imports":[{"note":"The library ships as an ESM module, requiring `import` statements. TypeScript users benefit from strong typing.","wrong":"const { update } = require('slonik-utilities');","symbol":"update","correct":"import { update } from 'slonik-utilities';"},{"note":"Similar to `update`, this is a named export. It's useful for avoiding unnecessary writes when data hasn't changed by comparing distinct values.","wrong":"const updateDistinct = require('slonik-utilities').updateDistinct;","symbol":"updateDistinct","correct":"import { updateDistinct } from 'slonik-utilities';"},{"note":"The `upsert` utility is a named export. Ensure your database table has appropriate unique constraints for `upsert` to function correctly.","wrong":"import upsert from 'slonik-utilities';","symbol":"upsert","correct":"import { upsert } from 'slonik-utilities';"}],"quickstart":{"code":"import { createPool, sql } from 'slonik';\nimport { update } from 'slonik-utilities';\n\nconst connectionString = process.env.DATABASE_URL ?? 'postgres://user:password@localhost:5432/database';\n\nasync function runExample() {\n  const pool = await createPool(connectionString);\n\n  try {\n    // Create a dummy table for demonstration\n    await pool.query(sql`\n      CREATE TABLE IF NOT EXISTS \"user\" (\n        id SERIAL PRIMARY KEY,\n        given_name TEXT,\n        last_name TEXT\n      );\n    `);\n\n    // Insert some initial data\n    await pool.query(sql`\n      INSERT INTO \"user\" (given_name, last_name) VALUES ('John', 'Doe'), ('Jane', 'Smith');\n    `);\n\n    console.log('Initial data inserted.');\n\n    // Use slonik-utilities to update rows matching a condition\n    const updateResult = await pool.connect(async (connection) => {\n      return await update(\n        connection,\n        'user',\n        {\n          givenName: 'Jonathan'\n        },\n        {\n          lastName: 'Doe'\n        }\n      );\n    });\n\n    console.log(`Updated ${updateResult.rowCount} row(s).`);\n\n    // Verify the update\n    const updatedUsers = await pool.query(sql`SELECT * FROM \"user\" WHERE last_name = 'Doe'`);\n    console.log('Updated user:', updatedUsers.rows[0]);\n\n  } catch (error) {\n    console.error('Error during example execution:', error);\n  } finally {\n    await pool.end();\n  }\n}\n\nrunExample();","lang":"typescript","description":"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."},"warnings":[{"fix":"Ensure your `package.json` specifies `slonik: \"^28.0.0\"` or `\"^29.0.0\"` (or newer compatible versions) and run `npm install` or `yarn install`.","message":"Slonik-utilities requires a peer dependency of `slonik` version `>28`. Mismatched Slonik versions can lead to type errors, runtime failures, or unexpected behavior due to API changes in Slonik itself.","severity":"breaking","affected_versions":">=1.9.3"},{"fix":"Use `import { ... } from 'slonik-utilities';` in an ES module context. For Node.js, ensure your `package.json` has `\"type\": \"module\"` or use a `.mjs` file extension.","message":"Since major version 2.0.0, `slonik-utilities` is published as an ESM module. Attempting to `require()` it in a CommonJS context will result in a `TypeError: require() of ES Module`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Ensure your JavaScript property names in `namedValueBindings` and `booleanExpressionValues` match the snake_case representation of your PostgreSQL column names. For example, `givenName` in JS becomes `given_name` in SQL.","message":"When passing named value bindings or boolean expression values, `slonik-utilities` (and Slonik by default) will automatically snake_case property names to match typical PostgreSQL column naming conventions. If your column names use a different casing (e.g., `camelCase`), you must explicitly match them or configure Slonik's naming convention transformer.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Update your TypeScript code to remove the `Type` suffix from imported types from `slonik-utilities`.","message":"In version 1.9.1, the library removed the `Type` suffix from its TypeScript interfaces (e.g., `UpdateResultType` became `UpdateResult`). While not a runtime breaking change, it requires updates to type imports in TypeScript projects.","severity":"deprecated","affected_versions":">=1.9.1"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you are passing a valid `Slonik` `Connection` or `Pool` instance. When using a `pool.connect()` callback, ensure you pass the `connection` argument from the callback, e.g., `const result = await pool.connect(async (connection) => update(connection, ...));`","cause":"The `connection` object passed to `slonik-utilities` functions is not a valid Slonik `Connection` or `Pool` instance, or it's `undefined`.","error":"TypeError: Cannot read properties of undefined (reading 'query')"},{"fix":"Verify your Slonik pool creation. Ensure `createPool` is called with a valid `connectionString` (e.g., `process.env.DATABASE_URL`) and that your database is accessible.","cause":"This error originates from `slonik` itself, indicating that `createPool` was not called or its connection string was invalid, preventing a proper Slonik client from being initialized.","error":"Error: Slonik client has not been configured."},{"fix":"Install the package (`npm install slonik-utilities`). If the error persists and you are in a Node.js project, switch to `import` statements and ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json` or `.mjs` file extension).","cause":"Attempting to use `require()` to import `slonik-utilities` when the package is an ES Module, or the package is not installed.","error":"TypeError: require() of ES Module [...] from [...] not supported."}],"ecosystem":"npm"}