Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"bytes"
"database/sql/driver"
"encoding/csv"
"errors"
"fmt"
"io"
"reflect"
"strings"
)

Expand Down Expand Up @@ -127,6 +129,113 @@ type Rows struct {
closeErr error
}

// NewRowsFromStruct new Rows from struct reflect with tagName
// tagName default "json"
func newRowsFromStruct(m interface{}, tagName ...string) (*Rows, error) {
/* if m == nil {
return nil, errors.New("param m is nil")
}*/
val := reflect.ValueOf(m).Elem()
/* if val.Kind() != reflect.Struct {
return nil, errors.New("param type must be struct")
}*/
num := val.NumField()
if num == 0 {
return nil, errors.New("no properties available")
}
columns := make([]string, 0, num)
var values []driver.Value
tag := "json"
if len(tagName) > 0 {
tag = tagName[0]
}
for i := 0; i < num; i++ {
f := val.Type().Field(i)
column := f.Tag.Get(tag)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code allows to use JSON tags, but doesn't fully support them.

Examples of incorrectly handled values: "-", "data,omitempty".

I think that using JSON tags is a bad default.

if len(column) > 0 {
columns = append(columns, column)
values = append(values, val.Field(i).Interface())
}
}
if len(columns) == 0 {
return nil, errors.New("tag not match")
}
rows := &Rows{
cols: columns,
nextErr: make(map[int]error),
converter: driver.DefaultParameterConverter,
}
return rows.AddRow(values...), nil
}

// NewRowsFromInterface new Rows from struct or slice or array reflect with tagName
// NOTE: arr/slice must be of the same type
// tagName default "json"
func NewRowsFromInterface(m interface{}, tagName string) (*Rows, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go has generics now. It would be better to have multiple functions with stronger typing.

NewRowsFromSlice
NewRowsFromStruct

kind := reflect.TypeOf(m).Elem().Kind()
if kind == reflect.Ptr {
kind = reflect.TypeOf(m).Kind()
}
switch kind {
case reflect.Slice, reflect.Array:
return newRowsFromSliceOrArray(m, tagName)
case reflect.Struct:
return newRowsFromStruct(m, tagName)
default:
return nil, errors.New("the type m must in struct or slice or array")
}
}

// NewRowsFromStructs new Rows from struct slice reflect with tagName
// NOTE: arr must be of the same type
// tagName default "json"
func newRowsFromSliceOrArray(m interface{}, tagName string) (*Rows, error) {
vals := reflect.ValueOf(m)
if vals.Len() == 0 {
return nil, errors.New("the len of m is zero")
}
typ := reflect.TypeOf(vals.Index(0).Interface()).Elem()
if typ.Kind() != reflect.Struct {
return nil, errors.New("param type must be struct")
}
if typ.NumField() == 0 {
return nil, errors.New("no properties available")
}

var idx []int
tag := "json"
if len(tagName) > 0 {
tag = tagName
}
columns := make([]string, 0, typ.NumField())
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
column := f.Tag.Get(tag)
if len(column) > 0 {
columns = append(columns, column)
idx = append(idx, i)
}
}
if len(columns) == 0 {
return nil, errors.New("tag not match")
}
rows := &Rows{
cols: columns,
nextErr: make(map[int]error),
converter: driver.DefaultParameterConverter,
}
for i := 0; i < vals.Len(); i++ {
val := vals.Index(i).Elem()
values := make([]driver.Value, 0, len(idx))
for _, i := range idx {
// NOTE: field by name ptr nil
values = append(values, val.Field(i).Interface())
}
rows.AddRow(values...)
}
return rows, nil
}

// NewRows allows Rows to be created from a
// sql driver.Value slice or from the CSV string and
// to be used as sql driver.Rows.
Expand Down
59 changes: 59 additions & 0 deletions rows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"testing"
"time"
)

const invalid = `☠☠☠ MEMORY OVERWRITTEN ☠☠☠ `
Expand Down Expand Up @@ -753,3 +755,60 @@ func ExampleRows_AddRows() {
// Output: scanned id: 1 and title: one
// scanned id: 2 and title: two
}

type MockStruct struct {
Type int `mock:"type"`
Name string `mock:"name"`
CreateTime time.Time `mock:"createTime"`
}

func TestNewRowsFromInterface(t *testing.T) {
m := &MockStruct{
Type: 1,
Name: "sqlMock",
CreateTime: time.Now(),
}
excepted := NewRows([]string{"type", "name", "createTime"}).AddRow(m.Type, m.Name, m.CreateTime)

actual, err := NewRowsFromInterface(m, "mock")
if err != nil {
t.Fatal(err)
}
same := reflect.DeepEqual(excepted.cols, actual.cols)
if !same {
t.Fatal("custom tag reflect failed")
}
same = reflect.DeepEqual(excepted.rows, actual.rows)
if !same {
t.Fatal("reflect value from tag failed")
}

m1 := &MockStruct{
Type: 1,
Name: "sqlMock1",
CreateTime: time.Now(),
}
m2 := &MockStruct{
Type: 2,
Name: "sqlMock2",
CreateTime: time.Now(),
}
arr := [3]*MockStruct{m, m1, m2}

excepted2 := NewRows([]string{"type", "name", "createTime"})
for _, v := range arr {
excepted2.AddRow(v.Type, v.Name, v.CreateTime)
}
actual2, err := NewRowsFromInterface(arr, "mock")
if err != nil {
t.Fatal(err)
}
same = reflect.DeepEqual(excepted2.cols, actual2.cols)
if !same {
t.Fatal("custom tag reflect failed")
}
same = reflect.DeepEqual(excepted2.rows, actual2.rows)
if !same {
t.Fatal("reflect value from tag failed")
}
}