Example #1
16
//Scan a value into the float64, error on nil or unparseable
func (f *Float64) Scan(value interface{}) error {
	tmp := sql.NullFloat64{}
	tmp.Scan(value)

	if tmp.Valid == false {
		return errors.New("Value should be a float64 and not nil")
	}

	f.Float64 = tmp.Float64

	f.DoInit(func() {
		f.shadow = tmp.Float64
	})

	return nil
}
Example #2
0
func TestPositiveFloatOrNull(t *testing.T) {
	var (
		nullFloat sql.NullFloat64
		value     driver.Value
		err       error
	)

	// When the number is negative
	nullFloat = PositiveFloatOrNull(-0.5)

	// nullFloat.Valid should be false
	assert.False(t, nullFloat.Valid)

	// nullFloat.Value() should return nil
	value, err = nullFloat.Value()
	assert.Nil(t, err)
	assert.Nil(t, value)

	// When the number is greater than zero
	nullFloat = PositiveFloatOrNull(1.5)

	// nullFloat.Valid should be true
	assert.True(t, nullFloat.Valid)

	// nullFloat.Value() should return the integer
	value, err = nullFloat.Value()
	assert.Nil(t, err)
	assert.Equal(t, 1.5, value)
}
Example #3
0
func checkFloatForNull(eventFloat string, event *sql.NullFloat64) {
	var err error

	if eventFloat == "" {
		event.Valid = false
	} else {
		event.Float64, err = strconv.ParseFloat(eventFloat, 64)
		if err != nil {
			event.Valid = false
			return
		}

		event.Valid = true
	}
}
Example #4
0
func (db *Database) AddActivity(type_id int64, description string, user_id int64, is_public bool, lat, long string) error {
	var latitude sql.NullFloat64
	var longitude sql.NullFloat64

	var err error
	if latitude.Float64, err = strconv.ParseFloat(lat, 64); err != nil {
		latitude.Valid = false
	} else {
		latitude.Valid = true
	}

	if longitude.Float64, err = strconv.ParseFloat(long, 64); err != nil {
		longitude.Valid = false
	} else {
		longitude.Valid = true
	}

	public := 0
	if is_public {
		public = 1
	}

	txn, err := db.conn.Begin()
	if err != nil {
		log.Printf("Starting transaction failed: %v", err)
		return err
	}

	row := txn.QueryRow("SELECT count(1) FROM activity_type_flags WHERE type_id = ? AND flag_id = ?", type_id, db.flagNameToIdMapping[FLAG_POINT_IN_TIME])
	var point_in_time_count int64
	if err = row.Scan(&point_in_time_count); err != nil {
		log.Printf("row.Scan failed: %v", err)
		txn.Rollback()
		return err
	}

	result, err := txn.Exec("INSERT INTO activities (type_id, timestamp, description, user_id, public, latitude, longitude) VALUES (?, NOW(), ?, ?, ?, ?, ?)", type_id, description, user_id, public, latitude, longitude)
	if err == nil {
		activity_id, _ := result.LastInsertId()
		if point_in_time_count != 0 {
			_, err = txn.Exec("UPDATE activities SET end_timestamp = NOW() WHERE id = ?", activity_id)
			if err != nil {
				log.Printf("db.conn.Exec failed: %v", err)
			}
		}
	}

	if err != nil {
		txn.Rollback()
	} else {
		err = txn.Commit()
		if err != nil {
			log.Printf("committing transaction failed: %v", err)
		}
	}
	return err
}
Example #5
0
func AddActivity(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, SESSION_NAME)
	if authenticated, ok := session.Values["Authenticated"].(bool); !ok || !authenticated {
		http.Error(w, "unauthenticated", http.StatusForbidden)
		return
	}

	username := session.Values["UserName"].(string)
	user_id := session.Values["UserId"].(int64)

	type_id := r.FormValue("type_id")
	description := r.FormValue("desc")
	is_public := 0
	if r.FormValue("public") == "on" {
		is_public = 1
	}

	var err error
	var latitude sql.NullFloat64
	var longitude sql.NullFloat64

	if latitude.Float64, err = strconv.ParseFloat(r.FormValue("lat"), 64); err != nil {
		latitude.Valid = false
	} else {
		latitude.Valid = true
	}

	if longitude.Float64, err = strconv.ParseFloat(r.FormValue("long"), 64); err != nil {
		longitude.Valid = false
	} else {
		longitude.Valid = true
	}

	if _, err := db.Exec("INSERT INTO activities (type_id, timestamp, description, user_id, public, latitude, longitude) VALUES (?, NOW(), ?, ?, ?, ?, ?)", type_id, description, user_id, is_public, latitude, longitude); err != nil {
		log.Printf("AddActivity: db.Exec failed: %v", err)
	} else {
		log.Printf("added activity %s (type_id = %s) for user %s", description, type_id, username)
	}

	fmt.Fprintf(w, "OK")
}
Example #6
0
func fetchResult(itemT reflect.Type, rows *sql.Rows, columns []string) (reflect.Value, error) {
	var item reflect.Value
	var err error

	switch itemT.Kind() {
	case reflect.Map:
		item = reflect.MakeMap(itemT)
	case reflect.Struct:
		item = reflect.New(itemT)
	default:
		return item, db.ErrExpectingMapOrStruct
	}

	expecting := len(columns)

	// Allocating results.
	values := make([]*sql.RawBytes, expecting)
	scanArgs := make([]interface{}, expecting)

	for i := range columns {
		scanArgs[i] = &values[i]
	}

	if err = rows.Scan(scanArgs...); err != nil {
		return item, err
	}

	// Range over row values.
	for i, value := range values {

		if value != nil {
			// Real column name
			column := columns[i]

			// Value as string.
			svalue := string(*value)

			var cv reflect.Value

			v, _ := to.Convert(svalue, reflect.String)
			cv = reflect.ValueOf(v)

			switch itemT.Kind() {
			// Destination is a map.
			case reflect.Map:
				if cv.Type() != itemT.Elem() {
					if itemT.Elem().Kind() == reflect.Interface {
						cv, _ = util.StringToType(svalue, cv.Type())
					} else {
						cv, _ = util.StringToType(svalue, itemT.Elem())
					}
				}
				if cv.IsValid() {
					item.SetMapIndex(reflect.ValueOf(column), cv)
				}
			// Destionation is a struct.
			case reflect.Struct:

				index := util.GetStructFieldIndex(itemT, column)

				if index == nil {
					continue
				} else {

					// Destination field.
					destf := item.Elem().FieldByIndex(index)

					if destf.IsValid() {

						if cv.Type() != destf.Type() {

							if destf.Type().Kind() != reflect.Interface {

								switch destf.Type() {
								case nullFloat64Type:
									nullFloat64 := sql.NullFloat64{}
									if svalue != `` {
										nullFloat64.Scan(svalue)
									}
									cv = reflect.ValueOf(nullFloat64)
								case nullInt64Type:
									nullInt64 := sql.NullInt64{}
									if svalue != `` {
										nullInt64.Scan(svalue)
									}
									cv = reflect.ValueOf(nullInt64)
								case nullBoolType:
									nullBool := sql.NullBool{}
									if svalue != `` {
										nullBool.Scan(svalue)
									}
									cv = reflect.ValueOf(nullBool)
								case nullStringType:
									nullString := sql.NullString{}
									nullString.Scan(svalue)
									cv = reflect.ValueOf(nullString)
								default:
									var decodingNull bool

									if svalue == "" {
										decodingNull = true
									}

									u, _ := indirect(destf, decodingNull)

									if u != nil {
										u.UnmarshalDB(svalue)

										if destf.Kind() == reflect.Interface || destf.Kind() == reflect.Ptr {
											cv = reflect.ValueOf(u)
										} else {
											cv = reflect.ValueOf(u).Elem()
										}

									} else {
										cv, _ = util.StringToType(svalue, destf.Type())
									}

								}
							}

						}

						// Copying value.
						if cv.IsValid() {
							destf.Set(cv)
						}

					}
				}

			}
		}
	}

	return item, nil
}
Example #7
0
// Scan implements the Scanner interface.
func (ns *Float32) Scan(value interface{}) error {
	n := sql.NullFloat64{Float64: float64(ns.Float32)}
	err := n.Scan(value)
	ns.Float32, ns.Valid = float32(n.Float64), n.Valid
	return err
}
Example #8
0
// Scan implements the Scanner interface.
func (ns *Float64) Scan(value interface{}) error {
	n := sql.NullFloat64{Float64: ns.Float64}
	err := n.Scan(value)
	ns.Float64, ns.Valid = n.Float64, n.Valid
	return err
}
Example #9
0
func CreateNullFloat64(v float64) sql.NullFloat64 {
	var ni sql.NullFloat64
	ni.Valid = true
	ni.Float64 = v
	return ni
}