github.com/dolthub/go-mysql-server@v0.18.0/sql/uservars.go (about)

     1  // Copyright 2022 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package sql
    16  
    17  import (
    18  	"strings"
    19  	"sync"
    20  )
    21  
    22  // SessionUserVariables is a simple dictionary to set and retrieve user variables within a session.
    23  type SessionUserVariables interface {
    24  	// SetUserVariable sets the user variable name to the given value and type
    25  	SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error
    26  	// GetUserVariable returns the value and type of the user variable named
    27  	GetUserVariable(ctx *Context, varName string) (Type, interface{}, error)
    28  }
    29  
    30  type UserVars struct {
    31  	userVars map[string]TypedValue
    32  	mu       *sync.RWMutex
    33  }
    34  
    35  var _ SessionUserVariables = (*UserVars)(nil)
    36  
    37  func NewUserVars() SessionUserVariables {
    38  	return &UserVars{
    39  		userVars: make(map[string]TypedValue),
    40  		mu:       &sync.RWMutex{},
    41  	}
    42  }
    43  
    44  func (u *UserVars) SetUserVariable(ctx *Context, varName string, value interface{}, typ Type) error {
    45  	u.mu.Lock()
    46  	defer u.mu.Unlock()
    47  	u.userVars[strings.ToLower(varName)] = TypedValue{Value: value, Typ: typ}
    48  	return nil
    49  }
    50  
    51  // GetUserVariable implements the Session interface.
    52  func (u *UserVars) GetUserVariable(ctx *Context, varName string) (Type, interface{}, error) {
    53  	u.mu.Lock()
    54  	defer u.mu.Unlock()
    55  	val, ok := u.userVars[strings.ToLower(varName)]
    56  	if !ok {
    57  		return nil, nil, nil
    58  	}
    59  
    60  	return val.Typ, val.Value, nil
    61  }