CodeSampleX

サンプル

pg 8.23.0: Client.query

検証済みサンプル — npm pg 8.23.0: Client.query. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: Client is exported as a constructor function and…

sha256:554588895e552aa679948f08852134f6e5f0f4b0cb8eb9633bbe7a1664759180

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

検証実行環境

環境 コントラクト ステージ 実行日
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 Client.query in pkg:npm/pg@8.23.0
パッケージ
シンボル
  • Client.query
環境
node 22.23.2
作成日
2026-08-30T14:39:29Z

コントラクト

  1. Client is exported as a constructor function and Client.prototype.query is a function
  2. Client.prototype.query throws TypeError when query configuration is null or undefined
  3. Client.prototype.query throws TypeError when callback argument is not a function
  4. Client.prototype.query accepts and returns custom submittable query objects
  5. Client.prototype.query executes simple text queries and resolves with query result rows, rowCount, and field metadata
  6. Client.prototype.query executes parameterized queries with positional parameters
  7. Client.prototype.query executes queries specified with query config objects
  8. Client.prototype.query supports callback-style invocation with error and result arguments
  9. Client.prototype.query rejects with DatabaseError when the server returns an error response

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 Client.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:
  - Client.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:ceb57fd45bc34bc21689518ac2f9fe0ba8ed2cf0d4a921e33533fccfc83c061d","contract":["Client is exported as a constructor function and Client.prototype.query is a function","Client.prototype.query throws TypeError when query configuration is null or undefined","Client.prototype.query throws TypeError when callback argument is not a function","Client.prototype.query accepts and returns custom submittable query objects","Client.prototype.query executes simple text queries and resolves with query result rows, rowCount, and field metadata","Client.prototype.query executes parameterized queries with positional parameters","Client.prototype.query executes queries specified with query config objects","Client.prototype.query supports callback-style invocation with error and result arguments","Client.prototype.query rejects with DatabaseError when the server returns an error response"],"goal":"verify Client.query in pkg:npm/pg@8.23.0","kind":"HOW","packages":["pkg:npm/pg@8.23.0"],"schemaVersion":1,"symbols":["Client.query"]},"contractCommand":["node","test/contract.mjs"],"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":["Client.query"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-pg-client-query",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pg-client-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-client-query",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of Client.query in pg",
  "main": "src/index.js",
  "dependencies": {
    "pg": "8.23.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Client.query in pkg:npm/pg@8.23.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pg@8.23.0"
  ],
  "symbols": [
    "Client.query"
  ]
}
src/index.js
const { Client } = require('pg');

/**
 * Creates a configured PostgreSQL Client instance.
 * @param {import('pg').ClientConfig} [config] - Client configuration.
 * @returns {Client}
 */
function createClient(config) {
  return new Client(config);
}

/**
 * Execute a query against a PostgreSQL client using Promise interface.
 * @param {Client} client - Connected or target PostgreSQL client.
 * @param {string | object} sqlOrConfig - SQL statement or query config.
 * @param {any[]} [values] - Optional query parameters.
 * @returns {Promise<import('pg').QueryResult>}
 */
function executeQuery(client, sqlOrConfig, values) {
  if (values !== undefined) {
    return client.query(sqlOrConfig, values);
  }
  return client.query(sqlOrConfig);
}

/**
 * Execute a query with a node-style callback.
 * @param {Client} client - PostgreSQL client.
 * @param {string | object} sqlOrConfig - SQL statement or query config.
 * @param {any[] | Function} valuesOrCallback - Parameters array or callback function.
 * @param {Function} [callback] - Callback function if parameters array is passed.
 */
function executeQueryCallback(client, sqlOrConfig, valuesOrCallback, callback) {
  if (typeof valuesOrCallback === 'function') {
    return client.query(sqlOrConfig, valuesOrCallback);
  }
  return client.query(sqlOrConfig, valuesOrCallback, callback);
}

/**
 * Execute a custom submittable query object.
 * @param {Client} client - PostgreSQL client.
 * @param {object} submittable - Custom query with submit method.
 * @returns {object} The submittable query object.
 */
function executeCustomQuery(client, submittable) {
  return client.query(submittable);
}

module.exports = {
  Client,
  createClient,
  executeQuery,
  executeQueryCallback,
  executeCustomQuery
};
test/contract.mjs
import assert from 'node:assert';
import net from 'node:net';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Client,
  createClient,
  executeQuery,
  executeQueryCallback,
  executeCustomQuery
} = require('../src/index.js');

