(t TBSubset)
| 106 | } |
| 107 | |
| 108 | func (b *Broker) init(t TBSubset) error { |
| 109 | b.Lock() |
| 110 | defer b.Unlock() |
| 111 | if b.coderTestingDB != nil { |
| 112 | // already initialized |
| 113 | b.refCount++ |
| 114 | t.Cleanup(b.decRef) |
| 115 | return nil |
| 116 | } |
| 117 | |
| 118 | connectionParamsInitOnce.Do(func() { |
| 119 | errDefaultConnectionParamsInit = initDefaultConnection(t) |
| 120 | }) |
| 121 | if errDefaultConnectionParamsInit != nil { |
| 122 | return xerrors.Errorf("init default connection params: %w", errDefaultConnectionParamsInit) |
| 123 | } |
| 124 | coderTestingParams := defaultConnectionParams |
| 125 | coderTestingParams.DBName = CoderTestingDBName |
| 126 | coderTestingDB, err := sql.Open("postgres", coderTestingParams.DSN()) |
| 127 | if err != nil { |
| 128 | return xerrors.Errorf("open postgres connection: %w", err) |
| 129 | } |
| 130 | |
| 131 | // coderTestingSQLInit is idempotent, so we can run it every time. |
| 132 | _, err = coderTestingDB.Exec(coderTestingSQLInit) |
| 133 | var pqErr *pq.Error |
| 134 | if xerrors.As(err, &pqErr) && pqErr.Code == "3D000" { |
| 135 | // database does not exist. |
| 136 | if closeErr := coderTestingDB.Close(); closeErr != nil { |
| 137 | return xerrors.Errorf("close postgres connection: %w", closeErr) |
| 138 | } |
| 139 | err = createCoderTestingDB(t) |
| 140 | if err != nil { |
| 141 | return xerrors.Errorf("create coder testing db: %w", err) |
| 142 | } |
| 143 | coderTestingDB, err = sql.Open("postgres", coderTestingParams.DSN()) |
| 144 | if err != nil { |
| 145 | return xerrors.Errorf("open postgres connection: %w", err) |
| 146 | } |
| 147 | } else if err != nil { |
| 148 | _ = coderTestingDB.Close() |
| 149 | return xerrors.Errorf("ping '%s' database: %w", CoderTestingDBName, err) |
| 150 | } |
| 151 | b.coderTestingDB = coderTestingDB |
| 152 | b.refCount++ |
| 153 | t.Cleanup(b.decRef) |
| 154 | |
| 155 | if b.uuid == uuid.Nil { |
| 156 | b.uuid = uuid.New() |
| 157 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 158 | defer cancel() |
| 159 | b.cleanerFD, err = startCleaner(ctx, t, b.uuid, coderTestingParams.DSN()) |
| 160 | if err != nil { |
| 161 | return xerrors.Errorf("start test db cleaner: %w", err) |
| 162 | } |
| 163 | } |
| 164 | return nil |
| 165 | } |
no test coverage detected