IntrospectSchema queries the database to build a catalog containing tables and columns for the database.
(ctx context.Context, schemas []string)
| 259 | // IntrospectSchema queries the database to build a catalog containing |
| 260 | // tables and columns for the database. |
| 261 | func (a *Analyzer) IntrospectSchema(ctx context.Context, schemas []string) (*catalog.Catalog, error) { |
| 262 | a.mu.Lock() |
| 263 | defer a.mu.Unlock() |
| 264 | |
| 265 | if a.conn == nil { |
| 266 | return nil, fmt.Errorf("database connection not initialized") |
| 267 | } |
| 268 | |
| 269 | // Build catalog |
| 270 | cat := &catalog.Catalog{ |
| 271 | DefaultSchema: "main", |
| 272 | } |
| 273 | |
| 274 | // Create default schema |
| 275 | mainSchema := &catalog.Schema{Name: "main"} |
| 276 | cat.Schemas = append(cat.Schemas, mainSchema) |
| 277 | |
| 278 | // Query tables from sqlite_master |
| 279 | stmt, _, err := a.conn.Prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") |
| 280 | if err != nil { |
| 281 | return nil, fmt.Errorf("introspect tables: %w", err) |
| 282 | } |
| 283 | |
| 284 | tableNames := []string{} |
| 285 | for stmt.Step() { |
| 286 | tableName := stmt.ColumnText(0) |
| 287 | tableNames = append(tableNames, tableName) |
| 288 | } |
| 289 | stmt.Close() |
| 290 | |
| 291 | // For each table, get column information using PRAGMA table_info |
| 292 | for _, tableName := range tableNames { |
| 293 | tbl := &catalog.Table{ |
| 294 | Rel: &ast.TableName{ |
| 295 | Name: tableName, |
| 296 | }, |
| 297 | } |
| 298 | |
| 299 | pragmaStmt, _, err := a.conn.Prepare(fmt.Sprintf("PRAGMA table_info('%s')", tableName)) |
| 300 | if err != nil { |
| 301 | return nil, fmt.Errorf("pragma table_info for %s: %w", tableName, err) |
| 302 | } |
| 303 | |
| 304 | for pragmaStmt.Step() { |
| 305 | // PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk |
| 306 | colName := pragmaStmt.ColumnText(1) |
| 307 | colType := pragmaStmt.ColumnText(2) |
| 308 | notNull := pragmaStmt.ColumnInt(3) != 0 |
| 309 | |
| 310 | tbl.Columns = append(tbl.Columns, &catalog.Column{ |
| 311 | Name: colName, |
| 312 | Type: ast.TypeName{Name: normalizeType(colType)}, |
| 313 | IsNotNull: notNull, |
| 314 | }) |
| 315 | } |
| 316 | pragmaStmt.Close() |
| 317 | |
| 318 | mainSchema.Tables = append(mainSchema.Tables, tbl) |
nothing calls this directly
no test coverage detected