//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.
550749
func (me CrudExec) ScanVals(i interface{}) error {
	return me.ScanValsContext(context.Background(), i)
}
220187
func (me *Dataset) ToSql() (string, []interface{}, error) {
	buf := NewSqlBuilder(me.isPrepared)
	if err := me.selectSqlWriteTo(buf); err != nil {
		return "", nil, err
	}
	sql, args := buf.ToSql()
	return sql, args, nil
}
994057
func (b *InsertBuilder) Values(columnValues ...interface{}) *InsertBuilder {
	b.lock.Lock()
	sqlValue := "("
	if b.prepared {
		for k, columnValue := range columnValues {
			switch v := columnValue.(type) {
			case string:
				sqlValue = fmt.Sprintf("%s'%s'", sqlValue, strings.Replace(v, "'", "''", -1))
			default:
				sqlValue = fmt.Sprintf("%s%v", sqlValue, v)
			}
			if k < len(columnValues)-1 {
				sqlValue = fmt.Sprintf("%s, ", sqlValue)
			}
		}
	} else {
		for k := range columnValues {
			sqlValue = fmt.Sprintf("%s?", sqlValue)
			if k < len(columnValues)-1 {
				sqlValue = fmt.Sprintf("%s, ", sqlValue)
			}
		}
	}
	b.sqlValues = append(b.sqlValues, fmt.Sprintf(`%s)`, sqlValue))

	b.lock.Unlock()

	return b
}
568234
func (session *Session) SQL(query interface{}, args ...interface{}) *Session {
	session.Statement.SQL(query, args...)
	return session
}
959423
func (result *Result) AppendResult(src *Result) {
	if src.RowsAffected == 0 && len(src.Fields) == 0 {
		return
	}
	if result.Fields == nil {
		result.Fields = src.Fields
	}
	result.RowsAffected += src.RowsAffected
	if src.InsertID != 0 {
		result.InsertID = src.InsertID
	}
	if len(result.Rows) == 0 {
		// we haven't gotten any result yet, just save the new extras.
		result.Extras = src.Extras
	} else {
		// Merge the EventTokens / Fresher flags within Extras.
		if src.Extras == nil {
			// We didn't get any from innerq. Have to clear any
			// we'd have gotten already.
			if result.Extras != nil {
				result.Extras.EventToken = nil
				result.Extras.Fresher = false
			}
		} else {
			// We may have gotten an EventToken from
			// innerqr.  If we also got one earlier, merge
			// it. If we didn't get one earlier, we
			// discard the new one.
			if result.Extras != nil {
				// Note if any of the two is nil, we get nil.
				result.Extras.EventToken = EventTokenMinimum(result.Extras.EventToken, src.Extras.EventToken)

				result.Extras.Fresher = result.Extras.Fresher && src.Extras.Fresher
			}
		}
	}
	result.Rows = append(result.Rows, src.Rows...)
}
1291283
func (stmt InsertStmt) Values(arg interface{}) InsertStmt {
	// For now, inserts can be performed on pointers or values
	// NOTE: If auto-updating fields are required, they will need pointers
	elem := reflect.Indirect(reflect.ValueOf(arg))

	switch elem.Kind() {
	case reflect.Struct:
		// Inspect the fields of the given struct
		unaligned := SelectFieldsFromElem(elem.Type())

		// TODO function to return names of columns
		columns := make([]string, len(stmt.columns))
		for i, column := range stmt.columns {
			columns[i] = column.Name()
		}

		stmt.fields = AlignColumns(columns, unaligned)

		// If no fields were found and the number of fields matches the
		// columns requested, then insert the struct's values as is.
		if stmt.fields.Empty() && len(unaligned) == len(stmt.columns) {
			stmt.fields = unaligned
			stmt.argsFromElem(elem)
			return stmt
		}

		// Remove unmatched columns and empty values from fields
		// with the 'omitempty' option
		stmt.updateColumns()
		stmt.trimFields(elem)

		// If no fields remain after trimming, abort
		if len(stmt.fields) == 0 {
			stmt.SetError("aspect: could not match fields for INSERT - are the 'db' tags correct?")
			return stmt
		}

		// Collect the parameters
		stmt.argsFromElem(elem)

	case reflect.Slice:
		if elem.Len() == 0 {
			stmt.SetError("aspect: args cannot be set by empty slices")
			return stmt
		}
		// Slices of structs or Values are acceptable
		// TODO check kind of elem directly?
		elem0 := elem.Index(0)
		if elem0.Kind() == reflect.Struct {
			unaligned := SelectFieldsFromElem(elem.Type().Elem())

			// TODO function to return names of columns
			columns := make([]string, len(stmt.columns))
			for i, column := range stmt.columns {
				columns[i] = column.Name()
			}
			stmt.fields = AlignColumns(columns, unaligned)

			// If no fields were found and the number of fields matches the
			// columns requested, then insert the struct's values as is.
			if stmt.fields.Empty() && len(unaligned) == len(stmt.columns) {
				stmt.fields = unaligned
				for i := 0; i < elem.Len(); i++ {
					stmt.argsFromElem(elem.Index(i))
				}
				return stmt
			}

			// Remove unmatched columns and empty values from fields
			// with the 'omitempty' option
			stmt.updateColumns()
			stmt.trimFields(elem0)

			// If no fields remain after trimming, abort
			if len(stmt.fields) == 0 {
				stmt.SetError("aspect: could not match fields for INSERT - are the 'db' tags correct?")
				return stmt
			}

			// Add the parameters for each element
			for i := 0; i < elem.Len(); i++ {
				stmt.argsFromElem(elem.Index(i))
			}

			return stmt
		}

		valuesSlice, ok := arg.([]Values)
		if ok {
			if len(valuesSlice) == 0 {
				stmt.SetError(
					"aspect: cannot insert []Values of length zero",
				)
				return stmt
			}

			// Set the table columns according to the values
			var err error
			if stmt.fields, err = valuesMap(stmt, valuesSlice[0]); err != nil {
				stmt.SetError(err.Error())
				return stmt
			}

			// TODO Column names should match in each values element!
			stmt.updateColumns()

			// Add the args in the values
			for _, v := range valuesSlice {
				stmt.argsFromValues(v)
			}

			return stmt
		}

		stmt.SetError(
			"aspect: unsupported type %T for INSERT %s - values must be of type struct, Values, or a slice of either",
			arg, stmt,
		)

	case reflect.Map:
		// The only allowed map type is Values
		values, ok := arg.(Values)
		if !ok {
			stmt.SetError(
				"aspect: inserted maps must be of type Values",
			)
			return stmt
		}

		// Set the table columns according to the values
		var err error
		if stmt.fields, err = valuesMap(stmt, values); err != nil {
			stmt.SetError(err.Error())
			return stmt
		}

		// Remove unmatched columns and add args from the values
		stmt.updateColumns()
		stmt.argsFromValues(values)

	}
	return stmt
}
347494
func SQLScanStringSlice(obj interface{}, value interface{}) (err error) {
	if value == nil {
		return
	}

	pv, err := ensureScanValue(obj)
	if err != nil {
		return
	}

	switch value.(type) {
	case []byte:
		stringslice := parseArray(string(value.([]byte)))
		pv.Set(reflect.ValueOf(stringslice))
		return
	case string:
		stringslice := parseArray(value.(string))
		pv.Set(reflect.ValueOf(stringslice))
		return
	default:
		return ErrorUnsupportedScanType1.New(nil, value)
	}
}
227673
func InSlice(value, slice interface{}) bool {
	switch reflect.TypeOf(slice).Kind() {
	case reflect.Slice, reflect.Ptr:
		values := reflect.Indirect(reflect.ValueOf(slice))
		if values.Len() == 0 {
			return false
		}

		val := reflect.Indirect(reflect.ValueOf(value))

		if val.Kind() != values.Index(0).Kind() {
			return false
		}

		for i := 0; i < values.Len(); i++ {
			if reflect.DeepEqual(values.Index(i).Interface(), val.Interface()) {
				return true
			}
		}
	}
	return false
}
988589
func (ins *Insert) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	if ins.QueryTimeout != 0 {
		cancel := vcursor.SetContextTimeout(time.Duration(ins.QueryTimeout) * time.Millisecond)
		defer cancel()
	}

	switch ins.Opcode {
	case InsertUnsharded:
		return ins.execInsertUnsharded(vcursor, bindVars)
	case InsertSharded, InsertShardedIgnore:
		return ins.execInsertSharded(vcursor, bindVars)
	default:
		// Unreachable.
		return nil, fmt.Errorf("unsupported query route: %v", ins)
	}
}
749497
func (r *Rows) column(slice interface{}) error {
	defer r.Close()

	v := reflect.ValueOf(slice)
	if v.Kind() != reflect.Ptr || v.IsNil() {
		return VarTypeError("must be a pointer to a slice")
	}
	v = indirect(v)

	if v.Kind() != reflect.Slice {
		return VarTypeError("must be a pointer to a slice")
	}

	et := v.Type().Elem()

	cols, _ := r.Columns()
	for r.Next() {
		ev := reflect.New(et)
		refs := make([]interface{}, len(cols))
		for i := range cols {
			if i == 0 {
				refs[i] = ev.Interface()
			} else {
				refs[i] = &sql.NullString{}
			}
		}
		if err := r.Scan(refs...); err != nil {
			return err
		}
		v.Set(reflect.Append(v, ev.Elem()))
	}

	return r.Close()
}
1290144
func insert(i int, v string, s []string) []string {
	s = append(s, "")
	copy(s[i+1:], s[i:])
	s[i] = v
	return s
}
739331
func (oa *OrderedAggregate) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	qr, err := oa.execute(vcursor, bindVars, wantfields)
	if err != nil {
		return nil, err
	}
	return qr.Truncate(oa.TruncateColumnCount), nil
}
489689
func (vc *vcursorImpl) Execute(method string, query string, BindVars map[string]*querypb.BindVariable, isDML bool) (*sqltypes.Result, error) {
	qr, err := vc.executor.Execute(vc.ctx, method, vc.safeSession, vc.marginComments.Leading+query+vc.marginComments.Trailing, BindVars)
	if err == nil {
		vc.hasPartialDML = true
	}
	return qr, err
}
1113340
func appendQuery(buf []byte, query string) []byte {
	buf = append(buf, 'Q')
	sp := len(buf)
	buf = pgio.AppendInt32(buf, -1)
	buf = append(buf, query...)
	buf = append(buf, 0)
	pgio.SetInt32(buf[sp:], int32(len(buf[sp:])))

	return buf
}
776578
func (rows *Rows) Values() ([]interface{}, error) {
	if rows.closed {
		return nil, errors.New("rows is closed")
	}

	values := make([]interface{}, 0, len(rows.fields))

	for range rows.fields {
		buf, fd, _ := rows.nextColumn()

		if buf == nil {
			values = append(values, nil)
			continue
		}

		if dt, ok := rows.conn.ConnInfo.DataTypeForOID(fd.DataType); ok {
			value := reflect.New(reflect.ValueOf(dt.Value).Elem().Type()).Interface().(pgtype.Value)

			switch fd.FormatCode {
			case TextFormatCode:
				decoder := value.(pgtype.TextDecoder)
				if decoder == nil {
					decoder = &pgtype.GenericText{}
				}
				err := decoder.DecodeText(rows.conn.ConnInfo, buf)
				if err != nil {
					rows.fatal(err)
				}
				values = append(values, decoder.(pgtype.Value).Get())
			case BinaryFormatCode:
				decoder := value.(pgtype.BinaryDecoder)
				if decoder == nil {
					decoder = &pgtype.GenericBinary{}
				}
				err := decoder.DecodeBinary(rows.conn.ConnInfo, buf)
				if err != nil {
					rows.fatal(err)
				}
				values = append(values, value.Get())
			default:
				rows.fatal(errors.New("Unknown format code"))
			}
		} else {
			rows.fatal(errors.New("Unknown type"))
		}

		if rows.Err() != nil {
			return nil, rows.Err()
		}
	}

	return values, rows.Err()
}
1147314
func (tx *TX) Execute(stmt Executable, args ...interface{}) (sql.Result, error) {
	s, params, err := tx.compile(stmt)
	if err != nil {
		return nil, err
	}

	// Use any arguments given to Query() over compiled arguments
	if len(args) == 0 {
		args = params.args
	}
	return tx.Exec(s, args...)
}
221688
func (u *Uint32) Scan(value interface{}) (err error) {
	if value == nil {
		u.Uint32, u.Valid = 0, false
		return nil
	}
	u.Valid = true

	var tmp uint64
	switch v := value.(type) {
	case []byte:
		tmp, err = strconv.ParseUint(string(v), 10, 32)
		if err != nil {
			return fmt.Errorf("ntypes: Uint32.Scan failure: %s", err)
		}
		u.Uint32 = uint32(tmp)
	case string:
		tmp, err = strconv.ParseUint(v, 10, 32)
		if err != nil {
			return fmt.Errorf("ntypes: Uint32.Scan failure: %s", err)
		}
		u.Uint32 = uint32(tmp)
	case int64:
		if v > math.MaxUint32 {
			return errors.New("ntypes: Uint32.Scan failure: value out of range")
		}
		u.Uint32 = uint32(v)
	default:
		err = fmt.Errorf("ntypes: unsuported type (%T) passed to Uint32.Scan", value)
	}

	return
}