github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/sessiondata/session_data.go (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package sessiondata 12 13 import ( 14 "fmt" 15 "net" 16 "strings" 17 "time" 18 19 "github.com/cockroachdb/cockroach/pkg/sql/lex" 20 "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice" 21 ) 22 23 // SessionData contains session parameters. They are all user-configurable. 24 // A SQL Session changes fields in SessionData through sql.sessionDataMutator. 25 type SessionData struct { 26 // ApplicationName is the name of the application running the 27 // current session. This can be used for logging and per-application 28 // statistics. 29 ApplicationName string 30 // Database indicates the "current" database for the purpose of 31 // resolving names. See searchAndQualifyDatabase() for details. 32 Database string 33 // DefaultTxnPriority indicates the default priority of newly created 34 // transactions. 35 // NOTE: we'd prefer to use tree.UserPriority here, but doing so would 36 // introduce a package dependency cycle. 37 DefaultTxnPriority int 38 // DefaultReadOnly indicates the default read-only status of newly created 39 // transactions. 40 DefaultReadOnly bool 41 // DistSQLMode indicates whether to run queries using the distributed 42 // execution engine. 43 DistSQLMode DistSQLExecMode 44 // EnumsEnabled indicates whether use of ENUM types are allowed. 45 EnumsEnabled bool 46 // ExperimentalDistSQLPlanningMode indicates whether the experimental 47 // DistSQL planning driven by the optimizer is enabled. 48 ExperimentalDistSQLPlanningMode ExperimentalDistSQLPlanningMode 49 // OptimizerFKChecks indicates whether we should use the new paths to plan foreign 50 // key checks in the optimizer. 51 OptimizerFKChecks bool 52 // OptimizerFKCascades indicates whether we should use the new paths to plan foreign 53 // key cascades in the optimizer. 54 OptimizerFKCascades bool 55 // OptimizerFKCascadesLimit is the maximum number of cascading operations that 56 // are run for a single query. 57 OptimizerFKCascadesLimit int 58 // OptimizerUseHistograms indicates whether we should use histograms for 59 // cardinality estimation in the optimizer. 60 OptimizerUseHistograms bool 61 // OptimizerUseMultiColStats indicates whether we should use multi-column 62 // statistics for cardinality estimation in the optimizer. 63 OptimizerUseMultiColStats bool 64 // PartialIndexes indicates whether creation of partial indexes are allowed. 65 // TODO(mgartner): remove this once partial indexes are fully supported. 66 PartialIndexes bool 67 // SerialNormalizationMode indicates how to handle the SERIAL pseudo-type. 68 SerialNormalizationMode SerialNormalizationMode 69 // SearchPath is a list of namespaces to search builtins in. 70 SearchPath SearchPath 71 // StmtTimeout is the duration a query is permitted to run before it is 72 // canceled by the session. If set to 0, there is no timeout. 73 StmtTimeout time.Duration 74 // User is the name of the user logged into the session. 75 User string 76 // SafeUpdates causes errors when the client 77 // sends syntax that may have unwanted side effects. 78 SafeUpdates bool 79 // RemoteAddr is used to generate logging events. 80 RemoteAddr net.Addr 81 // ZigzagJoinEnabled indicates whether the optimizer should try and plan a 82 // zigzag join. 83 ZigzagJoinEnabled bool 84 // ReorderJoinsLimit indicates the number of joins at which the optimizer should 85 // stop attempting to reorder. 86 ReorderJoinsLimit int 87 // RequireExplicitPrimaryKeys indicates whether CREATE TABLE statements should 88 // error out if no primary key is provided. 89 RequireExplicitPrimaryKeys bool 90 // SequenceState gives access to the SQL sequences that have been manipulated 91 // by the session. 92 SequenceState *SequenceState 93 // DataConversion gives access to the data conversion configuration. 94 DataConversion DataConversionConfig 95 // VectorizeMode indicates which kinds of queries to use vectorized execution 96 // engine for. 97 VectorizeMode VectorizeExecMode 98 // VectorizeRowCountThreshold indicates the row count above which the 99 // vectorized execution engine will be used if possible. 100 VectorizeRowCountThreshold uint64 101 // ForceSavepointRestart overrides the default SAVEPOINT behavior 102 // for compatibility with certain ORMs. When this flag is set, 103 // the savepoint name will no longer be compared against the magic 104 // identifier `cockroach_restart` in order use a restartable 105 // transaction. 106 ForceSavepointRestart bool 107 // DefaultIntSize specifies the size in bits or bytes (preferred) 108 // of how a "naked" INT type should be parsed. 109 DefaultIntSize int 110 // ResultsBufferSize specifies the size at which the pgwire results buffer 111 // will self-flush. 112 ResultsBufferSize int64 113 // AllowPrepareAsOptPlan must be set to allow use of 114 // PREPARE name AS OPT PLAN '...' 115 AllowPrepareAsOptPlan bool 116 // SaveTablesPrefix indicates that a table should be created with the 117 // given prefix for the output of each subexpression in a query. If 118 // SaveTablesPrefix is empty, no tables are created. 119 SaveTablesPrefix string 120 // TempTablesEnabled indicates whether temporary tables can be created or not. 121 TempTablesEnabled bool 122 // HashShardedIndexesEnabled indicates whether hash sharded indexes can be created. 123 HashShardedIndexesEnabled bool 124 // ImplicitSelectForUpdate is true if FOR UPDATE locking may be used during 125 // the row-fetch phase of mutation statements. 126 ImplicitSelectForUpdate bool 127 // InsertFastPath is true if the fast path for insert (with VALUES input) may 128 // be used. 129 InsertFastPath bool 130 // NoticeDisplaySeverity indicates the level of Severity to send notices for the given 131 // session. 132 NoticeDisplaySeverity pgnotice.DisplaySeverity 133 // AlterColumnTypeGeneralEnabled is true if ALTER TABLE ... ALTER COLUMN ... 134 // TYPE x may be used for general conversions requiring online schema change/ 135 AlterColumnTypeGeneralEnabled bool 136 } 137 138 // DataConversionConfig contains the parameters that influence 139 // the conversion between SQL data types and strings/byte arrays. 140 type DataConversionConfig struct { 141 // Location indicates the current time zone. 142 Location *time.Location 143 144 // BytesEncodeFormat indicates how to encode byte arrays when converting 145 // to string. 146 BytesEncodeFormat lex.BytesEncodeFormat 147 148 // ExtraFloatDigits indicates the number of digits beyond the 149 // standard number to use for float conversions. 150 // This must be set to a value between -15 and 3, inclusive. 151 ExtraFloatDigits int 152 } 153 154 // GetFloatPrec computes a precision suitable for a call to 155 // strconv.FormatFloat() or for use with '%.*g' in a printf-like 156 // function. 157 func (c *DataConversionConfig) GetFloatPrec() int { 158 // The user-settable parameter ExtraFloatDigits indicates the number 159 // of digits to be used to format the float value. PostgreSQL 160 // combines this with %g. 161 // The formula is <type>_DIG + extra_float_digits, 162 // where <type> is either FLT (float4) or DBL (float8). 163 164 // Also the value "3" in PostgreSQL is special and meant to mean 165 // "all the precision needed to reproduce the float exactly". The Go 166 // formatter uses the special value -1 for this and activates a 167 // separate path in the formatter. We compare >= 3 here 168 // just in case the value is not gated properly in the implementation 169 // of SET. 170 if c.ExtraFloatDigits >= 3 { 171 return -1 172 } 173 174 // CockroachDB only implements float8 at this time and Go does not 175 // expose DBL_DIG, so we use the standard literal constant for 176 // 64bit floats. 177 const StdDoubleDigits = 15 178 179 nDigits := StdDoubleDigits + c.ExtraFloatDigits 180 if nDigits < 1 { 181 // Ensure the value is clamped at 1: printf %g does not allow 182 // values lower than 1. PostgreSQL does this too. 183 nDigits = 1 184 } 185 return nDigits 186 } 187 188 // Equals returns true if the two DataConversionConfigs are identical. 189 func (c *DataConversionConfig) Equals(other *DataConversionConfig) bool { 190 if c.BytesEncodeFormat != other.BytesEncodeFormat || 191 c.ExtraFloatDigits != other.ExtraFloatDigits { 192 return false 193 } 194 if c.Location != other.Location && c.Location.String() != other.Location.String() { 195 return false 196 } 197 return true 198 } 199 200 // ExperimentalDistSQLPlanningMode controls if and when the opt-driven DistSQL 201 // planning is used to create physical plans. 202 type ExperimentalDistSQLPlanningMode int64 203 204 const ( 205 // ExperimentalDistSQLPlanningOff means that we always use the old path of 206 // going from opt.Expr to planNodes and then to processor specs. 207 ExperimentalDistSQLPlanningOff ExperimentalDistSQLPlanningMode = iota 208 // ExperimentalDistSQLPlanningOn means that we will attempt to use the new 209 // path for performing DistSQL planning in the optimizer, and if that 210 // doesn't succeed for some reason, we will fallback to the old path. 211 ExperimentalDistSQLPlanningOn 212 // ExperimentalDistSQLPlanningAlways means that we will only use the new path, 213 // and if it fails for any reason, the query will fail as well. 214 ExperimentalDistSQLPlanningAlways 215 ) 216 217 func (m ExperimentalDistSQLPlanningMode) String() string { 218 switch m { 219 case ExperimentalDistSQLPlanningOff: 220 return "off" 221 case ExperimentalDistSQLPlanningOn: 222 return "on" 223 case ExperimentalDistSQLPlanningAlways: 224 return "always" 225 default: 226 return fmt.Sprintf("invalid (%d)", m) 227 } 228 } 229 230 // ExperimentalDistSQLPlanningModeFromString converts a string into a 231 // ExperimentalDistSQLPlanningMode. False is returned if the conversion was 232 // unsuccessful. 233 func ExperimentalDistSQLPlanningModeFromString(val string) (ExperimentalDistSQLPlanningMode, bool) { 234 var m ExperimentalDistSQLPlanningMode 235 switch strings.ToUpper(val) { 236 case "OFF": 237 m = ExperimentalDistSQLPlanningOff 238 case "ON": 239 m = ExperimentalDistSQLPlanningOn 240 case "ALWAYS": 241 m = ExperimentalDistSQLPlanningAlways 242 default: 243 return 0, false 244 } 245 return m, true 246 } 247 248 // DistSQLExecMode controls if and when the Executor distributes queries. 249 // Since 2.1, we run everything through the DistSQL infrastructure, 250 // and these settings control whether to use a distributed plan, or use a plan 251 // that only involves local DistSQL processors. 252 type DistSQLExecMode int64 253 254 const ( 255 // DistSQLOff means that we never distribute queries. 256 DistSQLOff DistSQLExecMode = iota 257 // DistSQLAuto means that we automatically decide on a case-by-case basis if 258 // we distribute queries. 259 DistSQLAuto 260 // DistSQLOn means that we distribute queries that are supported. 261 DistSQLOn 262 // DistSQLAlways means that we only distribute; unsupported queries fail. 263 DistSQLAlways 264 ) 265 266 func (m DistSQLExecMode) String() string { 267 switch m { 268 case DistSQLOff: 269 return "off" 270 case DistSQLAuto: 271 return "auto" 272 case DistSQLOn: 273 return "on" 274 case DistSQLAlways: 275 return "always" 276 default: 277 return fmt.Sprintf("invalid (%d)", m) 278 } 279 } 280 281 // DistSQLExecModeFromString converts a string into a DistSQLExecMode 282 func DistSQLExecModeFromString(val string) (_ DistSQLExecMode, ok bool) { 283 switch strings.ToUpper(val) { 284 case "OFF": 285 return DistSQLOff, true 286 case "AUTO": 287 return DistSQLAuto, true 288 case "ON": 289 return DistSQLOn, true 290 case "ALWAYS": 291 return DistSQLAlways, true 292 default: 293 return 0, false 294 } 295 } 296 297 // VectorizeExecMode controls if an when the Executor executes queries using the 298 // columnar execution engine. 299 // WARNING: When adding a VectorizeExecMode, note that nodes at previous 300 // versions might interpret the integer value differently. To avoid this, only 301 // append to the list or bump the minimum required distsql version (maybe also 302 // take advantage of that to reorder the list as you see fit). 303 type VectorizeExecMode int64 304 305 const ( 306 // VectorizeOff means that columnar execution is disabled. 307 VectorizeOff VectorizeExecMode = iota 308 // Vectorize201Auto means that that any supported queries that use only 309 // streaming operators (i.e. those that do not require any buffering) will 310 // be run using the columnar execution. If any part of a query is not 311 // supported by the vectorized execution engine, the whole query will fall 312 // back to row execution. 313 // This is the default setting in 20.1. 314 Vectorize201Auto 315 // VectorizeOn means that any supported queries will be run using the 316 // columnar execution. 317 VectorizeOn 318 // VectorizeExperimentalAlways means that we attempt to vectorize all 319 // queries; unsupported queries will fail. Mostly used for testing. 320 VectorizeExperimentalAlways 321 ) 322 323 func (m VectorizeExecMode) String() string { 324 switch m { 325 case VectorizeOff: 326 return "off" 327 case Vectorize201Auto: 328 return "201auto" 329 case VectorizeOn: 330 return "on" 331 case VectorizeExperimentalAlways: 332 return "experimental_always" 333 default: 334 return fmt.Sprintf("invalid (%d)", m) 335 } 336 } 337 338 // VectorizeExecModeFromString converts a string into a VectorizeExecMode. False 339 // is returned if the conversion was unsuccessful. 340 func VectorizeExecModeFromString(val string) (VectorizeExecMode, bool) { 341 var m VectorizeExecMode 342 switch strings.ToUpper(val) { 343 case "OFF": 344 m = VectorizeOff 345 case "201AUTO": 346 m = Vectorize201Auto 347 case "ON": 348 m = VectorizeOn 349 case "EXPERIMENTAL_ALWAYS": 350 m = VectorizeExperimentalAlways 351 default: 352 return 0, false 353 } 354 return m, true 355 } 356 357 // SerialNormalizationMode controls if and when the Executor uses DistSQL. 358 type SerialNormalizationMode int64 359 360 const ( 361 // SerialUsesRowID means use INT NOT NULL DEFAULT unique_rowid(). 362 SerialUsesRowID SerialNormalizationMode = iota 363 // SerialUsesVirtualSequences means create a virtual sequence and 364 // use INT NOT NULL DEFAULT nextval(...). 365 SerialUsesVirtualSequences 366 // SerialUsesSQLSequences means create a regular SQL sequence and 367 // use INT NOT NULL DEFAULT nextval(...). 368 SerialUsesSQLSequences 369 ) 370 371 func (m SerialNormalizationMode) String() string { 372 switch m { 373 case SerialUsesRowID: 374 return "rowid" 375 case SerialUsesVirtualSequences: 376 return "virtual_sequence" 377 case SerialUsesSQLSequences: 378 return "sql_sequence" 379 default: 380 return fmt.Sprintf("invalid (%d)", m) 381 } 382 } 383 384 // SerialNormalizationModeFromString converts a string into a SerialNormalizationMode 385 func SerialNormalizationModeFromString(val string) (_ SerialNormalizationMode, ok bool) { 386 switch strings.ToUpper(val) { 387 case "ROWID": 388 return SerialUsesRowID, true 389 case "VIRTUAL_SEQUENCE": 390 return SerialUsesVirtualSequences, true 391 case "SQL_SEQUENCE": 392 return SerialUsesSQLSequences, true 393 default: 394 return 0, false 395 } 396 }