github.com/wangyougui/gf/v2@v2.6.5/database/gdb/gdb_core_ctx.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gdb
     8  
     9  import (
    10  	"context"
    11  
    12  	"github.com/wangyougui/gf/v2/os/gctx"
    13  )
    14  
    15  // internalCtxData stores data in ctx for internal usage purpose.
    16  type internalCtxData struct {
    17  	// Operation DB.
    18  	DB DB
    19  
    20  	// Used configuration node in current operation.
    21  	ConfigNode *ConfigNode
    22  
    23  	// The first column in result response from database server.
    24  	// This attribute is used for Value/Count selection statement purpose,
    25  	// which is to avoid HOOK handler that might modify the result columns
    26  	// that can confuse the Value/Count selection statement logic.
    27  	FirstResultColumn string
    28  }
    29  
    30  const (
    31  	internalCtxDataKeyInCtx gctx.StrKey = "InternalCtxData"
    32  
    33  	// `ignoreResultKeyInCtx` is a mark for some db drivers that do not support `RowsAffected` function,
    34  	// for example: `clickhouse`. The `clickhouse` does not support fetching insert/update results,
    35  	// but returns errors when execute `RowsAffected`. It here ignores the calling of `RowsAffected`
    36  	// to avoid triggering errors, rather than ignoring errors after they are triggered.
    37  	ignoreResultKeyInCtx gctx.StrKey = "IgnoreResult"
    38  )
    39  
    40  func (c *Core) InjectInternalCtxData(ctx context.Context) context.Context {
    41  	// If the internal data is already injected, it does nothing.
    42  	if ctx.Value(internalCtxDataKeyInCtx) != nil {
    43  		return ctx
    44  	}
    45  	return context.WithValue(ctx, internalCtxDataKeyInCtx, &internalCtxData{
    46  		DB:         c.db,
    47  		ConfigNode: c.config,
    48  	})
    49  }
    50  
    51  func (c *Core) GetInternalCtxDataFromCtx(ctx context.Context) *internalCtxData {
    52  	if v := ctx.Value(internalCtxDataKeyInCtx); v != nil {
    53  		return v.(*internalCtxData)
    54  	}
    55  	return nil
    56  }
    57  
    58  func (c *Core) InjectIgnoreResult(ctx context.Context) context.Context {
    59  	if ctx.Value(ignoreResultKeyInCtx) != nil {
    60  		return ctx
    61  	}
    62  	return context.WithValue(ctx, ignoreResultKeyInCtx, true)
    63  }
    64  
    65  func (c *Core) GetIgnoreResultFromCtx(ctx context.Context) bool {
    66  	return ctx.Value(ignoreResultKeyInCtx) != nil
    67  }