github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/doltcore/sqle/dsess/variables.go (about)

     1  // Copyright 2020 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 dsess
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/dolthub/go-mysql-server/sql"
    22  	"github.com/dolthub/go-mysql-server/sql/types"
    23  )
    24  
    25  // Per-DB system variables
    26  const (
    27  	HeadKeySuffix          = "_head"
    28  	HeadRefKeySuffix       = "_head_ref"
    29  	WorkingKeySuffix       = "_working"
    30  	StagedKeySuffix        = "_staged"
    31  	DefaultBranchKeySuffix = "_default_branch"
    32  )
    33  
    34  // General system variables
    35  const (
    36  	DoltCommitOnTransactionCommit        = "dolt_transaction_commit"
    37  	DoltCommitOnTransactionCommitMessage = "dolt_transaction_commit_message"
    38  	TransactionsDisabledSysVar           = "dolt_transactions_disabled"
    39  	ForceTransactionCommit               = "dolt_force_transaction_commit"
    40  	CurrentBatchModeKey                  = "batch_mode"
    41  	DoltOverrideSchema                   = "dolt_override_schema"
    42  	AllowCommitConflicts                 = "dolt_allow_commit_conflicts"
    43  	ReplicateToRemote                    = "dolt_replicate_to_remote"
    44  	ReadReplicaRemote                    = "dolt_read_replica_remote"
    45  	ReadReplicaForcePull                 = "dolt_read_replica_force_pull"
    46  	ReplicationRemoteURLTemplate         = "dolt_replication_remote_url_template"
    47  	SkipReplicationErrors                = "dolt_skip_replication_errors"
    48  	ReplicateHeads                       = "dolt_replicate_heads"
    49  	ReplicateAllHeads                    = "dolt_replicate_all_heads"
    50  	AsyncReplication                     = "dolt_async_replication"
    51  	AwsCredsFile                         = "aws_credentials_file"
    52  	AwsCredsProfile                      = "aws_credentials_profile"
    53  	AwsCredsRegion                       = "aws_credentials_region"
    54  	ShowBranchDatabases                  = "dolt_show_branch_databases"
    55  	DoltLogLevel                         = "dolt_log_level"
    56  	ShowSystemTables                     = "dolt_show_system_tables"
    57  
    58  	DoltClusterRoleVariable         = "dolt_cluster_role"
    59  	DoltClusterRoleEpochVariable    = "dolt_cluster_role_epoch"
    60  	DoltClusterAckWritesTimeoutSecs = "dolt_cluster_ack_writes_timeout_secs"
    61  
    62  	DoltStatsAutoRefreshEnabled   = "dolt_stats_auto_refresh_enabled"
    63  	DoltStatsAutoRefreshThreshold = "dolt_stats_auto_refresh_threshold"
    64  	DoltStatsAutoRefreshInterval  = "dolt_stats_auto_refresh_interval"
    65  	DoltStatsMemoryOnly           = "dolt_stats_memory_only"
    66  	DoltStatsBranches             = "dolt_stats_branches"
    67  )
    68  
    69  const URLTemplateDatabasePlaceholder = "{database}"
    70  
    71  // DefineSystemVariablesForDB defines per database dolt-session variables in the engine as necessary
    72  func DefineSystemVariablesForDB(name string) {
    73  	name, _ = SplitRevisionDbName(name)
    74  
    75  	if _, _, ok := sql.SystemVariables.GetGlobal(name + HeadKeySuffix); !ok {
    76  		sql.SystemVariables.AddSystemVariables([]sql.SystemVariable{
    77  			&sql.MysqlSystemVariable{
    78  				Name:              HeadRefKey(name),
    79  				Scope:             sql.GetMysqlScope(sql.SystemVariableScope_Session),
    80  				Dynamic:           true,
    81  				SetVarHintApplies: false,
    82  				Type:              types.NewSystemStringType(HeadRefKey(name)),
    83  				Default:           "",
    84  			},
    85  			// The following variable are Dynamic, but read-only. Their values
    86  			// can only be updates by the system, not by users.
    87  			&sql.MysqlSystemVariable{
    88  				Name:              HeadKey(name),
    89  				Scope:             sql.GetMysqlScope(sql.SystemVariableScope_Session),
    90  				Dynamic:           true,
    91  				SetVarHintApplies: false,
    92  				Type:              types.NewSystemStringType(HeadKey(name)),
    93  				Default:           "",
    94  			},
    95  			&sql.MysqlSystemVariable{
    96  				Name:              WorkingKey(name),
    97  				Scope:             sql.GetMysqlScope(sql.SystemVariableScope_Session),
    98  				Dynamic:           true,
    99  				SetVarHintApplies: false,
   100  				Type:              types.NewSystemStringType(WorkingKey(name)),
   101  				Default:           "",
   102  			},
   103  			&sql.MysqlSystemVariable{
   104  				Name:              StagedKey(name),
   105  				Scope:             sql.GetMysqlScope(sql.SystemVariableScope_Session),
   106  				Dynamic:           true,
   107  				SetVarHintApplies: false,
   108  				Type:              types.NewSystemStringType(StagedKey(name)),
   109  				Default:           "",
   110  			},
   111  			&sql.MysqlSystemVariable{
   112  				Name:              DefaultBranchKey(name),
   113  				Scope:             sql.GetMysqlScope(sql.SystemVariableScope_Global),
   114  				Dynamic:           true,
   115  				SetVarHintApplies: false,
   116  				Type:              types.NewSystemStringType(DefaultBranchKey(name)),
   117  				Default:           "",
   118  			},
   119  		})
   120  	}
   121  }
   122  
   123  func HeadKey(dbName string) string {
   124  	return dbName + HeadKeySuffix
   125  }
   126  
   127  func HeadRefKey(dbName string) string {
   128  	return dbName + HeadRefKeySuffix
   129  }
   130  
   131  func WorkingKey(dbName string) string {
   132  	return dbName + WorkingKeySuffix
   133  }
   134  
   135  func StagedKey(dbName string) string {
   136  	return dbName + StagedKeySuffix
   137  }
   138  
   139  func DefaultBranchKey(dbName string) string {
   140  	return dbName + DefaultBranchKeySuffix
   141  }
   142  
   143  func IsHeadKey(key string) (bool, string) {
   144  	if strings.HasSuffix(key, HeadKeySuffix) {
   145  		return true, key[:len(key)-len(HeadKeySuffix)]
   146  	}
   147  
   148  	return false, ""
   149  }
   150  
   151  func IsHeadRefKey(key string) (bool, string) {
   152  	if strings.HasSuffix(key, HeadRefKeySuffix) {
   153  		return true, key[:len(key)-len(HeadRefKeySuffix)]
   154  	}
   155  
   156  	return false, ""
   157  }
   158  
   159  func IsWorkingKey(key string) (bool, string) {
   160  	if strings.HasSuffix(key, WorkingKeySuffix) {
   161  		return true, key[:len(key)-len(WorkingKeySuffix)]
   162  	}
   163  
   164  	return false, ""
   165  }
   166  
   167  func IsReadOnlyVersionKey(key string) bool {
   168  	return strings.HasSuffix(key, HeadKeySuffix) ||
   169  		strings.HasSuffix(key, StagedKeySuffix) ||
   170  		strings.HasSuffix(key, WorkingKeySuffix)
   171  }
   172  
   173  // GetBooleanSystemVar returns a boolean value for the system variable named, returning an error if the variable
   174  // doesn't exist in the session or has a non-boolean type.
   175  func GetBooleanSystemVar(ctx *sql.Context, varName string) (bool, error) {
   176  	val, err := ctx.GetSessionVariable(ctx, varName)
   177  	if err != nil {
   178  		return false, err
   179  	}
   180  
   181  	i8, isInt8 := val.(int8)
   182  	if !isInt8 {
   183  		return false, fmt.Errorf("unexpected type for variable %s: %T", varName, val)
   184  	}
   185  
   186  	return i8 == int8(1), nil
   187  }
   188  
   189  // IgnoreReplicationErrors returns true if the dolt_skip_replication_errors system variable is set to true, which means
   190  // that errors that occur during replication should be logged and ignored.
   191  func IgnoreReplicationErrors() bool {
   192  	_, skip, ok := sql.SystemVariables.GetGlobal(SkipReplicationErrors)
   193  	if !ok {
   194  		panic("dolt system variables not loaded")
   195  	}
   196  	return skip == SysVarTrue
   197  }
   198  
   199  // WarnReplicationError logs a warning for the replication error given
   200  func WarnReplicationError(ctx *sql.Context, err error) {
   201  	ctx.GetLogger().Warn(fmt.Errorf("replication failure: %w", err))
   202  }
   203  
   204  const (
   205  	SysVarFalse = int8(0)
   206  	SysVarTrue  = int8(1)
   207  )