MCPcopy Create free account
hub / github.com/egonelbre/exp / withDatabase

Function withDatabase

schema/database_test.go:78–117  ·  view source on GitHub ↗
(ctx context.Context, connstr string, tb TB, fn func(t TB, db *pgx.Conn))

Source from the content-addressed store, hash-verified

76}
77
78func withDatabase[TB testing.TB](ctx context.Context, connstr string, tb TB, fn func(t TB, db *pgx.Conn)) {
79 if connstr == "" {
80 tb.Skip("connstr not defined")
81 }
82
83 var id [8]byte
84 rand.Read(id[:])
85 uniqueName := tb.Name() + "/" + hex.EncodeToString(id[:])
86
87 // Create the first connection that we use to create the database.
88 maindb, err := pgx.Connect(ctx, connstr)
89 if err != nil {
90 tb.Fatalf("Unable to connect to database: %v", err)
91 }
92
93 // Run the database creation query and defer the database cleanup query.
94 if err := createDatabase(ctx, maindb, uniqueName); err != nil {
95 tb.Fatalf("unable to create database: %v", err)
96 }
97 defer func() {
98 if err := dropDatabase(ctx, maindb, uniqueName); err != nil {
99 tb.Fatalf("unable to drop database: %v", err)
100 }
101 }()
102
103 // Make a connection the new database.
104 connstr, err = connstrWithDatabase(connstr, uniqueName)
105 if err != nil {
106 tb.Fatal(err)
107 }
108
109 db, err := pgx.Connect(ctx, connstr)
110 if err != nil {
111 tb.Fatalf("Unable to connect to database: %v", err)
112 }
113 defer func() { _ = db.Close(ctx) }()
114
115 // Run our test code.
116 fn(tb, db)
117}
118
119func sanitizeDatabaseName(schema string) string {
120 return pgx.Identifier{schema}.Sanitize()

Callers 4

WithDatabaseFunction · 0.85

Calls 8

createDatabaseFunction · 0.85
dropDatabaseFunction · 0.85
connstrWithDatabaseFunction · 0.85
fnFunction · 0.85
NameMethod · 0.65
CloseMethod · 0.65
ReadMethod · 0.45
ConnectMethod · 0.45

Tested by

no test coverage detected