//This will execute the SQL and append results to the slice. // var ids []uint32 // if err := From("test").Select("id").ScanVals(&ids); err != nil{ // panic(err.Error() // } // //i: Takes a pointer to a slice of primitive values. func (me CrudExec) ScanVals(i interface{}) error { if me.err != nil { return me.err } val := reflect.ValueOf(i) if val.Kind() != reflect.Ptr { return NewGoquError("Type must be a pointer to a slice when calling ScanVals") } val = reflect.Indirect(val) if val.Kind() != reflect.Slice { return NewGoquError("Type must be a pointer to a slice when calling ScanVals") } t, _, isSliceOfPointers := getTypeInfo(i, val) rows, err := me.database.Query(me.Sql, me.Args...) if err != nil { return err } defer rows.Close() for rows.Next() { row := reflect.New(t) if err := rows.Scan(row.Interface()); err != nil { return err } if isSliceOfPointers { val.Set(reflect.Append(val, row)) } else { val.Set(reflect.Append(val, reflect.Indirect(row))) } } if err := rows.Err(); err != nil { return err } return nil }
func stringTypeOf(i interface{}) (string, error) { _, isByteSlice := i.([]byte) if !isByteSlice { // Check if we found a higher kinded type switch reflect.ValueOf(i).Kind() { case reflect.Slice: elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface() ct := cassaType(elemVal) if ct == gocql.TypeCustom { return "", fmt.Errorf("Unsupported type %T", i) } return fmt.Sprintf("list<%v>", ct), nil case reflect.Map: keyVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Key())).Interface() elemVal := reflect.Indirect(reflect.New(reflect.TypeOf(i).Elem())).Interface() keyCt := cassaType(keyVal) elemCt := cassaType(elemVal) if keyCt == gocql.TypeCustom || elemCt == gocql.TypeCustom { return "", fmt.Errorf("Unsupported map key or value type %T", i) } return fmt.Sprintf("map<%v, %v>", keyCt, elemCt), nil } } ct := cassaType(i) if ct == gocql.TypeCustom { return "", fmt.Errorf("Unsupported type %T", i) } return cassaTypeToString(ct) }
/* * I also don't see that golang exports an API to get at the underlying FD, but * we need it to get at SO_PEERCRED, so let's grab it. */ func extractUnderlyingFd(unixConnPtr *net.UnixConn) int { conn := reflect.Indirect(reflect.ValueOf(unixConnPtr)) netFdPtr := conn.FieldByName("fd") netFd := reflect.Indirect(netFdPtr) fd := netFd.FieldByName("sysfd") return int(fd.Int()) }
// sendRPC sends one or more RPCs to replicas from the supplied // storage.Replica slice. First, replicas which have gossipped // addresses are corraled and then sent via rpc.Send, with requirement // that one RPC to a server must succeed. func (db *DistDB) sendRPC(replicas []storage.Replica, method string, args, replyChanI interface{}) error { if len(replicas) == 0 { return util.Errorf("%s: replicas set is empty", method) } // Build a map from replica address (if gossipped) to args struct // with replica set in header. argsMap := map[net.Addr]interface{}{} for _, replica := range replicas { addr, err := db.nodeIDToAddr(replica.NodeID) if err != nil { glog.V(1).Infof("node %d address is not gossipped", replica.NodeID) continue } // Copy the args value and set the replica in the header. argsVal := reflect.New(reflect.TypeOf(args).Elem()) reflect.Indirect(argsVal).Set(reflect.Indirect(reflect.ValueOf(args))) reflect.Indirect(argsVal).FieldByName("Replica").Set(reflect.ValueOf(replica)) argsMap[addr] = argsVal.Interface() } if len(argsMap) == 0 { return noNodeAddrsAvailErr{util.Errorf("%s: no replica node addresses available via gossip", method)} } rpcOpts := rpc.Options{ N: 1, SendNextTimeout: defaultSendNextTimeout, Timeout: defaultRPCTimeout, } return rpc.Send(argsMap, method, replyChanI, rpcOpts) }
func TestDataCustomTypes(t *testing.T) { d := DataCustom{} ind := reflect.Indirect(reflect.ValueOf(&d)) for name, value := range Data_Values { e := ind.FieldByName(name) if !e.IsValid() { continue } e.Set(reflect.ValueOf(value).Convert(e.Type())) } id, err := dORM.Insert(&d) throwFail(t, err) throwFail(t, AssertIs(id, 1)) d = DataCustom{Id: 1} err = dORM.Read(&d) throwFail(t, err) ind = reflect.Indirect(reflect.ValueOf(&d)) for name, value := range Data_Values { e := ind.FieldByName(name) if !e.IsValid() { continue } vu := e.Interface() value = reflect.ValueOf(value).Convert(e.Type()).Interface() throwFail(t, AssertIs(vu == value, true), value, vu) } }
func (orm *Model) FindAll(rowsSlicePtr interface{}) error { orm.ScanPK(rowsSlicePtr) sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return errors.New("needs a pointer to a slice") } sliceElementType := sliceValue.Type().Elem() st := reflect.New(sliceElementType) var keys []string results, _ := scanStructIntoMap(st.Interface()) if orm.TableName == "" { orm.TableName = getTableName(rowsSlicePtr) } for key, _ := range results { keys = append(keys, key) } orm.ColumnStr = strings.Join(keys, ", ") resultsSlice, err := orm.FindMap() if err != nil { return err } for _, results := range resultsSlice { newValue := reflect.New(sliceElementType) scanMapIntoStruct(newValue.Interface(), results) sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface())))) } return nil }
func updateAndGetSqlColumnsValues(thing interface{}, table *tableMap, data map[string]interface{}) ([]string, []interface{}) { thingValue := reflect.Indirect(reflect.ValueOf(thing)) columns := make([]string, 0, len(table.Columns)) values := make([]interface{}, 0, len(table.Columns)) for i := 0; i < len(table.Columns); i++ { column := table.Columns[i] if val, ok := data[column.Name]; ok { destField := thingValue.Field(column.Field) value := reflect.ValueOf(val) // assign the value from the data map to the destination struct field destField.Set(value) if column.Serialize { // TODO(jr): don't eat this marshal error value marshaled, _ := json.Marshal(val) values = append(values, string(marshaled)) } else { values = append(values, reflect.Indirect(value).Interface()) } columns = append(columns, column.Name) } } return columns, values }
func (tbl *TableCached) Diff(entA EntryCached, entB EntryCached) uint64 { ret := uint64(0) refvalA := reflect.Indirect(reflect.ValueOf(entA)) refvalB := reflect.Indirect(reflect.ValueOf(entB)) for _, v := range tbl.Table.Fields { if v.Primary { continue } if len(v.Name) <= 0 { continue } if v.VarIndex == -1 { continue } if v.VarIndex >= 64 { log.Println("Field index too damn high:", tbl.Table.Name, v.Name) return ^uint64(0) } bEq := refvalA.Field(v.VarIndex).Interface() == refvalB.Field(v.VarIndex).Interface() if !bEq { ret |= (uint64(1) << uint(v.VarIndex)) } } return ret }
func (tbl *TableCached) MarkChildEntryRem(ent EntryCached, ctIdx int, cent EntryCached) { ct := tbl.Children[ctIdx] cid := reflect.Indirect(reflect.ValueOf(cent)).Field(ct.Table._idxid).Interface() dbce := tbl.GetChildCacheEnt(ent, ctIdx) if dbce.ValsAdd != nil { for i, v := range dbce.ValsAdd { if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid { dbce.ValsAdd[i], dbce.ValsAdd = dbce.ValsAdd[len(dbce.ValsAdd)-1], dbce.ValsAdd[:len(dbce.ValsAdd)-1] break } } } if dbce.ValsMod != nil { for i, v := range dbce.ValsMod { if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid { dbce.ValsMod[i], dbce.ValsMod = dbce.ValsMod[len(dbce.ValsMod)-1], dbce.ValsMod[:len(dbce.ValsMod)-1] break } } } if dbce.ValsRem != nil { for _, v := range dbce.ValsRem { if reflect.Indirect(reflect.ValueOf(v)).Field(ct.Table._idxid).Interface() == cid { return } } } if dbce.ValsRem == nil { dbce.ValsRem = make([]interface{}, 0, 8) } dbce.ValsRem = append(dbce.ValsRem, cent) }
func (scope *Scope) createJoinTable(field *StructField) { if relationship := field.Relationship; relationship != nil && relationship.JoinTableHandler != nil { joinTableHandler := relationship.JoinTableHandler joinTable := joinTableHandler.Table(scope.db) if !scope.Dialect().HasTable(scope, joinTable) { toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()} var sqlTypes []string for idx, fieldName := range relationship.ForeignFieldNames { if field, ok := scope.Fields()[fieldName]; ok { value := reflect.Indirect(reflect.New(field.Struct.Type)) primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false) sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+primaryKeySqlType) } } for idx, fieldName := range relationship.AssociationForeignFieldNames { if field, ok := toScope.Fields()[fieldName]; ok { value := reflect.Indirect(reflect.New(field.Struct.Type)) primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false) sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+primaryKeySqlType) } } scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v) %s", scope.Quote(joinTable), strings.Join(sqlTypes, ","), scope.getTableOptions())).Error) } scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler) } }
func (tbl *TableCached) ReadParam(ent EntryCached, rwp *RWParams) bool { if tbl.Cache == nil { return tbl.ReadUncached(ent, rwp) } refval := reflect.Indirect(reflect.ValueOf(ent)) id := refval.Field(tbl._idxid).Interface() v, _ := tbl.Cache.Get(id) if v == nil { log.Println("ReadCached cache miss:", id) if !tbl.ReadUncached(ent, rwp) { return false } entCached := tbl.Table.NewValue().(EntryCached) entCached.CopyFrom(ent) refval := reflect.Indirect(reflect.ValueOf(entCached)) if tbl._idxdbcache != -1 { refval.Field(tbl._idxdbcache).Set(dbCacheTypeZero) } if tbl.Children != nil { tbl.ClearChildren(entCached) } tbl.Cache.Set(id, entCached) } else { entCached, _ := v.(EntryCached) tbl.ReadAccess(entCached, rwp) ent.CopyFrom(entCached) if tbl.Children != nil { tbl.ReadChildrenParams(ent, rwp) } } return true }
// query by s and return a slice by type s // field mapping rule is: HelloWorld => hello_world // mean that struct's field "HelloWorld" in database table's field is "hello_world" // table name mapping use the same rule as field // @param slicePtr: a pointer to a slice // var blogs []Blog // err := db.GetStructs(&blogs, SqlQueryInfo{}) func (db *DB) GetStructs(slicePtr interface{}, qi SqlQueryInfo) error { ptr := reflect.ValueOf(slicePtr) if ptr.Kind() != reflect.Ptr { return errors.New("db.GetStructs: needs a pointer to a slice") } sliceValue := reflect.Indirect(ptr) if sliceValue.Kind() != reflect.Slice { return errors.New("db.GetStructs: needs a pointer to a slice") } structType := sliceValue.Type().Elem() rows, fields, err := db.rawSelectByStruct(structType, qi) if err != nil { return err } defer rows.Close() for rows.Next() { v := reflect.New(structType) err = rawScanStruct(v, fields, rows) if err != nil { return err } fmt.Println(v.Interface()) sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(v.Interface())))) } return nil }
func machoUpdateSections(r loadCmdReader, seg, sect reflect.Value, delta uint64) error { iseg := reflect.Indirect(seg) nsect := iseg.FieldByName("Nsect").Uint() if nsect == 0 { return nil } sectOffset := int64(iseg.Type().Size()) isect := reflect.Indirect(sect) offsetField := isect.FieldByName("Offset") reloffField := isect.FieldByName("Reloff") sectSize := int64(isect.Type().Size()) for i := uint64(0); i < nsect; i++ { if err := r.ReadAt(sectOffset, sect.Interface()); err != nil { return err } if offsetField.Uint() != 0 { offsetField.SetUint(offsetField.Uint() + delta) } if reloffField.Uint() != 0 { reloffField.SetUint(reloffField.Uint() + delta) } if err := r.WriteAt(sectOffset, sect.Interface()); err != nil { return err } sectOffset += sectSize } return nil }
// set values from one struct to other struct // both need ptr struct func SetFormValues(from interface{}, to interface{}, skips ...string) { val := reflect.ValueOf(from) elm := reflect.Indirect(val) valTo := reflect.ValueOf(to) elmTo := reflect.Indirect(valTo) panicAssertStructPtr(val) panicAssertStructPtr(valTo) outFor: for i := 0; i < elmTo.NumField(); i++ { toF := elmTo.Field(i) name := elmTo.Type().Field(i).Name // skip specify field for _, skip := range skips { if skip == name { continue outFor } } f := elm.FieldByName(name) if f.Kind() != reflect.Invalid { // set value if type matched if f.Type().String() == toF.Type().String() { toF.Set(f) } } } }
func (scope *Scope) handleBelongsToPreload(field *Field, conditions []interface{}) { relation := field.Relationship primaryKeys := scope.getColumnAsArray(relation.ForeignFieldName) if len(primaryKeys) == 0 { return } results := makeSlice(field.Struct.Type) associationPrimaryKey := scope.New(results).PrimaryField().Name scope.Err(scope.NewDB().Where(primaryKeys).Find(results, conditions...).Error) resultValues := reflect.Indirect(reflect.ValueOf(results)) for i := 0; i < resultValues.Len(); i++ { result := resultValues.Index(i) if scope.IndirectValue().Kind() == reflect.Slice { value := getRealValue(result, associationPrimaryKey) objects := scope.IndirectValue() for j := 0; j < objects.Len(); j++ { object := reflect.Indirect(objects.Index(j)) if equalAsString(getRealValue(object, relation.ForeignFieldName), value) { object.FieldByName(field.Name).Set(result) } } } else { scope.SetColumn(field, result) } } }
func (j *JavaToGoObjectArray) Convert(obj *gojvm.Object) (err error) { objs := GetEnv().ToObjectArray(obj) r_value := reflect.ValueOf(j.list) if r_value.Type().Kind() != reflect.Ptr { return errors.New("JavaToGoList.Convert: dest not ptr") } r_slice := reflect.Indirect(r_value) if r_slice.Type().Kind() != reflect.Slice { return errors.New("JavaToGoList.Convert: dest ptr , does not point to slice") } for i := 0; i < len(objs); i++ { r_newElemV := reflect.New(r_slice.Type().Elem().Elem()) c := &Callable{} j.item.Dest(c) if err = j.item.Convert(objs[i]); err != nil { return err } if err = j.item.CleanUp(); err != nil { return err } reflect.Indirect(r_newElemV).FieldByName("Callable").Set(reflect.ValueOf(c)) r_newSlice := reflect.Append(r_slice, r_newElemV) r_slice.Set(r_newSlice) } return }
func (scope *Scope) handleHasOnePreload(field *Field, conditions []interface{}) { primaryName := scope.PrimaryField().Name primaryKeys := scope.getColumnAsArray(primaryName) if len(primaryKeys) == 0 { return } results := makeSlice(field.Struct.Type) relation := field.Relationship condition := fmt.Sprintf("%v IN (?)", scope.Quote(relation.ForeignDBName)) scope.Err(scope.NewDB().Where(condition, primaryKeys).Find(results, conditions...).Error) resultValues := reflect.Indirect(reflect.ValueOf(results)) for i := 0; i < resultValues.Len(); i++ { result := resultValues.Index(i) if scope.IndirectValue().Kind() == reflect.Slice { value := getRealValue(result, relation.ForeignFieldName) objects := scope.IndirectValue() for j := 0; j < objects.Len(); j++ { if equalAsString(getRealValue(objects.Index(j), primaryName), value) { reflect.Indirect(objects.Index(j)).FieldByName(field.Name).Set(result) break } } } else { if err := scope.SetColumn(field, result); err != nil { scope.Err(err) return } } } }
// StructScan's a single Row (result of QueryRowx) into dest func (r *Row) StructScan(dest interface{}) error { var v reflect.Value v = reflect.ValueOf(dest) if v.Kind() != reflect.Ptr { return errors.New("Must pass a pointer, not a value, to StructScan destination.") } direct := reflect.Indirect(v) base, err := BaseStructType(direct.Type()) if err != nil { return err } fm, err := getFieldmap(base) if err != nil { return err } columns, err := r.Columns() if err != nil { return err } fields, err := getFields(fm, columns) if err != nil { return err } values := make([]interface{}, len(columns)) // create a new struct type (which returns PtrTo) and indirect it setValues(fields, reflect.Indirect(v), values) // scan into the struct field pointers and append to our results return r.Scan(values...) }
func prepareInsertSqlColumnsValues(thing interface{}, table *tableMap) ([]string, []interface{}) { thingValue := reflect.Indirect(reflect.ValueOf(thing)) columns := make([]string, 0, len(table.Columns)) values := make([]interface{}, 0, len(table.Columns)) for i := 0; i < len(table.Columns); i++ { column := table.Columns[i] value := thingValue.Field(column.Field) kind := value.Kind() // skip fields that are nil pointers or empty slices/maps/arrays if (kind == reflect.Ptr && value.IsNil()) || ((kind == reflect.Slice || kind == reflect.Map || kind == reflect.Array) && value.Len() < 1) { continue } if column.Serialize { // TODO(jr): don't eat this marshal error value marshaled, _ := json.Marshal(value.Interface()) values = append(values, string(marshaled)) } else { values = append(values, reflect.Indirect(value).Interface()) } columns = append(columns, column.Name) } return columns, values }
// insert some models to database func (o *orm) InsertMulti(bulk int, mds interface{}) (int64, error) { var cnt int64 sind := reflect.Indirect(reflect.ValueOf(mds)) switch sind.Kind() { case reflect.Array, reflect.Slice: if sind.Len() == 0 { return cnt, ErrArgs } default: return cnt, ErrArgs } if bulk <= 1 { for i := 0; i < sind.Len(); i++ { ind := reflect.Indirect(sind.Index(i)) mi, _ := o.getMiInd(ind.Interface(), false) id, err := o.alias.DbBaser.Insert(o.db, mi, ind, o.alias.TZ) if err != nil { return cnt, err } o.setPk(mi, ind, id) cnt++ } } else { mi, _ := o.getMiInd(sind.Index(0).Interface(), false) return o.alias.DbBaser.InsertMulti(o.db, mi, sind, bulk, o.alias.TZ) } return cnt, nil }
func (c *ServiceClient) send(retry, giveup time.Duration, ri *skynet.RequestInfo, fn string, in interface{}, out interface{}) (err error) { if ri == nil { ri = c.NewRequestInfo() } attempts := make(chan sendAttempt) var retryTicker <-chan time.Time retryChan := make(chan bool, 1) if retry > 0 { retryTicker = time.Tick(retry) } var timeoutTimer <-chan time.Time if giveup > 0 { timeoutTimer = time.NewTimer(giveup).C } attemptCount := 1 go c.attemptSend(retry, attempts, ri, fn, in, out) for { select { case <-retryTicker: retryChan <- true case <-retryChan: attemptCount++ ri.RetryCount++ log.Println(log.TRACE, fmt.Sprintf("Sending Attempt# %d with RequestInfo %+v", attemptCount, ri)) go c.attemptSend(retry, attempts, ri, fn, in, out) case <-timeoutTimer: err = RequestTimeout log.Println(log.WARN, fmt.Sprintf("Timing out request after %d attempts within %s ", attemptCount, giveup.String())) return case attempt := <-attempts: if attempt.err != nil { log.Println(log.ERROR, "Attempt Error: ", attempt.err) // If there is no retry timer we need to exit as retries were disabled if retryTicker == nil { return err } else { // Don't wait for next retry tick retry now retryChan <- true } continue } // copy into the caller's value v := reflect.Indirect(reflect.ValueOf(out)) v.Set(reflect.Indirect(reflect.ValueOf(attempt.result))) return } } }
func loadOneBy(id string, idField string, result interface{}) error { v := reflect.ValueOf(result) if v.Kind() != reflect.Ptr { panic("loadOne passed a non-pointer") } v = reflect.Indirect(v) if v.Kind() != reflect.Ptr { panic("loadOne passed a pointer to a non-pointer") } v = reflect.Indirect(v) if v.Kind() != reflect.Struct { panic("loadOne passed a pointer to a non-structure type " + v.Kind().String()) } elemType := v.Type() table := tableName(elemType.Name()) rows, err := config.DB.Query(`SELECT * FROM `+table+` WHERE `+idField+` = ?`, id) if err != nil { return err } found := false for rows.Next() { extractRow(v, rows) found = true } if !found { v := reflect.ValueOf(result).Elem() v.Set(reflect.Zero(v.Type())) } return nil }
func TestDataTypes(t *testing.T) { d := Data{} ind := reflect.Indirect(reflect.ValueOf(&d)) for name, value := range Data_Values { e := ind.FieldByName(name) e.Set(reflect.ValueOf(value)) } id, err := dORM.Insert(&d) throwFail(t, err) throwFail(t, AssertIs(id, 1)) d = Data{Id: 1} err = dORM.Read(&d) throwFail(t, err) ind = reflect.Indirect(reflect.ValueOf(&d)) for name, value := range Data_Values { e := ind.FieldByName(name) vu := e.Interface() switch name { case "Date": vu = vu.(time.Time).In(DefaultTimeLoc).Format(test_Date) value = value.(time.Time).In(DefaultTimeLoc).Format(test_Date) case "DateTime": vu = vu.(time.Time).In(DefaultTimeLoc).Format(test_DateTime) value = value.(time.Time).In(DefaultTimeLoc).Format(test_DateTime) } throwFail(t, AssertIs(vu == value, true), value, vu) } }
// LoadModuleSettings loads the given module's configuration. // // module is the name of the module, e.g. "data" // cfgPath is the path to the configuration directory // settings is a pointer to a struct to be filled with the module settings. It // must contain a field named "Monsti" of type settings.Monsti to be filled // with Monsti's common settings. func LoadModuleSettings(module, cfgPath string, settings interface{}) error { // Value checking value := reflect.ValueOf(settings) if !value.IsValid() || value.Kind() != reflect.Ptr || reflect.Indirect(value).Kind() != reflect.Struct { return fmt.Errorf("util: LoadModuleSettings expects its third " + "argument to be a pointer to a struct") } monstiSettings := reflect.Indirect(value).FieldByName("Monsti") if reflect.ValueOf(monstiSettings).Kind() != reflect.Struct { return fmt.Errorf("util: LoadModuleSettings expects its third " + `argument to contain a field named "Monsti" of type ` + `settings.Monsti`) } // Load module settings path := filepath.Join(cfgPath, module+".yaml") if err := yaml.Parse(path, settings); err != nil { return fmt.Errorf("util: Could not parse module settings: %v", err) } // Load Monsti settings monstiSettingsRet, err := LoadMonstiSettings(cfgPath) if err != nil { return fmt.Errorf("util: Could not load monsti settings: %v", err) } monstiSettings.Set(reflect.ValueOf(*monstiSettingsRet)) return nil }
// fillRuntimeIndexes fills a runtimeIndexes structure will the field // indexes gathered from the remoteTypes recorded in a runtimeValues // structure. func fillRuntimeIndexes(runtime *runtimeValues, out *runtimeIndexes) { outv := reflect.Indirect(reflect.NewValue(out)).(*reflect.StructValue) outt := outv.Type().(*reflect.StructType) runtimev := reflect.Indirect(reflect.NewValue(runtime)).(*reflect.StructValue) // out contains fields corresponding to each runtime type for i := 0; i < outt.NumField(); i++ { // Find the interpreter type for this runtime type name := outt.Field(i).Name et := runtimev.FieldByName(name).Interface().(*remoteType).Type.(*eval.StructType) // Get the field indexes of the interpreter struct type indexes := make(map[string]int, len(et.Elems)) for j, f := range et.Elems { if f.Anonymous { continue } name := f.Name if name[0] >= 'a' && name[0] <= 'z' { name = string(name[0]+'A'-'a') + name[1:] } indexes[name] = j } // Fill this field of out outStructv := outv.Field(i).(*reflect.StructValue) outStructt := outStructv.Type().(*reflect.StructType) for j := 0; j < outStructt.NumField(); j++ { f := outStructv.Field(j).(*reflect.IntValue) name := outStructt.Field(j).Name f.Set(indexes[name]) } } }
func (scope *Scope) handleBelongsToPreload(field *Field, conditions []interface{}) { relation := field.Relationship primaryKeys := scope.getColumnAsArray(relation.ForeignFieldNames) if len(primaryKeys) == 0 { return } results := makeSlice(field.Struct.Type) scope.Err(scope.NewDB().Where(fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relation.AssociationForeignDBNames), toQueryMarks(primaryKeys)), toQueryValues(primaryKeys)...).Find(results, conditions...).Error) resultValues := reflect.Indirect(reflect.ValueOf(results)) for i := 0; i < resultValues.Len(); i++ { result := resultValues.Index(i) if scope.IndirectValue().Kind() == reflect.Slice { value := getRealValue(result, relation.AssociationForeignFieldNames) objects := scope.IndirectValue() for j := 0; j < objects.Len(); j++ { object := reflect.Indirect(objects.Index(j)) if object.Kind() == reflect.Ptr { object = reflect.Indirect(objects.Index(j).Elem()) } if equalAsString(getRealValue(object, relation.ForeignFieldNames), value) { object.FieldByName(field.Name).Set(result) } } } else { scope.SetColumn(field, result) } } }
func goStructEnumerate(self *_object, all bool, each func(string) bool) { object := self.value.(*_goStructObject) // Enumerate fields for index := 0; index < reflect.Indirect(object.value).NumField(); index++ { name := reflect.Indirect(object.value).Type().Field(index).Name if isExported(name) { if !each(toJavascriptName(name)) { return } } } // Enumerate methods for index := 0; index < object.value.NumMethod(); index++ { name := object.value.Type().Method(index).Name if isExported(name) { if !each(toJavascriptName(name)) { return } } } objectEnumerate(self, all, each) }
func (q *queryT) First() error { q.op = otQuery l := 1 q.limit = &l rv := reflect.ValueOf(q.inst) rvi := reflect.Indirect(rv) if rvi.Kind() == reflect.Struct { dv := reflect.New(reflect.SliceOf(rvi.Type())) dv.Elem().Set(reflect.MakeSlice(reflect.SliceOf(rvi.Type()), 0, 1)) if b, err := defaultClient.doRequest(q); err != nil { return err } else if err := handleResponse(b, dv.Interface()); err != nil { return err } dvi := reflect.Indirect(dv) if dvi.Len() > 0 { rv.Elem().Set(dv.Elem().Index(0)) } } else if rvi.Kind() == reflect.Slice { if b, err := defaultClient.doRequest(q); err != nil { return err } else if err := handleResponse(b, q.inst); err != nil { return err } } else { return fmt.Errorf("expected struct or slice, got %s", rvi.Kind()) } return nil }
func (context *Context) isIncluded(value interface{}, hasValue interface{}) bool { primaryKeys := []interface{}{} reflectValue := reflect.Indirect(reflect.ValueOf(value)) if reflectValue.Kind() == reflect.Slice { for i := 0; i < reflectValue.Len(); i++ { if value := reflectValue.Index(i); value.IsValid() { if reflect.Indirect(value).Kind() == reflect.Struct { scope := &gorm.Scope{Value: reflectValue.Index(i).Interface()} primaryKeys = append(primaryKeys, scope.PrimaryKeyValue()) } else { primaryKeys = append(primaryKeys, reflect.Indirect(reflectValue.Index(i)).Interface()) } } } } else if reflectValue.Kind() == reflect.Struct { scope := &gorm.Scope{Value: value} primaryKeys = append(primaryKeys, scope.PrimaryKeyValue()) } else if reflectValue.Kind() == reflect.String { return strings.Contains(reflectValue.Interface().(string), fmt.Sprintf("%v", hasValue)) } else { if reflectValue.IsValid() { primaryKeys = append(primaryKeys, reflect.Indirect(reflectValue).Interface()) } } for _, key := range primaryKeys { if fmt.Sprintf("%v", hasValue) == fmt.Sprintf("%v", key) { return true } } return false }
func processTags(config interface{}, prefix ...string) error { configValue := reflect.Indirect(reflect.ValueOf(config)) if configValue.Kind() != reflect.Struct { return errors.New("invalid config, should be struct") } configType := configValue.Type() for i := 0; i < configType.NumField(); i++ { fieldStruct := configType.Field(i) field := configValue.Field(i) // read configuration from shell env var envName = fieldStruct.Tag.Get("env") if envName == "" { envName = strings.ToUpper(strings.Join(append(prefix, fieldStruct.Name), "_")) } if envName != "" { if value := os.Getenv(envName); value != "" { if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil { return err } } } if isBlank := reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface()); isBlank { // set default configuration if is blank if value := fieldStruct.Tag.Get("default"); value != "" { if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil { return err } } else if fieldStruct.Tag.Get("required") == "true" { // set configuration has value if it is required return errors.New(fieldStruct.Name + " is required, but blank") } } for field.Kind() == reflect.Ptr { field = field.Elem() } if field.Kind() == reflect.Struct { if err := processTags(field.Addr().Interface(), getPrefixForStruct(prefix, &fieldStruct)...); err != nil { return err } } if field.Kind() == reflect.Slice { var length = field.Len() for i := 0; i < length; i++ { if reflect.Indirect(field.Index(i)).Kind() == reflect.Struct { if err := processTags(field.Index(i).Addr().Interface(), append(getPrefixForStruct(prefix, &fieldStruct), fmt.Sprintf("%d", i))...); err != nil { return err } } } } } return nil }