gitee.com/h79/goutils@v1.22.10/dao/wrapper/expr.go (about)

     1  package wrapper
     2  
     3  import (
     4  	"reflect"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  func AddTable(builder *strings.Builder, table string) {
    10  	if table == "" {
    11  		return
    12  	}
    13  	AddQuoted(builder, table)
    14  	builder.WriteByte('.')
    15  }
    16  
    17  func IsQuoted(v string) bool {
    18  	if v == "" {
    19  		return false
    20  	}
    21  	first := v[0]
    22  	end := v[len(v)-1]
    23  	return first == '`' && end == '`'
    24  }
    25  
    26  func AddQuoted(builder *strings.Builder, v string) bool {
    27  	if v == "" {
    28  		return false
    29  	}
    30  	first := v[0]
    31  	end := v[len(v)-1]
    32  	if first != '`' { //引号
    33  		builder.WriteByte('`')
    34  	}
    35  	builder.WriteString(v)
    36  	if end != '`' {
    37  		builder.WriteByte('`')
    38  	}
    39  	return true
    40  }
    41  
    42  func AddAlias(builder *strings.Builder, v string) bool {
    43  	if v == "" {
    44  		return false
    45  	}
    46  	builder.WriteString(" AS ")
    47  	builder.WriteString(v)
    48  	return true
    49  }
    50  
    51  func AddVar(builder *strings.Builder, val interface{}) {
    52  	ref := reflect.Indirect(reflect.ValueOf(val))
    53  
    54  	switch ref.Kind() {
    55  
    56  	case reflect.String:
    57  		s := ref.String()
    58  		s = strings.ReplaceAll(s, "\"", "\\\"")
    59  		s = strings.ReplaceAll(s, "'", "\\'")
    60  		builder.WriteByte('\'')
    61  		builder.WriteString(s)
    62  		builder.WriteByte('\'')
    63  
    64  	case reflect.Int:
    65  		fallthrough
    66  	case reflect.Int8:
    67  		fallthrough
    68  	case reflect.Int16:
    69  		fallthrough
    70  	case reflect.Int32:
    71  		fallthrough
    72  	case reflect.Int64:
    73  		builder.WriteString(strconv.FormatInt(ref.Int(), 10))
    74  
    75  	case reflect.Uint:
    76  		fallthrough
    77  	case reflect.Uint8:
    78  		fallthrough
    79  	case reflect.Uint16:
    80  		fallthrough
    81  	case reflect.Uint32:
    82  		fallthrough
    83  	case reflect.Uint64:
    84  		builder.WriteString(strconv.FormatUint(ref.Uint(), 10))
    85  
    86  	case reflect.Float32:
    87  		fallthrough
    88  	case reflect.Float64:
    89  		builder.WriteString(strconv.FormatFloat(ref.Float(), 'f', 5, 64))
    90  
    91  	case reflect.Bool:
    92  		if ref.Bool() {
    93  			builder.WriteString("true")
    94  		} else {
    95  			builder.WriteString("false")
    96  		}
    97  
    98  	case reflect.Struct:
    99  		if sql, ok := val.(*SQL); ok {
   100  			builder.WriteString(sql.Build())
   101  			return
   102  		}
   103  		if sql, ok := val.(SQL); ok {
   104  			builder.WriteString(sql.Build())
   105  		}
   106  	default:
   107  	}
   108  }