• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang driver.Model类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中gnd/la/orm/driver.Model的典型用法代码示例。如果您正苦于以下问题:Golang Model类的具体用法?Golang Model怎么用?Golang Model使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Model类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Insert

func (d *Driver) Insert(m driver.Model, data interface{}) (driver.Result, error) {
	_, fields, values, err := d.saveParameters(m, data)
	if err != nil {
		return nil, err
	}
	buf := getBuffer()
	buf.WriteString("INSERT INTO ")
	buf.WriteByte('"')
	buf.WriteString(m.Table())
	buf.WriteByte('"')
	count := len(fields)
	if count > 0 {
		buf.WriteString(" (")
		for _, v := range fields {
			buf.WriteByte('"')
			buf.WriteString(v)
			buf.WriteByte('"')
			buf.WriteByte(',')
		}
		buf.Truncate(buf.Len() - 1)
		buf.WriteString(") VALUES (")
		buf.WriteString(d.backend.Placeholders(count))
		buf.WriteByte(')')
	} else {
		buf.WriteByte(' ')
		buf.WriteString(d.backend.DefaultValues())
	}
	res, err := d.backend.Insert(d.db, m, buftos(buf), values...)
	putBuffer(buf)
	return res, err
}
开发者ID:rainycape,项目名称:gondola,代码行数:31,代码来源:driver.go


示例2: Update

func (d *Driver) Update(m driver.Model, q query.Q, data interface{}) (driver.Result, error) {
	_, fields, values, err := d.saveParameters(m, data)
	if err != nil {
		return nil, err
	}
	buf := getBuffer()
	buf.WriteString("UPDATE ")
	buf.WriteByte('"')
	buf.WriteString(m.Table())
	buf.WriteByte('"')
	buf.WriteString(" SET ")
	for ii, v := range fields {
		buf.WriteByte('"')
		buf.WriteString(v)
		buf.WriteByte('"')
		buf.WriteByte('=')
		buf.WriteString(d.backend.Placeholder(ii))
		buf.WriteByte(',')
	}
	// remove last ,
	buf.Truncate(buf.Len() - 1)
	qParams, err := d.where(buf, m, q, len(values))
	if err != nil {
		return nil, err
	}
	params := append(values, qParams...)
	res, err := d.db.Exec(buftos(buf), params...)
	putBuffer(buf)
	return res, err
}
开发者ID:rainycape,项目名称:gondola,代码行数:30,代码来源:driver.go


示例3: SQL

