Esempio n. 1
0
func (this *FunServantImpl) MgFindAll(ctx *rpc.Context,
	pool string, table string, shardId int32,
	query []byte, fields []byte, limit int32, skip int32,
	orderBy []string) (r [][]byte, ex error) {
	const IDENT = "mg.findAll"

	if this.mg == nil {
		ex = ErrServantNotStarted
		return
	}

	svtStats.inc(IDENT)

	profiler, err := this.getSession(ctx).startProfiler()
	if err != nil {
		ex = err
		return
	}

	sess, err := this.mongoSession(pool, shardId)
	if err != nil {
		ex = err
		return
	}
	defer sess.Recyle(&err)

	bsonQuery, err := mongo.UnmarshalIn(query)
	if err != nil {
		ex = err
		return
	}
	var bsonFields bson.M
	if !mongo.FieldsIsNil(fields) {
		bsonFields, err = mongo.UnmarshalIn(fields)
		if err != nil {
			ex = err
			return
		}
	}

	q := sess.DB().C(table).Find(bsonQuery)
	if !mongo.FieldsIsNil(fields) {
		q.Select(bsonFields)
	}
	if limit > 0 {
		q.Limit(int(limit))
	}
	if skip > 0 {
		q.Skip(int(skip))
	}
	if len(orderBy) > 0 {
		q.Sort(orderBy...)
	}

	var result []bson.M
	err = q.All(&result)
	if err == nil {
		r = make([][]byte, len(result))
		for i, v := range result {
			r[i] = mongo.MarshalOut(v)
		}
	} else {
		ex = err
	}

	profiler.do(IDENT, ctx,
		"{pool^%s table^%s query^%v fields^%v} {err^%v rN^%d}",
		pool, table,
		bsonQuery,
		bsonFields,
		ex,
		len(r))

	return
}
Esempio n. 2
0
func (this *FunServantImpl) MgFindOne(ctx *rpc.Context,
	pool string, table string, shardId int32,
	query []byte, fields []byte) (r []byte,
	miss *rpc.TMongoNotFound, ex error) {
	const IDENT = "mg.findOne"

	if this.mg == nil {
		ex = ErrServantNotStarted
		return
	}

	svtStats.inc(IDENT)

	profiler, err := this.getSession(ctx).startProfiler()
	if err != nil {
		ex = err
		return
	}

	// get mongodb session
	sess, err := this.mongoSession(pool, shardId)
	if err != nil {
		ex = err
		return
	}
	defer sess.Recyle(&err)

	bsonQuery, err := mongo.UnmarshalIn(query)
	if err != nil {
		ex = err
		return
	}
	var bsonFields bson.M
	if !mongo.FieldsIsNil(fields) {
		bsonFields, err = mongo.UnmarshalIn(fields)
		if err != nil {
			ex = err
			return
		}
	}

	var result bson.M
	q := sess.DB().C(table).Find(bsonQuery)
	if !mongo.FieldsIsNil(fields) {
		q.Select(bsonFields)
	}
	err = q.One(&result)
	if err != nil {
		if err != mgo.ErrNotFound {
			log.Error("%s: %v", IDENT, err)
		} else {
			miss = rpc.NewTMongoNotFound()
			miss.Message = thrift.StringPtr(err.Error())
			profiler.do(IDENT, ctx,
				"{pool^%s table^%s query^%v fields^%v} {miss^%v err^%v val^%v}",
				pool, table,
				bsonQuery,
				bsonFields,
				miss,
				ex,
				result)
			return
		}

		ex = err
		return
	}

	r = mongo.MarshalOut(result)

	profiler.do(IDENT, ctx,
		"{pool^%s table^%s query^%v fields^%v} {miss^%v err^%v val^%v}",
		pool, table,
		bsonQuery,
		bsonFields,
		miss,
		ex,
		result)

	return
}