-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.go
More file actions
271 lines (240 loc) · 9.39 KB
/
Copy pathgenerator.go
File metadata and controls
271 lines (240 loc) · 9.39 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package sqlseeder
import (
"bytes"
"fmt"
"os"
"strings"
"text/template"
"github.com/iancoleman/strcase"
)
// GeneratorInterface defines methods for generating SQL queries and related data.
type GeneratorInterface interface {
IsLastIndex(index int, a interface{}) bool
// GenerateTableData generates SQLData from a slice of maps (representing rows)
// for a given schema and table.
GenerateTableData(data []map[string]interface{}, schemaName string, tableName string) (*SQLData, error)
// GenerateRootTableData generates a map representing a single row of data for root columns
// (columns that are not part of many-to-many relationships).
GenerateRootTableDataRow(rootColumns []string, row map[string]interface{}, tableName string) (map[string]interface{}, error)
// GetColumnName extracts the base column name (the part before any delimiters).
GetColumnName(column string) string
// Generate generates the SQL insert statements from the provided SQLData.
Generate(model SQLData) (string, error)
// GenerateOneToManySubquery generates a subquery for a one-to-many relationship column.
GenerateOneToManySubquery(columnName string, tableName string, value string) (string, error)
}
type Generator struct {
TemplatePath string
ManyToManyDelimiter string
OneToManyDelimiter string
Delimiter string
ArrayDelimiter string
ColumnsMapper map[string]string
HashFunc func(string) string
Adapter AdapterInterface
}
func NewGenerator(adapter AdapterInterface, columnsMapper map[string]string, delimiter string, arrayDelimiter string, oneToManyDelimiter string, manyToManyDelimiter string, hashFunc func(string) string) GeneratorInterface {
execPath, err := os.Executable()
if err != nil {
panic(err) // Handle the error appropriately
}
tmpleatePath := fmt.Sprintf("%s/insert.tmpl", execPath)
return &Generator{
TemplatePath: tmpleatePath, // Path to the SQL template file
Delimiter: delimiter,
ManyToManyDelimiter: manyToManyDelimiter,
OneToManyDelimiter: oneToManyDelimiter,
ColumnsMapper: columnsMapper,
ArrayDelimiter: arrayDelimiter,
HashFunc: hashFunc,
Adapter: adapter,
}
}
// GenerateOneToManySubquery generates a subquery for a one-to-many relationship column.
// It takes the column name, table name, and the value to search for.
// If the value is "*", it selects the primary key from the related table without any WHERE clause.
// Otherwise, it generates a subquery to select the primary key where the search key equals the provided value.
func (g *Generator) GenerateOneToManySubquery(columnName string, tableName string, value string) (string, error) {
relation, err := g.Adapter.ParseOneToMany(columnName, tableName)
if err != nil {
return "", err
}
if value == "null" || value == "NULL" || value == "EMPTY" || value == "empty" || value == "" {
return "NULL", nil
}
cleaned := strings.TrimSpace(value)
return fmt.Sprintf("(SELECT %s FROM %s WHERE %s = '%s')", relation.PrimaryKey, relation.Table, relation.SearchKey, cleaned), nil
}
func (g *Generator) IsLastIndex(index int, a interface{}) bool {
return index == g.Adapter.GetLastIndex(a)
}
// GetColumnName extracts the base column name (the part before any delimiters).
func (g *Generator) GetColumnName(column string) string {
norimalizedColumn := strcase.ToSnake(strings.ToLower(strings.TrimLeft(strings.TrimRight(column, " "), " ")))
mappedColumnName, ok := g.ColumnsMapper[norimalizedColumn]
if !ok {
mappedColumnName = column
}
if g.Adapter.IsOneToMany(mappedColumnName) {
parts := strings.Split(column, g.OneToManyDelimiter)
return parts[0]
}
if g.Adapter.IsHashedColumn(mappedColumnName) {
parts := strings.Split(column, "#")
return parts[0]
}
if g.Adapter.IsArrayColumn(mappedColumnName) {
return strings.TrimSuffix(mappedColumnName, "[]")
}
return mappedColumnName
}
// GenerateRootTableDataRow generates a map representing a single row of data for root columns.
// It handles one-to-many relationships by generating subqueries.
func (g *Generator) GenerateRootTableDataRow(rootColumns []string, row map[string]interface{}, tableName string) (map[string]interface{}, error) {
rootRow := make(map[string]interface{})
for _, rootColumn := range rootColumns {
var err error
value := row[rootColumn].(string)
isOneToMany := g.Adapter.IsOneToMany(rootColumn)
isArrayColumn := g.Adapter.IsArrayColumn(rootColumn)
if isOneToMany {
value, err = g.GenerateOneToManySubquery(rootColumn, tableName, row[rootColumn].(string))
if err != nil {
return nil, err
}
} else if isArrayColumn {
value = g.FormatArrayValue(value)
}
rootRow[rootColumn] = value
}
return rootRow, nil
}
func (g *Generator) EscapeSQLString(s string) string {
return strings.ReplaceAll(s, "'", "''")
}
func (g *Generator) FormatArrayValue(value string) string {
if value == "" || value == "NULL" || value == "null" {
return "NULL"
}
parts := strings.Split(value, g.ArrayDelimiter)
quotedParts := make([]string, len(parts))
for i, p := range parts {
cleaned := strings.TrimSpace(p)
escaped := g.EscapeSQLString(cleaned) // escape single quotes
quotedParts[i] = fmt.Sprintf("'%s'", escaped)
}
return fmt.Sprintf("ARRAY[%s]", strings.Join(quotedParts, ", "))
}
// GenerateTableData generates SQLData from a slice of maps.
// It handles both root columns and many-to-many relationships.
func (g *Generator) GenerateTableData(data []map[string]interface{}, schemaName string, tableName string) (*SQLData, error) {
if len(data) == 0 {
return nil, fmt.Errorf("empty data")
}
columnsStatemntParts := g.Adapter.SplitColumnsToStatemntParts(data[0])
fullTableName := g.Adapter.GetFullTableName(schemaName, tableName)
manyToManyRelations, err := g.Adapter.ParseManyToManyColumns(columnsStatemntParts.ManyToManyColumns, schemaName, tableName)
if err != nil {
return nil, err
}
rootRows := make([]map[string]interface{}, 0)
manyToManyRows := make(map[string][]map[string]interface{})
for _, item := range data {
rootRow, err := g.GenerateRootTableDataRow(columnsStatemntParts.RootColumns, item, fullTableName)
if err != nil {
return nil, err
}
rootRows = append(rootRows, rootRow)
for key, manyToManyColumn := range manyToManyRelations {
cellValue := item[key].(string)
cellValueRows := strings.Split(cellValue, g.Delimiter)
value1, err := g.GenerateOneToManySubquery(manyToManyColumn.Columns[0], manyToManyColumn.Table, item[manyToManyColumn.FirstSearchColumn].(string))
if err != nil {
return nil, err
}
for _, row := range cellValueRows {
value2, err := g.GenerateOneToManySubquery(manyToManyColumn.Columns[1], manyToManyColumn.SecondTable, row)
if err != nil {
return nil, err
}
manyToManyRows[key] = append(manyToManyRows[key], map[string]interface{}{
manyToManyColumn.Columns[0]: value1,
manyToManyColumn.Columns[1]: value2,
})
}
}
}
sqlData := SQLData{
Statements: []SQLStatement{
{
Table: tableName,
Schema: schemaName,
Columns: columnsStatemntParts.RootColumns,
Rows: rootRows,
},
},
}
for key, rel := range manyToManyRelations {
sqlData.Statements = append(sqlData.Statements, SQLStatement{
Table: rel.Table,
Schema: "",
Columns: rel.Columns,
Rows: manyToManyRows[key],
})
}
return &sqlData, nil
}
// Generate creates the SQL string from the provided SQLData using a template.
func (g *Generator) Generate(data SQLData) (string, error) {
// Define the template functions.
funcMap := template.FuncMap{
"IsLastIndex": g.IsLastIndex,
"GetFullTableName": g.Adapter.GetFullTableName,
"HashFunc": g.HashFunc,
"WraptWithSingleQuoute": g.Adapter.WrapWithSingleQoute,
"GetColumnName": g.GetColumnName,
"IsHashedColumn": g.Adapter.IsHashedColumn,
"IsArrayColumn": g.Adapter.IsArrayColumn,
"Escape": g.EscapeSQLString,
"IsOneToMany": g.Adapter.IsOneToMany,
}
// Read the SQL template from the template path.
templateContent := `
{{- range $stmt := .Statements }}
INSERT INTO {{ GetFullTableName $stmt.Schema $stmt.Table }} (
{{- range $index, $column := $stmt.Columns }}
{{ GetColumnName $column }} {{- if not (IsLastIndex $index $stmt.Columns) }}, {{ end }}
{{- end }}
) VALUES
{{- range $rowIndex, $row := $stmt.Rows }}
(
{{- range $colIndex, $column := $stmt.Columns }}
{{- $value := index $row $column }}
{{- if IsHashedColumn $column }}
'{{ HashFunc $value }}' {{- if not (IsLastIndex $colIndex $stmt.Columns) }}, {{ end }}
{{- else if IsArrayColumn $column }}
{{ $value }} {{- if not (IsLastIndex $colIndex $stmt.Columns) }}, {{ end }}
{{- else if IsOneToMany $column }}
{{ WraptWithSingleQuoute ($value) }} {{- if not (IsLastIndex $colIndex $stmt.Columns) }}, {{ end }}
{{- else }}
{{ WraptWithSingleQuoute (Escape $value) }} {{- if not (IsLastIndex $colIndex $stmt.Columns) }}, {{ end }}
{{- end }}
{{- end }}
) {{- if not (IsLastIndex $rowIndex $stmt.Rows) }}, {{ end }}
{{- end }} ON CONFLICT DO NOTHING;
{{- end }}
`
// Parse the SQL template.
tmpl, err := template.New("sql").Funcs(funcMap).Parse(templateContent)
if err != nil {
return "", err
}
// Use a buffer to capture the generated SQL output.
var sqlBuffer bytes.Buffer
err = tmpl.Execute(&sqlBuffer, data)
if err != nil {
return "", err
}
// Return the generated SQL as a string.
return sqlBuffer.String(), nil
}