MCPcopy
hub / github.com/modelcontextprotocol/registry / ensureTemplateDB

Function ensureTemplateDB

internal/database/testutil.go:21–55  ·  view source on GitHub ↗

ensureTemplateDB creates a template database with migrations applied Multiple processes may call this, so we handle race conditions

(ctx context.Context, adminConn *pgx.Conn)

Source from the content-addressed store, hash-verified

19// ensureTemplateDB creates a template database with migrations applied
20// Multiple processes may call this, so we handle race conditions
21func ensureTemplateDB(ctx context.Context, adminConn *pgx.Conn) error {
22 // Check if template exists
23 var exists bool
24 err := adminConn.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", templateDBName).Scan(&exists)
25 if err != nil {
26 return fmt.Errorf("failed to check template database: %w", err)
27 }
28
29 if exists {
30 // Template already exists
31 return nil
32 }
33
34 // Create template database
35 _, err = adminConn.Exec(ctx, fmt.Sprintf("CREATE DATABASE %s", templateDBName))
36 if err != nil {
37 // Ignore duplicate database name error - another process created it concurrently
38 var pgErr *pgconn.PgError
39 if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "pg_database_datname_index" {
40 return nil
41 }
42 return fmt.Errorf("failed to create template database: %w", err)
43 }
44
45 // Connect to template and run migrations
46 templateURI := fmt.Sprintf("postgres://mcpregistry:mcpregistry@localhost:5432/%s?sslmode=disable", templateDBName)
47 templateDB, err := NewPostgreSQL(ctx, templateURI)
48 if err != nil {
49 return fmt.Errorf("failed to connect to template database: %w", err)
50 }
51 defer templateDB.Close()
52
53 // Migrations run automatically in NewPostgreSQL
54 return nil
55}
56
57// NewTestDB creates an isolated PostgreSQL database for each test by copying a template.
58// The template database has migrations pre-applied, so each test is fast.

Callers 1

NewTestDBFunction · 0.85

Calls 4

CloseMethod · 0.95
NewPostgreSQLFunction · 0.85
QueryRowMethod · 0.80
ExecMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…