MCPcopy
hub / github.com/jackc/pgx / TestConnConcurrency

Function TestConnConcurrency

stdlib/sql_test.go:335–421  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

333}
334
335func TestConnConcurrency(t *testing.T) {
336 testWithAllQueryExecModes(t, func(t *testing.T, db *sql.DB) {
337 _, err := db.Exec("create table t (id integer primary key, str text, dur_str interval)")
338 require.NoError(t, err)
339
340 defer func() {
341 _, err := db.Exec("drop table t")
342 require.NoError(t, err)
343 }()
344
345 var wg sync.WaitGroup
346
347 concurrency := 50
348 errChan := make(chan error, concurrency)
349
350 for i := 1; i <= concurrency; i++ {
351 wg.Go(func() {
352 ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
353 defer cancel()
354
355 str := strconv.Itoa(i)
356 duration := time.Duration(i) * time.Second
357 _, err := db.ExecContext(ctx, "insert into t values($1)", i)
358 if err != nil {
359 errChan <- fmt.Errorf("insert failed: %d %w", i, err)
360 return
361 }
362 _, err = db.ExecContext(ctx, "update t set str = $1 where id = $2", str, i)
363 if err != nil {
364 errChan <- fmt.Errorf("update 1 failed: %d %w", i, err)
365 return
366 }
367 _, err = db.ExecContext(ctx, "update t set dur_str = $1 where id = $2", duration, i)
368 if err != nil {
369 errChan <- fmt.Errorf("update 2 failed: %d %w", i, err)
370 return
371 }
372
373 errChan <- nil
374 })
375 }
376 wg.Wait()
377 for i := 1; i <= concurrency; i++ {
378 err := <-errChan
379 require.NoError(t, err)
380 }
381
382 for i := 1; i <= concurrency; i++ {
383 wg.Go(func() {
384 ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
385 defer cancel()
386
387 var id int
388 var str string
389 var duration pgtype.Interval
390 err := db.QueryRowContext(ctx, "select id,str,dur_str from t where id = $1", i).Scan(&id, &str, &duration)
391 if err != nil {
392 errChan <- fmt.Errorf("select failed: %d %w", i, err)

Callers

nothing calls this directly

Calls 4

ExecMethod · 0.65
ScanMethod · 0.65
ExecContextMethod · 0.45

Tested by

no test coverage detected