Skip to content

Instantly share code, notes, and snippets.

@qiwihui
Created October 23, 2017 07:07
Show Gist options
  • Save qiwihui/defe831ba6327747cc9bee738c0a26a5 to your computer and use it in GitHub Desktop.
Save qiwihui/defe831ba6327747cc9bee738c0a26a5 to your computer and use it in GitHub Desktop.
Extract table names from SQL statement
// 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))
}
@qiwihui
Copy link
Author

qiwihui commented Oct 23, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment