postgresai 0.14.0-dev.7 → 0.14.0-dev.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +161 -61
- package/bin/postgres-ai.ts +1982 -404
- package/bun.lock +258 -0
- package/bunfig.toml +20 -0
- package/dist/bin/postgres-ai.js +29395 -1576
- package/dist/sql/01.role.sql +16 -0
- package/dist/sql/02.permissions.sql +37 -0
- package/dist/sql/03.optional_rds.sql +6 -0
- package/dist/sql/04.optional_self_managed.sql +8 -0
- package/dist/sql/05.helpers.sql +439 -0
- package/dist/sql/sql/01.role.sql +16 -0
- package/dist/sql/sql/02.permissions.sql +37 -0
- package/dist/sql/sql/03.optional_rds.sql +6 -0
- package/dist/sql/sql/04.optional_self_managed.sql +8 -0
- package/dist/sql/sql/05.helpers.sql +439 -0
- package/lib/auth-server.ts +124 -106
- package/lib/checkup-api.ts +386 -0
- package/lib/checkup.ts +1396 -0
- package/lib/config.ts +6 -3
- package/lib/init.ts +568 -155
- package/lib/issues.ts +400 -191
- package/lib/mcp-server.ts +213 -90
- package/lib/metrics-embedded.ts +79 -0
- package/lib/metrics-loader.ts +127 -0
- package/lib/supabase.ts +769 -0
- package/lib/util.ts +61 -0
- package/package.json +20 -10
- package/packages/postgres-ai/README.md +26 -0
- package/packages/postgres-ai/bin/postgres-ai.js +27 -0
- package/packages/postgres-ai/package.json +27 -0
- package/scripts/embed-metrics.ts +154 -0
- package/sql/01.role.sql +16 -0
- package/sql/02.permissions.sql +37 -0
- package/sql/03.optional_rds.sql +6 -0
- package/sql/04.optional_self_managed.sql +8 -0
- package/sql/05.helpers.sql +439 -0
- package/test/auth.test.ts +258 -0
- package/test/checkup.integration.test.ts +321 -0
- package/test/checkup.test.ts +1117 -0
- package/test/config-consistency.test.ts +36 -0
- package/test/init.integration.test.ts +500 -0
- package/test/init.test.ts +682 -0
- package/test/issues.cli.test.ts +314 -0
- package/test/issues.test.ts +456 -0
- package/test/mcp-server.test.ts +988 -0
- package/test/schema-validation.test.ts +81 -0
- package/test/supabase.test.ts +568 -0
- package/test/test-utils.ts +128 -0
- package/tsconfig.json +12 -20
- package/dist/bin/postgres-ai.d.ts +0 -3
- package/dist/bin/postgres-ai.d.ts.map +0 -1
- package/dist/bin/postgres-ai.js.map +0 -1
- package/dist/lib/auth-server.d.ts +0 -31
- package/dist/lib/auth-server.d.ts.map +0 -1
- package/dist/lib/auth-server.js +0 -263
- package/dist/lib/auth-server.js.map +0 -1
- package/dist/lib/config.d.ts +0 -45
- package/dist/lib/config.d.ts.map +0 -1
- package/dist/lib/config.js +0 -181
- package/dist/lib/config.js.map +0 -1
- package/dist/lib/init.d.ts +0 -61
- package/dist/lib/init.d.ts.map +0 -1
- package/dist/lib/init.js +0 -359
- package/dist/lib/init.js.map +0 -1
- package/dist/lib/issues.d.ts +0 -75
- package/dist/lib/issues.d.ts.map +0 -1
- package/dist/lib/issues.js +0 -336
- package/dist/lib/issues.js.map +0 -1
- package/dist/lib/mcp-server.d.ts +0 -9
- package/dist/lib/mcp-server.d.ts.map +0 -1
- package/dist/lib/mcp-server.js +0 -168
- package/dist/lib/mcp-server.js.map +0 -1
- package/dist/lib/pkce.d.ts +0 -32
- package/dist/lib/pkce.d.ts.map +0 -1
- package/dist/lib/pkce.js +0 -101
- package/dist/lib/pkce.js.map +0 -1
- package/dist/lib/util.d.ts +0 -27
- package/dist/lib/util.d.ts.map +0 -1
- package/dist/lib/util.js +0 -46
- package/dist/lib/util.js.map +0 -1
- package/dist/package.json +0 -46
- package/test/init.integration.test.cjs +0 -269
- package/test/init.test.cjs +0 -69
package/lib/mcp-server.ts
CHANGED
|
@@ -1,44 +1,172 @@
|
|
|
1
|
-
import
|
|
1
|
+
import pkg from "../package.json";
|
|
2
2
|
import * as config from "./config";
|
|
3
|
-
import { fetchIssues, fetchIssueComments, createIssueComment, fetchIssue } from "./issues";
|
|
3
|
+
import { fetchIssues, fetchIssueComments, createIssueComment, fetchIssue, createIssue, updateIssue, updateIssueComment } from "./issues";
|
|
4
4
|
import { resolveBaseUrls } from "./util";
|
|
5
5
|
|
|
6
|
-
// MCP SDK imports
|
|
7
|
-
import { Server } from "@modelcontextprotocol/sdk/server";
|
|
8
|
-
import
|
|
9
|
-
|
|
6
|
+
// MCP SDK imports - Bun handles these directly
|
|
7
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
8
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
10
10
|
|
|
11
|
-
interface RootOptsLike {
|
|
11
|
+
export interface RootOptsLike {
|
|
12
12
|
apiKey?: string;
|
|
13
13
|
apiBaseUrl?: string;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
16
|
+
// Interpret escape sequences (e.g., \n -> newline). Input comes from JSON, but
|
|
17
|
+
// we still normalize common escapes for consistency.
|
|
18
|
+
export const interpretEscapes = (str: string): string =>
|
|
19
|
+
(str || "")
|
|
20
|
+
.replace(/\\n/g, "\n")
|
|
21
|
+
.replace(/\\t/g, "\t")
|
|
22
|
+
.replace(/\\r/g, "\r")
|
|
23
|
+
.replace(/\\"/g, '"')
|
|
24
|
+
.replace(/\\'/g, "'");
|
|
25
|
+
|
|
26
|
+
export interface McpToolRequest {
|
|
27
|
+
params: {
|
|
28
|
+
name: string;
|
|
29
|
+
arguments?: Record<string, unknown>;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface McpToolResponse {
|
|
34
|
+
content: Array<{ type: string; text: string }>;
|
|
35
|
+
isError?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Handle MCP tool calls - exported for testing */
|
|
39
|
+
export async function handleToolCall(
|
|
40
|
+
req: McpToolRequest,
|
|
41
|
+
rootOpts?: RootOptsLike,
|
|
42
|
+
extra?: { debug?: boolean }
|
|
43
|
+
): Promise<McpToolResponse> {
|
|
44
|
+
const toolName = req.params.name;
|
|
45
|
+
const args = (req.params.arguments as Record<string, unknown>) || {};
|
|
46
|
+
|
|
47
|
+
const cfg = config.readConfig();
|
|
48
|
+
const apiKey = (rootOpts?.apiKey || process.env.PGAI_API_KEY || cfg.apiKey || "").toString();
|
|
49
|
+
const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
|
|
50
|
+
|
|
51
|
+
const debug = Boolean(args.debug ?? extra?.debug);
|
|
52
|
+
|
|
53
|
+
if (!apiKey) {
|
|
54
|
+
return {
|
|
55
|
+
content: [
|
|
56
|
+
{
|
|
57
|
+
type: "text",
|
|
58
|
+
text: "API key is required. Run 'pgai auth' or set PGAI_API_KEY.",
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
isError: true,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
26
64
|
|
|
65
|
+
try {
|
|
66
|
+
if (toolName === "list_issues") {
|
|
67
|
+
const issues = await fetchIssues({ apiKey, apiBaseUrl, debug });
|
|
68
|
+
return { content: [{ type: "text", text: JSON.stringify(issues, null, 2) }] };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (toolName === "view_issue") {
|
|
72
|
+
const issueId = String(args.issue_id || "").trim();
|
|
73
|
+
if (!issueId) {
|
|
74
|
+
return { content: [{ type: "text", text: "issue_id is required" }], isError: true };
|
|
75
|
+
}
|
|
76
|
+
const issue = await fetchIssue({ apiKey, apiBaseUrl, issueId, debug });
|
|
77
|
+
if (!issue) {
|
|
78
|
+
return { content: [{ type: "text", text: "Issue not found" }], isError: true };
|
|
79
|
+
}
|
|
80
|
+
const comments = await fetchIssueComments({ apiKey, apiBaseUrl, issueId, debug });
|
|
81
|
+
const combined = { issue, comments };
|
|
82
|
+
return { content: [{ type: "text", text: JSON.stringify(combined, null, 2) }] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (toolName === "post_issue_comment") {
|
|
86
|
+
const issueId = String(args.issue_id || "").trim();
|
|
87
|
+
const rawContent = String(args.content || "");
|
|
88
|
+
const parentCommentId = args.parent_comment_id ? String(args.parent_comment_id) : undefined;
|
|
89
|
+
if (!issueId) {
|
|
90
|
+
return { content: [{ type: "text", text: "issue_id is required" }], isError: true };
|
|
91
|
+
}
|
|
92
|
+
if (!rawContent) {
|
|
93
|
+
return { content: [{ type: "text", text: "content is required" }], isError: true };
|
|
94
|
+
}
|
|
95
|
+
const content = interpretEscapes(rawContent);
|
|
96
|
+
const result = await createIssueComment({ apiKey, apiBaseUrl, issueId, content, parentCommentId, debug });
|
|
97
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (toolName === "create_issue") {
|
|
101
|
+
const rawTitle = String(args.title || "").trim();
|
|
102
|
+
if (!rawTitle) {
|
|
103
|
+
return { content: [{ type: "text", text: "title is required" }], isError: true };
|
|
104
|
+
}
|
|
105
|
+
const title = interpretEscapes(rawTitle);
|
|
106
|
+
const rawDescription = args.description ? String(args.description) : undefined;
|
|
107
|
+
const description = rawDescription ? interpretEscapes(rawDescription) : undefined;
|
|
108
|
+
const projectId = args.project_id !== undefined ? Number(args.project_id) : undefined;
|
|
109
|
+
const labels = Array.isArray(args.labels) ? args.labels.map(String) : undefined;
|
|
110
|
+
// Get orgId from args or fall back to config
|
|
111
|
+
const orgId = args.org_id !== undefined ? Number(args.org_id) : cfg.orgId;
|
|
112
|
+
// Note: orgId=0 is technically valid (though unlikely), so don't use falsy check
|
|
113
|
+
if (orgId === undefined || orgId === null || Number.isNaN(orgId)) {
|
|
114
|
+
return { content: [{ type: "text", text: "org_id is required. Either provide it as a parameter or run 'pgai auth' to set it in config." }], isError: true };
|
|
115
|
+
}
|
|
116
|
+
const result = await createIssue({ apiKey, apiBaseUrl, title, orgId, description, projectId, labels, debug });
|
|
117
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (toolName === "update_issue") {
|
|
121
|
+
const issueId = String(args.issue_id || "").trim();
|
|
122
|
+
if (!issueId) {
|
|
123
|
+
return { content: [{ type: "text", text: "issue_id is required" }], isError: true };
|
|
124
|
+
}
|
|
125
|
+
const rawTitle = args.title !== undefined ? String(args.title) : undefined;
|
|
126
|
+
const title = rawTitle !== undefined ? interpretEscapes(rawTitle) : undefined;
|
|
127
|
+
const rawDescription = args.description !== undefined ? String(args.description) : undefined;
|
|
128
|
+
const description = rawDescription !== undefined ? interpretEscapes(rawDescription) : undefined;
|
|
129
|
+
const status = args.status !== undefined ? Number(args.status) : undefined;
|
|
130
|
+
const labels = Array.isArray(args.labels) ? args.labels.map(String) : undefined;
|
|
131
|
+
// Validate that at least one update field is provided
|
|
132
|
+
if (title === undefined && description === undefined && status === undefined && labels === undefined) {
|
|
133
|
+
return { content: [{ type: "text", text: "At least one field to update is required (title, description, status, or labels)" }], isError: true };
|
|
134
|
+
}
|
|
135
|
+
// Validate status value if provided (check for NaN and valid values)
|
|
136
|
+
if (status !== undefined && (Number.isNaN(status) || (status !== 0 && status !== 1))) {
|
|
137
|
+
return { content: [{ type: "text", text: "status must be 0 (open) or 1 (closed)" }], isError: true };
|
|
138
|
+
}
|
|
139
|
+
const result = await updateIssue({ apiKey, apiBaseUrl, issueId, title, description, status, labels, debug });
|
|
140
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (toolName === "update_issue_comment") {
|
|
144
|
+
const commentId = String(args.comment_id || "").trim();
|
|
145
|
+
const rawContent = String(args.content || "");
|
|
146
|
+
if (!commentId) {
|
|
147
|
+
return { content: [{ type: "text", text: "comment_id is required" }], isError: true };
|
|
148
|
+
}
|
|
149
|
+
if (!rawContent.trim()) {
|
|
150
|
+
return { content: [{ type: "text", text: "content is required" }], isError: true };
|
|
151
|
+
}
|
|
152
|
+
const content = interpretEscapes(rawContent);
|
|
153
|
+
const result = await updateIssueComment({ apiKey, apiBaseUrl, commentId, content, debug });
|
|
154
|
+
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
throw new Error(`Unknown tool: ${toolName}`);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
160
|
+
return { content: [{ type: "text", text: message }], isError: true };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function startMcpServer(rootOpts?: RootOptsLike, extra?: { debug?: boolean }): Promise<void> {
|
|
27
165
|
const server = new Server(
|
|
28
166
|
{ name: "postgresai-mcp", version: pkg.version },
|
|
29
167
|
{ capabilities: { tools: {} } }
|
|
30
168
|
);
|
|
31
169
|
|
|
32
|
-
// Interpret escape sequences (e.g., \n -> newline). Input comes from JSON, but
|
|
33
|
-
// we still normalize common escapes for consistency.
|
|
34
|
-
const interpretEscapes = (str: string): string =>
|
|
35
|
-
(str || "")
|
|
36
|
-
.replace(/\\n/g, "\n")
|
|
37
|
-
.replace(/\\t/g, "\t")
|
|
38
|
-
.replace(/\\r/g, "\r")
|
|
39
|
-
.replace(/\\"/g, '"')
|
|
40
|
-
.replace(/\\'/g, "'");
|
|
41
|
-
|
|
42
170
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
43
171
|
return {
|
|
44
172
|
tools: [
|
|
@@ -81,76 +209,71 @@ export async function startMcpServer(rootOpts?: RootOptsLike, extra?: { debug?:
|
|
|
81
209
|
additionalProperties: false,
|
|
82
210
|
},
|
|
83
211
|
},
|
|
212
|
+
{
|
|
213
|
+
name: "create_issue",
|
|
214
|
+
description: "Create a new issue in PostgresAI",
|
|
215
|
+
inputSchema: {
|
|
216
|
+
type: "object",
|
|
217
|
+
properties: {
|
|
218
|
+
title: { type: "string", description: "Issue title (required)" },
|
|
219
|
+
description: { type: "string", description: "Issue description (supports \\n as newline)" },
|
|
220
|
+
org_id: { type: "number", description: "Organization ID (uses config value if not provided)" },
|
|
221
|
+
project_id: { type: "number", description: "Project ID to associate the issue with" },
|
|
222
|
+
labels: {
|
|
223
|
+
type: "array",
|
|
224
|
+
items: { type: "string" },
|
|
225
|
+
description: "Labels to apply to the issue",
|
|
226
|
+
},
|
|
227
|
+
debug: { type: "boolean", description: "Enable verbose debug logs" },
|
|
228
|
+
},
|
|
229
|
+
required: ["title"],
|
|
230
|
+
additionalProperties: false,
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
name: "update_issue",
|
|
235
|
+
description: "Update an existing issue (title, description, status, labels). Use status=1 to close, status=0 to reopen.",
|
|
236
|
+
inputSchema: {
|
|
237
|
+
type: "object",
|
|
238
|
+
properties: {
|
|
239
|
+
issue_id: { type: "string", description: "Issue ID (UUID)" },
|
|
240
|
+
title: { type: "string", description: "New title (supports \\n as newline)" },
|
|
241
|
+
description: { type: "string", description: "New description (supports \\n as newline)" },
|
|
242
|
+
status: { type: "number", description: "Status: 0=open, 1=closed" },
|
|
243
|
+
labels: {
|
|
244
|
+
type: "array",
|
|
245
|
+
items: { type: "string" },
|
|
246
|
+
description: "Labels to set on the issue",
|
|
247
|
+
},
|
|
248
|
+
debug: { type: "boolean", description: "Enable verbose debug logs" },
|
|
249
|
+
},
|
|
250
|
+
required: ["issue_id"],
|
|
251
|
+
additionalProperties: false,
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
name: "update_issue_comment",
|
|
256
|
+
description: "Update an existing issue comment",
|
|
257
|
+
inputSchema: {
|
|
258
|
+
type: "object",
|
|
259
|
+
properties: {
|
|
260
|
+
comment_id: { type: "string", description: "Comment ID (UUID)" },
|
|
261
|
+
content: { type: "string", description: "New comment text (supports \\n as newline)" },
|
|
262
|
+
debug: { type: "boolean", description: "Enable verbose debug logs" },
|
|
263
|
+
},
|
|
264
|
+
required: ["comment_id", "content"],
|
|
265
|
+
additionalProperties: false,
|
|
266
|
+
},
|
|
267
|
+
},
|
|
84
268
|
],
|
|
85
269
|
};
|
|
86
270
|
});
|
|
87
271
|
|
|
272
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
88
273
|
server.setRequestHandler(CallToolRequestSchema, async (req: any) => {
|
|
89
|
-
|
|
90
|
-
const args = (req.params.arguments as Record<string, unknown>) || {};
|
|
91
|
-
|
|
92
|
-
const cfg = config.readConfig();
|
|
93
|
-
const apiKey = (rootOpts?.apiKey || process.env.PGAI_API_KEY || cfg.apiKey || "").toString();
|
|
94
|
-
const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
|
|
95
|
-
|
|
96
|
-
const debug = Boolean(args.debug ?? extra?.debug);
|
|
97
|
-
|
|
98
|
-
if (!apiKey) {
|
|
99
|
-
return {
|
|
100
|
-
content: [
|
|
101
|
-
{
|
|
102
|
-
type: "text",
|
|
103
|
-
text: "API key is required. Run 'pgai auth' or set PGAI_API_KEY.",
|
|
104
|
-
},
|
|
105
|
-
],
|
|
106
|
-
isError: true,
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
try {
|
|
111
|
-
if (toolName === "list_issues") {
|
|
112
|
-
const issues = await fetchIssues({ apiKey, apiBaseUrl, debug });
|
|
113
|
-
return { content: [{ type: "text", text: JSON.stringify(issues, null, 2) }] };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
if (toolName === "view_issue") {
|
|
117
|
-
const issueId = String(args.issue_id || "").trim();
|
|
118
|
-
if (!issueId) {
|
|
119
|
-
return { content: [{ type: "text", text: "issue_id is required" }], isError: true };
|
|
120
|
-
}
|
|
121
|
-
const issue = await fetchIssue({ apiKey, apiBaseUrl, issueId, debug });
|
|
122
|
-
if (!issue) {
|
|
123
|
-
return { content: [{ type: "text", text: "Issue not found" }], isError: true };
|
|
124
|
-
}
|
|
125
|
-
const comments = await fetchIssueComments({ apiKey, apiBaseUrl, issueId, debug });
|
|
126
|
-
const combined = { issue, comments };
|
|
127
|
-
return { content: [{ type: "text", text: JSON.stringify(combined, null, 2) }] };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
if (toolName === "post_issue_comment") {
|
|
131
|
-
const issueId = String(args.issue_id || "").trim();
|
|
132
|
-
const rawContent = String(args.content || "");
|
|
133
|
-
const parentCommentId = args.parent_comment_id ? String(args.parent_comment_id) : undefined;
|
|
134
|
-
if (!issueId) {
|
|
135
|
-
return { content: [{ type: "text", text: "issue_id is required" }], isError: true };
|
|
136
|
-
}
|
|
137
|
-
if (!rawContent) {
|
|
138
|
-
return { content: [{ type: "text", text: "content is required" }], isError: true };
|
|
139
|
-
}
|
|
140
|
-
const content = interpretEscapes(rawContent);
|
|
141
|
-
const result = await createIssueComment({ apiKey, apiBaseUrl, issueId, content, parentCommentId, debug });
|
|
142
|
-
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
throw new Error(`Unknown tool: ${toolName}`);
|
|
146
|
-
} catch (err) {
|
|
147
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
148
|
-
return { content: [{ type: "text", text: message }], isError: true };
|
|
149
|
-
}
|
|
274
|
+
return handleToolCall(req, rootOpts, extra);
|
|
150
275
|
});
|
|
151
276
|
|
|
152
277
|
const transport = new StdioServerTransport();
|
|
153
278
|
await server.connect(transport);
|
|
154
279
|
}
|
|
155
|
-
|
|
156
|
-
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// AUTO-GENERATED FILE - DO NOT EDIT
|
|
2
|
+
// Generated from config/pgwatch-prometheus/metrics.yml by scripts/embed-metrics.ts
|
|
3
|
+
// Generated at: 2026-01-09T12:41:56.884Z
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Metric definition from metrics.yml
|
|
7
|
+
*/
|
|
8
|
+
export interface MetricDefinition {
|
|
9
|
+
description?: string;
|
|
10
|
+
sqls: Record<number, string>; // PG major version -> SQL query
|
|
11
|
+
gauges?: string[];
|
|
12
|
+
statement_timeout_seconds?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Embedded metrics for express mode reports.
|
|
17
|
+
* Only includes metrics required for CLI checkup reports.
|
|
18
|
+
*/
|
|
19
|
+
export const METRICS: Record<string, MetricDefinition> = {
|
|
20
|
+
"settings": {
|
|
21
|
+
description: "This metric collects various PostgreSQL server settings and configurations. It provides insights into the server's configuration, including version, memory settings, and other important parameters. This metric is useful for monitoring server settings and ensuring optimal performance. Note: For lock_timeout and statement_timeout, we use reset_val instead of setting because pgwatch overrides these during metric collection, which would mask the actual configured values.",
|
|
22
|
+
sqls: {
|
|
23
|
+
11: "with base as ( /* pgwatch_generated */\n select\n name,\n -- Use reset_val for lock_timeout/statement_timeout because pgwatch overrides them\n -- during collection (lock_timeout=100ms, statement_timeout per-metric).\n case\n when name in ('lock_timeout', 'statement_timeout') then reset_val\n else setting\n end as effective_setting,\n unit,\n category,\n vartype,\n -- For lock_timeout/statement_timeout, compare reset_val with boot_val\n -- since source becomes 'session' during collection.\n case\n when name in ('lock_timeout', 'statement_timeout') then (reset_val = boot_val)\n else (source = 'default')\n end as is_default_bool\n from pg_settings\n), with_numeric as (\n select\n *,\n case\n when effective_setting ~ '^-?[0-9]+$' then effective_setting::bigint\n else null\n end as numeric_value\n from base\n)\nselect\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n name as tag_setting_name,\n effective_setting as tag_setting_value,\n unit as tag_unit,\n category as tag_category,\n vartype as tag_vartype,\n numeric_value,\n case\n when numeric_value is null then null\n when unit = '8kB' then numeric_value * 8192\n when unit = 'kB' then numeric_value * 1024\n when unit = 'MB' then numeric_value * 1024 * 1024\n when unit = 'B' then numeric_value\n when unit = 'ms' then numeric_value::numeric / 1000\n when unit = 's' then numeric_value::numeric\n when unit = 'min' then numeric_value::numeric * 60\n else null\n end as setting_normalized,\n case unit\n when '8kB' then 'bytes'\n when 'kB' then 'bytes'\n when 'MB' then 'bytes'\n when 'B' then 'bytes'\n when 'ms' then 'seconds'\n when 's' then 'seconds'\n when 'min' then 'seconds'\n else null\n end as unit_normalized,\n case when is_default_bool then 1 else 0 end as is_default,\n 1 as configured\nfrom with_numeric",
|
|
24
|
+
},
|
|
25
|
+
gauges: ["*"],
|
|
26
|
+
statement_timeout_seconds: 15,
|
|
27
|
+
},
|
|
28
|
+
"db_stats": {
|
|
29
|
+
description: "Retrieves key statistics from the PostgreSQL `pg_stat_database` view, providing insights into the current database's performance. It returns the number of backends, transaction commits and rollbacks, buffer reads and hits, tuple statistics, conflicts, temporary files and bytes, deadlocks, block read and write times, postmaster uptime, backup duration, recovery status, system identifier, and invalid indexes. This metric helps administrators monitor database activity and performance.",
|
|
30
|
+
sqls: {
|
|
31
|
+
11: "select /* pgwatch_generated */\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n numbackends,\n xact_commit,\n xact_rollback,\n blks_read,\n blks_hit,\n tup_returned,\n tup_fetched,\n tup_inserted,\n tup_updated,\n tup_deleted,\n conflicts,\n temp_files,\n temp_bytes,\n deadlocks,\n blk_read_time,\n blk_write_time,\n extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,\n case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,\n system_identifier::text as tag_sys_id,\n (select count(*) from pg_index i\n where not indisvalid\n and not exists ( /* leave out ones that are being actively rebuilt */\n select * from pg_locks l\n join pg_stat_activity a using (pid)\n where l.relation = i.indexrelid\n and a.state = 'active'\n and a.query ~* 'concurrently'\n )) as invalid_indexes\nfrom\n pg_stat_database, pg_control_system()\nwhere\n datname = current_database()",
|
|
32
|
+
12: "select /* pgwatch_generated */\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n numbackends,\n xact_commit,\n xact_rollback,\n blks_read,\n blks_hit,\n tup_returned,\n tup_fetched,\n tup_inserted,\n tup_updated,\n tup_deleted,\n conflicts,\n temp_files,\n temp_bytes,\n deadlocks,\n blk_read_time,\n blk_write_time,\n extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,\n extract(epoch from (now() - pg_backup_start_time()))::int8 as backup_duration_s,\n checksum_failures,\n extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,\n case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,\n system_identifier::text as tag_sys_id,\n (select count(*) from pg_index i\n where not indisvalid\n and not exists ( /* leave out ones that are being actively rebuilt */\n select * from pg_locks l\n join pg_stat_activity a using (pid)\n where l.relation = i.indexrelid\n and a.state = 'active'\n and a.query ~* 'concurrently'\n )) as invalid_indexes\nfrom\n pg_stat_database, pg_control_system()\nwhere\n datname = current_database()",
|
|
33
|
+
14: "select /* pgwatch_generated */\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n numbackends,\n xact_commit,\n xact_rollback,\n blks_read,\n blks_hit,\n tup_returned,\n tup_fetched,\n tup_inserted,\n tup_updated,\n tup_deleted,\n conflicts,\n temp_files,\n temp_bytes,\n deadlocks,\n blk_read_time,\n blk_write_time,\n extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,\n extract(epoch from (now() - pg_backup_start_time()))::int8 as backup_duration_s,\n checksum_failures,\n extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,\n case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,\n system_identifier::text as tag_sys_id,\n session_time::int8,\n active_time::int8,\n idle_in_transaction_time::int8,\n sessions,\n sessions_abandoned,\n sessions_fatal,\n sessions_killed,\n (select count(*) from pg_index i\n where not indisvalid\n and not exists ( /* leave out ones that are being actively rebuilt */\n select * from pg_locks l\n join pg_stat_activity a using (pid)\n where l.relation = i.indexrelid\n and a.state = 'active'\n and a.query ~* 'concurrently'\n )) as invalid_indexes\nfrom\n pg_stat_database, pg_control_system()\nwhere\n datname = current_database()",
|
|
34
|
+
15: "select /* pgwatch_generated */\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n numbackends,\n xact_commit,\n xact_rollback,\n blks_read,\n blks_hit,\n tup_returned,\n tup_fetched,\n tup_inserted,\n tup_updated,\n tup_deleted,\n conflicts,\n temp_files,\n temp_bytes,\n deadlocks,\n blk_read_time,\n blk_write_time,\n extract(epoch from (now() - pg_postmaster_start_time()))::int8 as postmaster_uptime_s,\n checksum_failures,\n extract(epoch from (now() - checksum_last_failure))::int8 as checksum_last_failure_s,\n case when pg_is_in_recovery() then 1 else 0 end as in_recovery_int,\n system_identifier::text as tag_sys_id,\n session_time::int8,\n active_time::int8,\n idle_in_transaction_time::int8,\n sessions,\n sessions_abandoned,\n sessions_fatal,\n sessions_killed,\n (select count(*) from pg_index i\n where not indisvalid\n and not exists ( /* leave out ones that are being actively rebuilt */\n select * from pg_locks l\n join pg_stat_activity a using (pid)\n where l.relation = i.indexrelid\n and a.state = 'active'\n and a.query ~* 'concurrently'\n )) as invalid_indexes\nfrom\n pg_stat_database, pg_control_system()\nwhere\n datname = current_database()",
|
|
35
|
+
},
|
|
36
|
+
gauges: ["*"],
|
|
37
|
+
statement_timeout_seconds: 15,
|
|
38
|
+
},
|
|
39
|
+
"db_size": {
|
|
40
|
+
description: "Retrieves the size of the current database and the size of the `pg_catalog` schema, providing insights into the storage usage of the database. It returns the size in bytes for both the current database and the catalog schema. This metric helps administrators monitor database size and storage consumption.",
|
|
41
|
+
sqls: {
|
|
42
|
+
11: "select /* pgwatch_generated */\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n pg_database_size(current_database()) as size_b,\n (select sum(pg_total_relation_size(c.oid))::int8\n from pg_class c join pg_namespace n on n.oid = c.relnamespace\n where nspname = 'pg_catalog' and relkind = 'r'\n ) as catalog_size_b",
|
|
43
|
+
},
|
|
44
|
+
gauges: ["*"],
|
|
45
|
+
statement_timeout_seconds: 300,
|
|
46
|
+
},
|
|
47
|
+
"pg_invalid_indexes": {
|
|
48
|
+
description: "This metric identifies invalid indexes in the database with decision tree data for remediation. It provides insights into whether to DROP (if duplicate exists), RECREATE (if backs constraint), or flag as UNCERTAIN (if additional RCA is needed to check query plans). Decision tree: 1) Valid duplicate exists -> DROP, 2) Backs PK/UNIQUE constraint -> RECREATE, 3) Table < 10K rows -> RECREATE (small tables rebuild quickly, typically under 1 second), 4) Otherwise -> UNCERTAIN (need query plan analysis to assess impact).",
|
|
49
|
+
sqls: {
|
|
50
|
+
11: "with fk_indexes as ( /* pgwatch_generated */\n select\n schemaname as schema_name,\n indexrelid,\n (indexrelid::regclass)::text as index_name,\n (relid::regclass)::text as table_name,\n (confrelid::regclass)::text as fk_table_ref,\n array_to_string(indclass, ', ') as opclasses\n from pg_stat_all_indexes\n join pg_index using (indexrelid)\n left join pg_constraint\n on array_to_string(indkey, ',') = array_to_string(conkey, ',')\n and schemaname = (connamespace::regnamespace)::text\n and conrelid = relid\n and contype = 'f'\n where idx_scan = 0\n and indisunique is false\n and conkey is not null\n),\n-- Find valid indexes that could be duplicates (same table, same columns)\nvalid_duplicates as (\n select\n inv.indexrelid as invalid_indexrelid,\n val.indexrelid as valid_indexrelid,\n (val.indexrelid::regclass)::text as valid_index_name,\n pg_get_indexdef(val.indexrelid) as valid_index_definition\n from pg_index inv\n join pg_index val on inv.indrelid = val.indrelid -- same table\n and inv.indkey = val.indkey -- same columns (in same order)\n and inv.indexrelid != val.indexrelid -- different index\n and val.indisvalid = true -- valid index\n where inv.indisvalid = false\n),\ndata as (\n select\n pci.relname as tag_index_name,\n pn.nspname as tag_schema_name,\n pct.relname as tag_table_name,\n coalesce(nullif(quote_ident(pn.nspname), 'public') || '.', '') || quote_ident(pct.relname) as tag_relation_name,\n pg_get_indexdef(pidx.indexrelid) as index_definition,\n pg_relation_size(pidx.indexrelid) as index_size_bytes,\n -- Constraint info\n pidx.indisprimary as is_pk,\n pidx.indisunique as is_unique,\n con.conname as constraint_name,\n -- Table row estimate\n pct.reltuples::bigint as table_row_estimate,\n -- Valid duplicate check\n (vd.valid_indexrelid is not null) as has_valid_duplicate,\n vd.valid_index_name,\n vd.valid_index_definition,\n -- FK support check\n ((\n select count(1)\n from fk_indexes fi\n where fi.fk_table_ref = pct.relname\n and fi.opclasses like (array_to_string(pidx.indclass, ', ') || '%')\n ) > 0)::int as supports_fk\n from pg_index pidx\n join pg_class pci on pci.oid = pidx.indexrelid\n join pg_class pct on pct.oid = pidx.indrelid\n left join pg_namespace pn on pn.oid = pct.relnamespace\n left join pg_constraint con on con.conindid = pidx.indexrelid\n left join valid_duplicates vd on vd.invalid_indexrelid = pidx.indexrelid\n where pidx.indisvalid = false\n),\nnum_data as (\n select\n row_number() over () as num,\n data.*\n from data\n)\nselect\n (extract(epoch from now()) * 1e9)::int8 as epoch_ns,\n current_database() as tag_datname,\n num_data.*\nfrom num_data\nlimit 1000;\n",
|
|
51
|
+
},
|
|
52
|
+
gauges: ["*"],
|
|
53
|
+
statement_timeout_seconds: 15,
|
|
54
|
+
},
|
|
55
|
+
"unused_indexes": {
|
|
56
|
+
description: "This metric identifies unused indexes in the database. It provides insights into the number of unused indexes and their details. This metric helps administrators identify and fix unused indexes to improve database performance.",
|
|
57
|
+
sqls: {
|
|
58
|
+
11: "with fk_indexes as ( /* pgwatch_generated */\n select\n n.nspname as schema_name,\n ci.relname as index_name,\n cr.relname as table_name,\n (confrelid::regclass)::text as fk_table_ref,\n array_to_string(indclass, ', ') as opclasses\n from pg_index i\n join pg_class ci on ci.oid = i.indexrelid and ci.relkind = 'i'\n join pg_class cr on cr.oid = i.indrelid and cr.relkind = 'r'\n join pg_namespace n on n.oid = ci.relnamespace\n join pg_constraint cn on cn.conrelid = cr.oid\n left join pg_stat_all_indexes as si on si.indexrelid = i.indexrelid\n where\n contype = 'f'\n and i.indisunique is false\n and conkey is not null\n and ci.relpages > 5\n and si.idx_scan < 10\n), table_scans as (\n select relid,\n tables.idx_scan + tables.seq_scan as all_scans,\n ( tables.n_tup_ins + tables.n_tup_upd + tables.n_tup_del ) as writes,\n pg_relation_size(relid) as table_size\n from pg_stat_all_tables as tables\n join pg_class c on c.oid = relid\n where c.relpages > 5\n), indexes as (\n select\n i.indrelid,\n i.indexrelid,\n n.nspname as schema_name,\n cr.relname as table_name,\n ci.relname as index_name,\n si.idx_scan,\n pg_relation_size(i.indexrelid) as index_bytes,\n ci.relpages,\n (case when a.amname = 'btree' then true else false end) as idx_is_btree,\n array_to_string(i.indclass, ', ') as opclasses\n from pg_index i\n join pg_class ci on ci.oid = i.indexrelid and ci.relkind = 'i'\n join pg_class cr on cr.oid = i.indrelid and cr.relkind = 'r'\n join pg_namespace n on n.oid = ci.relnamespace\n join pg_am a on ci.relam = a.oid\n left join pg_stat_all_indexes as si on si.indexrelid = i.indexrelid\n where\n i.indisunique = false\n and i.indisvalid = true\n and ci.relpages > 5\n), index_ratios as (\n select\n i.indexrelid as index_id,\n i.schema_name,\n i.table_name,\n i.index_name,\n idx_scan,\n all_scans,\n round(( case when all_scans = 0 then 0.0::numeric\n else idx_scan::numeric/all_scans * 100 end), 2) as index_scan_pct,\n writes,\n round((case when writes = 0 then idx_scan::numeric else idx_scan::numeric/writes end), 2)\n as scans_per_write,\n index_bytes as index_size_bytes,\n table_size as table_size_bytes,\n i.relpages,\n idx_is_btree,\n i.opclasses,\n (\n select count(1)\n from fk_indexes fi\n where fi.fk_table_ref = i.table_name\n and fi.schema_name = i.schema_name\n and fi.opclasses like (i.opclasses || '%')\n ) > 0 as supports_fk\n from indexes i\n join table_scans ts on ts.relid = i.indrelid\n)\nselect\n 'Never Used Indexes' as tag_reason,\n current_database() as tag_datname,\n index_id,\n schema_name as tag_schema_name,\n table_name as tag_table_name,\n index_name as tag_index_name,\n pg_get_indexdef(index_id) as index_definition,\n idx_scan,\n all_scans,\n index_scan_pct,\n writes,\n scans_per_write,\n index_size_bytes,\n table_size_bytes,\n relpages,\n idx_is_btree,\n opclasses as tag_opclasses,\n supports_fk\nfrom index_ratios\nwhere\n idx_scan = 0\n and idx_is_btree\norder by index_size_bytes desc\nlimit 1000;\n",
|
|
59
|
+
},
|
|
60
|
+
gauges: ["*"],
|
|
61
|
+
statement_timeout_seconds: 15,
|
|
62
|
+
},
|
|
63
|
+
"redundant_indexes": {
|
|
64
|
+
description: "This metric identifies redundant indexes that can potentially be dropped to save storage space and improve write performance. It analyzes index relationships and finds indexes that are covered by other indexes, considering column order, operator classes, and foreign key constraints. Uses the exact logic from tmp.sql with JSON aggregation and proper thresholds.",
|
|
65
|
+
sqls: {
|
|
66
|
+
11: "with fk_indexes as ( /* pgwatch_generated */\n select\n n.nspname as schema_name,\n ci.relname as index_name,\n cr.relname as table_name,\n (confrelid::regclass)::text as fk_table_ref,\n array_to_string(indclass, ', ') as opclasses\n from pg_index i\n join pg_class ci on ci.oid = i.indexrelid and ci.relkind = 'i'\n join pg_class cr on cr.oid = i.indrelid and cr.relkind = 'r'\n join pg_namespace n on n.oid = ci.relnamespace\n join pg_constraint cn on cn.conrelid = cr.oid\n left join pg_stat_all_indexes as si on si.indexrelid = i.indexrelid\n where\n contype = 'f'\n and i.indisunique is false\n and conkey is not null\n and ci.relpages > 5\n and si.idx_scan < 10\n),\n-- Redundant indexes\nindex_data as (\n select\n *,\n indkey::text as columns,\n array_to_string(indclass, ', ') as opclasses\n from pg_index i\n join pg_class ci on ci.oid = i.indexrelid and ci.relkind = 'i'\n where indisvalid = true and ci.relpages > 5\n), redundant_indexes as (\n select\n i2.indexrelid as index_id,\n tnsp.nspname as schema_name,\n trel.relname as table_name,\n pg_relation_size(trel.oid) as table_size_bytes,\n irel.relname as index_name,\n am1.amname as access_method,\n (i1.indexrelid::regclass)::text as reason,\n i1.indexrelid as reason_index_id,\n pg_get_indexdef(i1.indexrelid) main_index_def,\n pg_relation_size(i1.indexrelid) main_index_size_bytes,\n pg_get_indexdef(i2.indexrelid) index_def,\n pg_relation_size(i2.indexrelid) index_size_bytes,\n s.idx_scan as index_usage,\n quote_ident(tnsp.nspname) as formated_schema_name,\n coalesce(nullif(quote_ident(tnsp.nspname), 'public') || '.', '') || quote_ident(irel.relname) as formated_index_name,\n quote_ident(trel.relname) as formated_table_name,\n coalesce(nullif(quote_ident(tnsp.nspname), 'public') || '.', '') || quote_ident(trel.relname) as formated_relation_name,\n i2.opclasses\n from (\n select indrelid, indexrelid, opclasses, indclass, indexprs, indpred, indisprimary, indisunique, columns\n from index_data\n order by indexrelid\n ) as i1\n join index_data as i2 on (\n i1.indrelid = i2.indrelid -- same table\n and i1.indexrelid <> i2.indexrelid -- NOT same index\n )\n inner join pg_opclass op1 on i1.indclass[0] = op1.oid\n inner join pg_opclass op2 on i2.indclass[0] = op2.oid\n inner join pg_am am1 on op1.opcmethod = am1.oid\n inner join pg_am am2 on op2.opcmethod = am2.oid\n join pg_stat_all_indexes as s on s.indexrelid = i2.indexrelid\n join pg_class as trel on trel.oid = i2.indrelid\n join pg_namespace as tnsp on trel.relnamespace = tnsp.oid\n join pg_class as irel on irel.oid = i2.indexrelid\n where\n not i2.indisprimary -- index 1 is not primary\n and not i2.indisunique -- index 1 is not unique (unique indexes serve constraint purpose)\n and am1.amname = am2.amname -- same access type\n and i1.columns like (i2.columns || '%') -- index 2 includes all columns from index 1\n and i1.opclasses like (i2.opclasses || '%')\n -- index expressions is same\n and pg_get_expr(i1.indexprs, i1.indrelid) is not distinct from pg_get_expr(i2.indexprs, i2.indrelid)\n -- index predicates is same\n and pg_get_expr(i1.indpred, i1.indrelid) is not distinct from pg_get_expr(i2.indpred, i2.indrelid)\n), redundant_indexes_fk as (\n select\n ri.*,\n ((\n select count(1)\n from fk_indexes fi\n where\n fi.fk_table_ref = ri.table_name\n and fi.opclasses like (ri.opclasses || '%')\n ) > 0)::int as supports_fk\n from redundant_indexes ri\n),\n-- Cut recursive links\nredundant_indexes_tmp_num as (\n select row_number() over () num, rig.*\n from redundant_indexes_fk rig\n), redundant_indexes_tmp_links as (\n select\n ri1.*,\n ri2.num as r_num\n from redundant_indexes_tmp_num ri1\n left join redundant_indexes_tmp_num ri2 on ri2.reason_index_id = ri1.index_id and ri1.reason_index_id = ri2.index_id\n), redundant_indexes_tmp_cut as (\n select\n *\n from redundant_indexes_tmp_links\n where num < r_num or r_num is null\n), redundant_indexes_cut_grouped as (\n select\n distinct(num),\n *\n from redundant_indexes_tmp_cut\n order by index_size_bytes desc\n), redundant_indexes_grouped as (\n select\n index_id,\n schema_name as tag_schema_name,\n table_name,\n table_size_bytes,\n index_name as tag_index_name,\n access_method as tag_access_method,\n string_agg(distinct reason, ', ') as tag_reason,\n index_size_bytes,\n index_usage,\n index_def as index_definition,\n formated_index_name as tag_index_name,\n formated_schema_name as tag_schema_name,\n formated_table_name as tag_table_name,\n formated_relation_name as tag_relation_name,\n supports_fk::int as supports_fk,\n json_agg(\n distinct jsonb_build_object(\n 'index_name', reason,\n 'index_definition', main_index_def,\n 'index_size_bytes', main_index_size_bytes\n )\n )::text as redundant_to_json\n from redundant_indexes_cut_grouped\n group by\n index_id,\n table_size_bytes,\n schema_name,\n table_name,\n index_name,\n access_method,\n index_def,\n index_size_bytes,\n index_usage,\n formated_index_name,\n formated_schema_name,\n formated_table_name,\n formated_relation_name,\n supports_fk\n order by index_size_bytes desc\n)\nselect * from redundant_indexes_grouped\nlimit 1000;\n",
|
|
67
|
+
},
|
|
68
|
+
gauges: ["*"],
|
|
69
|
+
statement_timeout_seconds: 15,
|
|
70
|
+
},
|
|
71
|
+
"stats_reset": {
|
|
72
|
+
description: "This metric tracks when statistics were last reset at the database level. It provides visibility into the freshness of statistics data, which is essential for understanding the reliability of usage metrics. A recent reset time indicates that usage statistics may not reflect long-term patterns. Note that Postgres tracks stats resets at the database level, not per-index or per-table.",
|
|
73
|
+
sqls: {
|
|
74
|
+
11: "select /* pgwatch_generated */\n datname as tag_database_name,\n extract(epoch from stats_reset)::int as stats_reset_epoch,\n extract(epoch from now() - stats_reset)::int as seconds_since_reset\nfrom pg_stat_database\nwhere datname = current_database()\n and stats_reset is not null;\n",
|
|
75
|
+
},
|
|
76
|
+
gauges: ["stats_reset_epoch","seconds_since_reset"],
|
|
77
|
+
statement_timeout_seconds: 15,
|
|
78
|
+
},
|
|
79
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metrics loader for express checkup reports
|
|
3
|
+
*
|
|
4
|
+
* Loads SQL queries from embedded metrics data (generated from metrics.yml at build time).
|
|
5
|
+
* Provides version-aware query selection and row transformation utilities.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { METRICS, MetricDefinition } from "./metrics-embedded";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Get SQL query for a specific metric, selecting the appropriate version.
|
|
12
|
+
*
|
|
13
|
+
* @param metricName - Name of the metric (e.g., "settings", "db_stats")
|
|
14
|
+
* @param pgMajorVersion - PostgreSQL major version (default: 16)
|
|
15
|
+
* @returns SQL query string
|
|
16
|
+
* @throws Error if metric not found or no compatible version available
|
|
17
|
+
*/
|
|
18
|
+
export function getMetricSql(metricName: string, pgMajorVersion: number = 16): string {
|
|
19
|
+
const metric = METRICS[metricName];
|
|
20
|
+
|
|
21
|
+
if (!metric) {
|
|
22
|
+
throw new Error(`Metric "${metricName}" not found. Available metrics: ${Object.keys(METRICS).join(", ")}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Find the best matching version: highest version <= pgMajorVersion
|
|
26
|
+
const availableVersions = Object.keys(metric.sqls)
|
|
27
|
+
.map(v => parseInt(v, 10))
|
|
28
|
+
.sort((a, b) => b - a); // Sort descending
|
|
29
|
+
|
|
30
|
+
const matchingVersion = availableVersions.find(v => v <= pgMajorVersion);
|
|
31
|
+
|
|
32
|
+
if (matchingVersion === undefined) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`No compatible SQL version for metric "${metricName}" with PostgreSQL ${pgMajorVersion}. ` +
|
|
35
|
+
`Available versions: ${availableVersions.join(", ")}`
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return metric.sqls[matchingVersion];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Get metric definition including all metadata.
|
|
44
|
+
*
|
|
45
|
+
* @param metricName - Name of the metric
|
|
46
|
+
* @returns MetricDefinition or undefined if not found
|
|
47
|
+
*/
|
|
48
|
+
export function getMetricDefinition(metricName: string): MetricDefinition | undefined {
|
|
49
|
+
return METRICS[metricName];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* List all available metric names.
|
|
54
|
+
*/
|
|
55
|
+
export function listMetricNames(): string[] {
|
|
56
|
+
return Object.keys(METRICS);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Metric names that correspond to express report checks.
|
|
61
|
+
* Maps check IDs and logical names to metric names in the METRICS object.
|
|
62
|
+
*/
|
|
63
|
+
export const METRIC_NAMES = {
|
|
64
|
+
// Index health checks
|
|
65
|
+
H001: "pg_invalid_indexes",
|
|
66
|
+
H002: "unused_indexes",
|
|
67
|
+
H004: "redundant_indexes",
|
|
68
|
+
// Settings and version info (A002, A003, A007, A013)
|
|
69
|
+
settings: "settings",
|
|
70
|
+
// Database statistics (A004)
|
|
71
|
+
dbStats: "db_stats",
|
|
72
|
+
dbSize: "db_size",
|
|
73
|
+
// Stats reset info (H002)
|
|
74
|
+
statsReset: "stats_reset",
|
|
75
|
+
} as const;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Transform a row from metrics query output to JSON report format.
|
|
79
|
+
* Metrics use `tag_` prefix for dimensions; we strip it for JSON reports.
|
|
80
|
+
* Also removes Prometheus-specific fields like epoch_ns, num, tag_datname.
|
|
81
|
+
*/
|
|
82
|
+
export function transformMetricRow(row: Record<string, unknown>): Record<string, unknown> {
|
|
83
|
+
const result: Record<string, unknown> = {};
|
|
84
|
+
|
|
85
|
+
for (const [key, value] of Object.entries(row)) {
|
|
86
|
+
// Skip Prometheus-specific fields
|
|
87
|
+
if (key === "epoch_ns" || key === "num" || key === "tag_datname") {
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Strip tag_ prefix
|
|
92
|
+
const newKey = key.startsWith("tag_") ? key.slice(4) : key;
|
|
93
|
+
result[newKey] = value;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Transform settings metric row to the format expected by express reports.
|
|
101
|
+
* The settings metric returns one row per setting with tag_setting_name as key.
|
|
102
|
+
*/
|
|
103
|
+
export function transformSettingsRow(row: Record<string, unknown>): {
|
|
104
|
+
name: string;
|
|
105
|
+
setting: string;
|
|
106
|
+
unit: string;
|
|
107
|
+
category: string;
|
|
108
|
+
vartype: string;
|
|
109
|
+
is_default: boolean;
|
|
110
|
+
} {
|
|
111
|
+
return {
|
|
112
|
+
name: String(row.tag_setting_name || ""),
|
|
113
|
+
setting: String(row.tag_setting_value || ""),
|
|
114
|
+
unit: String(row.tag_unit || ""),
|
|
115
|
+
category: String(row.tag_category || ""),
|
|
116
|
+
vartype: String(row.tag_vartype || ""),
|
|
117
|
+
is_default: row.is_default === 1 || row.is_default === true,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Re-export types for convenience
|
|
122
|
+
export type { MetricDefinition } from "./metrics-embedded";
|
|
123
|
+
|
|
124
|
+
// Legacy export for backward compatibility
|
|
125
|
+
export function loadMetricsYml(): { metrics: Record<string, unknown> } {
|
|
126
|
+
return { metrics: METRICS };
|
|
127
|
+
}
|