Add smart quote helper
This commit is contained in:
parent
65b80ddc13
commit
b171fd42ba
2 changed files with 26 additions and 88 deletions
strmangle
|
@ -7,6 +7,7 @@ package strmangle
|
|||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/jinzhu/inflection"
|
||||
|
@ -15,37 +16,29 @@ import (
|
|||
var (
|
||||
idAlphabet = []byte("abcdefghijklmnopqrstuvwxyz")
|
||||
uppercaseWords = []string{"id", "uid", "uuid", "guid", "ssn", "tz"}
|
||||
smartQuoteRgx = regexp.MustCompile(`^(?i)"?[a-z_][_a-z0-9]*"?(\."?[_a-z][_a-z0-9]*"?)*$`)
|
||||
)
|
||||
|
||||
type state int
|
||||
type smartStack []state
|
||||
|
||||
const (
|
||||
stateNothing = iota
|
||||
stateSubExpression
|
||||
stateFunction
|
||||
stateIdentifier
|
||||
)
|
||||
|
||||
func (stack *smartStack) push(s state) {
|
||||
*stack = append(*stack, s)
|
||||
}
|
||||
|
||||
func (stack *smartStack) pop() state {
|
||||
l := len(*stack)
|
||||
if l == 0 {
|
||||
return stateNothing
|
||||
}
|
||||
|
||||
v := (*stack)[l-1]
|
||||
*stack = (*stack)[:l-1]
|
||||
return v
|
||||
}
|
||||
|
||||
// SmartQuote intelligently quotes identifiers in sql statements
|
||||
func SmartQuote(s string) string {
|
||||
// split on comma, treat as individual thing
|
||||
return s
|
||||
if s == "null" {
|
||||
return s
|
||||
}
|
||||
|
||||
if m := smartQuoteRgx.MatchString(s); m != true {
|
||||
return s
|
||||
}
|
||||
|
||||
splits := strings.Split(s, ".")
|
||||
for i, split := range splits {
|
||||
if strings.HasPrefix(split, `"`) || strings.HasSuffix(split, `"`) {
|
||||
continue
|
||||
}
|
||||
|
||||
splits[i] = fmt.Sprintf(`"%s"`, split)
|
||||
}
|
||||
|
||||
return strings.Join(splits, ".")
|
||||
}
|
||||
|
||||
// Identifier is a base conversion from Base 10 integers to Base 26
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue