| 227 | } |
| 228 | |
| 229 | export async function executeIntrospect( |
| 230 | sql: any, |
| 231 | schemaName = 'public' |
| 232 | ): Promise<IntrospectionResult> { |
| 233 | const schemasResult = await sql` |
| 234 | SELECT schema_name |
| 235 | FROM information_schema.schemata |
| 236 | WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast') |
| 237 | ORDER BY schema_name |
| 238 | ` |
| 239 | const schemas = schemasResult.map((row: { schema_name: string }) => row.schema_name) |
| 240 | |
| 241 | const tablesResult = await sql` |
| 242 | SELECT table_name, table_schema |
| 243 | FROM information_schema.tables |
| 244 | WHERE table_schema = ${schemaName} |
| 245 | AND table_type = 'BASE TABLE' |
| 246 | ORDER BY table_name |
| 247 | ` |
| 248 | |
| 249 | const tables = [] |
| 250 | |
| 251 | for (const tableRow of tablesResult) { |
| 252 | const tableName = tableRow.table_name |
| 253 | const tableSchema = tableRow.table_schema |
| 254 | |
| 255 | const columnsResult = await sql` |
| 256 | SELECT |
| 257 | c.column_name, |
| 258 | c.data_type, |
| 259 | c.is_nullable, |
| 260 | c.column_default, |
| 261 | c.udt_name |
| 262 | FROM information_schema.columns c |
| 263 | WHERE c.table_schema = ${tableSchema} |
| 264 | AND c.table_name = ${tableName} |
| 265 | ORDER BY c.ordinal_position |
| 266 | ` |
| 267 | |
| 268 | const pkResult = await sql` |
| 269 | SELECT kcu.column_name |
| 270 | FROM information_schema.table_constraints tc |
| 271 | JOIN information_schema.key_column_usage kcu |
| 272 | ON tc.constraint_name = kcu.constraint_name |
| 273 | AND tc.table_schema = kcu.table_schema |
| 274 | WHERE tc.constraint_type = 'PRIMARY KEY' |
| 275 | AND tc.table_schema = ${tableSchema} |
| 276 | AND tc.table_name = ${tableName} |
| 277 | ` |
| 278 | const primaryKeyColumns = pkResult.map((row: { column_name: string }) => row.column_name) |
| 279 | |
| 280 | const fkResult = await sql` |
| 281 | SELECT |
| 282 | kcu.column_name, |
| 283 | ccu.table_name AS foreign_table_name, |
| 284 | ccu.column_name AS foreign_column_name |
| 285 | FROM information_schema.table_constraints tc |
| 286 | JOIN information_schema.key_column_usage kcu |