Пример #1
0
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
}
Пример #2
0
func (d *Driver) selectStmt(buf *bytes.Buffer, params *[]interface{}, fields []string, quote bool, m driver.Model, opts driver.QueryOptions) error {
	buf.WriteString("SELECT ")
	if opts.Distinct {
		buf.WriteString("DISTINCT ")
	}
	if fields != nil {
		if quote {
			for _, v := range fields {
				buf.WriteByte('"')
				buf.WriteString(v)
				buf.WriteByte('"')
				buf.WriteByte(',')
			}
		} else {
			for _, v := range fields {
				buf.WriteString(v)
				buf.WriteByte(',')
			}
		}
	} else {
		// Select all fields for the given model (which might be joined)
		cur := m
		for {
			if !cur.Skip() {
				for _, v := range cur.Fields().QuotedNames {
					buf.WriteString(v)
					buf.WriteByte(',')
				}
			}
			join := cur.Join()
			if join == nil {
				break
			}
			cur = join.Model()
		}
	}
	buf.Truncate(buf.Len() - 1)
	buf.WriteString(" FROM ")
	buf.WriteByte('"')
	buf.WriteString(m.Table())
	buf.WriteByte('"')
	for join := m.Join(); join != nil; {
		jm := join.Model()
		switch join.Type() {
		case driver.OuterJoin:
			buf.WriteString(" FULL OUTER")
		case driver.LeftJoin:
			buf.WriteString(" LEFT OUTER")
		case driver.RightJoin:
			buf.WriteString(" RIGHT OUTER")
		}
		buf.WriteString(" JOIN ")
		buf.WriteByte('"')
		buf.WriteString(jm.Table())
		buf.WriteByte('"')
		buf.WriteString(" ON ")
		if err := d.condition(buf, params, m, join.Query(), len(*params)); err != nil {
			return err
		}
		join = jm.Join()
	}
	return nil
}