github.com/paweljw/pop@v4.13.1+incompatible/columns/columns_for_struct.go (about)

     1  package columns
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/gobuffalo/pop/internal/oncer"
     7  )
     8  
     9  // ColumnsForStruct returns a Columns instance for
    10  // the struct passed in.
    11  //
    12  // Deprecated: use ForStruct instead.
    13  func ColumnsForStruct(s interface{}, tableName string) (columns Columns) {
    14  	oncer.Deprecate(0, "columns.ColumnsForStruct", "Use columns.ForStruct instead.")
    15  	return ForStruct(s, tableName)
    16  }
    17  
    18  // ColumnsForStructWithAlias returns a Columns instance for the struct passed in.
    19  // If the tableAlias is not empty, it will be used.
    20  //
    21  // Deprecated: use ForStructWithAlias instead.
    22  func ColumnsForStructWithAlias(s interface{}, tableName string, tableAlias string) (columns Columns) {
    23  	oncer.Deprecate(0, "columns.ColumnsForStructWithAlias", "Use columns.ForStructWithAlias instead.")
    24  	return ForStructWithAlias(s, tableName, tableAlias)
    25  }
    26  
    27  // ForStruct returns a Columns instance for
    28  // the struct passed in.
    29  func ForStruct(s interface{}, tableName string) (columns Columns) {
    30  	return ForStructWithAlias(s, tableName, "")
    31  }
    32  
    33  // ForStructWithAlias returns a Columns instance for the struct passed in.
    34  // If the tableAlias is not empty, it will be used.
    35  func ForStructWithAlias(s interface{}, tableName string, tableAlias string) (columns Columns) {
    36  	columns = NewColumnsWithAlias(tableName, tableAlias)
    37  	defer func() {
    38  		if r := recover(); r != nil {
    39  			columns = NewColumnsWithAlias(tableName, tableAlias)
    40  			columns.Add("*")
    41  		}
    42  	}()
    43  	st := reflect.TypeOf(s)
    44  	if st.Kind() == reflect.Ptr {
    45  		st = st.Elem()
    46  	}
    47  	if st.Kind() == reflect.Slice {
    48  		st = st.Elem()
    49  		if st.Kind() == reflect.Ptr {
    50  			st = st.Elem()
    51  		}
    52  	}
    53  
    54  	fieldCount := st.NumField()
    55  
    56  	for i := 0; i < fieldCount; i++ {
    57  		field := st.Field(i)
    58  
    59  		popTags := TagsFor(field)
    60  		tag := popTags.Find("db")
    61  
    62  		if !tag.Ignored() && !tag.Empty() {
    63  			col := tag.Value
    64  
    65  			// add writable or readable.
    66  			tag := popTags.Find("rw")
    67  			if !tag.Empty() {
    68  				col = col + "," + tag.Value
    69  			}
    70  
    71  			cs := columns.Add(col)
    72  
    73  			// add select clause.
    74  			tag = popTags.Find("select")
    75  			if !tag.Empty() {
    76  				c := cs[0]
    77  				c.SetSelectSQL(tag.Value)
    78  			}
    79  		}
    80  	}
    81  
    82  	return columns
    83  }