CodeSampleX

Exemplo

pg 8.23.0: Pool.query

Amostra verificada para npm pg 8.23.0: Pool.query. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: Pool.query executes SQL query string and…

sha256:a3d419fd9c2ff1876fdb2c3aaefe9b77ad8b40ede932f229183f780b7a730f28

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-30

Caso

HOW
Objetivo
verify Pool.query in pkg:npm/pg@8.23.0
Pacotes
Símbolos
  • Pool.query
Criado
2026-08-30T14:38:19Z

Contrato

  1. Pool.query executes SQL query string and returns a Promise resolving with QueryResult
  2. Pool.query executes parameterized query with text and values array
  3. Pool.query accepts a query configuration object containing text and values
  4. Pool.query supports callback-based invocation with (err, result)
  5. Pool.query invokes callback with error when a function is passed as the first parameter
  6. Pool.query propagates query execution errors
  7. Pool.query propagates client connection errors

Arquivos

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify Pool.query in pkg:npm/pg@8.23.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pg@8.23.0
Demonstrate these symbols/APIs:
  - Pool.query

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:28fba8ddd8cc19db32aef6121e133b1e72cd162e02c3dfd8ce8ed280531067bd","contract":["Pool.query executes SQL query string and returns a Promise resolving with QueryResult","Pool.query executes parameterized query with text and values array","Pool.query accepts a query configuration object containing text and values","Pool.query supports callback-based invocation with (err, result)","Pool.query invokes callback with error when a function is passed as the first parameter","Pool.query propagates query execution errors","Pool.query propagates client connection errors"],"goal":"verify Pool.query in pkg:npm/pg@8.23.0","kind":"HOW","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"symbols":["Pool.query"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"subject":"pkg:npm/pg@8.23.0","symbols":["Pool.query"],"verifierAdapter":"node-typescript@1"}
index.mjs
import pg from 'pg';

const { Pool } = pg;

/**
 * Execute a query using a pg Pool instance.
 * Supports query strings, parameterized queries, and query configuration objects.
 *
 * @param {pg.Pool} pool - The connection pool
 * @param {string|object} queryTextOrConfig - SQL statement or query configuration object
 * @param {Array<any>} [params] - Parameterized query values
 * @returns {Promise<pg.QueryResult>}
 */
export async function executeQuery(pool, queryTextOrConfig, params) {
  if (params !== undefined) {
    return await pool.query(queryTextOrConfig, params);
  }
  return await pool.query(queryTextOrConfig);
}

/**
 * Create a new PostgreSQL connection pool.
 *
 * @param {object} [options] - Pool configuration options
 * @returns {pg.Pool}
 */
