Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add sql queries #201

Merged
merged 5 commits into from Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
87 changes: 87 additions & 0 deletions sql.go
@@ -0,0 +1,87 @@
package gofakeit

import (
"errors"
"fmt"
"math/rand"
"strings"
)

type SQLOptions struct {
Table string `json:"table" xml:"table"` // Table name we are inserting into
EntryCount int `json:"entry_count" xml:"entry_count"` // How many entries (tuples) we're generating
Fields []Field `json:"fields" xml:"fields"` // The fields to be generated
}

func SQLInsert(so *SQLOptions) ([]byte, error) { return sqlInsertFunc(globalFaker.Rand, so) }

func (f *Faker) SQLInsert(so *SQLOptions) ([]byte, error) { return sqlInsertFunc(f.Rand, so) }

func sqlInsertFunc(r *rand.Rand, so *SQLOptions) ([]byte, error) {
if so.Table == "" {
return nil, errors.New("must provide table name to generate SQL")
}
if so.Fields == nil || len(so.Fields) <= 0 {
return nil, errors.New(("must pass fields in order to generate SQL queries"))
}
if so.EntryCount <= 0 {
return nil, errors.New("must have entry count")
}

var sb strings.Builder
sb.WriteString("INSERT INTO " + so.Table + " VALUES")

for i := 0; i < so.EntryCount; i++ {
sb.WriteString(" (")
// Now, we need to add all of our fields
for ii, field := range so.Fields {
if field.Function == "autoincrement" { // One
autoIncNum := fmt.Sprintf("%v", i+1)
if ii == len(so.Fields)-1 { // Last field
sb.WriteString(autoIncNum)
} else {
sb.WriteString(autoIncNum + ", ")
}
continue
}

// Get the function info for the field
funcInfo := GetFuncLookup(field.Function)
if funcInfo == nil {
return nil, errors.New("invalid function, " + field.Function + " does not exist")
}

// Generate the value
val, err := funcInfo.Generate(r, &field.Params, funcInfo)
if err != nil {
return nil, err
}

convertType := ConvertType(funcInfo.Output, val)

if ii == len(so.Fields)-1 { // Last field
sb.WriteString(convertType)
} else {
sb.WriteString(convertType + ", ")
}
}
if i == so.EntryCount-1 { // Last tuple
sb.WriteString(");")
} else {
sb.WriteString("),")
}
}

return []byte(sb.String()), nil
}

func ConvertType(t string, val interface{}) string {
switch t {
case "string":
return `'` + fmt.Sprintf("%v", val) + `'`
case "[]byte":
return `'` + fmt.Sprintf("%s", val) + `'`
default:
return fmt.Sprintf("%v", val)
}
}
167 changes: 167 additions & 0 deletions sql_test.go
@@ -0,0 +1,167 @@
package gofakeit

import (
"fmt"
"math/rand"
"testing"
)

func TestMultiSQLInsert(t *testing.T) {
Seed(11)

res, _ := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 3,
Fields: []Field{
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
{Name: "age", Function: "number", Params: MapParams{"min": {"1"}, "max": {"99"}}},
},
})

fmt.Println(string(res))

// Output:
// INSERT INTO People VALUES ('Markus', 'Moen', 21), ('Anibal', 'Kozey', 60), ('Sylvan', 'Mraz', 59);
}

func TestMultiSQLInsertJSON(t *testing.T) {

Seed(12)

AddFuncLookup("jsonperson", Info{
Category: "custom",
Description: "random JSON of a person",
Example: `{"first_name":"Bob", "last_name":"Jones"}`,
Output: "[]byte",
Generate: func(r *rand.Rand, m *MapParams, info *Info) (interface{}, error) {

v, _ := JSON(&JSONOptions{
Type: "object",
RowCount: 1,
Fields: []Field{
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
},
})

return v, nil
},
})

type RandomPerson struct {
FakePerson []byte `fake:{jsonperson}"`
}

var f RandomPerson
Struct(&f)
fmt.Printf("%s\n", (f.FakePerson))
}

func TestMultiSQLInsertFloat(t *testing.T) {
Seed(11)

res, _ := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 3,
Fields: []Field{
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
{Name: "balance", Function: "float32"},
},
})

fmt.Println(string(res))

// Output:
// INSERT INTO People VALUES ('Markus', 'Moen', 2.7766049e+38), ('Anibal', 'Kozey', 3.8815667e+37), ('Sylvan', 'Mraz', 1.6268478e+38);
}

func TestMultiSQLInsertAutoincrement(t *testing.T) {
Seed(11)

res, _ := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 3,
Fields: []Field{
{Name: "id", Function: "autoincrement"},
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
{Name: "age", Function: "number", Params: MapParams{"min": {"1"}, "max": {"99"}}},
},
})

fmt.Println(string(res))

// Output:
// INSERT INTO People VALUES (1, 'Markus', 'Moen', 21), (2, 'Anibal', 'Kozey', 60), (3, 'Sylvan', 'Mraz', 59);
}

func TestSignleSQLInsert(t *testing.T) {
Seed(114)

res, _ := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 1,
Fields: []Field{
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
},
})
fmt.Println(string(res))

// Output:
// INSERT INTO People VALUES ('Colt', 'Koss');
}

func TestSQLInsertNoFields(t *testing.T) {
Seed(114)

_, err := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 1,
Fields: []Field{},
})

if err != nil {
fmt.Println(err.Error())
}

// Output:
// must pass fields in order to generate SQL queries
}

func TestSQLInsertNilFields(t *testing.T) {
Seed(114)

_, err := SQLInsert(&SQLOptions{
Table: "People",
EntryCount: 1,
})

if err != nil {
fmt.Println(err.Error())
}

// Output:
// must pass fields in order to generate SQL queries
}

func TestSQLInsertNilTable(t *testing.T) {
Seed(11)

_, err := SQLInsert(&SQLOptions{
EntryCount: 3,
Fields: []Field{
{Name: "first_name", Function: "firstname"},
{Name: "last_name", Function: "lastname"},
},
})

if err != nil {
fmt.Println(err.Error())
}

// Output:
// must provide table name to generate SQL
}