Created
October 23, 2017 07:07
-
-
Save qiwihui/defe831ba6327747cc9bee738c0a26a5 to your computer and use it in GitHub Desktop.
Extract table names from SQL statement
This file contains hidden or 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
// Extract table names from SQL statement | |
package main | |
import ( | |
"fmt" | |
"regexp" | |
) | |
// extractTableNames from sql statement | |
func extractTableNames(fromSQL string) (rets []string) { | |
reg := "(\\s+from\\s+(?P<table1>\\w+)\\s+((\\w+)\\s+)?(where|left|join|inner))|(\\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 != "" { | |
// fmt.Println("=>", n1[ii], vv) | |
rets = append(rets, string(vv)) | |
} | |
} | |
} | |
return | |
} | |
func main() { | |
sql := `select * from Outvisit l | |
left join patient p on l.patid=p.patientid | |
join patstatic c on l.patid=c.patid inner join patphone ph on l.patid=ph.patid | |
from pharmacywestpas p where p.outvisitid=l.outvisitid) | |
unit all | |
select * from invisit where` | |
fmt.Println(extractTableNames(sql)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.golang.org/p/Ruz5z6R3LJ