github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/config/prefix_config.go (about)

     1  // Copyright 2021 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 config
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  )
    21  
    22  // PrefixConfig decorates read and write access to the underlying config by appending a prefix to the accessed keys
    23  // on reads and writes. Used for the sqlserver.global persisted system variables.
    24  type PrefixConfig struct {
    25  	c      ReadWriteConfig
    26  	prefix string
    27  }
    28  
    29  func NewPrefixConfig(cfg ReadWriteConfig, prefix string) PrefixConfig {
    30  	return PrefixConfig{c: cfg, prefix: prefix}
    31  }
    32  
    33  func (nsc PrefixConfig) path(key string) string {
    34  	return fmt.Sprintf("%s.%s", nsc.prefix, key)
    35  }
    36  
    37  func (nsc PrefixConfig) GetString(key string) (value string, err error) {
    38  	return nsc.c.GetString(nsc.path(key))
    39  }
    40  
    41  func (nsc PrefixConfig) GetStringOrDefault(key, defStr string) string {
    42  	return nsc.c.GetStringOrDefault(nsc.path(key), defStr)
    43  }
    44  
    45  func (nsc PrefixConfig) SetStrings(updates map[string]string) error {
    46  	for k, v := range updates {
    47  		delete(updates, k)
    48  		updates[nsc.path(k)] = v
    49  	}
    50  	return nsc.c.SetStrings(updates)
    51  }
    52  
    53  func (nsc PrefixConfig) Iter(cb func(string, string) (stop bool)) {
    54  	nsc.c.Iter(func(k, v string) (stop bool) {
    55  		if strings.HasPrefix(k, nsc.prefix+".") {
    56  			return cb(strings.TrimPrefix(k, nsc.prefix+"."), v)
    57  		}
    58  		return false
    59  	})
    60  	return
    61  }
    62  
    63  func (nsc PrefixConfig) Size() int {
    64  	count := 0
    65  	nsc.Iter(func(k, v string) (stop bool) {
    66  		count += 1
    67  		return false
    68  	})
    69  	return count
    70  }
    71  
    72  func (nsc PrefixConfig) Unset(params []string) error {
    73  	for i, k := range params {
    74  		params[i] = nsc.path(k)
    75  	}
    76  	return nsc.c.Unset(params)
    77  }