// 1. Export and prototype verification
assert.strictEqual(typeof Client, 'function', 'Client should be exported as a constructor');
assert.strictEqual(typeof createClient, 'function', 'createClient should be exported as a function');
assert.strictEqual(typeof executeQuery, 'function', 'executeQuery should be exported as a function');
assert.strictEqual(typeof executeQueryCallback, 'function', 'executeQueryCallback should be exported as a function');
assert.strictEqual(typeof executeCustomQuery, 'function', 'executeCustomQuery should be exported as a function');
assert.strictEqual(typeof Client.prototype.query, 'function', 'Client.prototype.query must be a function');

// 2. Input validation: null / undefined query config throws TypeError
const unstartedClient = createClient();
assert.throws(
  () => unstartedClient.query(null),
  {
    name: 'TypeError',
    message: /Client was passed a null or undefined query/
  },
  'Client.query(null) should throw TypeError'
);
assert.throws(
  () => unstartedClient.query(undefined),
  {
    name: 'TypeError',
    message: /Client was passed a null or undefined query/
  },
  'Client.query(undefined) should throw TypeError'
);

// 3. Input validation: invalid callback throws TypeError
assert.throws(
  () => unstartedClient.query('SELECT 1', [], 'invalid-callback'),
  {
    name: 'TypeError',
    message: /callback is not a function/
  },
  'Client.query with non-function callback should throw TypeError'
);
assert.throws(
  () => unstartedClient.query({ text: 'SELECT 1', callback: 'invalid-callback' }),
  {
    name: 'TypeError',
    message: /callback is not a function/
  },
  'Client.query with invalid callback property should throw TypeError'
);

// 4. Custom Submittable object support
let submittedConn = null;
const customSubmittable = {
  submit(conn) {
    submittedConn = conn;
    return null;
  }
};
const returnedSubmittable = executeCustomQuery(unstartedClient, customSubmittable);
assert.strictEqual(returnedSubmittable, customSubmittable, 'Client.query should return custom submittable instance');

// Helper to construct postgres wire messages for offline mock server
function createMsg(type, body = Buffer.alloc(0)) {
  const len = body.length + 4;
  const header = Buffer.alloc(5);
  header.write(type, 0);
  header.writeInt32BE(len, 1);
  return Buffer.concat([header, body]);
}

function buildRowDescription(fields) {
  const buffers = [Buffer.alloc(2)];
  buffers[0].writeInt16BE(fields.length, 0);
  for (const f of fields) {
    const nameBuf = Buffer.from(f.name + '\0', 'utf8');
    const meta = Buffer.alloc(18);
    meta.writeInt32BE(f.tableID || 0, 0);
    meta.writeInt16BE(f.columnID || 0, 4);
    meta.writeInt32BE(f.dataTypeID || 25, 6);
    meta.writeInt16BE(f.dataTypeSize || -1, 10);
    meta.writeInt32BE(f.dataTypeModifier || -1, 12);
    meta.writeInt16BE(f.format || 0, 16);
    buffers.push(nameBuf, meta);
  }
  return createMsg('T', Buffer.concat(buffers));
}

function buildDataRow(values) {
  const buffers = [Buffer.alloc(2)];
  buffers[0].writeInt16BE(values.length, 0);
  for (const val of values) {
    if (val === null || val === undefined) {
      const lenBuf = Buffer.alloc(4);
      lenBuf.writeInt32BE(-1, 0);
      buffers.push(lenBuf);
    } else {
      const strBuf = Buffer.from(String(val), 'utf8');
      const lenBuf = Buffer.alloc(4);
      lenBuf.writeInt32BE(strBuf.length, 0);
      buffers.push(lenBuf, strBuf);
    }
  }
  return createMsg('D', Buffer.concat(buffers));
}

function buildCommandComplete(tag) {
  return createMsg('C', Buffer.from(tag + '\0', 'utf8'));
}

function buildReadyForQuery(status = 'I') {
  const b = Buffer.alloc(1);
  b.write(status, 0);
  return createMsg('Z', b);
}

function buildAuthenticationOk() {
  const b = Buffer.alloc(4);
  b.writeInt32BE(0, 0);
  return createMsg('R', b);
}

function buildErrorResponse(message, code = '42000') {
  const payload = Buffer.concat([
    Buffer.from('SERROR\0', 'utf8'),
    Buffer.from('C' + code + '\0', 'utf8'),
    Buffer.from('M' + message + '\0', 'utf8'),
    Buffer.from('\0')
  ]);
  return createMsg('E', payload);
}

