github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/sqx/split.go (about) 1 package sqx 2 3 import ( 4 "strings" 5 "unicode/utf8" 6 ) 7 8 // SplitSqls splits sqls by separate. 9 func SplitSqls(sqls string, separate rune) []string { 10 subs := make([]string, 0) 11 12 inQuoted := false 13 pos := 0 14 l := len(sqls) 15 16 var runeValue rune 17 for i, w := 0, 0; i < l; i += w { 18 runeValue, w = utf8.DecodeRuneInString(sqls[i:]) 19 20 var nextRuneValue rune 21 22 nextWidth := 0 23 24 if i+w < l { 25 nextRuneValue, nextWidth = utf8.DecodeRuneInString(sqls[i+w:]) 26 } 27 28 jumpNext := false 29 30 switch { 31 case runeValue == '\\': 32 jumpNext = true 33 case runeValue == '\'': 34 if inQuoted && nextWidth > 0 && nextRuneValue == '\'' { 35 jumpNext = true // jump escape for literal apostrophe, or single quote 36 } else { 37 inQuoted = !inQuoted 38 } 39 case !inQuoted && runeValue == separate: 40 subs = tryAddSQL(subs, sqls[pos:i]) 41 pos = i + w 42 } 43 44 if jumpNext { 45 i += w + nextWidth 46 } 47 } 48 49 if pos < l { 50 subs = tryAddSQL(subs, sqls[pos:]) 51 } 52 53 return subs 54 } 55 56 func tryAddSQL(sqls []string, sql string) []string { 57 s := strings.TrimSpace(sql) 58 if s != "" { 59 return append(sqls, s) 60 } 61 62 return sqls 63 }