Created
October 28, 2022 10:34
-
-
Save abcdlsj/93e97572af92fc9f22afc1e4f2759ab0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package utils | |
import ( | |
"regexp" | |
) | |
// ExtractTableName from sql statement | |
func ExtractTableName(fromSQL string) (table string) { | |
tableNames := make([]string, 0) | |
reg := "(\\s+FROM\\s+\\`(?P<table1>\\w+)\\`\\s+((\\w+)\\s+)?(WHERE|LEFT|JOIN|INNER|ORDER))|(\\s+JOIN\\s+\\`(?P<table2>\\w+)\\`\\s+((\\w+)\\s+)?ON)" | |
r, _ := regexp.Compile(reg) | |
n1 := r.SubexpNames() | |
finds := r.FindAllStringSubmatch(fromSQL, -1) | |
for _, v := range finds { | |
for ii, vv := range v { | |
if n1[ii] != "" && vv != "" { | |
tableNames = append(tableNames, removeDigitsFromString(vv)) | |
} | |
} | |
} | |
// only return first table name. | |
if len(tableNames) == 0 { // not extract any table | |
table = "not query sql." | |
} else { | |
table = tableNames[0] | |
} | |
return table | |
} | |
func removeDigitsFromString(str string) (ret string) { | |
r, _ := regexp.Compile(`_\d+`) | |
ret = r.ReplaceAllString(str, "") | |
return ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment