Select statement execution and mapping to struct or slice added.

This commit is contained in:
sub0Zero 2019-03-05 18:55:47 +01:00 committed by zer0sub
parent 319c9f757d
commit 75f8e0dfec
6 changed files with 291 additions and 13 deletions

View file

@ -0,0 +1,144 @@
package execution
import (
"database/sql"
"errors"
"github.com/serenize/snaker"
"reflect"
)
func Execute(db *sql.DB, query string, destinationPtr interface{}) error {
if db == nil {
return errors.New("db is nil")
}
if destinationPtr == nil {
return errors.New("Destination is nil ")
}
destinationType := reflect.TypeOf(destinationPtr)
if destinationType.Kind() != reflect.Ptr {
return errors.New("Destination has to be a pointer to slice or pointer to struct ")
}
rows, err := db.Query(query)
if err != nil {
return err
}
columnNames, _ := rows.Columns()
columnTypes, _ := rows.ColumnTypes()
values := createScanValue(columnTypes)
for rows.Next() {
err := rows.Scan(values...)
if err != nil {
return err
}
if destinationType.Elem().Kind() == reflect.Slice {
destinationStructPtr := newElemForSlice(destinationPtr)
err = mapValuesToStruct(columnNames, values, destinationStructPtr)
if err != nil {
return err
}
appendElemToSlice(destinationPtr, destinationStructPtr)
} else if destinationType.Elem().Kind() == reflect.Struct {
return mapValuesToStruct(columnNames, values, destinationPtr)
}
}
err = rows.Err()
if err != nil {
return err
}
return nil
}
func appendElemToSlice(slice interface{}, obj interface{}) {
//spew.Dump(slice)
sliceValue := reflect.ValueOf(slice).Elem()
sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(obj).Elem()))
}
func newElemForSlice(destinationSlicePtr interface{}) interface{} {
destinationSliceType := reflect.TypeOf(destinationSlicePtr).Elem()
return reflect.New(destinationSliceType.Elem()).Interface()
}
func mapValuesToStruct(columnNames []string, row []interface{}, destination interface{}) error {
structType := reflect.TypeOf(destination).Elem()
structValue := reflect.ValueOf(destination).Elem()
for i := 0; i < structType.NumField(); i++ {
fieldType := structType.Field(i)
fieldValue := structValue.Field(i)
fieldName := fieldType.Name
//columnName := structName + "." + fieldName
columnName := snaker.CamelToSnake(fieldName)
rowIndex := getIndex(columnNames, columnName)
if rowIndex < 0 {
continue
}
rowColumnValue := reflect.ValueOf(row[rowIndex])
setReflectValue(rowColumnValue, fieldValue)
}
return nil
}
func setReflectValue(source, destination reflect.Value) {
if destination.Kind() == reflect.Ptr {
if source.Kind() == reflect.Ptr {
destination.Set(source)
} else {
destination.Set(source.Addr())
}
} else {
if source.Kind() == reflect.Ptr {
destination.Set(source.Elem())
} else {
destination.Set(source)
}
}
}
func getIndex(list []string, text string) int {
for i, str := range list {
if str == text {
return i
}
}
return -1
}
func createScanValue(columnTypes []*sql.ColumnType) []interface{} {
values := make([]interface{}, len(columnTypes))
for i, sqlColumnType := range columnTypes {
columnType := sqlColumnType.ScanType()
columnValue := reflect.New(columnType)
values[i] = columnValue.Interface()
}
return values
}

View file

@ -2,7 +2,10 @@ package sqlbuilder
import (
"bytes"
"database/sql"
"fmt"
"github.com/sub0Zero/go-sqlbuilder/sqlbuilder/execution"
"reflect"
"regexp"
"github.com/dropbox/godropbox/errors"
@ -11,6 +14,7 @@ import (
type Statement interface {
// String returns generated SQL as string.
String(database string) (sql string, err error)
Execute(db *sql.DB, destination interface{}) error
}
type SelectStatement interface {
@ -133,6 +137,10 @@ type unionStatementImpl struct {
unique bool
}
func (us *unionStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (us *unionStatementImpl) Where(expression BoolExpression) UnionStatement {
us.where = expression
return us
@ -305,6 +313,22 @@ type selectStatementImpl struct {
distinct bool
}
func (s *selectStatementImpl) Execute(db *sql.DB, destination interface{}) error {
destinationType := reflect.TypeOf(destination)
if destinationType.Kind() == reflect.Ptr && destinationType.Elem().Kind() == reflect.Struct {
s.Limit(1)
}
query, err := s.String("dvds")
if err != nil {
return err
}
return execution.Execute(db, query, destination)
}
func (s *selectStatementImpl) Copy() SelectStatement {
ret := *s
return &ret
@ -495,6 +519,10 @@ type insertStatementImpl struct {
ignore bool
}
func (i *insertStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (s *insertStatementImpl) Add(
row ...Expression) InsertStatement {
@ -665,6 +693,10 @@ type updateStatementImpl struct {
comment string
}
func (u *updateStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (u *updateStatementImpl) Set(
column NonAliasColumn,
expression Expression) UpdateStatement {
@ -808,6 +840,10 @@ type deleteStatementImpl struct {
comment string
}
func (d *deleteStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (d *deleteStatementImpl) Where(expression BoolExpression) DeleteStatement {
d.where = expression
return d
@ -895,6 +931,10 @@ type tableLock struct {
w bool
}
func (l *lockStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
// AddReadLock takes read lock on the table.
func (s *lockStatementImpl) AddReadLock(t *Table) LockStatement {
s.locks = append(s.locks, tableLock{t: t, w: false})
@ -951,6 +991,10 @@ func NewUnlockStatement() UnlockStatement {
type unlockStatementImpl struct {
}
func (u *unlockStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (s *unlockStatementImpl) String(database string) (sql string, err error) {
return "UNLOCK TABLES", nil
}
@ -968,6 +1012,10 @@ type gtidNextStatementImpl struct {
gno uint64
}
func (g *gtidNextStatementImpl) Execute(db *sql.DB, data interface{}) error {
return nil
}
func (s *gtidNextStatementImpl) String(database string) (sql string, err error) {
// This statement sets a session local variable defining what the next transaction ID is. It
// does not interact with other MySQL sessions. It is neither a DDL nor DML statement, so we