// 5. Run offline protocol verification against an in-memory mock PostgreSQL server
async function runProtocolTests() {
  const server = net.createServer((socket) => {
    let isStartup = true;

    socket.on('data', (chunk) => {
      if (isStartup) {
        isStartup = false;
        socket.write(Buffer.concat([buildAuthenticationOk(), buildReadyForQuery()]));
        return;
      }

      let offset = 0;
      const responses = [];

      while (offset < chunk.length) {
        const type = String.fromCharCode(chunk[offset]);
        if (type === 'X') {
          socket.end();
          return;
        }

        const len = chunk.readInt32BE(offset + 1);
        const payload = chunk.slice(offset + 5, offset + 1 + len);

        if (type === 'Q') {
          const sql = payload.toString('utf8').replace(/\0$/, '');
          if (sql.includes('SYNTAX_ERROR')) {
            responses.push(buildErrorResponse('syntax error in query', '42601'), buildReadyForQuery());
          } else if (sql.includes('SELECT 1')) {
            responses.push(
              buildRowDescription([{ name: 'num', dataTypeID: 23 }]),
              buildDataRow(['1']),
              buildCommandComplete('SELECT 1'),
              buildReadyForQuery()
            );
          } else if (sql.includes('SELECT NOW')) {
            responses.push(
              buildRowDescription([{ name: 'ts', dataTypeID: 25 }]),
              buildDataRow(['2026-08-30 00:00:00']),
              buildCommandComplete('SELECT 1'),
              buildReadyForQuery()
            );
          }
        } else if (type === 'P') {
          responses.push(createMsg('1')); // ParseComplete
        } else if (type === 'B') {
          responses.push(createMsg('2')); // BindComplete
        } else if (type === 'D') {
          responses.push(buildRowDescription([
            { name: 'greeting', dataTypeID: 25 },
            { name: 'val', dataTypeID: 23 }
          ]));
        } else if (type === 'E') {
          responses.push(
            buildDataRow(['hello world', '42']),
            buildCommandComplete('SELECT 1')
          );
        } else if (type === 'S') {
          responses.push(buildReadyForQuery());
        }

        offset += 1 + len;
      }

      if (responses.length > 0) {
        socket.write(Buffer.concat(responses));
      }
    });
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const port = server.address().port;

  const client = createClient({
    host: '127.0.0.1',
    port,
    user: 'test_user',
    database: 'test_db'
  });

  try {
    await client.connect();

    // 5a. Simple text query via Promise
    const simpleResult = await executeQuery(client, 'SELECT 1 AS num');
    assert.strictEqual(simpleResult.command, 'SELECT');
    assert.strictEqual(simpleResult.rowCount, 1);
    assert.strictEqual(simpleResult.fields.length, 1);
    assert.strictEqual(simpleResult.fields[0].name, 'num');
    assert.deepStrictEqual(simpleResult.rows, [{ num: 1 }]);

    // 5b. Parameterized query via Promise
    const paramResult = await executeQuery(
      client,
      'SELECT $1::text AS greeting, $2::int AS val',
      ['hello world', 42]
    );
    assert.strictEqual(paramResult.rowCount, 1);
    assert.strictEqual(paramResult.fields.length, 2);
    assert.strictEqual(paramResult.fields[0].name, 'greeting');
    assert.strictEqual(paramResult.fields[1].name, 'val');
    assert.deepStrictEqual(paramResult.rows, [{ greeting: 'hello world', val: 42 }]);

    // 5c. Query config object
    const configResult = await executeQuery(client, {
      text: 'SELECT 1 AS num'
    });
    assert.deepStrictEqual(configResult.rows, [{ num: 1 }]);

    // 5d. Callback-based query execution
    const callbackResult = await new Promise((resolve, reject) => {
      executeQueryCallback(client, 'SELECT NOW() AS ts', (err, res) => {
        if (err) return reject(err);
        resolve(res);
      });
    });
    assert.strictEqual(callbackResult.rowCount, 1);
    assert.strictEqual(callbackResult.rows[0].ts, '2026-08-30 00:00:00');

    // 5e. Error handling for failing query
    await assert.rejects(
      async () => {
        await executeQuery(client, 'SYNTAX_ERROR');
      },
      (err) => {
        assert.strictEqual(err.code, '42601');
        assert.ok(err.message.includes('syntax error in query'));
        return true;
      },
      'Client.query should reject with DatabaseError on backend query failure'
    );
  } finally {
    await client.end();
    await new Promise((resolve) => server.close(resolve));
  }
}

await runProtocolTests();
console.log('Contract tests passed successfully.');

オリジンシーダー

匿名