export function createPool(options = {}) {
  return new Pool(options);
}
package-lock.json
{
  "name": "sample-pg-pool-query",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pg-pool-query",
      "version": "1.0.0",
      "dependencies": {
        "pg": "8.23.0"
      }
    },
    "node_modules/pg": {
      "version": "8.23.0",
      "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.0.tgz",
      "integrity": "sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==",
      "license": "MIT",
      "dependencies": {
        "pg-connection-string": "^2.14.0",
        "pg-pool": "^3.14.0",
        "pg-protocol": "^1.16.0",
        "pg-types": "2.2.0",
        "pgpass": "1.0.5"
      },
      "engines": {
        "node": ">= 16.0.0"
      },
      "optionalDependencies": {
        "pg-cloudflare": "^1.4.0"
      },
      "peerDependencies": {
        "pg-native": ">=3.0.1"
      },
      "peerDependenciesMeta": {
        "pg-native": {
          "optional": true
        }
      }
    },
    "node_modules/pg-cloudflare": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
      "integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
      "license": "MIT",
      "optional": true
    },
    "node_modules/pg-connection-string": {
      "version": "2.14.0",
      "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
      "integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
      "license": "MIT"
    },
    "node_modules/pg-int8": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
      "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
      "license": "ISC",
      "engines": {
        "node": ">=4.0.0"
      }
    },
    "node_modules/pg-pool": {
      "version": "3.14.0",
      "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
      "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
      "license": "MIT",
      "peerDependencies": {
        "pg": ">=8.0"
      }
    },
    "node_modules/pg-protocol": {
      "version": "1.16.0",
      "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.0.tgz",
      "integrity": "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==",
      "license": "MIT"
    },
    "node_modules/pg-types": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
      "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
      "license": "MIT",
      "dependencies": {
        "pg-int8": "1.0.1",
        "postgres-array": "~2.0.0",
        "postgres-bytea": "~1.0.0",
        "postgres-date": "~1.0.4",
        "postgres-interval": "^1.1.0"
      },
      "engines": {
        "node": ">=4"
      }
    },
    "node_modules/pgpass": {
      "version": "1.0.5",
      "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
      "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
      "license": "MIT",
      "dependencies": {
        "split2": "^4.1.0"
      }
    },
    "node_modules/postgres-array": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
      "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
      "license": "MIT",
      "engines": {
        "node": ">=4"
      }
    },
    "node_modules/postgres-bytea": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
      "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/postgres-date": {
      "version": "1.0.7",
      "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
      "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/postgres-interval": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
      "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
      "license": "MIT",
      "dependencies": {
        "xtend": "^4.0.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/split2": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
      "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
      "license": "ISC",
      "engines": {
        "node": ">= 10.x"
      }
    },
    "node_modules/xtend": {
      "version": "4.0.2",
      "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
      "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
      "license": "MIT",
      "engines": {
        "node": ">=0.4"
      }
    }
  }
}
package.json
{
  "name": "sample-pg-pool-query",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "pg": "8.23.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Pool.query in pkg:npm/pg@8.23.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pg@8.23.0"
  ],
  "symbols": [
    "Pool.query"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { EventEmitter } from 'node:events';
import pg from 'pg';
import { executeQuery, createPool } from '../index.mjs';

const { Pool } = pg;

class MockClient extends EventEmitter {
  constructor(options = {}) {
    super();
    this.options = options;
    this._queryable = true;
    this._ending = false;
    this._poolUseCount = 0;
  }

  connect(cb) {
    if (this.options.simulateConnectError) {
      process.nextTick(() => cb(new Error('Connection failed')));
      return;
    }
    process.nextTick(() => cb(null));
  }

  query(config, values, cb) {
    if (typeof values === 'function') {
      cb = values;
      values = undefined;
    }

    if (this.options.simulateQueryError) {
      const err = new Error('Query execution failed');
      if (cb) {
        process.nextTick(() => cb(err));
        return;
      }
      return Promise.reject(err);
    }

    let text = typeof config === 'string' ? config : config.text;
    let queryValues = typeof config === 'object' && config.values ? config.values : values;

    const result = {
      command: 'SELECT',
      rowCount: queryValues ? queryValues.length : 1,
      rows: queryValues ? queryValues.map((v, i) => ({ id: i + 1, value: v })) : [{ id: 1, value: 'default' }],
      fields: [{ name: 'id' }, { name: 'value' }]
    };

    if (cb) {
      process.nextTick(() => cb(null, result));
      return;
    }
    return Promise.resolve(result);
  }

  end(cb) {
    if (cb) process.nextTick(cb);
    return Promise.resolve();
  }

  ref() {}
  unref() {}
}

async function runContractTests() {
  // Contract 1: Pool.query executes query string and returns a Promise resolving with QueryResult
  const pool = createPool({ Client: MockClient, max: 5 });
  const res1 = await pool.query('SELECT 1');
  assert.strictEqual(res1.command, 'SELECT');
  assert.strictEqual(res1.rowCount, 1);
  assert.deepStrictEqual(res1.rows, [{ id: 1, value: 'default' }]);

  // Contract 2: Pool.query accepts parameterized query values with text
  const res2 = await pool.query('SELECT * FROM items WHERE name = $1', ['alpha']);
  assert.strictEqual(res2.rowCount, 1);
  assert.deepStrictEqual(res2.rows, [{ id: 1, value: 'alpha' }]);

  // Contract 3: Pool.query accepts a query configuration object with text and values
  const res3 = await pool.query({ text: 'SELECT * FROM items WHERE id = $1', values: [100] });
  assert.strictEqual(res3.rowCount, 1);
  assert.deepStrictEqual(res3.rows, [{ id: 1, value: 100 }]);

  // Contract 4: Pool.query supports callback-based invocation with query text
  const res4 = await new Promise((resolve, reject) => {
    pool.query('SELECT 1', (err, res) => {
      if (err) return reject(err);
      resolve(res);
    });
  });
  assert.strictEqual(res4.rowCount, 1);

  // Contract 5: Pool.query supports callback-based invocation with text and parameters
  const res5 = await new Promise((resolve, reject) => {
    pool.query('SELECT * FROM items WHERE id = $1', [42], (err, res) => {
      if (err) return reject(err);
      resolve(res);
    });
  });
  assert.strictEqual(res5.rowCount, 1);
  assert.deepStrictEqual(res5.rows, [{ id: 1, value: 42 }]);

  // Contract 6: executeQuery helper wraps Pool.query for parameterized and plain queries
  const helperRes = await executeQuery(pool, 'SELECT * FROM items WHERE name = $1', ['helper']);
  assert.strictEqual(helperRes.rowCount, 1);
  assert.deepStrictEqual(helperRes.rows, [{ id: 1, value: 'helper' }]);

  await pool.end();

  // Contract 7: Pool.query guards against passing a function as first argument and calls callback with descriptive error
  const poolGuard = createPool({ Client: MockClient });
  const guardErr = await new Promise((resolve) => {
    poolGuard.query((err) => {
      resolve(err);
    });
  });
  assert.strictEqual(guardErr.message, 'Passing a function as the first parameter to pool.query is not supported');
  await poolGuard.end();

  // Contract 8: Pool.query propagates query errors and releases client
  const errorPool = createPool({ Client: MockClient, simulateQueryError: true });
  await assert.rejects(
    async () => {
      await errorPool.query('SELECT * FROM bad_table');
    },
    {
      name: 'Error',
      message: 'Query execution failed'
    }
  );
  await errorPool.end();

  // Contract 9: Pool.query propagates connection failure errors
  const connErrorPool = createPool({ Client: MockClient, simulateConnectError: true });
  await assert.rejects(
    async () => {
      await connErrorPool.query('SELECT 1');
    },
    {
      name: 'Error',
      message: 'Connection failed'
    }
  );
  await connErrorPool.end();

  console.log('Contract tests passed successfully.');
}

runContractTests();

Seeder de origem

anônimo