Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat(typescript): add PostgreSQL (pg) instrumentation (#1245) (#1312)

Impactquadrant50cd885299bf
diff --git a/sdk/typescript/src/instrumentation/__tests__/pg-trace-comparison.test.ts b/sdk/typescript/src/instrumentation/__tests__/pg-trace-comparison.test.ts
new file mode 100644
index 00000000..a3f02f9a
--- /dev/null
+++ b/sdk/typescript/src/instrumentation/__tests__/pg-trace-comparison.test.ts
@@ -0,0 +1,603 @@
+/**
+ * Cross-Language Trace Comparison Tests for PostgreSQL (`pg`) Integration
+ *
+ * Verifies that the TypeScript SDK generates traces consistent with the Python SDK
+ * psycopg instrumentation for PostgreSQL queries.
+ *
+ * Python SDK reference: sdk/python/src/openlit/instrumentation/psycopg/utils.py
+ *
+ * Key alignment:
+ * - db.system.name = 'postgresql'
+ * - db.operation.name parsed from the SQL verb (SELECT/INSERT/UPDATE/DELETE/...)
+ * - db.collection.name = target table
+ * - db.namespace = database name
+ * - server.address, server.port (default localhost:5432)
+ * - db.query.text (when captureMessageContent is enabled)
+ * - db.query.parameter.<index> (only when captureDbParameters is enabled)
+ * - db.search.similarity_metric for pgvector operators (<=>, <->, <#>)
+ * - db.query.summary
+ * - db.response.returned_rows from result.rowCount
+ */
+
+import PgWrapper from '../pg/wrapper';
+import OpenlitConfig from '../../config';
+import OpenLitHelper, { applyCustomSpanAttributes } from '../../helpers';
+import Metrics from '../../otel/metrics';
+import SemanticConvention from '../../semantic-convention';
+import { ATTR_SERVICE_NAME, ATTR_TELEMETRY_SDK_NAME, SEMRESATTRS_DEPLOYMENT_ENVIRONMENT } from '@opentelemetry/semantic-conventions';
+import { SpanKind } from '@opentelemetry/api';
+import { isTracingSuppressed } from '@opentelemetry/core';
+
+jest.mock('../../config');
+jest.mock('../../helpers', () => ({
+ __esModule: true,
+ default: { handleException: jest.fn() },
+ applyCustomSpanAttributes: jest.fn(),
+}));
+jest.mock('../../otel/metrics', () => ({
+ __esModule: true,
+ default: {
+ dbRequests: { add: jest.fn() },
+ dbClientOperationDuration: { record: jest.fn() },
+ },
+}));
+jest.mock('@opentelemetry/core', () => ({
+ isTracingSuppressed: jest.fn().mockReturnValue(false),
+}));
+
+describe('PostgreSQL (pg) Cross-Language Trace Comparison', () => {
+ let mockSpan: any;
+ let mockTracer: any;
+
+ beforeEach(() => {
+ mockSpan = {
+ setAttribute: jest.fn(),
+ addEvent: jest.fn(),
+ end: jest.fn(),
+ setStatus: jest.fn(),
+ };
+
+ mockTracer = {
+ startSpan: jest.fn().mockReturnValue(mockSpan),
+ };
+
+ (OpenlitConfig as any).environment = 'openlit-testing';
+ (OpenlitConfig as any).applicationName = 'openlit-test';
+ (OpenlitConfig as any).captureMessageContent = true;
+ (OpenlitConfig as any).maxContentLength = null;
+ (OpenlitConfig as any).disableMetrics = false;
+ (OpenLitHelper as any).handleException = jest.fn();
+ (isTracingSuppressed as jest.Mock).mockReturnValue(false);
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ // Fake `pg` Client instance carrying connection parameters.
+ const fakeClient = () => ({
+ connectionParameters: { host: 'db.example.com', port: 5433, database: 'app_db' },
+ });
+
+ // Invoke the patched query() in promise form and await completion.
+ async function invokePromise(
+ args: any[],
+ result: any = { rowCount: 0 },
+ config: { captureDbParameters?: boolean } = {}
+ ) {
+ const patchFn = PgWrapper._patchQuery(mockTracer, config);
+ const original = jest.fn().mockResolvedValue(result);
+ const wrapped = patchFn(original);
+ await wrapped.apply(fakeClient(), args);
+ return original;
+ }
+
+ // ── Pure-function parity checks (mirror Python utils) ───────────────────────
+
+ describe('SQL operation parsing (parseSqlOperation)', () => {
+ it('detects SELECT', () => {
+ expect(PgWrapper.parseSqlOperation('SELECT * FROM users')).toBe(
+ SemanticConvention.DB_OPERATION_SELECT
+ );
+ });
+ it('detects INSERT', () => {
+ expect(PgWrapper.parseSqlOperation('INSERT INTO users (id) VALUES (1)')).toBe(
+ SemanticConvention.DB_OPERATION_INSERT
+ );
+ });
+ it('falls back to QUERY for unknown statements', () => {
+ expect(PgWrapper.parseSqlOperation('EXPLAIN ANALYZE foo')).toBe(
+ SemanticConvention.DB_OPERATION_QUERY
+ );
+ });
+ it('resolves CTE (WITH ... SELECT) to the inner operation', () => {
+ expect(PgWrapper.parseSqlOperation('WITH t AS (...) SELECT * FROM t')).toBe(
+ SemanticConvention.DB_OPERATION_SELECT
+ );
+ });
+ });
+
+ describe('table extraction (extractTableName)', () => {
+ it('extracts table from SELECT ... FROM', () => {
+ expect(PgWrapper.extractTableName('SELECT * FROM items WHERE id = $1')).toBe('items');
+ });
+ it('extracts table from INSERT INTO', () => {
+ expect(PgWrapper.extractTableName('INSERT INTO documents (x) VALUES ($1)')).toBe('documents');
+ });
+ it('returns unknown when no table matches', () => {
+ expect(PgWrapper.extractTableName('COMMIT')).toBe('unknown');
+ });
+ });
+
+ describe('pgvector similarity detection (detectSimilarityMetric)', () => {
+ it('maps <=> to cosine', () => {
+ expect(PgWrapper.detectSimilarityMetric('... ORDER BY embedding <=> $1')).toBe('cosine');
+ });
+ it('maps <-> to l2', () => {
+ expect(PgWrapper.detectSimilarityMetric('... ORDER BY embedding <-> $1')).toBe('l2');
+ });
+ it('maps <#> to inner_product', () => {
+ expect(PgWrapper.detectSimilarityMetric('... ORDER BY embedding <#> $1')).toBe(
+ 'inner_product'
+ );
+ });
+ it('returns undefined when no operator present', () => {
+ expect(PgWrapper.detectSimilarityMetric('SELECT 1')).toBeUndefined();
+ });
+ });
+
+ // ── Common DB span attributes ───────────────────────────────────────────────
+
+ it('sets db.system.name = "postgresql"', async () => {
+ await invokePromise(['SELECT * FROM users']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_SYSTEM_NAME,
+ 'postgresql'
+ );
+ });
+
+ it('sets server.address and server.port from the client connection params', async () => {
+ await invokePromise(['SELECT 1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.SERVER_ADDRESS,
+ 'db.example.com'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_PORT, 5433);
+ });
+
+ it('defaults to localhost:5432 when connection params are missing (Python defaults)', async () => {
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockResolvedValue({ rowCount: 0 });
+ const wrapped = patchFn(original);
+ await wrapped.apply({}, ['SELECT 1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_ADDRESS, 'localhost');
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_PORT, 5432);
+ });
+
+ it('sets db.namespace from the database name', async () => {
+ await invokePromise(['SELECT 1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_NAMESPACE_POSTGRESQL,
+ 'app_db'
+ );
+ });
+
+ it('sets deployment.environment and service.name (not gen_ai.* env attrs)', async () => {
+ await invokePromise(['SELECT 1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT,
+ 'openlit-testing'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(ATTR_SERVICE_NAME, 'openlit-test');
+ expect(mockSpan.setAttribute).not.toHaveBeenCalledWith(
+ SemanticConvention.GEN_AI_ENVIRONMENT,
+ expect.anything()
+ );
+ expect(mockSpan.setAttribute).not.toHaveBeenCalledWith(
+ SemanticConvention.GEN_AI_APPLICATION_NAME,
+ expect.anything()
+ );
+ });
+
+ it('sets telemetry.sdk.name, gen_ai.operation.name=vectordb, and custom span attrs', async () => {
+ await invokePromise(['SELECT 1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(ATTR_TELEMETRY_SDK_NAME, 'openlit');
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.GEN_AI_OPERATION,
+ SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB
+ );
+ expect(applyCustomSpanAttributes).toHaveBeenCalledWith(mockSpan);
+ });
+
+ it('records db metrics when disableMetrics is false', async () => {
+ await invokePromise(['SELECT * FROM users'], { rowCount: 1 });
+ expect(Metrics.dbRequests.add).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({
+ [SemanticConvention.DB_SYSTEM_NAME]: 'postgresql',
+ [SemanticConvention.DB_OPERATION_NAME]: 'SELECT',
+ [SemanticConvention.SERVER_ADDRESS]: 'db.example.com',
+ [SemanticConvention.SERVER_PORT]: 5433,
+ [ATTR_SERVICE_NAME]: 'openlit-test',
+ [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: 'openlit-testing',
+ })
+ );
+ expect(Metrics.dbClientOperationDuration.record).toHaveBeenCalledWith(
+ expect.any(Number),
+ expect.objectContaining({
+ [SemanticConvention.DB_OPERATION_NAME]: 'SELECT',
+ })
+ );
+ });
+
+ it('skips db metrics when disableMetrics is true', async () => {
+ (OpenlitConfig as any).disableMetrics = true;
+ await invokePromise(['SELECT 1']);
+ expect(Metrics.dbRequests.add).not.toHaveBeenCalled();
+ expect(Metrics.dbClientOperationDuration.record).not.toHaveBeenCalled();
+ });
+
+ it('bypasses instrumentation when tracing is suppressed', async () => {
+ (isTracingSuppressed as jest.Mock).mockReturnValue(true);
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockResolvedValue({ rowCount: 0 });
+ const wrapped = patchFn(original);
+ await wrapped.apply(fakeClient(), ['SELECT 1']);
+ expect(original).toHaveBeenCalled();
+ expect(mockTracer.startSpan).not.toHaveBeenCalled();
+ });
+
+ // ── Basic query span ─────────────────────────────────────────────────────────
+
+ describe('basic query span', () => {
+ it('sets db.operation.name and db.collection.name', async () => {
+ await invokePromise(['SELECT id, name FROM users WHERE id = $1', [42]]);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_OPERATION_NAME,
+ 'SELECT'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_COLLECTION_NAME,
+ 'users'
+ );
+ });
+
+ it('names the span "<operation> <table>"', async () => {
+ await invokePromise(['SELECT * FROM users']);
+ expect(mockTracer.startSpan).toHaveBeenCalledWith('SELECT users', expect.anything());
+ });
+
+ it('captures query text when captureMessageContent is enabled', async () => {
+ await invokePromise(['SELECT * FROM users']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_QUERY_TEXT,
+ 'SELECT * FROM users'
+ );
+ });
+
+ it('sets db.response.returned_rows from result.rowCount', async () => {
+ await invokePromise(['SELECT * FROM users'], { rowCount: 7 });
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_RESPONSE_RETURNED_ROWS,
+ 7
+ );
+ });
+
+ it('sets db.query.summary', async () => {
+ await invokePromise(['SELECT * FROM users']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_QUERY_SUMMARY,
+ 'SELECT users'
+ );
+ });
+
+ it('ends the span and marks status OK', async () => {
+ await invokePromise(['SELECT 1']);
+ expect(mockSpan.setStatus).toHaveBeenCalledWith({ code: 1 });
+ expect(mockSpan.end).toHaveBeenCalled();
+ });
+ });
+
+ // ── pgvector query ───────────────────────────────────────────────────────────
+
+ describe('pgvector similarity query', () => {
+ it('sets db.search.similarity_metric = cosine for the <=> operator', async () => {
+ await invokePromise([
+ 'SELECT id FROM embeddings ORDER BY vec <=> $1 LIMIT 5',
+ ['[0.1,0.2]'],
+ ]);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_SEARCH_SIMILARITY_METRIC,
+ 'cosine'
+ );
+ });
+
+ it('includes the vector metric in the query summary', async () => {
+ await invokePromise(['SELECT id FROM embeddings ORDER BY vec <-> $1']);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_QUERY_SUMMARY,
+ 'SELECT embeddings (vector l2)'
+ );
+ });
+ });
+
+ // ── Full-text search ─────────────────────────────────────────────────────────
+
+ describe('full-text search query', () => {
+ it('appends (full-text) to the query summary for TSVECTOR queries', async () => {
+ await invokePromise(['SELECT id FROM docs WHERE body @@ to_tsquery($1)', ['search']]);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_QUERY_SUMMARY,
+ 'SELECT docs (full-text)'
+ );
+ });
+
+ it('detects full-text search via detectFullTextSearch()', () => {
+ expect(PgWrapper.detectFullTextSearch('SELECT * FROM docs WHERE col @@ TSQUERY')).toBe(true);
+ expect(PgWrapper.detectFullTextSearch('SELECT rank FROM ts_rank(col, q)')).toBe(true);
+ expect(PgWrapper.detectFullTextSearch('SELECT * FROM users')).toBe(false);
+ });
+ });
+
+ // ── Batch queries ────────────────────────────────────────────────────────────
+
+ describe('batch parameter arrays', () => {
+ it('names the span with (batch) and sets db.batch.size', async () => {
+ await invokePromise(
+ ['INSERT INTO users (name) VALUES ($1)', [['alice'], ['bob']]],
+ { rowCount: 2 },
+ { captureDbParameters: true }
+ );
+ expect(mockTracer.startSpan).toHaveBeenCalledWith('INSERT users (batch)', { kind: SpanKind.CLIENT });
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_BATCH_SIZE, 2);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.0`,
+ 'alice'
+ );
+ });
+ });
+
+ // ── captureDbParameters toggle ────────────────────────────────────────────────
+
+ describe('captureDbParameters toggle', () => {
+ it('does NOT capture query parameters when disabled (default)', async () => {
+ await invokePromise(['SELECT * FROM users WHERE id = $1', [42]], { rowCount: 1 }, {
+ captureDbParameters: false,
+ });
+ const paramCalls = mockSpan.setAttribute.mock.calls.filter((c: any[]) =>
+ String(c[0]).startsWith(SemanticConvention.DB_QUERY_PARAMETER)
+ );
+ expect(paramCalls).toHaveLength(0);
+ });
+
+ it('captures query parameters per-index when enabled', async () => {
+ await invokePromise(
+ ['SELECT * FROM users WHERE id = $1 AND status = $2', [42, 'active']],
+ { rowCount: 1 },
+ { captureDbParameters: true }
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.0`,
+ '42'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.1`,
+ 'active'
+ );
+ });
+
+ it('sanitizes Buffer parameters to <bytes:N> when enabled', async () => {
+ await invokePromise(
+ ['INSERT INTO files (data) VALUES ($1)', [Buffer.from('abc')]],
+ { rowCount: 1 },
+ { captureDbParameters: true }
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.0`,
+ '<bytes:3>'
+ );
+ });
+ });
+
+ // ── Query-config object form ──────────────────────────────────────────────────
+
+ it('supports the { text, values } query-config object form', async () => {
+ await invokePromise(
+ [{ text: 'UPDATE accounts SET balance = $1 WHERE id = $2', values: [100, 5] }],
+ { rowCount: 1 },
+ { captureDbParameters: true }
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_OPERATION_NAME,
+ 'UPDATE'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_COLLECTION_NAME,
+ 'accounts'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.0`,
+ '100'
+ );
+ });
+
+ // ── Callback form ─────────────────────────────────────────────────────────────
+
+ describe('callback form', () => {
+ it('finalizes the span and invokes the user callback on success', (done) => {
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn((_text: string, _vals: any, cb: any) =>
+ cb(null, { rowCount: 3 })
+ );
+ const wrapped = patchFn(original);
+ wrapped.apply(fakeClient(), [
+ 'SELECT * FROM logs',
+ [],
+ (err: any, res: any) => {
+ expect(err).toBeNull();
+ expect(res.rowCount).toBe(3);
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_RESPONSE_RETURNED_ROWS,
+ 3
+ );
+ expect(mockSpan.end).toHaveBeenCalled();
+ done();
+ },
+ ]);
+ });
+
+ it('records an exception and still invokes the callback on error', (done) => {
+ const error = new Error('connection refused');
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn((_text: string, cb: any) => cb(error, undefined));
+ const wrapped = patchFn(original);
+ wrapped.apply(fakeClient(), [
+ 'SELECT 1',
+ (err: any) => {
+ expect(err).toBe(error);
+ expect(OpenLitHelper.handleException).toHaveBeenCalledWith(mockSpan, error);
+ expect(mockSpan.end).toHaveBeenCalled();
+ done();
+ },
+ ]);
+ });
+ });
+
+ // ── Error handling (promise form) ───────────────────────────────────────────────
+
+ it('records an exception when the promise rejects', async () => {
+ const error = new Error('syntax error');
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockRejectedValue(error);
+ const wrapped = patchFn(original);
+ await expect(wrapped.apply(fakeClient(), ['SELET 1'])).rejects.toThrow('syntax error');
+ expect(OpenLitHelper.handleException).toHaveBeenCalledWith(mockSpan, error);
+ expect(mockSpan.end).toHaveBeenCalled();
+ });
+
+ // ── Submittable / Cursor form (result.on('end' | 'error')) ──────────────────────
+
+ describe('submittable / cursor form', () => {
+ // Minimal EventEmitter-like fake submittable (neither a promise nor a callback).
+ const makeSubmittable = (extra: Record<string, unknown> = {}) => {
+ const listeners: Record<string, Array<(...a: any[]) => void>> = {};
+ return {
+ ...extra,
+ on(event: string, cb: (...a: any[]) => void) {
+ (listeners[event] ||= []).push(cb);
+ return this;
+ },
+ emit(event: string, ...args: any[]) {
+ (listeners[event] || []).forEach((cb) => cb(...args));
+ },
+ };
+ };
+
+ it('finalizes the span when the submittable emits "end"', () => {
+ const submittable = makeSubmittable({ rowCount: 4 });
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockReturnValue(submittable);
+ const wrapped = patchFn(original);
+
+ const returned: any = wrapped.apply(fakeClient(), ['SELECT * FROM events']);
+ expect(returned).toBe(submittable); // submittable passed through unchanged
+ expect(mockSpan.end).not.toHaveBeenCalled(); // not finalized until completion
+
+ returned.emit('end');
+
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_SYSTEM_NAME,
+ 'postgresql'
+ );
+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(
+ SemanticConvention.DB_RESPONSE_RETURNED_ROWS,
+ 4
+ );
+ expect(mockSpan.setStatus).toHaveBeenCalledWith({ code: 1 }); // SpanStatusCode.OK
+ expect(mockSpan.end).toHaveBeenCalledTimes(1);
+ });
+
+ it('records an exception when the submittable emits "error"', () => {
+ const submittable = makeSubmittable();
+ const error = new Error('cursor failed');
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockReturnValue(submittable);
+ const wrapped = patchFn(original);
+
+ const returned: any = wrapped.apply(fakeClient(), ['SELECT * FROM events']);
+ returned.emit('error', error);
+
+ expect(OpenLitHelper.handleException).toHaveBeenCalledWith(mockSpan, error);
+ expect(mockSpan.end).toHaveBeenCalledTimes(1);
+ });
+
+ it('finalizes the span only once even if "end" fires after "error"', () => {
+ const submittable = makeSubmittable();
+ const error = new Error('boom');
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const original = jest.fn().mockReturnValue(submittable);
+ const wrapped = patchFn(original);
+
+ const returned: any = wrapped.apply(fakeClient(), ['SELECT 1']);
+ returned.emit('error', error);
+ returned.emit('end');
+
+ expect(OpenLitHelper.handleException).toHaveBeenCalledTimes(1);
+ expect(mockSpan.end).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // ── Single-span guarantee ──────────────────────────────────────────────────────
+
+ describe('exactly one span per logical query', () => {
+ it('creates exactly one span for a promise-form query', async () => {
+ await invokePromise(['SELECT * FROM users'], { rowCount: 1 });
+ expect(mockTracer.startSpan).toHaveBeenCalledTimes(1);
+ expect(mockSpan.end).toHaveBeenCalledTimes(1);
+ });
+
+ it('creates exactly one span for a pool.query() that delegates to client.query()', async () => {
+ // Model `pg`: Pool.query() checks out a Client and calls client.query().
+ // Only Client.query is patched, so a pool query must yield ONE span.
+ const patchFn = PgWrapper._patchQuery(mockTracer, {});
+ const realClientQuery = jest.fn().mockResolvedValue({ rowCount: 2 });
+ const patchedClientQuery = patchFn(realClientQuery);
+
+ const client = { ...fakeClient(), query: patchedClientQuery };
+ // Unpatched Pool.query delegating to the patched client query.
+ const poolQuery = (...args: any[]) => client.query(...args);
+
+ await poolQuery('SELECT * FROM users WHERE id = $1', [1]);
+
+ expect(mockTracer.startSpan).toHaveBeenCalledTimes(1);
+ expect(mockSpan.end).toHaveBeenCalledTimes(1);
+ });
+ });
+});
+
+// ── Instrumentation patching: only Client.query is wrapped, never Pool.query ──────
+
+describe('OpenlitPgInstrumentation patch targets', () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const PgInstrumentation = require('../pg').default;
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const { isWrapped } = require('@opentelemetry/instrumentation');
+
+ it('wraps Client.prototype.query but leaves Pool.prototype.query untouched', () => {
+ const clientQuery = function () {};
+ const poolQuery = function () {};
+ const fakePgModule = {
+ Client: function () {},
+ Pool: function () {},
+ } as any;
+ fakePgModule.Client.prototype.query = clientQuery;
+ fakePgModule.Pool.prototype.query = poolQuery;
+
+ const instr = new PgInstrumentation();
+ instr.manualPatch(fakePgModule);
+
+ expect(isWrapped(fakePgModule.Client.prototype.query)).toBe(true);
+ expect(isWrapped(fakePgModule.Pool.prototype.query)).toBe(false);
+ expect(fakePgModule.Pool.prototype.query).toBe(poolQuery); // unchanged
+ });
+});
diff --git a/sdk/typescript/src/instrumentation/index.ts b/sdk/typescript/src/instrumentation/index.ts
index 5eb7fdac..f0b5d343 100644
--- a/sdk/typescript/src/instrumentation/index.ts
+++ b/sdk/typescript/src/instrumentation/index.ts
@@ -36,6 +36,7 @@ import Mem0Instrumentation from './mem0';
import ElevenLabsInstrumentation from './elevenlabs';
import AssemblyAIInstrumentation from './assemblyai';
import TransformersInstrumentation from './transformers';
+import PgInstrumentation from './pg';
/**
* OTel community instrumentations loaded dynamically (like Python SDK).
@@ -114,6 +115,7 @@ export default class Instrumentations {
elevenlabs: new ElevenLabsInstrumentation(),
assemblyai: new AssemblyAIInstrumentation(),
transformers: new TransformersInstrumentation(),
+ pg: new PgInstrumentation(),
};
static setup(
diff --git a/sdk/typescript/src/instrumentation/pg/index.ts b/sdk/typescript/src/instrumentation/pg/index.ts
new file mode 100644
index 00000000..c3404b7c
--- /dev/null
+++ b/sdk/typescript/src/instrumentation/pg/index.ts
@@ -0,0 +1,93 @@
+import {
+ InstrumentationBase,
+ InstrumentationModuleDefinition,
+ InstrumentationNodeModuleDefinition,
+ InstrumentationConfig,
+ isWrapped,
+} from '@opentelemetry/instrumentation';
+import { diag } from '@opentelemetry/api';
+import { INSTRUMENTATION_PREFIX } from '../../constant';
+import PgWrapper from './wrapper';
+
+/**
+ * Configuration for the PostgreSQL (`pg`) instrumentation.
+ *
+ * `captureDbParameters` mirrors the Python psycopg instrumentor's
+ * `capture_db_parameters` flag. It is OFF by default because query parameters
+ * may contain PII / secrets. Enable only when you are certain parameters are safe.
+ */
+export interface PgInstrumentationConfig extends InstrumentationConfig {
+ captureDbParameters?: boolean;
+}
+
+export default class OpenlitPgInstrumentation extends InstrumentationBase {
+ private _clientProto: any = null;
+
+ constructor(config: PgInstrumentationConfig = {}) {
+ super(`${INSTRUMENTATION_PREFIX}/instrumentation-pg`, '1.0.0', config);
+ }
+
+ private get captureDbParameters(): boolean {
+ return Boolean((this.getConfig() as PgInstrumentationConfig)?.captureDbParameters);
+ }
+
+ protected init(): void | InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {
+ const module = new InstrumentationNodeModuleDefinition(
+ 'pg',
+ ['>=7.0.0', '>=8.0.0'],
+ (moduleExports, moduleVersion) => {
+ this._patch(moduleExports, moduleVersion);
+ return moduleExports;
+ },
+ (moduleExports) => {
+ if (moduleExports !== undefined) {
+ this._unpatch(moduleExports);
+ }
+ }
+ );
+ return [module];
+ }
+
+ public manualPatch(pg: any): void {
+ this._patch(pg);
+ }
+
+ protected _patch(moduleExports: any, moduleVersion?: string) {
+ try {
+ if (!moduleExports) return;
+ const sdkVersion = moduleVersion ? String(moduleVersion) : undefined;
+ const wrapperConfig = { captureDbParameters: this.captureDbParameters, sdkVersion };
+
+ // Wrap ONLY Client.prototype.query.
+ //
+ // We deliberately do NOT wrap Pool.prototype.query. In `pg`, Pool.query()
+ // checks out a pooled Client and delegates to that Client's query(), so
+ // client-level wrapping already captures pool-routed queries. Wrapping both
+ // would emit two spans for a single logical pool query (a Pool span plus a
+ // child Client span). This matches the OTel community pg instrumentation,
+ // which also instruments only the Client. Result: exactly one span per query.
+ const Client = moduleExports.Client;
+ if (Client?.prototype && typeof Client.prototype.query === 'function') {
+ if (isWrapped(Client.prototype.query)) {
+ this._unwrap(Client.prototype, 'query');
+ }
+ this._clientProto = Client.prototype;
+ this._wrap(Client.prototype, 'query', PgWrapper._patchQuery(this.tracer, wrapperConfig));
+ }
+ } catch (e) {
+ diag.error('pg instrumentation: error in _patch method', e);
+ }
+ }
+
+ protected _unpatch(moduleExports?: any) {
+ try {
+ if (moduleExports?.Client?.prototype && isWrapped(moduleExports.Client.prototype.query)) {
+ this._unwrap(moduleExports.Client.prototype, 'query');
+ } else if (this._clientProto && isWrapped(this._clientProto.query)) {
+ this._unwrap(this._clientProto, 'query');
+ }
+ } catch {
+ /* ignore */
+ }
+ }
+}
diff --git a/sdk/typescript/src/instrumentation/pg/wrapper.ts b/sdk/typescript/src/instrumentation/pg/wrapper.ts
new file mode 100644
index 00000000..9eea776a
--- /dev/null
+++ b/sdk/typescript/src/instrumentation/pg/wrapper.ts
@@ -0,0 +1,493 @@
+import {
+ Attributes,
+ SpanKind,
+ SpanStatusCode,
+ Span,
+ Tracer,
+ context,
+ trace,
+} from '@opentelemetry/api';
+import { isTracingSuppressed } from '@opentelemetry/core';
+import {
+ ATTR_SERVICE_NAME,
+ ATTR_TELEMETRY_SDK_NAME,
+ SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,
+} from '@opentelemetry/semantic-conventions';
+import OpenlitConfig from '../../config';
+import { SDK_NAME } from '../../constant';
+import OpenLitHelper, { applyCustomSpanAttributes } from '../../helpers';
+import Metrics from '../../otel/metrics';
+import SemanticConvention from '../../semantic-convention';
+import BaseWrapper from '../base-wrapper';
+
+/**
+ * PostgreSQL (`pg`) instrumentation wrapper.
+ *
+ * Mirrors the Python SDK psycopg instrumentation
+ * (sdk/python/src/openlit/instrumentation/psycopg) for the Node `pg` driver:
+ * - parses the SQL operation (SELECT/INSERT/...) and target table for span naming,
+ * - detects pgvector similarity operators (`<=>`, `<->`, `<#>`),
+ * - honors a `captureDbParameters` toggle to record query parameters
+ * (off by default — parameters can contain PII/secrets),
+ * - sets the same `db.*` semantic-convention attributes the Python SDK sets.
+ *
+ * The `pg` `query()` method has three call shapes which must all be handled:
+ * 1. callback: client.query(text, values?, (err, res) => {}) → no return value
+ * 2. promise: const res = await client.query(text, values?) → returns a thenable
+ * 3. submittable: client.query(new Query(...)) / cursors → returns the submittable
+ */
+
+// Maximum number of query parameters to capture (matches Python MAX_PARAMS_COUNT).
+const MAX_PARAMS_COUNT = 50;
+// Maximum captured parameter value length (matches Python MAX_PARAM_LENGTH).
+const MAX_PARAM_LENGTH = 256;
+
+// Map of leading SQL keyword → db.operation.name value (mirrors Python SQL_OPERATION_MAP).
+const SQL_OPERATION_MAP: Record<string, string> = {
+ SELECT: SemanticConvention.DB_OPERATION_SELECT,
+ INSERT: SemanticConvention.DB_OPERATION_INSERT,
+ UPDATE: SemanticConvention.DB_OPERATION_UPDATE,
+ DELETE: SemanticConvention.DB_OPERATION_DELETE,
+ COPY: SemanticConvention.DB_OPERATION_COPY,
+ CREATE: SemanticConvention.DB_OPERATION_CREATE,
+ ALTER: SemanticConvention.DB_OPERATION_ALTER,
+ DROP: SemanticConvention.DB_OPERATION_DROP,
+ TRUNCATE: SemanticConvention.DB_OPERATION_TRUNCATE,
+ COMMIT: SemanticConvention.DB_OPERATION_COMMIT,
+ ROLLBACK: SemanticConvention.DB_OPERATION_ROLLBACK,
+};
+
+// Table-name extraction patterns (mirrors Python TABLE_PATTERNS).
+const TABLE_PATTERNS: RegExp[] = [
+ /INSERT\s+INTO\s+["']?(\w+)["']?/i,
+ /UPDATE\s+["']?(\w+)["']?/i,
+ /DELETE\s+FROM\s+["']?(\w+)["']?/i,
+ /FROM\s+["']?(\w+)["']?/i,
+ /TRUNCATE\s+(?:TABLE\s+)?["']?(\w+)["']?/i,
+ /CREATE\s+(?:TABLE|INDEX)\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?(\w+)["']?/i,
+ /ALTER\s+TABLE\s+["']?(\w+)["']?/i,
+ /DROP\s+(?:TABLE|INDEX)\s+(?:IF\s+EXISTS\s+)?["']?(\w+)["']?/i,
+ /COPY\s+["']?(\w+)["']?/i,
+];
+
+export interface PgWrapperConfig {
+ captureDbParameters?: boolean;
+ sdkVersion?: string;
+}
+
+function recordDbMetrics(
+ dbOperation: string,
+ connInfo: { host: string; port: number },
+ durationSeconds: number,
+): void {
+ if (OpenlitConfig.disableMetrics) {
+ return;
+ }
+
+ const applicationName = OpenlitConfig.applicationName || '';
+ const environment = OpenlitConfig.environment || '';
+
+ const attributes: Attributes = {
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_NAME,
+ [ATTR_SERVICE_NAME]: applicationName,
+ [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]: environment,
+ [SemanticConvention.DB_SYSTEM_NAME]: PgWrapper.dbSystem,
+ [SemanticConvention.DB_OPERATION_NAME]: dbOperation,
+ [SemanticConvention.SERVER_ADDRESS]: connInfo.host,
+ [SemanticConvention.SERVER_PORT]: connInfo.port,
+ };
+
+ Metrics.dbRequests?.add(1, attributes);
+ Metrics.dbClientOperationDuration?.record(durationSeconds, attributes);
+}
+
+class PgWrapper extends BaseWrapper {
+ static dbSystem = SemanticConvention.DB_SYSTEM_POSTGRESQL;
+
+ /** Detect the SQL operation verb from a query string (mirrors Python parse_sql_operation). */
+ static parseSqlOperation(query: unknown): string {
+ if (query === null || query === undefined) {
+ return SemanticConvention.DB_OPERATION_QUERY;
+ }
+ const queryStr = String(query).trim();
+ if (!queryStr) {
+ return SemanticConvention.DB_OPERATION_QUERY;
+ }
+ const queryUpper = queryStr.toUpperCase();
+ for (const [keyword, operation] of Object.entries(SQL_OPERATION_MAP)) {
+ if (queryUpper.startsWith(keyword)) {
+ return operation;
+ }
+ }
+ // Handle WITH ... SELECT/INSERT/UPDATE/DELETE (CTEs).
+ if (queryUpper.startsWith('WITH')) {
+ for (const [keyword, operation] of Object.entries(SQL_OPERATION_MAP)) {
+ if (queryUpper.includes(keyword)) {
+ return operation;
+ }
+ }
+ }
+ return SemanticConvention.DB_OPERATION_QUERY;
+ }
+
+ /** Extract the target table name for span naming (mirrors Python extract_table_name). */
+ static extractTableName(query: unknown): string {
+ if (query === null || query === undefined) {
+ return 'unknown';
+ }
+ const queryStr = String(query);
+ for (const pattern of TABLE_PATTERNS) {
+ const match = pattern.exec(queryStr);
+ if (match) {
+ return match[1];
+ }
+ }
+ return 'unknown';
+ }
+
+ /** Detect pgvector similarity operator → metric name (mirrors Python detect_special_features). */
+ static detectSimilarityMetric(query: unknown): string | undefined {
+ if (query === null || query === undefined) {
+ return undefined;
+ }
+ const queryStr = String(query);
+ if (queryStr.includes('<=>')) return 'cosine';
+ if (queryStr.includes('<->')) return 'l2';
+ if (queryStr.includes('<#>')) return 'inner_product';
+ return undefined;
+ }
+
+ /** Detect full-text search keywords (mirrors Python detect_special_features). */
+ static detectFullTextSearch(query: unknown): boolean {
+ if (query === null || query === undefined) {
+ return false;
+ }
+ const queryUpper = String(query).toUpperCase();
+ return (
+ queryUpper.includes('TSVECTOR') ||
+ queryUpper.includes('TSQUERY') ||
+ queryUpper.includes('TS_RANK') ||
+ queryUpper.includes('WEBSEARCH_TO_TSQUERY')
+ );
+ }
+
+ /** Resolve batch size when values is an array of parameter arrays (executemany-style). */
+ static resolveBatchSize(values: unknown): number | undefined {
+ if (!Array.isArray(values) || values.length === 0) {
+ return undefined;
+ }
+ if (Array.isArray(values[0])) {
+ return values.length;
+ }
+ return undefined;
+ }
+
+ /** Build the human-readable query summary (mirrors Python get_query_summary). */
+ static getQuerySummary(dbOperation: string, tableName: string, query: unknown): string {
+ let summary = `${dbOperation} ${tableName}`;
+ const metric = PgWrapper.detectSimilarityMetric(query);
+ if (metric) {
+ summary += ` (vector ${metric})`;
+ }
+ if (PgWrapper.detectFullTextSearch(query)) {
+ summary += ' (full-text)';
+ }
+ return summary;
+ }
+
+ /** Sanitize a parameter value for safe inclusion in a span (mirrors Python sanitize_parameter). */
+ static sanitizeParameter(value: unknown): string {
+ if (value === null || value === undefined) {
+ return 'NULL';
+ }
+ if (value instanceof Uint8Array || Buffer.isBuffer(value)) {
+ return `<bytes:${(value as Uint8Array).length}>`;
+ }
+ let strValue: string;
+ try {
+ strValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
+ } catch {
+ return '<unrepresentable>';
+ }
+ if (strValue.length > MAX_PARAM_LENGTH) {
+ return `${strValue.slice(0, MAX_PARAM_LENGTH)}...<truncated:${strValue.length}>`;
+ }
+ return strValue;
+ }
+
+ /**
+ * Extract { host, port, database } from a `pg` Client / Pool instance.
+ * `pg` stores connection params on the instance (and Pool on `options`).
+ * Defaults mirror the Python psycopg instrumentation (localhost:5432).
+ */
+ static extractConnectionInfo(instance: any): { host: string; port: number; database?: string } {
+ const defaults = { host: 'localhost', port: 5432 };
+ try {
+ const params = instance?.connectionParameters || instance?.options || instance || {};
+ const host = params.host || defaults.host;
+ const port = params.port ? Number(params.port) : defaults.port;
+ const database = params.database;
+ return { host, port: Number.isFinite(port) ? port : defaults.port, database };
+ } catch {
+ return defaults;
+ }
+ }
+
+ /**
+ * Resolve the SQL text and the parameter values from the `pg` query() arguments.
+ * Supports: (text, values?, cb?), ({ text, values, name }, cb?), and submittables.
+ */
+ static resolveQuery(args: any[]): { queryText: unknown; values: unknown } {
+ const first = args[0];
+ if (typeof first === 'string') {
+ return { queryText: first, values: Array.isArray(args[1]) ? args[1] : undefined };
+ }
+ if (first && typeof first === 'object') {
+ // Query config object or a Submittable (Query/Cursor) — both may carry `text`/`values`.
+ const queryText = 'text' in first ? first.text : undefined;
+ const values = 'values' in first ? first.values : undefined;
+ return { queryText, values };
+ }
+ return { queryText: undefined, values: undefined };
+ }
+
+ /** Pull the last argument if it is a node-style callback. */
+ static extractCallback(args: any[]): ((...cbArgs: any[]) => void) | undefined {
+ const last = args[args.length - 1];
+ return typeof last === 'function' ? last : undefined;
+ }
+
+ /** Stamp all span attributes (mirrors Python common_psycopg_logic). */
+ static setSpanAttributes(
+ span: Span,
+ {
+ dbOperation,
+ tableName,
+ queryText,
+ values,
+ connInfo,
+ durationSeconds,
+ rowCount,
+ batchSize,
+ captureDbParameters,
+ sdkVersion,
+ }: {
+ dbOperation: string;
+ tableName: string;
+ queryText: unknown;
+ values: unknown;
+ connInfo: { host: string; port: number; database?: string };
+ durationSeconds: number;
+ rowCount?: number | null;
+ batchSize?: number;
+ captureDbParameters: boolean;
+ sdkVersion?: string;
+ }
+ ): void {
+ const applicationName = OpenlitConfig.applicationName || '';
+ const environment = OpenlitConfig.environment || '';
+
+ span.setAttribute(ATTR_TELEMETRY_SDK_NAME, SDK_NAME);
+ span.setAttribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB);
+ span.setAttribute(SemanticConvention.DB_SYSTEM_NAME, PgWrapper.dbSystem);
+ span.setAttribute(SemanticConvention.DB_OPERATION_NAME, dbOperation);
+ span.setAttribute(SemanticConvention.SERVER_ADDRESS, connInfo.host);
+ span.setAttribute(SemanticConvention.SERVER_PORT, connInfo.port);
+ span.setAttribute(SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT, environment);
+ span.setAttribute(ATTR_SERVICE_NAME, applicationName);
+ span.setAttribute(SemanticConvention.DB_CLIENT_OPERATION_DURATION, durationSeconds);
+ if (sdkVersion) {
+ span.setAttribute(SemanticConvention.DB_SDK_VERSION, sdkVersion);
+ }
+
+ if (connInfo.database && connInfo.database !== 'unknown') {
+ span.setAttribute(SemanticConvention.DB_NAMESPACE_POSTGRESQL, connInfo.database);
+ }
+ if (tableName && tableName !== 'unknown') {
+ span.setAttribute(SemanticConvention.DB_COLLECTION_NAME, tableName);
+ }
+ if (typeof batchSize === 'number' && batchSize > 0) {
+ span.setAttribute(SemanticConvention.DB_BATCH_SIZE, batchSize);
+ }
+
+ // Capture query text when message-content capture is enabled (parity w/ Python).
+ if (OpenlitConfig.captureMessageContent && queryText) {
+ let queryStr = String(queryText);
+ const maxLen = OpenlitConfig.maxContentLength;
+ if (typeof maxLen === 'number' && maxLen > 0 && queryStr.length > maxLen) {
+ queryStr = queryStr.slice(0, maxLen);
+ }
+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, queryStr);
+ }
+
+ // Capture query parameters (OTel per-index convention) only when explicitly enabled.
+ const paramsForCapture =
+ typeof batchSize === 'number' && batchSize > 0 && Array.isArray(values)
+ ? values[0]
+ : values;
+
+ if (captureDbParameters && paramsForCapture !== null && paramsForCapture !== undefined) {
+ if (Array.isArray(paramsForCapture)) {
+ paramsForCapture.slice(0, MAX_PARAMS_COUNT).forEach((value, idx) => {
+ span.setAttribute(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.${idx}`,
+ PgWrapper.sanitizeParameter(value)
+ );
+ });
+ } else if (typeof paramsForCapture === 'object') {
+ Object.entries(paramsForCapture as Record<string, unknown>)
+ .slice(0, MAX_PARAMS_COUNT)
+ .forEach(([key, value]) => {
+ span.setAttribute(
+ `${SemanticConvention.DB_QUERY_PARAMETER}.${key}`,
+ PgWrapper.sanitizeParameter(value)
+ );
+ });
+ }
+ }
+
+ span.setAttribute(
+ SemanticConvention.DB_QUERY_SUMMARY,
+ PgWrapper.getQuerySummary(dbOperation, tableName, queryText)
+ );
+
+ if (typeof rowCount === 'number' && rowCount >= 0) {
+ span.setAttribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, rowCount);
+ }
+
+ // pgvector similarity metric.
+ const metric = PgWrapper.detectSimilarityMetric(queryText);
+ if (metric) {
+ span.setAttribute(SemanticConvention.DB_SEARCH_SIMILARITY_METRIC, metric);
+ }
+
+ applyCustomSpanAttributes(span);
+ span.setStatus({ code: SpanStatusCode.OK });
+ recordDbMetrics(dbOperation, connInfo, durationSeconds);
+ }
+
+ /**
+ * Build the patched `query()` replacement. Handles callback, promise, and
+ * submittable forms while always producing a single CLIENT span.
+ */
+ static _patchQuery(tracer: Tracer, config: PgWrapperConfig = {}): any {
+ const captureDbParameters = Boolean(config.captureDbParameters);
+ const sdkVersion = config.sdkVersion;
+
+ return (originalQuery: (...args: any[]) => any) => {
+ return function (this: any, ...args: any[]) {
+ if (isTracingSuppressed(context.active())) {
+ return originalQuery.apply(this, args);
+ }
+
+ const { queryText, values } = PgWrapper.resolveQuery(args);
+ const dbOperation = PgWrapper.parseSqlOperation(queryText);
+ const tableName = PgWrapper.extractTableName(queryText);
+ const batchSize = PgWrapper.resolveBatchSize(values);
+ const connInfo = PgWrapper.extractConnectionInfo(this);
+ const spanName =
+ typeof batchSize === 'number' && batchSize > 0
+ ? `${dbOperation} ${tableName} (batch)`
+ : `${dbOperation} ${tableName}`;
+ const span = tracer.startSpan(spanName, { kind: SpanKind.CLIENT });
+ const startTime = Date.now();
+
+ const finalize = (result: any) => {
+ try {
+ const durationSeconds = (Date.now() - startTime) / 1000;
+ const rowCount =
+ result && typeof result.rowCount === 'number' ? result.rowCount : undefined;
+ PgWrapper.setSpanAttributes(span, {
+ dbOperation,
+ tableName,
+ queryText,
+ values,
+ connInfo,
+ durationSeconds,
+ rowCount,
+ batchSize,
+ captureDbParameters,
+ sdkVersion,
+ });
+ } catch (attrErr: any) {
+ OpenLitHelper.handleException(span, attrErr);
+ } finally {
+ span.end();
+ }
+ };
+
+ const fail = (error: any) => {
+ OpenLitHelper.handleException(span, error);
+ span.end();
+ };
+
+ return context.with(trace.setSpan(context.active(), span), () => {
+ const callback = PgWrapper.extractCallback(args);
+
+ // ── Callback form ────────────────────────────────────────────────
+ if (callback) {
+ const wrappedCallback = function (this: any, err: any, res: any) {
+ if (err) {
+ fail(err);
+ } else {
+ finalize(res);
+ }
+ return callback.apply(this, [err, res]);
+ };
+ const newArgs = args.slice(0, -1).concat(wrappedCallback);
+ try {
+ return originalQuery.apply(this, newArgs);
+ } catch (syncErr: any) {
+ fail(syncErr);
+ throw syncErr;
+ }
+ }
+
+ // ── Promise / submittable form ───────────────────────────────────
+ let result: any;
+ try {
+ result = originalQuery.apply(this, args);
+ } catch (syncErr: any) {
+ fail(syncErr);
+ throw syncErr;
+ }
+
+ if (result && typeof result.then === 'function') {
+ return result.then(
+ (res: any) => {
+ finalize(res);
+ return res;
+ },
+ (err: any) => {
+ fail(err);
+ throw err;
+ }
+ );
+ }
+
+ // Submittable (Query/Cursor) — no promise, no callback. Listen for completion.
+ if (result && typeof result.on === 'function') {
+ let settled = false;
+ result.on('end', () => {
+ if (settled) return;
+ settled = true;
+ finalize(result);
+ });
+ result.on('error', (err: any) => {
+ if (settled) return;
+ settled = true;
+ fail(err);
+ });
+ return result;
+ }
+
+ // Unknown shape — close the span without a row count.
+ finalize(result);
+ return result;
+ });
+ };
+ };
+ }
+}
+
+export default PgWrapper;
diff --git a/sdk/typescript/src/semantic-convention.ts b/sdk/typescript/src/semantic-convention.ts
index 0ab33cf3..32ba4b1b 100644
--- a/sdk/typescript/src/semantic-convention.ts
+++ b/sdk/typescript/src/semantic-convention.ts
@@ -504,6 +504,30 @@ export default class SemanticConvention {
static DB_WITH_PAYLOAD = 'db.with_payload';
static DB_OUTPUT_FIELDS = 'db.output_fields';
+ // ----- PostgreSQL (pg) instrumentation -----
+ // Mirrors Python SDK psycopg instrumentation (sdk/python/src/openlit/instrumentation/psycopg).
+ static DB_SYSTEM_POSTGRESQL = 'postgresql';
+ // OTel database namespace (database name). Python psycopg uses "db.namespace";
+ // the existing TS DB_NAMESPACE = "db.query.namespace" is a vector-DB attribute,
+ // so a dedicated constant keeps parity with the Python attribute value.
+ static DB_NAMESPACE_POSTGRESQL = 'db.namespace';
+ // SQL operation names (statement verbs) — values mirror Python semcov.
+ static DB_OPERATION_COMMIT = 'COMMIT';
+ static DB_OPERATION_ROLLBACK = 'ROLLBACK';
+ static DB_OPERATION_COPY = 'COPY';
+ static DB_OPERATION_CREATE = 'CREATE';
+ static DB_OPERATION_ALTER = 'ALTER';
+ static DB_OPERATION_DROP = 'DROP';
+ static DB_OPERATION_TRUNCATE = 'TRUNCATE';
+ static DB_OPERATION_CALL = 'CALL';
+ // pgvector similarity metric (set when a similarity operator is present).
+ static DB_SEARCH_SIMILARITY_METRIC = 'db.search.similarity_metric';
+ // PostgreSQL-specific extras (mirror Python semcov).
+ static DB_POSTGRESQL_ROWS_AFFECTED = 'db.postgresql.rows_affected';
+ static DB_POSTGRESQL_PLAN = 'db.postgresql.plan';
+ // Batch size attribute used by executemany-style batched queries.
+ static DB_BATCH_SIZE = 'db.batch.size';
+
// ----- Mem0 (memory layer) instrumentation -----
// Session scope (mirrors Python semcov; stamped on memory spans when present)
static GEN_AI_USER_ID = 'gen_ai.user.id';
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index d2059150..255276b2 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -3,7 +3,7 @@ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { metrics } from '@opentelemetry/api';
import type { Guard } from './guard/base';
-export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'vertexai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21' | 'gradient' | 'mcp' | 'mem0' | 'elevenlabs' | 'assemblyai' | 'transformers';
+export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'vertexai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21' | 'gradient' | 'mcp' | 'mem0' | 'elevenlabs' | 'assemblyai' | 'transformers' | 'pg';
export type OpenlitInstrumentations = Partial<Record<InstrumentationType, any>>;