CodeSampleX

Ejemplo

pg 8.23.0: Pool.connect

Muestra verificada para npm pg 8.23.0: Pool.connect. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: Pool.connect resolves a connected…

sha256:a3175f0a8d79d4687264eb36a31a8eaa4b1323384a5b4433087be727de6f6e49

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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.connect in pkg:npm/pg@8.23.0
Paquetes
Símbolos
  • Pool.connect
Entorno
node 22.23.2
Creado
2026-08-30T14:40:11Z

Contrato

  1. Pool.connect resolves a connected client with query and release methods and increments totalCount.
  2. client.release returns the acquired connection back to the pool idle queue.
  3. Pool.connect accepts a callback with signature (err, client, release) and executes asynchronously.
  4. pool.end terminates the connection pool and causes subsequent Pool.connect calls to reject with an error.
  5. Pool.connect rejects with a connection error when connecting to an unreachable host or port.

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# PostgreSQL Client Pool Connection (Pool.connect)

## Pinned Release
- Package: `pg`
- Resolved Version: `8.23.0`
- Ecosystem: npm

## Observed Behaviors and Contract Proofs

### 1. Promise-based Client Acquisition
`Pool.connect()` resolves a connected `pg.PoolClient` instance exposing `.query()` and `.release()` methods. Acquiring a client increments the pool's `totalCount` and keeps `idleCount` at 0 while the connection is checked out.

### 2. Client Return via release()
Calling `client.release()` returns the active client connection back to the pool's idle queue, incrementing `idleCount` while maintaining `totalCount`.

### 3. Callback-based Signature Support
`Pool.connect((err, client, release) => ...)` provides backward-compatible callback execution, passing the client instance and a dedicated release function to the callback on success.

### 4. Pool Termination and Subsequent Connect Rejection
Calling `pool.end()` terminates all active and idle pool connections and sets `pool.ended = true`. Subsequent invocations of `pool.connect()` reject with an error stating `Cannot use a pool after calling end on the pool`.

### 5. Connection Error Rejection on Unreachable Hosts
When configuring the pool with an unreachable host or port, `pool.connect()` rejects with a connection error (such as `ECONNREFUSED`) within the configured `connectionTimeoutMillis`.
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.connect 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.connect
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:dd868b04b9f1f9ad39f94722eb05de91feb97f83c7891dbbf474c90db95d5b80","constraints":{"executionContext":"node"},"contract":["Pool.connect resolves a connected client with query and release methods and increments totalCount.","client.release returns the acquired connection back to the pool idle queue.","Pool.connect accepts a callback with signature (err, client, release) and executes asynchronously.","pool.end terminates the connection pool and causes subsequent Pool.connect calls to reject with an error.","Pool.connect rejects with a connection error when connecting to an unreachable host or port."],"goal":"verify Pool.connect in pkg:npm/pg@8.23.0","kind":"HOW","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"symbols":["Pool.connect"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"subject":"pkg:npm/pg@8.23.0","symbols":["Pool.connect"],"verifierAdapter":"node-typescript@1"}
index.js
const { Pool } = require('pg');

/**
 * Creates a PostgreSQL connection pool and acquires a client.
 * Demonstrates Pool.connect with Promise and callback handling,
 * client release, and pool termination.
 */
async function acquireAndUseClient(config) {
  const pool = new Pool(config);
  try {
    const client = await pool.connect();
    return { pool, client };
  } catch (err) {
    await pool.end().catch(() => {});
    throw err;
  }
}

module.exports = {
  Pool,
  acquireAndUseClient,
};
package-lock.json
{
  "name": "sample-pg-pool-connect",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pg-pool-connect",
      "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-connect",
  "version": "1.0.0",
  "description": "verify Pool.connect in pkg:npm/pg@8.23.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "pg": "8.23.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Pool.connect in pkg:npm/pg@8.23.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pg@8.23.0"
  ],
  "symbols": [
    "Pool.connect"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
const assert = require('assert');
const net = require('net');
const { Pool } = require('pg');

// Helper to create a mock PostgreSQL server
function createMockPgServer() {
  return new Promise((resolve, reject) => {
    const server = net.createServer((socket) => {
      socket.on('data', (data) => {
        if (data.length < 8) return;
        const code = data.readInt32BE(4);
        if (code === 80877103) {
          // SSLRequest: reject SSL with 'N'
          socket.write(Buffer.from([0x4e]));
          return;
        }

        // AuthenticationOk: 'R' len=8 authType=0
        const authOk = Buffer.from([0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00]);
        // ReadyForQuery: 'Z' len=5 status='I' (idle)
        const readyForQuery = Buffer.from([0x5a, 0x00, 0x00, 0x00, 0x05, 0x49]);
        socket.write(Buffer.concat([authOk, readyForQuery]));
      });
    });

    server.listen(0, '127.0.0.1', () => {
      const { port } = server.address();
      resolve({ server, port });
    });
    server.on('error', reject);
  });
}

async function runTests() {
  const { server, port } = await createMockPgServer();

  try {
    // 1. Pool.connect() resolves a connected client with query and release methods
    const pool = new Pool({
      host: '127.0.0.1',
      port,
      user: 'testuser',
      database: 'testdb',
      max: 5,
      idleTimeoutMillis: 1000,
    });

    assert.strictEqual(typeof pool.connect, 'function', 'Pool must have connect method');
    assert.strictEqual(pool.totalCount, 0, 'Initial pool totalCount should be 0');
    assert.strictEqual(pool.idleCount, 0, 'Initial pool idleCount should be 0');

    const client = await pool.connect();
    assert.ok(client, 'pool.connect() must resolve client');
    assert.strictEqual(typeof client.release, 'function', 'client must have release method');
    assert.strictEqual(typeof client.query, 'function', 'client must have query method');
    assert.strictEqual(pool.totalCount, 1, 'totalCount becomes 1 after connect');
    assert.strictEqual(pool.idleCount, 0, 'idleCount is 0 while client is acquired');

    // 2. client.release() returns the connection to pool idle queue
    client.release();
    assert.strictEqual(pool.idleCount, 1, 'idleCount becomes 1 after client.release()');
    assert.strictEqual(pool.totalCount, 1, 'totalCount remains 1 while pooled');

    // 3. Pool.connect(callback) supports callback signature (err, client, release)
    await new Promise((resolve, reject) => {
      pool.connect((err, cbClient, release) => {
        if (err) return reject(err);
        try {
          assert.ok(cbClient, 'Callback should receive client');
          assert.strictEqual(typeof release, 'function', 'Callback should receive release function');
          release();
          resolve();
        } catch (e) {
          release();
          reject(e);
        }
      });
    });

    // 4. pool.end() closes connections and rejects subsequent pool.connect() calls
    await pool.end();
    assert.strictEqual(pool.ended, true, 'pool.ended should be true after pool.end()');

    let postEndErr = null;
    try {
      await pool.connect();
    } catch (err) {
      postEndErr = err;
    }
    assert.ok(postEndErr, 'pool.connect() after pool.end() must throw/reject');
    assert.match(postEndErr.message, /Cannot use a pool after calling end/i);

    // 5. pool.connect() rejects with connection error when destination is unreachable
    const unreachablePool = new Pool({
      host: '127.0.0.1',
      port: 1, // Closed/unreachable port
      connectionTimeoutMillis: 1000,
    });

    let connErr = null;
    try {
      await unreachablePool.connect();
    } catch (err) {
      connErr = err;
    } finally {
      await unreachablePool.end().catch(() => {});
    }
    assert.ok(connErr, 'Connecting to unreachable host/port must reject');
    assert.ok(
      connErr.code === 'ECONNREFUSED' || /connect/i.test(connErr.message),
      `Expected ECONNREFUSED or connection error, got ${connErr.message}`
    );

    console.log('All Pool.connect contract tests passed successfully.');
  } finally {
    server.close();
  }
}

runTests().catch((err) => {
  console.error('Test failed:', err);
  process.exit(1);
});

Seeder de origen

anónimo