moving to struct as param, readme updates
This commit is contained in:
42
lazy.go
42
lazy.go
@@ -11,35 +11,51 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
const (
|
||||
DB_TAG = "db"
|
||||
LAZY_TAG = "lazy"
|
||||
KEY_VALUE = "key"
|
||||
)
|
||||
|
||||
type MockResults struct {
|
||||
Query string
|
||||
Columns []string
|
||||
Rows [][]driver.Value
|
||||
}
|
||||
|
||||
func GenerateRandomResults(query string, exampleObj any, keyVal []any, rowCount int) (*MockResults, error) {
|
||||
if exampleObj == nil {
|
||||
return nil, errors.New("exampleObj cannot be nil")
|
||||
type MockDetails struct {
|
||||
Query string
|
||||
Example any
|
||||
Keys []any
|
||||
RowCount int
|
||||
}
|
||||
|
||||
func GenerateRandomResults(m MockDetails) (*MockResults, error) {
|
||||
if m.Example == nil {
|
||||
return nil, errors.New("example value cannot be nil")
|
||||
}
|
||||
if rowCount == 0 {
|
||||
rowCount = 1
|
||||
if reflect.ValueOf(m.Example).Kind() != reflect.Struct {
|
||||
return nil, errors.New("example value must be a struct")
|
||||
}
|
||||
if len(keyVal) != 0 {
|
||||
if len(keyVal) != rowCount {
|
||||
if m.RowCount == 0 {
|
||||
m.RowCount = 1
|
||||
}
|
||||
if len(m.Keys) != 0 {
|
||||
if len(m.Keys) != m.RowCount {
|
||||
return nil, errors.New("you must provide a key for each row")
|
||||
}
|
||||
}
|
||||
|
||||
retType := reflect.TypeOf(exampleObj)
|
||||
retType := reflect.TypeOf(m.Example)
|
||||
maxFieldCount := retType.NumField()
|
||||
columns := make([]string, 0, maxFieldCount)
|
||||
rows := make([][]driver.Value, 0)
|
||||
|
||||
for y := 0; y < rowCount; y++ {
|
||||
for y := 0; y < m.RowCount; y++ {
|
||||
rows = append(rows, make([]driver.Value, 0))
|
||||
for x := 0; x < maxFieldCount; x++ {
|
||||
field := retType.Field(x)
|
||||
dbTag := field.Tag.Get("db")
|
||||
dbTag := field.Tag.Get(DB_TAG)
|
||||
if dbTag == "" {
|
||||
continue
|
||||
}
|
||||
@@ -48,8 +64,8 @@ func GenerateRandomResults(query string, exampleObj any, keyVal []any, rowCount
|
||||
columns = append(columns, dbTag)
|
||||
}
|
||||
|
||||
if field.Tag.Get("test") == "key" {
|
||||
rows[y] = append(rows[y], keyVal[y])
|
||||
if field.Tag.Get(LAZY_TAG) == KEY_VALUE {
|
||||
rows[y] = append(rows[y], m.Keys[y])
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -63,7 +79,7 @@ func GenerateRandomResults(query string, exampleObj any, keyVal []any, rowCount
|
||||
}
|
||||
|
||||
return &MockResults{
|
||||
Query: sqlx.Rebind(sqlx.AT, regexp.QuoteMeta(query)),
|
||||
Query: sqlx.Rebind(sqlx.AT, regexp.QuoteMeta(m.Query)),
|
||||
Columns: columns,
|
||||
Rows: rows,
|
||||
}, nil
|
||||
|
Reference in New Issue
Block a user