EnsureConn initializes the database connection if not already done. This is useful for database-only mode where we need to connect before analyzing queries.
(ctx context.Context, migrations []string)
| 186 | // EnsureConn initializes the database connection if not already done. |
| 187 | // This is useful for database-only mode where we need to connect before analyzing queries. |
| 188 | func (a *Analyzer) EnsureConn(ctx context.Context, migrations []string) error { |
| 189 | a.mu.Lock() |
| 190 | defer a.mu.Unlock() |
| 191 | |
| 192 | if a.conn != nil { |
| 193 | return nil |
| 194 | } |
| 195 | |
| 196 | var uri string |
| 197 | applyMigrations := a.db.Managed |
| 198 | if a.db.Managed { |
| 199 | // For managed databases, create an in-memory database |
| 200 | uri = ":memory:" |
| 201 | } else if a.dbg.OnlyManagedDatabases { |
| 202 | return fmt.Errorf("database: connections disabled via SQLCDEBUG=databases=managed") |
| 203 | } else { |
| 204 | uri = a.replacer.Replace(a.db.URI) |
| 205 | // For in-memory databases, we need to apply migrations since the database starts empty |
| 206 | if isInMemoryDatabase(uri) { |
| 207 | applyMigrations = true |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | conn, err := sqlite3.Open(uri) |
| 212 | if err != nil { |
| 213 | return fmt.Errorf("failed to open sqlite database: %w", err) |
| 214 | } |
| 215 | a.conn = conn |
| 216 | |
| 217 | // Apply migrations for managed or in-memory databases |
| 218 | if applyMigrations { |
| 219 | for _, m := range migrations { |
| 220 | if len(strings.TrimSpace(m)) == 0 { |
| 221 | continue |
| 222 | } |
| 223 | if err := a.conn.Exec(m); err != nil { |
| 224 | a.conn.Close() |
| 225 | a.conn = nil |
| 226 | return fmt.Errorf("migration failed: %s: %w", m, err) |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | // GetColumnNames implements the expander.ColumnGetter interface. |
| 235 | // It prepares a query and returns the column names from the result set description. |
nothing calls this directly
no test coverage detected