postgresai 0.14.0-beta.14 → 0.14.0-beta.15
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/bin/postgres-ai.ts +12 -6
- package/dist/bin/postgres-ai.js +686 -33
- package/lib/checkup-dictionary.ts +114 -0
- package/lib/checkup.ts +130 -14
- package/package.json +9 -7
- package/scripts/embed-checkup-dictionary.ts +106 -0
- package/test/checkup.test.ts +17 -18
- package/lib/metrics-embedded.ts +0 -79
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checkup Dictionary Module
|
|
3
|
+
* =========================
|
|
4
|
+
* Provides access to the checkup report dictionary data embedded at build time.
|
|
5
|
+
*
|
|
6
|
+
* The dictionary is fetched from https://postgres.ai/api/general/checkup_dictionary
|
|
7
|
+
* during the build process and embedded into checkup-dictionary-embedded.ts.
|
|
8
|
+
*
|
|
9
|
+
* This ensures no API calls are made at runtime while keeping the data up-to-date.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { CHECKUP_DICTIONARY_DATA } from "./checkup-dictionary-embedded";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A checkup dictionary entry describing a single check type.
|
|
16
|
+
*/
|
|
17
|
+
export interface CheckupDictionaryEntry {
|
|
18
|
+
/** Unique check code (e.g., "A001", "H002") */
|
|
19
|
+
code: string;
|
|
20
|
+
/** Human-readable title for the check */
|
|
21
|
+
title: string;
|
|
22
|
+
/** Brief description of what the check covers */
|
|
23
|
+
description: string;
|
|
24
|
+
/** Category grouping (e.g., "system", "indexes", "vacuum") */
|
|
25
|
+
category: string;
|
|
26
|
+
/** Optional sort order within category */
|
|
27
|
+
sort_order: number | null;
|
|
28
|
+
/** Whether this is a system-level report */
|
|
29
|
+
is_system_report: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Module-level cache for O(1) lookups by code.
|
|
34
|
+
* Initialized at module load time from embedded data.
|
|
35
|
+
* Keys are normalized to uppercase for case-insensitive lookups.
|
|
36
|
+
*/
|
|
37
|
+
const dictionaryByCode: Map<string, CheckupDictionaryEntry> = new Map(
|
|
38
|
+
CHECKUP_DICTIONARY_DATA.map((entry) => [entry.code.toUpperCase(), entry])
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Get all checkup dictionary entries.
|
|
43
|
+
*
|
|
44
|
+
* @returns Array of all checkup dictionary entries
|
|
45
|
+
*/
|
|
46
|
+
export function getAllCheckupEntries(): CheckupDictionaryEntry[] {
|
|
47
|
+
return CHECKUP_DICTIONARY_DATA;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Get a checkup dictionary entry by its code.
|
|
52
|
+
*
|
|
53
|
+
* @param code - The check code (e.g., "A001", "H002"). Lookup is case-insensitive.
|
|
54
|
+
* @returns The dictionary entry or null if not found
|
|
55
|
+
*/
|
|
56
|
+
export function getCheckupEntry(code: string): CheckupDictionaryEntry | null {
|
|
57
|
+
return dictionaryByCode.get(code.toUpperCase()) ?? null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Get the title for a checkup code.
|
|
62
|
+
*
|
|
63
|
+
* @param code - The check code (e.g., "A001", "H002")
|
|
64
|
+
* @returns The title or the code itself if not found
|
|
65
|
+
*/
|
|
66
|
+
export function getCheckupTitle(code: string): string {
|
|
67
|
+
const entry = getCheckupEntry(code);
|
|
68
|
+
return entry?.title ?? code;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Check if a code exists in the dictionary.
|
|
73
|
+
*
|
|
74
|
+
* @param code - The check code to validate
|
|
75
|
+
* @returns True if the code exists in the dictionary
|
|
76
|
+
*/
|
|
77
|
+
export function isValidCheckupCode(code: string): boolean {
|
|
78
|
+
return dictionaryByCode.has(code.toUpperCase());
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Get all check codes as an array.
|
|
83
|
+
*
|
|
84
|
+
* @returns Array of all check codes (e.g., ["A001", "A002", ...])
|
|
85
|
+
*/
|
|
86
|
+
export function getAllCheckupCodes(): string[] {
|
|
87
|
+
return CHECKUP_DICTIONARY_DATA.map((entry) => entry.code);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Get checkup entries filtered by category.
|
|
92
|
+
*
|
|
93
|
+
* @param category - The category to filter by (e.g., "indexes", "vacuum")
|
|
94
|
+
* @returns Array of entries in the specified category
|
|
95
|
+
*/
|
|
96
|
+
export function getCheckupEntriesByCategory(category: string): CheckupDictionaryEntry[] {
|
|
97
|
+
return CHECKUP_DICTIONARY_DATA.filter(
|
|
98
|
+
(entry) => entry.category.toLowerCase() === category.toLowerCase()
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Build a code-to-title mapping object.
|
|
104
|
+
* Useful for backwards compatibility with CHECK_INFO style usage.
|
|
105
|
+
*
|
|
106
|
+
* @returns Object mapping check codes to titles (e.g., { "A001": "System information", ... })
|
|
107
|
+
*/
|
|
108
|
+
export function buildCheckInfoMap(): Record<string, string> {
|
|
109
|
+
const result: Record<string, string> = {};
|
|
110
|
+
for (const entry of CHECKUP_DICTIONARY_DATA) {
|
|
111
|
+
result[entry.code] = entry.title;
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
package/lib/checkup.ts
CHANGED
|
@@ -51,6 +51,7 @@ import * as fs from "fs";
|
|
|
51
51
|
import * as path from "path";
|
|
52
52
|
import * as pkg from "../package.json";
|
|
53
53
|
import { getMetricSql, transformMetricRow, METRIC_NAMES } from "./metrics-loader";
|
|
54
|
+
import { getCheckupTitle, buildCheckInfoMap } from "./checkup-dictionary";
|
|
54
55
|
|
|
55
56
|
// Time constants
|
|
56
57
|
const SECONDS_PER_DAY = 86400;
|
|
@@ -1185,6 +1186,37 @@ async function generateD004(client: Client, nodeName: string): Promise<Report> {
|
|
|
1185
1186
|
return report;
|
|
1186
1187
|
}
|
|
1187
1188
|
|
|
1189
|
+
/**
|
|
1190
|
+
* Generate D001 report - Logging settings
|
|
1191
|
+
*
|
|
1192
|
+
* Collects all PostgreSQL logging-related settings including:
|
|
1193
|
+
* - Log destination and collector settings
|
|
1194
|
+
* - Log file rotation and naming
|
|
1195
|
+
* - Log verbosity and filtering
|
|
1196
|
+
* - Statement and duration logging
|
|
1197
|
+
*/
|
|
1198
|
+
async function generateD001(client: Client, nodeName: string): Promise<Report> {
|
|
1199
|
+
const report = createBaseReport("D001", "Logging settings", nodeName);
|
|
1200
|
+
const postgresVersion = await getPostgresVersion(client);
|
|
1201
|
+
const pgMajorVersion = parseInt(postgresVersion.server_major_ver, 10) || 16;
|
|
1202
|
+
const allSettings = await getSettings(client, pgMajorVersion);
|
|
1203
|
+
|
|
1204
|
+
// Filter logging-related settings (log_* and logging_*)
|
|
1205
|
+
const loggingSettings: Record<string, SettingInfo> = {};
|
|
1206
|
+
for (const [name, setting] of Object.entries(allSettings)) {
|
|
1207
|
+
if (name.startsWith("log_") || name.startsWith("logging_")) {
|
|
1208
|
+
loggingSettings[name] = setting;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
report.results[nodeName] = {
|
|
1213
|
+
data: loggingSettings,
|
|
1214
|
+
postgres_version: postgresVersion,
|
|
1215
|
+
};
|
|
1216
|
+
|
|
1217
|
+
return report;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1188
1220
|
/**
|
|
1189
1221
|
* Generate F001 report - Autovacuum: current settings
|
|
1190
1222
|
*/
|
|
@@ -1326,6 +1358,82 @@ async function generateG001(client: Client, nodeName: string): Promise<Report> {
|
|
|
1326
1358
|
return report;
|
|
1327
1359
|
}
|
|
1328
1360
|
|
|
1361
|
+
/**
|
|
1362
|
+
* Generate G003 report - Timeouts, locks, deadlocks
|
|
1363
|
+
*
|
|
1364
|
+
* Collects timeout and lock-related settings, plus deadlock statistics.
|
|
1365
|
+
*/
|
|
1366
|
+
async function generateG003(client: Client, nodeName: string): Promise<Report> {
|
|
1367
|
+
const report = createBaseReport("G003", "Timeouts, locks, deadlocks", nodeName);
|
|
1368
|
+
const postgresVersion = await getPostgresVersion(client);
|
|
1369
|
+
const pgMajorVersion = parseInt(postgresVersion.server_major_ver, 10) || 16;
|
|
1370
|
+
const allSettings = await getSettings(client, pgMajorVersion);
|
|
1371
|
+
|
|
1372
|
+
// Timeout and lock-related setting names
|
|
1373
|
+
const lockTimeoutSettingNames = [
|
|
1374
|
+
"lock_timeout",
|
|
1375
|
+
"statement_timeout",
|
|
1376
|
+
"idle_in_transaction_session_timeout",
|
|
1377
|
+
"idle_session_timeout",
|
|
1378
|
+
"deadlock_timeout",
|
|
1379
|
+
"max_locks_per_transaction",
|
|
1380
|
+
"max_pred_locks_per_transaction",
|
|
1381
|
+
"max_pred_locks_per_relation",
|
|
1382
|
+
"max_pred_locks_per_page",
|
|
1383
|
+
"log_lock_waits",
|
|
1384
|
+
"transaction_timeout",
|
|
1385
|
+
];
|
|
1386
|
+
|
|
1387
|
+
const lockSettings: Record<string, SettingInfo> = {};
|
|
1388
|
+
for (const name of lockTimeoutSettingNames) {
|
|
1389
|
+
if (allSettings[name]) {
|
|
1390
|
+
lockSettings[name] = allSettings[name];
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// Get deadlock statistics from pg_stat_database
|
|
1395
|
+
let deadlockStats: {
|
|
1396
|
+
deadlocks: number;
|
|
1397
|
+
conflicts: number;
|
|
1398
|
+
stats_reset: string | null;
|
|
1399
|
+
} | null = null;
|
|
1400
|
+
let deadlockError: string | null = null;
|
|
1401
|
+
|
|
1402
|
+
try {
|
|
1403
|
+
const statsResult = await client.query(`
|
|
1404
|
+
select
|
|
1405
|
+
coalesce(sum(deadlocks), 0)::bigint as deadlocks,
|
|
1406
|
+
coalesce(sum(conflicts), 0)::bigint as conflicts,
|
|
1407
|
+
min(stats_reset)::text as stats_reset
|
|
1408
|
+
from pg_stat_database
|
|
1409
|
+
where datname = current_database()
|
|
1410
|
+
`);
|
|
1411
|
+
if (statsResult.rows.length > 0) {
|
|
1412
|
+
const row = statsResult.rows[0];
|
|
1413
|
+
deadlockStats = {
|
|
1414
|
+
deadlocks: parseInt(row.deadlocks, 10),
|
|
1415
|
+
conflicts: parseInt(row.conflicts, 10),
|
|
1416
|
+
stats_reset: row.stats_reset || null,
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
} catch (err) {
|
|
1420
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
1421
|
+
console.log(`[G003] Error querying deadlock stats: ${errorMsg}`);
|
|
1422
|
+
deadlockError = errorMsg;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
report.results[nodeName] = {
|
|
1426
|
+
data: {
|
|
1427
|
+
settings: lockSettings,
|
|
1428
|
+
deadlock_stats: deadlockStats,
|
|
1429
|
+
...(deadlockError && { deadlock_stats_error: deadlockError }),
|
|
1430
|
+
},
|
|
1431
|
+
postgres_version: postgresVersion,
|
|
1432
|
+
};
|
|
1433
|
+
|
|
1434
|
+
return report;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1329
1437
|
/**
|
|
1330
1438
|
* Available report generators
|
|
1331
1439
|
*/
|
|
@@ -1335,30 +1443,38 @@ export const REPORT_GENERATORS: Record<string, (client: Client, nodeName: string
|
|
|
1335
1443
|
A004: generateA004,
|
|
1336
1444
|
A007: generateA007,
|
|
1337
1445
|
A013: generateA013,
|
|
1446
|
+
D001: generateD001,
|
|
1338
1447
|
D004: generateD004,
|
|
1339
1448
|
F001: generateF001,
|
|
1340
1449
|
G001: generateG001,
|
|
1450
|
+
G003: generateG003,
|
|
1341
1451
|
H001: generateH001,
|
|
1342
1452
|
H002: generateH002,
|
|
1343
1453
|
H004: generateH004,
|
|
1344
1454
|
};
|
|
1345
1455
|
|
|
1346
1456
|
/**
|
|
1347
|
-
* Check IDs and titles
|
|
1457
|
+
* Check IDs and titles.
|
|
1458
|
+
*
|
|
1459
|
+
* This mapping is built from the embedded checkup dictionary, which is
|
|
1460
|
+
* fetched from https://postgres.ai/api/general/checkup_dictionary at build time.
|
|
1461
|
+
*
|
|
1462
|
+
* For the full dictionary (all available checks), use the checkup-dictionary module.
|
|
1463
|
+
* CHECK_INFO is filtered to only include checks that have express-mode generators.
|
|
1348
1464
|
*/
|
|
1349
|
-
export const CHECK_INFO: Record<string, string> = {
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
};
|
|
1465
|
+
export const CHECK_INFO: Record<string, string> = (() => {
|
|
1466
|
+
// Build the full dictionary map
|
|
1467
|
+
const fullMap = buildCheckInfoMap();
|
|
1468
|
+
|
|
1469
|
+
// Filter to only include checks that have express-mode generators
|
|
1470
|
+
const expressCheckIds = Object.keys(REPORT_GENERATORS);
|
|
1471
|
+
const filtered: Record<string, string> = {};
|
|
1472
|
+
for (const checkId of expressCheckIds) {
|
|
1473
|
+
// Use dictionary title if available, otherwise use a fallback
|
|
1474
|
+
filtered[checkId] = fullMap[checkId] || checkId;
|
|
1475
|
+
}
|
|
1476
|
+
return filtered;
|
|
1477
|
+
})();
|
|
1362
1478
|
|
|
1363
1479
|
/**
|
|
1364
1480
|
* Generate all available health check reports.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "postgresai",
|
|
3
|
-
"version": "0.14.0-beta.
|
|
3
|
+
"version": "0.14.0-beta.15",
|
|
4
4
|
"description": "postgres_ai CLI",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"private": false,
|
|
@@ -26,15 +26,17 @@
|
|
|
26
26
|
},
|
|
27
27
|
"scripts": {
|
|
28
28
|
"embed-metrics": "bun run scripts/embed-metrics.ts",
|
|
29
|
-
"
|
|
29
|
+
"embed-checkup-dictionary": "bun run scripts/embed-checkup-dictionary.ts",
|
|
30
|
+
"embed-all": "bun run embed-metrics && bun run embed-checkup-dictionary",
|
|
31
|
+
"build": "bun run embed-all && bun build ./bin/postgres-ai.ts --outdir ./dist/bin --target node && node -e \"const fs=require('fs');const f='./dist/bin/postgres-ai.js';fs.writeFileSync(f,fs.readFileSync(f,'utf8').replace('#!/usr/bin/env bun','#!/usr/bin/env node'))\" && cp -r ./sql ./dist/sql",
|
|
30
32
|
"prepublishOnly": "npm run build",
|
|
31
33
|
"start": "bun ./bin/postgres-ai.ts --help",
|
|
32
34
|
"start:node": "node ./dist/bin/postgres-ai.js --help",
|
|
33
|
-
"dev": "bun run embed-
|
|
34
|
-
"test": "bun run embed-
|
|
35
|
-
"test:fast": "bun run embed-
|
|
36
|
-
"test:coverage": "bun run embed-
|
|
37
|
-
"typecheck": "bun run embed-
|
|
35
|
+
"dev": "bun run embed-all && bun --watch ./bin/postgres-ai.ts",
|
|
36
|
+
"test": "bun run embed-all && bun test",
|
|
37
|
+
"test:fast": "bun run embed-all && bun test --coverage=false",
|
|
38
|
+
"test:coverage": "bun run embed-all && bun test --coverage && echo 'Coverage report: cli/coverage/lcov-report/index.html'",
|
|
39
|
+
"typecheck": "bun run embed-all && bunx tsc --noEmit"
|
|
38
40
|
},
|
|
39
41
|
"dependencies": {
|
|
40
42
|
"@modelcontextprotocol/sdk": "^1.20.2",
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Build script to fetch checkup dictionary from API and embed it.
|
|
4
|
+
*
|
|
5
|
+
* This script fetches from https://postgres.ai/api/general/checkup_dictionary
|
|
6
|
+
* and generates cli/lib/checkup-dictionary-embedded.ts with the data embedded.
|
|
7
|
+
*
|
|
8
|
+
* The generated file is NOT committed to git - it's regenerated at build time.
|
|
9
|
+
*
|
|
10
|
+
* Usage: bun run scripts/embed-checkup-dictionary.ts
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import * as fs from "fs";
|
|
14
|
+
import * as path from "path";
|
|
15
|
+
|
|
16
|
+
// API endpoint - always available without auth
|
|
17
|
+
const DICTIONARY_URL = "https://postgres.ai/api/general/checkup_dictionary";
|
|
18
|
+
|
|
19
|
+
// Output path relative to cli/ directory
|
|
20
|
+
const CLI_DIR = path.resolve(__dirname, "..");
|
|
21
|
+
const OUTPUT_PATH = path.resolve(CLI_DIR, "lib/checkup-dictionary-embedded.ts");
|
|
22
|
+
|
|
23
|
+
// Request timeout (10 seconds)
|
|
24
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
25
|
+
|
|
26
|
+
interface CheckupDictionaryEntry {
|
|
27
|
+
code: string;
|
|
28
|
+
title: string;
|
|
29
|
+
description: string;
|
|
30
|
+
category: string;
|
|
31
|
+
sort_order: number | null;
|
|
32
|
+
is_system_report: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function generateTypeScript(data: CheckupDictionaryEntry[], sourceUrl: string): string {
|
|
36
|
+
const lines: string[] = [
|
|
37
|
+
"// AUTO-GENERATED FILE - DO NOT EDIT",
|
|
38
|
+
`// Generated from: ${sourceUrl}`,
|
|
39
|
+
`// Generated at: ${new Date().toISOString()}`,
|
|
40
|
+
"// To regenerate: bun run embed-checkup-dictionary",
|
|
41
|
+
"",
|
|
42
|
+
'import { CheckupDictionaryEntry } from "./checkup-dictionary";',
|
|
43
|
+
"",
|
|
44
|
+
"/**",
|
|
45
|
+
" * Embedded checkup dictionary data fetched from API at build time.",
|
|
46
|
+
" * Contains all available checkup report codes, titles, and metadata.",
|
|
47
|
+
" */",
|
|
48
|
+
`export const CHECKUP_DICTIONARY_DATA: CheckupDictionaryEntry[] = ${JSON.stringify(data, null, 2)};`,
|
|
49
|
+
"",
|
|
50
|
+
];
|
|
51
|
+
return lines.join("\n");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function fetchWithTimeout(url: string, timeoutMs: number): Promise<Response> {
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
60
|
+
return response;
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timeoutId);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function main() {
|
|
67
|
+
console.log(`Fetching checkup dictionary from: ${DICTIONARY_URL}`);
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
const response = await fetchWithTimeout(DICTIONARY_URL, FETCH_TIMEOUT_MS);
|
|
71
|
+
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const data: CheckupDictionaryEntry[] = await response.json();
|
|
77
|
+
|
|
78
|
+
if (!Array.isArray(data)) {
|
|
79
|
+
throw new Error("Expected array response from API");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Validate entries have required fields
|
|
83
|
+
for (const entry of data) {
|
|
84
|
+
if (!entry.code || !entry.title) {
|
|
85
|
+
throw new Error(`Invalid entry missing code or title: ${JSON.stringify(entry)}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const tsCode = generateTypeScript(data, DICTIONARY_URL);
|
|
90
|
+
fs.writeFileSync(OUTPUT_PATH, tsCode, "utf8");
|
|
91
|
+
|
|
92
|
+
console.log(`Generated: ${OUTPUT_PATH}`);
|
|
93
|
+
console.log(`Dictionary contains ${data.length} entries`);
|
|
94
|
+
} catch (err) {
|
|
95
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
96
|
+
console.warn(`Warning: Failed to fetch checkup dictionary: ${errorMsg}`);
|
|
97
|
+
console.warn("Generating empty dictionary as fallback");
|
|
98
|
+
|
|
99
|
+
// Generate empty dictionary to allow build to proceed
|
|
100
|
+
const fallbackTs = generateTypeScript([], `N/A (fetch failed: ${errorMsg})`);
|
|
101
|
+
fs.writeFileSync(OUTPUT_PATH, fallbackTs, "utf8");
|
|
102
|
+
console.log(`Generated fallback dictionary at ${OUTPUT_PATH}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
main();
|
package/test/checkup.test.ts
CHANGED
|
@@ -85,28 +85,27 @@ describe("createBaseReport", () => {
|
|
|
85
85
|
|
|
86
86
|
// Tests for CHECK_INFO
|
|
87
87
|
describe("CHECK_INFO and REPORT_GENERATORS", () => {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
G001: "Memory-related settings",
|
|
97
|
-
H001: "Invalid indexes",
|
|
98
|
-
H002: "Unused indexes",
|
|
99
|
-
H004: "Redundant indexes",
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
test("CHECK_INFO contains all expected checks with correct descriptions", () => {
|
|
103
|
-
for (const [checkId, description] of Object.entries(expectedChecks)) {
|
|
104
|
-
expect(checkup.CHECK_INFO[checkId]).toBe(description);
|
|
88
|
+
// Express-mode checks that have generators
|
|
89
|
+
const expressCheckIds = ["A002", "A003", "A004", "A007", "A013", "D001", "D004", "F001", "G001", "G003", "H001", "H002", "H004"];
|
|
90
|
+
|
|
91
|
+
test("CHECK_INFO contains all express-mode checks", () => {
|
|
92
|
+
for (const checkId of expressCheckIds) {
|
|
93
|
+
expect(checkup.CHECK_INFO[checkId]).toBeDefined();
|
|
94
|
+
expect(typeof checkup.CHECK_INFO[checkId]).toBe("string");
|
|
95
|
+
expect(checkup.CHECK_INFO[checkId].length).toBeGreaterThan(0);
|
|
105
96
|
}
|
|
106
97
|
});
|
|
107
98
|
|
|
99
|
+
test("CHECK_INFO titles are loaded from embedded dictionary", () => {
|
|
100
|
+
// Verify a few known titles match the API dictionary
|
|
101
|
+
// These are canonical titles from postgres.ai/api/general/checkup_dictionary
|
|
102
|
+
expect(checkup.CHECK_INFO["A002"]).toBe("Postgres major version");
|
|
103
|
+
expect(checkup.CHECK_INFO["H001"]).toBe("Invalid indexes");
|
|
104
|
+
expect(checkup.CHECK_INFO["H002"]).toBe("Unused indexes");
|
|
105
|
+
});
|
|
106
|
+
|
|
108
107
|
test("REPORT_GENERATORS has function for each check", () => {
|
|
109
|
-
for (const checkId of
|
|
108
|
+
for (const checkId of expressCheckIds) {
|
|
110
109
|
expect(typeof checkup.REPORT_GENERATORS[checkId]).toBe("function");
|
|
111
110
|
}
|
|
112
111
|
});
|
package/lib/metrics-embedded.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
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-13T04:02:21.955Z
|
|
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
|
-
};
|