-
Notifications
You must be signed in to change notification settings - Fork 0
/
scan.go
77 lines (63 loc) · 1.56 KB
/
scan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package sqlGoString
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
tag = "--transform: "
)
func scanSQLFiles() ([]string, error) {
var sqlFiles []string
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == ".sql" {
sqlFiles = append(sqlFiles, path)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("Error for read files: %v", err)
}
return sqlFiles, nil
}
func transformSQLFiles(queryName string, sqlFiles []string) (string, error) {
if len(sqlFiles) == 0 {
return "", fmt.Errorf("No sql files found")
}
var sqlStatements []string
for _, filePath := range sqlFiles {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var isTransformBlock bool
for scanner.Scan() {
line := scanner.Text()
pattern := fmt.Sprintf("\\b%s\\b", queryName)
existsInLine, _ := regexp.MatchString(pattern, line)
if existsInLine {
isTransformBlock = true
} else if isTransformBlock && line == "" {
isTransformBlock = false
} else if isTransformBlock {
sqlStatements = append(sqlStatements, line)
}
}
if err := scanner.Err(); err != nil {
return "", err
}
}
if len(sqlStatements) <= 0 {
return "", errors.New("No SQL statements found for " + queryName)
}
return strings.Join(sqlStatements, "\n"), nil
}