(ctx context.Context, connstr string, tb TB, fn func(t TB, db *pgx.Conn))
| 76 | } |
| 77 | |
| 78 | func 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 | |
| 119 | func sanitizeDatabaseName(schema string) string { |
| 120 | return pgx.Identifier{schema}.Sanitize() |
no test coverage detected