github.com/vedadiyan/sqlparser@v1.0.0/pkg/sqlparser/truncate_query.go (about)

     1  /*
     2  Copyright 2019 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sqlparser
    18  
    19  import (
    20  	"github.com/spf13/pflag"
    21  )
    22  
    23  var (
    24  	// truncateUILen truncate queries in debug UIs to the given length. 0 means unlimited.
    25  	truncateUILen = 512
    26  
    27  	// truncateErrLen truncate queries in error logs to the given length. 0 means unlimited.
    28  	truncateErrLen = 0
    29  )
    30  
    31  func registerQueryTruncationFlags(fs *pflag.FlagSet) {
    32  	fs.IntVar(&truncateUILen, "sql-max-length-ui", truncateUILen, "truncate queries in debug UIs to the given length (default 512)")
    33  	fs.IntVar(&truncateErrLen, "sql-max-length-errors", truncateErrLen, "truncate queries in error logs to the given length (default unlimited)")
    34  }
    35  
    36  // GetTruncateErrLen is a function used to read the value of truncateErrLen
    37  func GetTruncateErrLen() int {
    38  	return truncateErrLen
    39  }
    40  
    41  // SetTruncateErrLen is a function used to override the value of truncateErrLen
    42  // It is only meant to be used from tests and not from production code.
    43  func SetTruncateErrLen(errLen int) {
    44  	truncateErrLen = errLen
    45  }
    46  
    47  func truncateQuery(query string, max int) string {
    48  	sql, comments := SplitMarginComments(query)
    49  
    50  	if max == 0 || len(sql) <= max {
    51  		return comments.Leading + sql + comments.Trailing
    52  	}
    53  
    54  	return comments.Leading + sql[:max-12] + " [TRUNCATED]" + comments.Trailing
    55  }
    56  
    57  // TruncateForUI is used when displaying queries on various Vitess status pages
    58  // to keep the pages small enough to load and render properly
    59  func TruncateForUI(query string) string {
    60  	return truncateQuery(query, truncateUILen)
    61  }
    62  
    63  // TruncateForLog is used when displaying queries as part of error logs
    64  // to avoid overwhelming logging systems with potentially long queries and
    65  // bind value data.
    66  func TruncateForLog(query string) string {
    67  	return truncateQuery(query, truncateErrLen)
    68  }