github.com/blend/go-sdk@v1.20220411.3/examples/db/statement-timeout/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 verifyStatementTimeout(ctx context.Context, pool *db.Connection) (time.Duration, error) {
    19  	type statementTimeoutRow struct {
    20  		StatementTimeout string `db:"statement_timeout"`
    21  	}
    22  
    23  	q := pool.QueryContext(ctx, "SHOW statement_timeout;")
    24  	r := statementTimeoutRow{}
    25  	found, err := q.Out(&r)
    26  	if !found {
    27  		return 0, ex.New("`SHOW statement_timeout;` query returned no results")
    28  	}
    29  	if err != nil {
    30  		return 0, err
    31  	}
    32  
    33  	d, err := time.ParseDuration(r.StatementTimeout)
    34  	if err != nil {
    35  		return 0, err
    36  	}
    37  
    38  	return d, nil
    39  }
    40  
    41  func ensureStatementTimeout(ctx context.Context, pool *db.Connection, cfg *config) (time.Duration, error) {
    42  	timeout, err := verifyStatementTimeout(ctx, pool)
    43  	if err != nil {
    44  		return 0, err
    45  	}
    46  
    47  	if timeout != cfg.StatementTimeout {
    48  		err = ex.New(
    49  			"Expected the default statement timeout to be set",
    50  			ex.OptMessagef("Timeout: %s, Expected: %s", timeout, cfg.StatementTimeout),
    51  		)
    52  		return 0, err
    53  	}
    54  
    55  	return timeout, nil
    56  }