-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlgen.go
55 lines (44 loc) · 1.4 KB
/
sqlgen.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
package sqlgen
import (
"fmt"
"regexp"
"strings"
"github.com/jinzhu/inflection"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// SnakeToPascal converts a snake_case string to PascalCase using golang.org/x/text/cases
func SnakeToPascal(input string) string {
// Split the string by underscores
words := strings.Split(input, "_")
// Create a Title casing transformer
caser := cases.Title(language.Und) // "Und" is for undetermined language
// Capitalize the first letter of each word
for i, word := range words {
words[i] = caser.String(word)
}
// Join the words together to form PascalCase
return strings.Join(words, "")
}
// GetTableName extracts the table name from an INSERT SQL statement.
func GetTableName(sql string) (string, error) {
// Normalize and trim the SQL statement
sql = strings.TrimSpace(sql)
sql = strings.ToUpper(sql)
// Regular expression to match the table name after "INSERT INTO"
re := regexp.MustCompile(`(?i)INSERT\s+INTO\s+([^\s\(\)]+)`)
match := re.FindStringSubmatch(sql)
if len(match) == 2 {
return strings.ToLower(match[1]), nil
}
re2 := regexp.MustCompile(`FROM\s+([^\s\(\)]+)`)
match2 := re2.FindStringSubmatch(sql)
if len(match2) < 2 {
return "", fmt.Errorf("failed to extract table name from SQL: %s", sql)
}
// Return the table name
return strings.ToLower(match2[1]), nil
}
func Singularize(str string) string {
return inflection.Singular(str)
}