sqlmap_xsql.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package xorm
  2. import (
  3. "bufio"
  4. "regexp"
  5. "strings"
  6. )
  7. type XSqlMap struct {
  8. sqlMapRootDir string
  9. extension string
  10. }
  11. func XSql(directory, extension string) *XSqlMap {
  12. return &XSqlMap{
  13. sqlMapRootDir: directory,
  14. extension: extension,
  15. }
  16. }
  17. func (sqlMap *XSqlMap) RootDir() string {
  18. return sqlMap.sqlMapRootDir
  19. }
  20. func (sqlMap *XSqlMap) Extension() string {
  21. return sqlMap.extension
  22. }
  23. type Scanner struct {
  24. line string
  25. queries map[string]string
  26. current string
  27. }
  28. type stateFn func(*Scanner) stateFn
  29. func getTag(line string) string {
  30. re := regexp.MustCompile("^\\s*--\\s*id:\\s*(\\S+)")
  31. matches := re.FindStringSubmatch(line)
  32. if matches == nil {
  33. return ""
  34. }
  35. return matches[1]
  36. }
  37. func initialState(s *Scanner) stateFn {
  38. if tag := getTag(s.line); len(tag) > 0 {
  39. s.current = tag
  40. return queryState
  41. }
  42. return initialState
  43. }
  44. func queryState(s *Scanner) stateFn {
  45. if tag := getTag(s.line); len(tag) > 0 {
  46. s.current = tag
  47. } else {
  48. s.appendQueryLine()
  49. }
  50. return queryState
  51. }
  52. func (s *Scanner) appendQueryLine() {
  53. current := s.queries[s.current]
  54. line := strings.Trim(s.line, " \t")
  55. if len(line) == 0 {
  56. return
  57. }
  58. if len(current) > 0 {
  59. current = current + "\n"
  60. }
  61. current = current + line
  62. s.queries[s.current] = current
  63. }
  64. func (s *Scanner) Run(io *bufio.Scanner) map[string]string {
  65. s.queries = make(map[string]string)
  66. for state := initialState; io.Scan(); {
  67. s.line = io.Text()
  68. state = state(s)
  69. }
  70. return s.queries
  71. }