reform icon indicating copy to clipboard operation
reform copied to clipboard

Add more helpers

Open AlekSi opened this issue 6 years ago • 7 comments

  • Functions to convert Struct from/to map[string]interface{} by field or column names.
func StructFields(s Struct) map[string]interface{} { … }
func StructColumns(s Struct) map[string]interface{} { … }
func MapFields(fields map[string]interface{}, s Struct) { … }
func MapColumns(columns map[string]interface{}, s Struct) { … }
  • Method to scan *sql.Row into the Struct by column names.
func (q *Querier) NextRowColumns(str Struct, rows *sql.Rows) error

AlekSi avatar Jan 03 '18 06:01 AlekSi

*sql.Row has no Columns method, but *sql.Rows do. https://godoc.org/database/sql#Row https://godoc.org/database/sql#Rows.Columns

How it is proposed to scan *sql.Row by columns?

bikbah avatar Jan 18 '18 08:01 bikbah

That was a bug. 🐞 Updated description.

AlekSi avatar Jan 18 '18 13:01 AlekSi

Hello. Does anyone work on this?

hIMEI29A avatar Jan 29 '18 11:01 hIMEI29A

@hIMEI29A nope

bikbah avatar Jan 29 '18 11:01 bikbah

i will dig. Буду рыть )

hIMEI29A avatar Jan 29 '18 12:01 hIMEI29A

I'll take this!

0xch4z avatar Oct 08 '18 14:10 0xch4z

Q: How would you implement this set of functions?

func MapFields(fields map[string]interface{}, s Struct) { … }
func MapColumns(columns map[string]interface{}, s Struct) { … }

My first guess for e.g. MapColumns would be iterating accross the columns of the reflect.Struct and assigning the value from the map to the corresponding pointer. E.g.

func mapColumns(m map[string]interface{}, s reform.Struct) {

	columns := s.View().Columns()
	values := s.Pointers()

	for i, column := range columns {
		// assign to values[i] the value of m[column]
	}

	// ...
}

The problem with this is that we would need to do type switches on the type of the field in the struct and handle all variants:

switch values[i].(type) {
		case *string:
			*values[i].(*string) = m[column].(string) // also make sure that the m[column] is a string too

This means having something like database/sql convertAssignRows() that handles all cases: https://github.com/golang/go/blob/go1.14.4/src/database/sql/convert.go#L219 .

OR the code could just be generated (e.g. create setters using go generate), which sounds a bit bloaty.. and perhaps a bit strange to extend the public interface for a helper function..

Sorry if it's a dumb question, I started looking into this for something I was working on, then it started looking a bit more verbose than I expected.

Maelkum avatar Jul 13 '20 09:07 Maelkum