func (t *Table) SQL(db *DB, b Backend, m driver.Model, name string) (string, error) {
	var lines []string
	var constraints []string
	for _, v := range t.Fields {
		def, cons, err := v.SQL(db, m, t)
		if err != nil {
			return "", err
		}
		lines = append(lines, def)
		constraints = append(constraints, cons...)
	}
	pk, err := t.definePks(db, m)
	if err != nil {
		return "", err
	}
	if pk != "" {
		lines = append(lines, pk)
	}
	lines = append(lines, constraints...)
	if name == "" {
		name = m.Table()
	}
	// Use IF NOT EXISTS, since the DB user might not have
	// the privileges to inspect the database but still
	// be allowed to read and write from the tables (e.g.
	// Postgres only allows superusers and the owner to
	// inspect the database).
	sql := fmt.Sprintf("\nCREATE TABLE IF NOT EXISTS %s (\n\t%s\n)", db.QuoteIdentifier(name), strings.Join(lines, ",\n\t"))
	return sql, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:30,代码来源:table.go


示例4: clause

func (d *Driver) clause(buf *bytes.Buffer, params *[]interface{}, m driver.Model, format string, f *query.Field, begin int) error {
	dbName, _, err := m.Map(f.Field)
	if err != nil {
		return err
	}
	if f.Value != nil {
		if field, ok := f.Value.(query.F); ok {
			fName, _, err := m.Map(string(field))
			if err != nil {
				return err
			}
			fmt.Fprintf(buf, format, dbName, fName)
			return nil
		}
		if sq, ok := f.Value.(query.Subquery); ok {
			fmt.Fprintf(buf, format, dbName, "("+string(sq)+")")
			return nil
		}
		fmt.Fprintf(buf, format, dbName, d.backend.Placeholder(len(*params)+begin))
		val, err := d.transformOutValue(f.Value)
		if err != nil {
			return err
		}
		*params = append(*params, val)
		return nil
	}
	fmt.Fprintf(buf, format, dbName)
	return nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:29,代码来源:driver.go


示例5: makeQuery

func (d *Driver) makeQuery(m driver.Model, q query.Q, opts *driver.QueryOptions) (*datastore.Query, error) {
	if m.Join() != nil {
		return nil, errJoinNotSupported
	}
	dq := datastore.NewQuery(m.Table()).Ancestor(d.parentKey(m))
	var err error
	if dq, err = d.applyQuery(m, dq, q); err != nil {
		return nil, err
	}
	if opts != nil {
		if opts.Distinct {
			dq = dq.Distinct()
		}
		for _, v := range opts.Sort {
			field := v.Field()
			if v.Direction() == driver.DESC {
				field = "-" + field
			}
			dq = dq.Order(field)
		}
		if opts.Limit >= 0 {
			dq = dq.Limit(opts.Limit)
		}
		if opts.Offset > 0 {
			dq = dq.Offset(opts.Offset)
		}
	}
	return dq, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:29,代码来源:driver.go


示例6: fieldHasDefault

func fieldHasDefault(m driver.Model, f *Field) bool {
	if f.Default != "" {
		return true
	}
	fields := m.Fields()
	idx := fields.MNameMap[f.Name]
	return fields.HasDefault(idx)
}
开发者ID:rainycape,项目名称:gondola,代码行数:8,代码来源:driver.go


示例7: createTable

func (d *Driver) createTable(m driver.Model, table *Table) error {
	sql, err := table.SQL(d.db, d.backend, m, m.Table())
	if err != nil {
		return err
	}
	_, err = d.db.Exec(sql)
	return err
}
开发者ID:rainycape,项目名称:gondola,代码行数:8,代码来源:driver.go


示例8: HasIndex

func (b *Backend) HasIndex(db *sql.DB, m driver.Model, idx *index.Index, name string) (bool, error) {
	rows, err := db.Query("SHOW INDEX FROM ? WHERE Key_name = ?", m.Table(), name)
	if err != nil {
		return false, err
	}
	has := rows.Next()
	rows.Close()
	return has, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:9,代码来源:backend.go


示例9: Inspect

func (b *Backend) Inspect(db *sql.DB, m driver.Model) (*sql.Table, error) {
	name := db.QuoteString(m.Table())
	rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", name))
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	fieldsByName := make(map[string]*sql.Field)
	var fields []*sql.Field
	for rows.Next() {
		var cid int
		var f sql.Field
		var notnull int
		var def *string
		var pk int
		if err := rows.Scan(&cid, &f.Name, &f.Type, &notnull, &def, &pk); err != nil {
			return nil, err
		}
		f.Type = strings.ToUpper(f.Type)
		if notnull != 0 {
			f.AddConstraint(sql.ConstraintNotNull)
		}
		if def != nil {
			f.Default = *def
		}
		if pk != 0 {
			f.AddConstraint(sql.ConstraintPrimaryKey)
		}
		fields = append(fields, &f)
		fieldsByName[f.Name] = &f
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	rows, err = db.Query(fmt.Sprintf("PRAGMA foreign_key_list(%s)", name))
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var id, seq int
		var table, from, to, onUpdate, onDelete, match string
		if err := rows.Scan(&id, &seq, &table, &from, &to, &onUpdate, &onDelete, &match); err != nil {
			return nil, err
		}
		field := fieldsByName[from]
		field.Constraints = append(field.Constraints, &sql.Constraint{Type: sql.ConstraintForeignKey, References: sql.MakeReference(table, to)})
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	if len(fields) > 0 {
		return &sql.Table{Fields: fields}, nil
	}
	return nil, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:56,代码来源:backend.go


示例10: less

func (s sortModels) less(mi, mj driver.Model) bool {
	for _, v := range mi.Fields().References {
		if v.Model == mj {
			return false
		}
		if v.Model != mi && !s.less(v.Model, mj) {
			return false
		}
	}
	return true
}
开发者ID:rainycape,项目名称:gondola,代码行数:11,代码来源:model.go


示例11: createIndexes

func (d *Driver) createIndexes(m driver.Model) error {
	for _, idx := range m.Indexes() {
		name, err := d.indexName(m, idx)
		if err != nil {
			return err
		}
		if err := d.createIndex(m, idx, name); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:12,代码来源:driver.go


示例12: Delete

func (d *Driver) Delete(m driver.Model, q query.Q) (driver.Result, error) {
	buf := getBuffer()
	buf.WriteString("DELETE FROM ")
	buf.WriteByte('"')
	buf.WriteString(m.Table())
	buf.WriteByte('"')
	params, err := d.where(buf, m, q, 0)
	if err != nil {
		return nil, err
	}
	res, err := d.db.Exec(buftos(buf), params...)
	putBuffer(buf)
	return res, err
}
开发者ID:rainycape,项目名称:gondola,代码行数:14,代码来源:driver.go


示例13: Insert

func (b *Backend) Insert(db *sql.DB, m driver.Model, query string, args ...interface{}) (driver.Result, error) {
	fields := m.Fields()
	if fields.AutoincrementPk {
		q := query + " RETURNING " + fields.MNames[fields.PrimaryKey]
		var id int64
		err := db.QueryRow(q, args...).Scan(&id)
		// We need to perform a "real" insert to find the real error, so
		// just let the code fall to the Exec at the end of the function
		// if there's an error.
		if err == nil {
			return insertResult(id), nil
		}
	}
	return db.Exec(query, args...)
}
开发者ID:rainycape,项目名称:gondola,代码行数:15,代码来源:backend.go


示例14: AddFields

func (b *SqlBackend) AddFields(db *DB, m driver.Model, prevTable *Table, newTable *Table, fields []*Field) error {
	modelFields := m.Fields()
	tableName := db.QuoteIdentifier(m.Table())
	for _, v := range fields {
		idx := modelFields.MNameMap[v.Name]
		field := v
		hasDefault := modelFields.HasDefault(idx)
		if hasDefault && v.HasConstraint(ConstraintNotNull) {
			// ORM level default
			// Must be added as nullable first, then the default value
			// must be set and finally the field has to be altered to be
			// nullable.
			field = field.Copy()
			var constraints []*Constraint
			for _, v := range field.Constraints {
				if v.Type != ConstraintNotNull {
					constraints = append(constraints, v)
				}
			}
			field.Constraints = constraints
		}
		sql, cons, err := field.SQL(db, m, newTable)
		if err != nil {
			return err
		}
		if _, err = db.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s", tableName, sql)); err != nil {
			return err
		}
		if hasDefault {
			value := modelFields.DefaultValue(idx)
			fieldName := db.QuoteIdentifier(v.Name)
			if _, err := db.Exec(fmt.Sprintf("UPDATE %s SET %s = ?", tableName, fieldName), value); err != nil {
				return err
			}
			if v.HasConstraint(ConstraintNotNull) {
				if err := db.Backend().AlterField(db, m, newTable, field, v); err != nil {
					return err
				}
			}
		}
		for _, c := range cons {
			if _, err = db.Exec(fmt.Sprintf("ALTER TABLE %s ADD CONSTRAINT %s", tableName, c)); err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:48,代码来源:backend.go


示例15: AlterField

func (b *Backend) AlterField(db *sql.DB, m driver.Model, table *sql.Table, oldField *sql.Field, newField *sql.Field) error {
	fsql, cons, err := newField.SQL(db, m, table)
	if err != nil {
		return err
	}
	tableName := db.QuoteIdentifier(m.Table())
	if _, err = db.Exec(fmt.Sprintf("ALTER TABLE %s CHANGE COLUMN %s %s", tableName, db.QuoteIdentifier(oldField.Name), fsql)); err != nil {
		return err
	}
	for _, c := range cons {
		if _, err = db.Exec(fmt.Sprintf("ALTER TABLE %s ADD CONSTRAINT %s", tableName, c)); err != nil {
			return err
		}
	}
	return err
}
开发者ID:rainycape,项目名称:gondola,代码行数:16,代码来源:backend.go


示例16: DefineField

func (b *Backend) DefineField(db *sql.DB, m driver.Model, table *sql.Table, field *sql.Field) (string, []string, error) {
	def, cons, err := b.SqlBackend.DefineField(db, m, table, field)
	if err != nil {
		return "", nil, err
	}
	if ref := field.Constraint(sql.ConstraintForeignKey); ref != nil {
		if pos := strings.Index(def, " REFERENCES"); pos >= 0 {
			def = def[:pos]
		}
		refTable := ref.References.Table()
		refField := ref.References.Field()
		fkName := db.QuoteIdentifier(fmt.Sprintf("%s_%s_%s_%s", m.Table(), field.Name, refTable, refField))
		cons = append(cons, fmt.Sprintf("FOREIGN KEY %s(%s) REFERENCES %s(%s)", fkName, db.QuoteIdentifier(field.Name),
			db.QuoteIdentifier(refTable), db.QuoteIdentifier(refField)))
	}
	return strings.Replace(def, "AUTOINCREMENT", "AUTO_INCREMENT", -1), cons, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:17,代码来源:backend.go


示例17: outValues

func (d *Driver) outValues(m driver.Model, out interface{}) (reflect.Value, *driver.Fields, []interface{}, []*scanner, error) {
	val := reflect.ValueOf(out)
	if !val.IsValid() {
		// Untyped nil pointer
		return reflect.Value{}, nil, nil, nil, nil
	}
	vt := val.Type()
	if vt.Kind() != reflect.Ptr {
		return reflect.Value{}, nil, nil, nil, fmt.Errorf("can't set object of type %T. Please, pass a %v rather than a %v", out, reflect.PtrTo(vt), vt)
	}
	if vt.Elem().Kind() == reflect.Ptr && vt.Elem().Elem().Kind() == reflect.Struct {
		// Received a pointer to pointer. Always create a new object,
		// to avoid overwriting the previous result.
		val = val.Elem()
		el := reflect.New(val.Type().Elem())
		val.Set(el)
	}
	for val.Kind() == reflect.Ptr {
		el := val.Elem()
		if !el.IsValid() {
			if !val.CanSet() {
				// Typed nil pointer
				return reflect.Value{}, nil, nil, nil, nil
			}
			el = reflect.New(val.Type().Elem())
			val.Set(el)
		}
		val = el
	}
	fields := m.Fields()
	if fields == nil {
		// Skipped model
		return reflect.Value{}, nil, nil, nil, nil
	}
	values := make([]interface{}, len(fields.Indexes))
	scanners := make([]*scanner, len(fields.Indexes))
	for ii, v := range fields.Indexes {
		field := d.fieldByIndex(val, v, true)
		tag := fields.Tags[ii]
		s := newScanner(&field, tag, d.backend)
		scanners[ii] = s
		values[ii] = s
	}
	return val, fields, values, scanners, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:45,代码来源:driver.go


示例18: Operate

func (d *Driver) Operate(m driver.Model, q query.Q, ops []*operation.Operation) (driver.Result, error) {
	buf := getBuffer()
	buf.WriteString("UPDATE ")
	buf.WriteByte('"')
	buf.WriteString(m.Table())
	buf.WriteByte('"')
	buf.WriteString(" SET ")
	var params []interface{}
	for ii, op := range ops {
		if ii > 0 {
			buf.WriteByte(',')
		}
		dbName, _, err := m.Map(op.Field)
		if err != nil {
			return nil, err
		}
		dbName = unquote(dbName)
		buf.WriteByte('"')
		buf.WriteString(dbName)
		buf.WriteByte('"')
		buf.WriteByte('=')
		switch op.Operator {
		case operation.OpAdd, operation.OpSub:
			buf.WriteString(dbName)
			if op.Operator == operation.OpAdd {
				buf.WriteByte('+')
			} else {
				buf.WriteByte('-')
			}
			buf.WriteString(d.backend.Placeholder(len(params)))
			params = append(params, op.Value)
		case operation.OpSet:
			if f, ok := op.Value.(operation.Field); ok {
				fieldName, _, err := m.Map(string(f))
				if err != nil {
					return nil, err
				}
				buf.WriteString(unquote(fieldName))
			} else {
				buf.WriteString(d.backend.Placeholder(len(params)))
				val, err := d.transformOutValue(op.Value)
				if err != nil {
					return nil, err
				}
				params = append(params, val)
			}
		default:
			return nil, fmt.Errorf("operator %d is not supported", op.Operator)
		}
	}
	qParams, err := d.where(buf, m, q, len(params))
	if err != nil {
		return nil, err
	}
	params = append(params, qParams...)
	res, err := d.db.Exec(buftos(buf), params...)
	putBuffer(buf)
	return res, err
}
开发者ID:rainycape,项目名称:gondola,代码行数:59,代码来源:driver.go


示例19: createIndex

func (d *Driver) createIndex(m driver.Model, idx *index.Index, name string) error {
	has, err := d.backend.HasIndex(d.db, m, idx, name)
	if err != nil {
		return err
	}
	if has {
		return nil
	}

	buf := getBuffer()
	buf.WriteString("CREATE ")
	if idx.Unique {
		buf.WriteString("UNIQUE ")
	}
	buf.WriteString("INDEX ")
	buf.WriteString(name)
	buf.WriteString(" ON \"")
	buf.WriteString(m.Table())
	buf.WriteString("\" (")
	fields := m.Fields()
	for _, v := range idx.Fields {
		name, _, err := fields.Map(v)
		if err != nil {
			return err
		}
		buf.WriteByte('"')
		buf.WriteString(name)
		buf.WriteByte('"')
		if DescField(idx, v) {
			buf.WriteString(" DESC")
		}
		buf.WriteByte(',')
	}
	buf.Truncate(buf.Len() - 1)
	buf.WriteString(")")
	_, err = d.db.Exec(buftos(buf))
	putBuffer(buf)
	return err
}
开发者ID:rainycape,项目名称:gondola,代码行数:39,代码来源:driver.go


示例20: Select

func (d *Driver) Select(fields []string, quote bool, m driver.Model, q query.Q, opts driver.QueryOptions) (*bytes.Buffer, []interface{}, error) {
	buf := getBuffer()
	var params []interface{}
	if err := d.selectStmt(buf, &params, fields, quote, m, opts); err != nil {
		return nil, nil, err
	}
	qParams, err := d.where(buf, m, q, 0)
	if err != nil {
		return nil, nil, err
	}
	params = append(params, qParams...)
	if len(opts.Sort) > 0 {
		buf.WriteString(" ORDER BY ")
		for _, v := range opts.Sort {
			dbName, _, err := m.Map(v.Field())
			if err != nil {
				return nil, nil, err
			}
			buf.WriteString(dbName)
			if v.Direction() == driver.DESC {
				buf.WriteString(" DESC")
			}
			buf.WriteByte(',')
		}
		buf.Truncate(buf.Len() - 1)
	}
	if opts.Limit >= 0 {
		buf.WriteString(" LIMIT ")
		buf.WriteString(strconv.Itoa(opts.Limit))
	}
	if opts.Offset >= 0 {
		buf.WriteString(" OFFSET ")
		buf.WriteString(strconv.Itoa(opts.Offset))
	}
	return buf, params, nil
}
开发者ID:rainycape,项目名称:gondola,代码行数:36,代码来源:driver.go



注:本文中的gnd/la/orm/driver.Model类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang sql.DB类代码示例发布时间:2022-05-28
下一篇:
Golang httpclient.Response类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap