CodeSampleX

示例

pg 8.23.0: Pool

已验证示例 — npm pg 8.23.0: Pool. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: assert pg.Pool constructor and createPool factory create Pool instance…

sha256:ab72a33dc483f431a6ddfe69e679e903cbdc8ce74c0b1a0abe101419ddfb9cc3

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify pg.Pool in pkg:npm/pg@8.23.0
包
符号
  • pg.Pool
创建时间
2026-08-30T14:48:54Z

契约

  1. assert pg.Pool constructor and createPool factory create Pool instance with expected configuration
  2. assert pool tracks connection counts (totalCount, idleCount, waitingCount)
  3. assert pool.connect acquires client with release callback
  4. assert client.release returns connection to idle pool for reuse
  5. assert client.release throws on double release
  6. assert client.release with error removes connection from pool
  7. assert pool.query delegates execution and returns client to idle pool
  8. assert withClient helper runs operation and safely releases client
  9. assert pool emits connect, acquire, and release lifecycle events
  10. assert pool.end drains pool and subsequent connect and query attempts reject

文件

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

下载源代码构件 (tar.gz)

源代码

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 pg.Pool 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:
  - pg.Pool

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:52c15bd5fa1e6563e1cc35b27bfa308c8b090e504af70b519a0825376fe96d38","contract":["assert pg.Pool constructor and createPool factory create Pool instance with expected configuration","assert pool tracks connection counts (totalCount, idleCount, waitingCount)","assert pool.connect acquires client with release callback","assert client.release returns connection to idle pool for reuse","assert client.release throws on double release","assert client.release with error removes connection from pool","assert pool.query delegates execution and returns client to idle pool","assert withClient helper runs operation and safely releases client","assert pool emits connect, acquire, and release lifecycle events","assert pool.end drains pool and subsequent connect and query attempts reject"],"goal":"verify pg.Pool in pkg:npm/pg@8.23.0","kind":"HOW","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"symbols":["pg.Pool"]},"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":["pg.Pool"],"verifierAdapter":"node-typescript@1"}
index.js
const pg = require('pg');
const { Pool } = pg;

function createPool(options = {}) {
  return new Pool(options);
}

async function executeQuery(pool, queryText, values = []) {
  return pool.query(queryText, values);
}

async function withClient(pool, callback) {
  const client = await pool.connect();
  try {
    return await callback(client);
  } finally {
    client.release();
  }
}

async function drainPool(pool) {
  return pool.end();
}

module.exports = {
  Pool,
  createPool,
  executeQuery,
  withClient,
  drainPool,
};
package-lock.json
{
  "name": "sample-pg",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pg",
      "version": "1.0.0",
      "license": "MIT-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",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pg.Pool in pg@8.23.0",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "pg": "8.23.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pg.Pool in pkg:npm/pg@8.23.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pg@8.23.0"
  ],
  "symbols": [
    "pg.Pool"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import EventEmitter from 'node:events';
import pg from 'pg';
import { createPool, executeQuery, withClient, drainPool } from '../index.js';

const { Pool } = pg;

// Define a minimal offline mock client that adheres to pg Client contract
class MockClient extends EventEmitter {
  constructor(config) {
    super();
    this.config = config;
    this._connected = false;
    this._queryable = true;
    this._ending = false;
    this._queryCount = 0;
  }

  connect(cb) {
    this._connected = true;
    if (cb) cb(null);
    return Promise.resolve();
  }

  query(config, values, cb) {
    if (typeof config === 'function') {
      cb = config;
      config = {};
    }
    if (typeof values === 'function') {
      cb = values;
      values = [];
    }
    this._queryCount++;
    const text = typeof config === 'string' ? config : (config && config.text) || '';
    const params = Array.isArray(values) ? values : (config && config.values) || [];
    const res = {
      command: 'SELECT',
      rowCount: 1,
      rows: [{ id: 1, text, params }],
      fields: [{ name: 'id' }, { name: 'text' }, { name: 'params' }],
    };
    if (cb) {
      cb(null, res);
      return;
    }
    return Promise.resolve(res);
  }

  end(cb) {
    this._connected = false;
    this._ending = true;
    this.emit('end');
    if (cb) cb(null);
    return Promise.resolve();
  }
}

// 1. assert pg.Pool constructor and createPool factory create Pool instance with expected configuration
const pool = createPool({
  Client: MockClient,
  max: 5,
  idleTimeoutMillis: 5000,
  connectionTimeoutMillis: 1000,
});
assert.strictEqual(typeof Pool, 'function', 'Pool must be a constructor function');
assert.strictEqual(pg.Pool, Pool, 'pg.Pool must export Pool');
assert.strictEqual(pool instanceof Pool, true, 'createPool must return a Pool instance');
assert.strictEqual(pool.options.max, 5, 'Pool should reflect max config');
assert.strictEqual(pool.options.idleTimeoutMillis, 5000, 'Pool should reflect idleTimeoutMillis');

// 2. assert pool tracks connection counts (totalCount, idleCount, waitingCount)
assert.strictEqual(pool.totalCount, 0, 'initial totalCount should be 0');
assert.strictEqual(pool.idleCount, 0, 'initial idleCount should be 0');
assert.strictEqual(pool.waitingCount, 0, 'initial waitingCount should be 0');

// 3. assert pool.connect acquires client with release callback
const client1 = await pool.connect();
assert.strictEqual(typeof client1.release, 'function', 'acquired client must have release function');
assert.strictEqual(pool.totalCount, 1, 'totalCount should be 1 after connect');
assert.strictEqual(pool.idleCount, 0, 'idleCount should be 0 while client is active');

// 4. assert client.release returns connection to idle pool for reuse
client1.release();
assert.strictEqual(pool.totalCount, 1, 'totalCount should remain 1');
assert.strictEqual(pool.idleCount, 1, 'idleCount should be 1 after release');

const client2 = await pool.connect();
assert.strictEqual(client2, client1, 'subsequent connect should reuse idle client');
assert.strictEqual(pool.idleCount, 0, 'idleCount should be 0 after re-acquiring');

// 5. assert client.release throws on double release
assert.throws(
  () => {
    client1.release();
    client1.release();
  },
  {
    message: 'Release called on client which has already been released to the pool.',
  },
  'calling release multiple times must throw error'
);

// 6. assert client.release with error removes connection from pool
const errorClient = await pool.connect();
assert.strictEqual(pool.totalCount, 1, 'totalCount should be 1');
errorClient.release(new Error('Connection broken'));
assert.strictEqual(pool.totalCount, 0, 'client released with error must be removed from pool');
assert.strictEqual(pool.idleCount, 0, 'idleCount should be 0 after removal');

// 7. assert pool.query delegates execution and returns client to idle pool
const queryRes = await executeQuery(pool, 'SELECT $1::text as msg', ['hello']);
assert.strictEqual(queryRes.rowCount, 1, 'query result should contain 1 row');
assert.strictEqual(queryRes.rows[0].text, 'SELECT $1::text as msg', 'query text should match');
assert.deepStrictEqual(queryRes.rows[0].params, ['hello'], 'query params should match');
assert.strictEqual(pool.totalCount, 1, 'pool.query should leave client in pool');
assert.strictEqual(pool.idleCount, 1, 'client used by pool.query should return to idle');

// 8. assert withClient helper runs operation and safely releases client
const helperRes = await withClient(pool, async (client) => {
  assert.strictEqual(typeof client.query, 'function', 'client in withClient must have query method');
  const res = await client.query('SELECT 42');
  return res.rows[0].id;
});
assert.strictEqual(helperRes, 1, 'withClient should return callback result');
assert.strictEqual(pool.idleCount, 1, 'withClient must release client back to idle pool');

// 9. assert pool emits connect, acquire, and release lifecycle events
const events = [];
pool.on('connect', () => events.push('connect'));
pool.on('acquire', () => events.push('acquire'));
pool.on('release', () => events.push('release'));

const client3 = await pool.connect();
assert.ok(events.includes('acquire'), 'pool must emit acquire event');
client3.release();
assert.ok(events.includes('release'), 'pool must emit release event');

// 10. assert pool.end drains pool and subsequent connect and query attempts reject
await drainPool(pool);
assert.strictEqual(pool.totalCount, 0, 'totalCount must be 0 after pool.end()');
assert.strictEqual(pool.idleCount, 0, 'idleCount must be 0 after pool.end()');

await assert.rejects(
  () => pool.connect(),
  {
    message: 'Cannot use a pool after calling end on the pool',
  },
  'connect after end must reject'
);

await assert.rejects(
  () => pool.query('SELECT 1'),
  {
    message: 'Cannot use a pool after calling end on the pool',
  },
  'query after end must reject'
);

console.log('All pg.Pool contract assertions passed.');

原始种子者

匿名