MCPcopy
hub / github.com/BuilderIO/agent-native / introspectPostgres

Function introspectPostgres

packages/core/src/scripts/db/schema.ts:74–219  ·  view source on GitHub ↗
(
  url: string,
  parsed: Record<string, string>,
)

Source from the content-addressed store, hash-verified

72// ---------------------------------------------------------------------------
73
74async function introspectPostgres(
75 url: string,
76 parsed: Record<string, string>,
77): Promise<void> {
78 const { default: pg } = await import("postgres");
79 const sql = pg(url);
80
81 try {
82 // List tables
83 const tables: { name: string }[] = await sql`
84 SELECT table_name as name
85 FROM information_schema.tables
86 WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
87 ORDER BY table_name
88 `;
89
90 const tableInfos: TableInfo[] = [];
91
92 for (const t of tables) {
93 // Columns
94 const cols: any[] = await sql`
95 SELECT
96 column_name as name,
97 data_type as type,
98 CASE WHEN is_nullable = 'NO' THEN 1 ELSE 0 END as notnull,
99 column_default as dflt_value
100 FROM information_schema.columns
101 WHERE table_name = ${t.name}
102 ORDER BY ordinal_position
103 `;
104
105 // Primary keys
106 const pks: any[] = await sql`
107 SELECT kcu.column_name
108 FROM information_schema.table_constraints tc
109 JOIN information_schema.key_column_usage kcu
110 ON tc.constraint_name = kcu.constraint_name
111 AND tc.table_schema = kcu.table_schema
112 WHERE tc.table_name = ${t.name}
113 AND tc.constraint_type = 'PRIMARY KEY'
114 `;
115 const pkSet = new Set(pks.map((p) => p.column_name));
116
117 // Foreign keys
118 const fks: any[] = await sql`
119 SELECT
120 kcu.column_name as "from",
121 ccu.table_name as "table",
122 ccu.column_name as "to"
123 FROM information_schema.table_constraints tc
124 JOIN information_schema.key_column_usage kcu
125 ON tc.constraint_name = kcu.constraint_name
126 JOIN information_schema.constraint_column_usage ccu
127 ON tc.constraint_name = ccu.constraint_name
128 WHERE tc.table_name = ${t.name}
129 AND tc.constraint_type = 'FOREIGN KEY'
130 `;
131

Callers 1

dbSchemaFunction · 0.70

Calls 4

pgFunction · 0.85
sqlFunction · 0.85
databaseLabelFunction · 0.85
getMethod · 0.80

Tested by

no test coverage detected