-
Notifications
You must be signed in to change notification settings - Fork 31
/
engine.go
executable file
·468 lines (426 loc) · 13.9 KB
/
engine.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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/icrowley/fake"
)
var (
fromYear = -10 // ranges of dates
toYear = 0
intervalKeywords = []string{"interval", "time without time zone"} // Time data types
ipKeywords = []string{"inet", "cidr"} // Networking data types
intKeywords = []string{"smallint", "integer", "bigint", "oid"} // Integer data types
intRanges = map[string]int{"smallint": 2767, "integer": 7483647, "bigint": 372036854775807, "oid": 7483647}
floatKeywords = []string{"double precision", "real", "money"} // Decimal data types
geoDataTypekeywords = []string{"path", "polygon", "line", "lseg", "box", "circle", "point"} // Geometry data types
)
// BuildData generates data
// It provided random data based on data types.
func BuildData(dt string) (interface{}, error) {
if StringHasPrefix(dt, intKeywords) { // Integer builder
return buildInteger(dt)
} else if strings.HasPrefix(dt, "character") { // String builder
return buildCharacter(dt)
} else if strings.HasPrefix(dt, "date") { // Date builder
return buildDate(dt)
} else if strings.HasPrefix(dt, "timestamp") { // Timestamp builder
return buildTimeStamp(dt)
} else if StringHasPrefix(dt, intervalKeywords) { // Generate Random time without timezone
return buildInterval(dt)
} else if strings.HasPrefix(dt, "time with time zone") { // Generate Random time with timezone
return buildTimeWithTz(dt)
} else if StringHasPrefix(dt, ipKeywords) { // Generate Random ips
return buildIps(dt)
} else if strings.HasPrefix(dt, "boolean") { // Generate Random boolean
return buildBoolean(dt)
} else if strings.HasPrefix(dt, "text") { // Generate Random text
return buildText(dt)
} else if strings.HasPrefix(dt, "citext") { // Generate CiText text
return buildCiText(dt)
} else if strings.EqualFold(dt, "bytea") { // Generate Random bytea
return buildBytea(dt)
} else if StringHasPrefix(dt, floatKeywords) { // Generate Random float values
return buildFloat(dt)
} else if strings.HasPrefix(dt, "numeric") { // Generate Random numeric values with precision
return buildNumeric(dt)
} else if strings.HasPrefix(dt, "bit") { // Random bit generator
return buildBit(dt)
} else if strings.HasPrefix(dt, "uuid") { // Random UUID generator
return buildUuid(dt)
} else if strings.HasPrefix(dt, "macaddr") { // Random MacAddr Generator
return buildMacAddr(dt)
} else if strings.HasPrefix(dt, "json") { // Random Json
return buildJson(dt)
} else if strings.HasPrefix(dt, "xml") { // Random Xml
return buildXml(dt)
} else if strings.HasPrefix(dt, "tsquery") { // Random Text Search Query
return buildTSQuery(dt)
} else if strings.HasPrefix(dt, "tsvector") { // Random Text Search Vector
return buildTSVector(dt)
} else if strings.HasPrefix(dt, "pg_lsn") { // Random Log Sequence number
return buildLseg(dt)
} else if strings.HasPrefix(dt, "txid_snapshot") { // Random transaction XID snapshot
return buildTxidSnapShot(dt)
} else if StringHasPrefix(dt, geoDataTypekeywords) { // Random GeoMetric data
return buildGeometry(dt)
} else { // if these are not the defaults, the ony custom we allow is enum data type, check if its them
return buildEnumDataTypes(dt)
}
}
// Build Integer
func buildInteger(dt string) (interface{}, error) {
isItArray, t := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("int", dt, -intRanges[t], intRanges[t])
}
value := RandomInt(-intRanges[dt], intRanges[dt])
return value, nil
}
// Character Builder
func buildCharacter(dt string) (interface{}, error) {
l, err := CharLen(dt)
if err != nil {
return "", fmt.Errorf("getting character length: %v", err)
}
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("string", dt, 0, l)
}
return RandomString(l), nil
}
// Date Builder
func buildDate(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("date", dt, fromYear, toYear)
}
return RandomDate(fromYear, toYear)
}
// TimeStamp Builder
func buildTimeStamp(dt string) (interface{}, error) {
isItArray, t := isDataTypeAnArray(dt)
if t == "timestamp without time zone" { // Without time zone
if isItArray {
return ArrayGenerator("timestamp", dt, fromYear, toYear)
}
return RandomTimestamp(fromYear, toYear)
} else if t == "timestamp with time zone" { // With time zone
if isItArray {
return ArrayGenerator("timestamptz", dt, fromYear, toYear)
}
return RandomTimeStampTz(fromYear, toYear)
} else if regexp.MustCompile(`timestamp\([0-6]\) without time zone`).MatchString(dt) ||
regexp.MustCompile(`timestamp\([0-6]\) with time zone`).MatchString(dt) { // time zone with precision
if isItArray {
return ArrayGenerator("timestamptzWithDecimals", dt, fromYear, toYear)
}
return RandomTimeStampTzWithDecimals(fromYear, toYear, findTimeStampDecimal(dt))
}
return "", nil
}
// Time Builder
func buildTimeWithTz(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("timetz", dt, fromYear, toYear)
}
return RandomTimeTz(fromYear, toYear)
}
// Interval builder
func buildInterval(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("time", dt, fromYear, toYear)
}
return RandomTime(fromYear, toYear)
}
// Ip's builder
func buildIps(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("IP", dt, 0, 0)
}
return RandomIP(), nil
}
// Boolean builder
func buildBoolean(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("bool", dt, 0, 0)
}
return RandomBoolean(), nil
}
// Text builder
func buildText(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("text", dt, 0, 0)
}
return RandomParagraphs(), nil
}
// CiText Builder
func buildCiText(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("citext", dt, 0, 0)
}
return RandomCiText(), nil
}
// Bytea builder
func buildBytea(dt string) (interface{}, error) {
return RandomBytea(1024), nil
}
// Float builder
func buildFloat(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("float", dt, 1, intRanges["smallint"])
}
return RandomFloat(1, intRanges["smallint"], 3), nil
}
// Numeric values with precision builder
func buildNumeric(dt string) (interface{}, error) {
max, precision, err := findNumberPrecision(dt)
value := RandomFloat(1, max, precision)
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("numericFloat", dt, 0, max)
}
return TruncateFloat(value, max, precision), err
}
// Bit builder
func buildBit(dt string) (interface{}, error) {
l, err := CharLen(dt)
if err != nil {
return "", fmt.Errorf("build bit: %v", err)
}
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("bit", dt, 0, l)
}
return RandomBit(l), nil
}
// Uuid Builder
func buildUuid(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("uuid", dt, 0, 0)
}
return RandomUUID(), nil
}
// Mac Addr builder
func buildMacAddr(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("macaddr", dt, 0, 0)
}
return RandomMacAddress(), nil
}
// Json builder
func buildJson(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return JsonXmlArrayGenerator("json"), nil
}
return RandomJSON(false), nil
}
// Xml Builder
func buildXml(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return JsonXmlArrayGenerator("xml"), nil
}
return RandomXML(false), nil
}
// Ts Query Builder
func buildTSQuery(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("tsquery", dt, 0, 0)
}
return RandomTSQuery(), nil
}
// Ts Vector Builder
func buildTSVector(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("tsvector", dt, 0, 0)
}
return RandomTSVector(), nil
}
// Log Sequence Builder
func buildLseg(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("pg_lsn", dt, fromYear, toYear)
}
return RandomLSN(), nil
}
// Transaction Xid Builder
func buildTxidSnapShot(dt string) (interface{}, error) {
isItArray, _ := isDataTypeAnArray(dt)
if isItArray {
return ArrayGenerator("txid_snapshot", dt, fromYear, toYear)
}
return RandomTXID(), nil
}
// GeoMetric data builder
func buildGeometry(dt string) (interface{}, error) {
var randomInt int
if dt == "path" || dt == "polygon" {
randomInt = RandomInt(1, 5)
} else {
randomInt = RandomInt(1, 2)
}
isItArray, t := isDataTypeAnArray(dt)
if isItArray {
return GeometricArrayGenerator(randomInt, t), nil
}
return RandomGeometricData(randomInt, dt, false), nil
}
// Find the number of decimal points needed
func findTimeStampDecimal(dt string) int {
tsReg := regexp.MustCompile(`\([0-6]\)`)
match := tsReg.FindString(dt)
if IsStringEmpty(match) {
return 0
}
decimal, _ := strconv.Atoi(strings.Split(tsReg.FindString(dt), "")[1])
return decimal
}
// Find number precision
func findNumberPrecision(dt string) (int, int, error) {
max, precision, err := FloatPrecision(dt)
if err != nil {
return 0, 0, fmt.Errorf("build numeric: %v", err)
}
return max, precision, nil
}
// Does the data type have array
func isDataTypeAnArray(dt string) (bool, string) {
if strings.HasSuffix(dt, "[]") {
t := strings.Replace(dt, "[]", "", 1)
return true, t
}
return false, dt
}
// ArrayGenerator generates random array for array data types
func ArrayGenerator(dt, originalDt string, min, max int) (string, error) {
maxValues := RandomInt(1, 6) // Getting the value of iterators
maxIteration := RandomInt(1, 3)
var resultArrayCollector []string
// Create a array of results
for i := 0; i < maxIteration; i++ { // Max number of arrays
var resultArray []string
for j := 0; j < maxValues; j++ { // max number of values in a array.
value, err := randomDataByDataTypeForArray(dt, originalDt, min, max)
if err != nil {
return "", fmt.Errorf("error when generating array for datatype %s, err: %v", dt, err)
}
resultArray = append(resultArray, value)
}
resultArrayCollector = append(resultArrayCollector, strings.Join(resultArray, ","))
}
return fmt.Sprintf("{%s}", strings.Join(resultArrayCollector, ",")), nil
}
// Send in appropriate random value based on data type
func randomDataByDataTypeForArray(dt, originalDt string, min, max int) (string, error) {
if dt == "int" {
return strconv.Itoa(RandomInt(min, max)), nil
} else if dt == "string" {
return RandomString(max), nil
} else if dt == "date" {
return RandomDate(min, max)
} else if dt == "timestamp" {
return RandomTimestamp(min, max)
} else if dt == "timestamptz" {
return RandomTimeStampTz(min, max)
} else if dt == "timestamptzWithDecimals" {
return RandomTimeStampTzWithDecimals(min, max, findTimeStampDecimal(originalDt))
} else if dt == "time" {
return RandomTime(min, max)
} else if dt == "float" {
value := RandomFloat(0, max, 3)
return fmt.Sprintf("%v", TruncateFloat(value, max, 3)), nil
} else if dt == "numericFloat" {
m, precision, err := FloatPrecision(dt)
value := RandomFloat(1, m, precision)
return fmt.Sprintf("%v", value), err
} else if dt == "bit" {
return RandomBit(max), nil
} else if dt == "text" {
return fake.WordsN(1), nil
} else if dt == "citext" {
return RandomCiText(), nil
} else if dt == "timetz" {
return RandomTimeTz(min, max)
} else if dt == "bool" {
if RandomBoolean() {
return "true", nil
}
return "false", nil
} else if dt == "IP" {
return RandomIP(), nil
} else if dt == "macaddr" {
return RandomMacAddress(), nil
} else if dt == "uuid" {
return RandomUUID(), nil
} else if dt == "txid_snapshot" {
return RandomTXID(), nil
} else if dt == "pg_lsn" {
return RandomLSN(), nil
} else if dt == "tsquery" {
return RandomTSQuery(), nil
} else if dt == "tsvector" {
return RandomTSVector(), nil
} else {
return "", fmt.Errorf("unsupported datatypes found in array %v", dt)
}
}
// GeometricArrayGenerator generates random geometric array
func GeometricArrayGenerator(maxInt int, geometryType string) string {
// Getting the value of iterators
maxIterations := RandomInt(1, 6)
var resultArray []string
if geometryType == "box" {
value := RandomGeometricData(maxInt, geometryType, false)
resultArray = append(resultArray, value)
} else {
for i := 0; i < maxIterations; i++ { // Max number of arrays
value := RandomGeometricData(maxInt, geometryType, true)
resultArray = append(resultArray, value)
}
}
return fmt.Sprintf("{%s}", strings.Join(resultArray, ","))
}
// JsonXmlArrayGenerator generates random XML & Json array.
func JsonXmlArrayGenerator(dt string) string {
// Getting the value of iterators
maxIterations := RandomInt(1, 6)
var resultArray []string
var value string
for i := 0; i < maxIterations; i++ { // Max number of arrays
switch dt { // Choose the appropriate random data generators
case "json":
value = fmt.Sprintf("\"%s\"", RandomJSON(true))
case "xml":
value = fmt.Sprintf("\"%s\"", RandomXML(true))
}
resultArray = append(resultArray, value)
}
return fmt.Sprintf("{%s}", strings.Join(resultArray, ","))
}
// Enum data types
func buildEnumDataTypes(dt string) (string, error) {
// Check if the data type is ENUM
enumOutput := checkEnumDatatype(dt)
// if there are none then pass in the error back to user
if len(enumOutput) <= 0 {
return "", fmt.Errorf("unsupported datatypes found: %v", dt)
}
// found some output, lets pick some random value
n := RandomValueFromLength(len(enumOutput))
return enumOutput[n].EnumValue, nil
}