github.com/blend/go-sdk@v1.20220411.3/examples/db/prevent-deadlock/ensure.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"context"
    12  	"time"
    13  
    14  	"github.com/blend/go-sdk/db"
    15  	"github.com/blend/go-sdk/ex"
    16  )
    17  
    18  func verifyLockTimeout(ctx context.Context, pool *db.Connection) (time.Duration, error) {
    19  	type lockTimeoutRow struct {
    20  		LockTimeout string `db:"lock_timeout"`
    21  	}
    22  
    23  	q := pool.QueryContext(ctx, "SHOW lock_timeout;")
    24  	r := lockTimeoutRow{}
    25  	found, err := q.Out(&r)
    26  	if err != nil {
    27  		return 0, err
    28  	}
    29  	if !found {
    30  		return 0, ex.New("`SHOW lock_timeout;` query returned no results")
    31  	}
    32  
    33  	d, err := time.ParseDuration(r.LockTimeout)
    34  	if err != nil {
    35  		return 0, err
    36  	}
    37  
    38  	return d, nil
    39  }
    40  
    41  func ensureLockTimeout(ctx context.Context, pool *db.Connection, cfg *config) (time.Duration, error) {
    42  	timeout, err := verifyLockTimeout(ctx, pool)
    43  	if err != nil {
    44  		return 0, err
    45  	}
    46  
    47  	if timeout != cfg.LockTimeout {
    48  		err = ex.New(
    49  			"Expected the default lock timeout to be set",
    50  			ex.OptMessagef("Timeout: %s, Expected: %s", timeout, cfg.LockTimeout),
    51  		)
    52  		return 0, err
    53  	}
    54  
    55  	return timeout, nil
    56  }