Пример #1
0
func getReflectTypeName(reflectType reflect.Type) (string, error) {
	buffer := bytes.NewBuffer(nil)
	for reflectType.Kind() == reflect.Ptr {
		if _, err := buffer.WriteString("*"); err != nil {
			return "", err
		}
		reflectType = reflectType.Elem()
	}
	pkgPath := reflectType.PkgPath()
	if pkgPath == "" {
		return "", fmt.Errorf("ledge: no package for type %v", reflectType)
	}
	if _, err := buffer.WriteString("\""); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString(pkgPath); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString("\""); err != nil {
		return "", err
	}
	name := reflectType.Name()
	if name == "" {
		return "", fmt.Errorf("ledge: no name for type %v", reflectType)
	}
	if _, err := buffer.WriteString("."); err != nil {
		return "", err
	}
	if _, err := buffer.WriteString(name); err != nil {
		return "", err
	}
	return buffer.String(), nil
}
Пример #2
0
// getTypName returns a string representing the name of the object typ.
// if the name is defined then it is used, otherwise, the name is derived from the
// Stringer interface.
//
// the stringer returns something like *somepkg.MyStruct, so skip
// the *somepkg and return MyStruct
func getTypName(typ reflect.Type) string {
	if typ.Name() != "" {
		return typ.Name()
	}
	split := strings.Split(typ.String(), ".")
	return split[len(split)-1]
}
Пример #3
0
func (d SqliteDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
	switch val.Kind() {
	case reflect.Ptr:
		return d.ToSqlType(val.Elem(), maxsize, isAutoIncr)
	case reflect.Bool:
		return "integer"
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return "integer"
	case reflect.Float64, reflect.Float32:
		return "real"
	case reflect.Slice:
		if val.Elem().Kind() == reflect.Uint8 {
			return "blob"
		}
	}

	switch val.Name() {
	case "NullInt64":
		return "integer"
	case "NullFloat64":
		return "real"
	case "NullBool":
		return "integer"
	case "Time":
		return "datetime"
	}

	if maxsize < 1 {
		maxsize = 255
	}
	return fmt.Sprintf("varchar(%d)", maxsize)
}
Пример #4
0
func (db *DB) rawSelectByStruct(structType reflect.Type, qi SqlQueryInfo) (rows *sql.Rows, fields []string, err error) {
	// nums of struct's fields
	lf := structType.NumField()
	// type's fields
	fields = make([]string, 0, lf)
	// sql select columns, it's Snake Cased
	columns := make([]string, 0, lf)

	// get fields in structType,
	// and convert to sql query column name
	for i := 0; i < lf; i++ {
		structField := structType.Field(i)
		fieldName := structField.Name
		fields = append(fields, fieldName)
		columns = append(columns, utils.SnakeCasedName(fieldName))
	}

	// tableName := utils.SnakeCasedName(utils.StructName(s))
	tableName := utils.SnakeCasedName(structType.Name())
	// TODO: check the fileds has specified ?
	qi.Fields = strings.Join(columns, ", ")
	// run query from db
	rows, err = db.Select(tableName, qi)
	return
}
Пример #5
0
func defaultType(t reflect.Type) TypeDesc {
	switch t.Kind() {
	case reflect.Bool:
		return BooleanType
	case reflect.String:
		return UTF8Type
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return LongType
	case reflect.Float32:
		return FloatType
	case reflect.Float64:
		return DoubleType
	case reflect.Array:
		if t.Name() == "UUID" && t.Size() == 16 {
			return UUIDType
		}
		return UnknownType
	case reflect.Struct:
		if t.Name() == "Time" && t.PkgPath() == "time" {
			return DateType
		}
		return UnknownType
	case reflect.Slice:
		if et := t.Elem(); et.Kind() == reflect.Uint8 {
			return BytesType
		}
		return UnknownType
	}
	return UnknownType
}
Пример #6
0
func (g *schemaGenerator) generate(t reflect.Type) (*JSONSchema, error) {
	if t.Kind() != reflect.Struct {
		return nil, fmt.Errorf("Only struct types can be converted.")
	}

	s := JSONSchema{
		ID:     "http://fabric8.io/fabric8/v2/" + t.Name() + "#",
		Schema: "http://json-schema.org/schema#",
		JSONDescriptor: JSONDescriptor{
			Type: "object",
		},
	}
	s.JSONObjectDescriptor = g.generateObjectDescriptor(t)
	if len(g.types) > 0 {
		s.Definitions = make(map[string]JSONPropertyDescriptor)
		for k, v := range g.types {
			name := g.qualifiedName(k)
			value := JSONPropertyDescriptor{
				JSONDescriptor: &JSONDescriptor{
					Type: "object",
				},
				JSONObjectDescriptor: v,
				JavaTypeDescriptor: &JavaTypeDescriptor{
					JavaType: g.javaType(k),
				},
				JavaInterfacesDescriptor: &JavaInterfacesDescriptor{
					JavaInterfaces: g.javaInterfaces(k),
				},
			}
			s.Definitions[name] = value
		}
	}
	return &s, nil
}
Пример #7
0
// The reflection type must have all its indirections processed out.
// typeLock must be held.
func getTypeInfo(rt reflect.Type) (*typeInfo, os.Error) {
	if _, ok := rt.(*reflect.PtrType); ok {
		panic("pointer type in getTypeInfo: " + rt.String())
	}
	info, ok := typeInfoMap[rt]
	if !ok {
		info = new(typeInfo)
		name := rt.Name()
		gt, err := getType(name, rt)
		if err != nil {
			return nil, err
		}
		info.id = gt.id()
		t := info.id.gobType()
		switch typ := rt.(type) {
		case *reflect.ArrayType:
			info.wire = &wireType{arrayT: t.(*arrayType)}
		case *reflect.MapType:
			info.wire = &wireType{mapT: t.(*mapType)}
		case *reflect.SliceType:
			// []byte == []uint8 is a special case handled separately
			if _, ok := typ.Elem().(*reflect.Uint8Type); !ok {
				info.wire = &wireType{sliceT: t.(*sliceType)}
			}
		case *reflect.StructType:
			info.wire = &wireType{structT: t.(*structType)}
		}
		typeInfoMap[rt] = info
	}
	return info, nil
}
Пример #8
0
func (b *Backend) FieldType(typ reflect.Type, t *structs.Tag) (string, error) {
	if c := codec.FromTag(t); c != nil {
		if c.Binary || t.PipeName() != "" {
			return "BLOB", nil
		}
		return "TEXT", nil
	}
	switch typ.Kind() {
	case reflect.Bool:
		return "BOOLEAN", nil
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return "INTEGER", nil
	case reflect.Float32, reflect.Float64:
		return "REAL", nil
	case reflect.String:
		return "TEXT", nil
	case reflect.Slice:
		// []byte
		if typ.Elem().Kind() == reflect.Uint8 {
			return "BLOB", nil
		}
	case reflect.Struct:
		if typ.Name() == "Time" && typ.PkgPath() == "time" {
			return "INTEGER", nil
		}
	}
	return "", fmt.Errorf("can't map field type %v to a database type", typ)
}
Пример #9
0
// Is this typoe exported or a builtin?
func isExportedOrBuiltinType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	return isExported(t.Name()) || t.PkgPath() == ""
}
Пример #10
0
func fromStruct(name string, s reflect.Type) (t Table, err error) {
	if name == "" {
		if s.Name() == "" {
			err = errors.New("please specify a name or use name type.")
			return t, err
		}
		name = s.Name()
	}

	t.name = strings.ToLower(name)
	n := s.NumField()
	if n <= 0 {
		return t, errors.New("struct doesn't have a field.")
	}

	for i := 0; i < n; i++ {
		field := s.Field(i)
		if field.Anonymous || !isExported(field) {
			continue
		}
		t.fields = append(t.fields, strings.ToLower(field.Name))
		t.fieldsIndex = append(t.fieldsIndex, i)
	}
	t.primaryKey, err = primaryKeys(s)
	return t, err
}
Пример #11
0
// GetTypeHash returns the TypeHash for a given reflect.Type
func GetTypeHash(t reflect.Type) TypeHash {
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	return TypeHash(fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()))
}
Пример #12
0
Файл: db.go Проект: go-gorp/gorp
func (m *DbMap) createIndexImpl(dialect reflect.Type,
	table *TableMap,
	index *IndexMap) error {
	s := bytes.Buffer{}
	s.WriteString("create")
	if index.Unique {
		s.WriteString(" unique")
	}
	s.WriteString(" index")
	s.WriteString(fmt.Sprintf(" %s on %s", index.IndexName, table.TableName))
	if dname := dialect.Name(); dname == "PostgresDialect" && index.IndexType != "" {
		s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
	}
	s.WriteString(" (")
	for x, col := range index.columns {
		if x > 0 {
			s.WriteString(", ")
		}
		s.WriteString(m.Dialect.QuoteField(col))
	}
	s.WriteString(")")

	if dname := dialect.Name(); dname == "MySQLDialect" && index.IndexType != "" {
		s.WriteString(fmt.Sprintf(" %s %s", m.Dialect.CreateIndexSuffix(), index.IndexType))
	}
	s.WriteString(";")
	_, err := m.Exec(s.String())
	return err
}
Пример #13
0
func (self *DB) emit(typ reflect.Type, oldValue, newValue *reflect.Value) (err error) {
	if oldValue != nil && newValue != nil {
		if chain := newValue.Addr().MethodByName("Updated"); chain.IsValid() {
			if err = callErr(chain, []reflect.Value{reflect.ValueOf(self), oldValue.Addr()}); err != nil {
				return
			}
		}
	} else if newValue != nil {
		if chain := newValue.Addr().MethodByName("Created"); chain.IsValid() {
			if err = callErr(chain, []reflect.Value{reflect.ValueOf(self)}); err != nil {
				return
			}
		}
	} else if oldValue != nil {
		if chain := oldValue.Addr().MethodByName("Deleted"); chain.IsValid() {
			if err = callErr(chain, []reflect.Value{reflect.ValueOf(self)}); err != nil {
				return
			}
		}
	}
	self.lock.RLock()
	defer self.lock.RUnlock()
	for _, subscription := range self.subscriptions[typ.Name()] {
		go subscription.handle(typ, oldValue, newValue)
	}
	return
}
func newStructEncoder(t reflect.Type) encoderFunc {
	n := t.NumField()
	fields := make([]reflect.StructField, n)
	for i := 0; i < n; i++ {
		fields[i] = t.Field(i)
	}
	return func(e *encodeState, v reflect.Value, _ []byte) {
		e.HeaderWrite(t.Name(), v)

		for i := 0; i < n; i++ {
			sf := fields[i]
			f := v.Field(i)
			name, mandatory := getName(sf)
			if !f.IsValid() || isEmptyValue(f) || len(name) == 0 {
				if mandatory {
					// TODO this must be an error
					panic("missing mandatory field")
				}
				continue
			}
			newTypeEncoder(sf.Type, false)(e, f, name)
		}
		e.WriteByte(']')
	}
}
Пример #15
0
func (g *conversionGenerator) typeName(inType reflect.Type) string {
	switch inType.Kind() {
	case reflect.Slice:
		return fmt.Sprintf("[]%s", g.typeName(inType.Elem()))
	case reflect.Ptr:
		return fmt.Sprintf("*%s", g.typeName(inType.Elem()))
	case reflect.Map:
		if len(inType.Name()) == 0 {
			return fmt.Sprintf("map[%s]%s", g.typeName(inType.Key()), g.typeName(inType.Elem()))
		}
		fallthrough
	default:
		pkg, name := inType.PkgPath(), inType.Name()
		if len(name) == 0 && inType.Kind() == reflect.Struct {
			return "struct{}"
		}
		if len(pkg) == 0 {
			// Default package.
			return name
		}
		if val, found := g.pkgOverwrites[pkg]; found {
			pkg = val
		}
		if len(pkg) == 0 {
			return name
		}
		short := g.addImportByPath(pkg)
		if len(short) > 0 {
			return fmt.Sprintf("%s.%s", short, name)
		}
		return name
	}
}
Пример #16
0
// defaultStart returns the default start element to use,
// given the reflect type, field info, and start template.
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
	var start StartElement
	// Precedence for the XML element name is as above,
	// except that we do not look inside structs for the first field.
	if startTemplate != nil {
		start.Name = startTemplate.Name
		start.Attr = append(start.Attr, startTemplate.Attr...)
	} else if finfo != nil && finfo.name != "" {
		start.Name.Local = finfo.name
		start.Name.Space = finfo.xmlns
	} else if typ.Name() != "" {
		start.Name.Local = typ.Name()
	} else {
		// Must be a pointer to a named type,
		// since it has the Marshaler methods.
		start.Name.Local = typ.Elem().Name()
	}

	// Add type attribute if necessary
	if finfo != nil && finfo.flags&fTypeAttr != 0 {
		start.Attr = append(start.Attr, Attr{xmlSchemaInstance, typeToString(typ)})
	}

	return start
}
Пример #17
0
func (g *conversionGenerator) conversionFunctionName(inType, outType reflect.Type) string {
	funcNameFormat := "convert_%s_%s_To_%s_%s"
	inPkg := packageForName(inType)
	outPkg := packageForName(outType)
	funcName := fmt.Sprintf(funcNameFormat, inPkg, inType.Name(), outPkg, outType.Name())
	return funcName
}
Пример #18
0
// MakeNewDatabaseMapped returns a new instance of a database mapped type.
func MakeNewDatabaseMapped(t reflect.Type) (DatabaseMapped, error) {
	newInterface := reflect.New(t).Interface()
	if typed, isTyped := newInterface.(DatabaseMapped); isTyped {
		return typed.(DatabaseMapped), nil
	}
	return nil, exception.Newf("`%s` does not implement DatabaseMapped.", t.Name())
}
Пример #19
0
func newStructInspection(t reflect.Type) (*structInspection, error) {
	si := &structInspection{
		rtype:           t,
		orderedFields:   make([]*field, 0),
		goFields:        make(map[string]*field, 0),
		cassandraFields: make(map[string]*field, 0),
		globalTags:      make(map[string]string),
	}
	n := t.NumField()
	for i := 0; i < n; i++ {
		sf := t.Field(i)
		for _, t := range recognizedGlobalTags {
			if v := sf.Tag.Get(t); v != "" {
				si.globalTags[t] = v
			}
		}
		f, err := newField(i, sf)
		if err != nil {
			return nil, errors.New(fmt.Sprint("Error in struct ", t.Name(), ": ", err))
		}
		if f != nil {
			si.orderedFields = append(si.orderedFields, f)
			si.goFields[f.name] = f
			si.cassandraFields[f.cassandraName] = f
		}
	}
	return si, nil
}
Пример #20
0
// Is this type exported or a builtin?
func isExportedOrBuiltinType(t reflect.Type) bool {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	// so we need to check the type name as well.
	return isExported(t.Name()) || t.PkgPath() == ""
}
Пример #21
0
// create new schema with type
func NewSchema(rt reflect.Type, size int) (sc *Schema, e error) {
	numField := rt.NumField()
	if numField < 1 {
		e = fmtError(ErrStrStructNeedField, rt)
		return
	}
	sc = new(Schema)
	sc.Name = rt.Name()
	sc.Max = 0
	sc.Index = []string{}
	sc.ChunkSize = size

	// parse fields
	for i := 0; i < numField; i++ {
		field := rt.Field(i)
		tag := field.Tag.Get("jx")
		if tag == "" || tag == "-" {
			continue
		}
		if tag == "pk" {
			if field.Type.Kind() != reflect.Int {
				e = fmtError(ErrStrStructPkNeedInt, rt, field.Name)
				return
			}
			sc.PK = field.Name
			continue
		}
		if tag == "index" {
			sc.Index = append(sc.Index, field.Name)
		}
	}
	return
}
Пример #22
0
func (t TranslationUnit) expectNodeType(node Node, kind reflect.Type) error {
	if reflect.TypeOf(node) != kind {
		return NewSemanticError(node, "expected "+kind.Name())
	}

	return nil
}
Пример #23
0
// defaultStart returns the default start element to use,
// given the reflect type, field info, and start template.
func (p *printer) defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement {
	var start StartElement
	// Precedence for the XML element name is as above,
	// except that we do not look inside structs for the first field.
	if startTemplate != nil {
		start.Name = startTemplate.Name
		start.Attr = append(start.Attr, startTemplate.Attr...)
	} else if finfo != nil && finfo.name != "" {
		start.Name.Local = finfo.name
		start.Name.Space = finfo.xmlns
	} else if typ.Name() != "" {
		start.Name.Local = typ.Name()
	} else {
		// Must be a pointer to a named type,
		// since it has the Marshaler methods.
		start.Name.Local = typ.Elem().Name()
	}
	// Historic behaviour: elements use the name space of
	// the element they are contained in by default.
	if start.Name.Space == "" {
		start.Name.Space = p.defaultNS
	}
	start.setDefaultNamespace()
	return start
}
Пример #24
0
// Given a reflected Go type, getUniversalType returns the default tag number
// and expected compound flag.
func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) {
	switch t {
	case objectIdentifierType:
		return tagOID, false, true
	case bitStringType:
		return tagBitString, false, true
	case timeType:
		return tagUTCTime, false, true
	case enumeratedType:
		return tagEnum, false, true
	}
	switch t := t.(type) {
	case *reflect.BoolType:
		return tagBoolean, false, true
	case *reflect.IntType:
		return tagInteger, false, true
	case *reflect.StructType:
		return tagSequence, true, true
	case *reflect.SliceType:
		if t.Elem().Kind() == reflect.Uint8 {
			return tagOctetString, false, true
		}
		if strings.HasSuffix(t.Name(), "SET") {
			return tagSet, true, true
		}
		return tagSequence, true, true
	case *reflect.StringType:
		return tagPrintableString, false, true
	}
	return 0, false, false
}
Пример #25
0
func typeNamesEqual(methVal reflect.Type, name2 string) bool {
	if strings.Index(name2, ".") == -1 {
		return methVal.Name() == name2
	}
	fullName := strings.Replace(methVal.PkgPath(), "/", ".", -1) + "." + methVal.Name()
	return fullName == name2
}
Пример #26
0
func verifyOrCreateDir(ctype reflect.Type) (dir string) {
	path := filepath.Join(testdir, ctype.Name())
	if e := os.MkdirAll(path, 0764); e != nil {
		panic(fmt.Errorf("verifyOrCreateDir - %s", e))
	}
	return path
}
Пример #27
0
func (m MySQLDialect) ToSqlType(val reflect.Type, maxsize int, isAutoIncr bool) string {
	switch val.Kind() {
	case reflect.Int, reflect.Int16, reflect.Int32:
		return "int"
	case reflect.Int64:
		return "bigint"
	case reflect.Float64, reflect.Float32:
		return "double"
	case reflect.Slice:
		if val.Elem().Kind() == reflect.Uint8 {
			return "mediumblob"
		}
	}

	switch val.Name() {
	case "NullableInt64":
		return "bigint"
	case "NullableFloat64":
		return "double"
	case "NullableBool":
		return "tinyint"
	case "NullableBytes":
		return "mediumblob"
	}

	if maxsize < 1 {
		maxsize = 255
	}
	return fmt.Sprintf("varchar(%d)", maxsize)
}
Пример #28
0
func checkJsonTags(objType reflect.Type, seen *map[reflect.Type]bool, t *testing.T) {
	if _, exists := (*seen)[objType]; exists {
		return
	}
	(*seen)[objType] = true
	if !strings.Contains(objType.PkgPath(), "openshift/origin") {
		return
	}
	if internalTypesWithAllowedJsonTags.Has(objType.Name()) {
		return
	}

	for i := 0; i < objType.NumField(); i++ {
		structField := objType.FieldByIndex([]int{i})

		jsonTag := structField.Tag.Get("json")
		if len(jsonTag) != 0 {
			t.Errorf("%v.%v should not have a json tag", objType, structField.Name)
		}

		switch structField.Type.Kind() {
		case reflect.Struct:
			checkJsonTags(structField.Type, seen, t)
		}
	}
}
Пример #29
0
func validateListType(target reflect.Type) error {
	// exceptions
	if listTypeExceptions.Has(target.Name()) {
		return nil
	}
	hasListSuffix := strings.HasSuffix(target.Name(), "List")
	hasMetadata := false
	hasItems := false
	for i := 0; i < target.NumField(); i++ {
		field := target.Field(i)
		tag := field.Tag.Get("json")
		switch {
		case strings.HasPrefix(tag, "metadata"):
			hasMetadata = true
		case tag == "items":
			hasItems = true
			if field.Type.Kind() != reflect.Slice {
				return fmt.Errorf("Expected items to be slice, got %s", field.Type.Kind())
			}
		}
	}
	if hasListSuffix && !hasMetadata {
		return fmt.Errorf("Expected type %s to contain \"metadata\"", target.Name())
	}
	if hasListSuffix && !hasItems {
		return fmt.Errorf("Expected type %s to contain \"items\"", target.Name())
	}
	// if a type contains field Items with JSON tag "items", its name should end with List.
	if !hasListSuffix && hasItems {
		return fmt.Errorf("Type %s has Items, its name is expected to end with \"List\"", target.Name())
	}
	return nil
}
Пример #30
0
Файл: meta.go Проект: lye/crud
/*
sqlToGoFields extracts the data contained within the "crud" struct tags.

The "crud" struct tags contain the name of the SQL column which stores the
tagged field. sqlToGoFields returns a mapping from SQL column name to Go
field name.
*/
func sqlToGoFields(ty reflect.Type) (map[string]fieldMeta, error) {
	ty = indirectT(ty)

	if ty.Kind() != reflect.Struct {
		return nil, fmt.Errorf("sqlToGoFields: type %s is not a struct", ty.Name())
	}

	fieldMap := make(map[string]fieldMeta)

	for i := 0; i < ty.NumField(); i += 1 {
		field := ty.Field(i)

		tag := field.Tag.Get("crud")

		if tag != "" {
			tagPieces := strings.Split(tag, ",")

			meta := fieldMeta{
				SqlName: tagPieces[0],
				GoName:  field.Name,
			}

			for idx := 1; idx < len(tagPieces); idx += 1 {
				if tagPieces[idx] == "unix" {
					meta.Unix = true
				}
			}

			fieldMap[meta.SqlName] = meta
		}
	}

	return fieldMap, nil
}