MCPcopy
hub / github.com/sqlc-dev/sqlc / EnsureConn

Method EnsureConn

internal/engine/sqlite/analyzer/analyze.go:188–232  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.
188func (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.

Callers

nothing calls this directly

Implementers 3

CachedAnalyzerinternal/analyzer/analyzer.go
Analyzerinternal/engine/postgresql/analyzer/an
Analyzerinternal/engine/sqlite/analyzer/analyz

Calls 5

isInMemoryDatabaseFunction · 0.85
OpenMethod · 0.80
ExecMethod · 0.65
CloseMethod · 0.65
ReplaceMethod · 0.45

Tested by

no test coverage detected