Exemplo n.º 1
0
func writeToPostgres(bucket *store.Bucket) error {
	tx, err := pg.Begin()
	if err != nil {
		return err
	}

	err = bucket.Get()
	if err != nil {
		return err
	}

	vals := string(encoding.EncodeArray(bucket.Vals, '{', '}', ','))
	row := tx.QueryRow(`
		SELECT id
		FROM buckets
		WHERE token = $1 AND measure = $2 AND source = $3 AND time = $4`,
		bucket.Key.Token, bucket.Key.Name, bucket.Key.Source, bucket.Key.Time)

	var id sql.NullInt64
	row.Scan(&id)

	if id.Valid {
		_, err = tx.Exec("UPDATE buckets SET vals = $1::FLOAT8[] WHERE id = $2",
			vals, id)
		if err != nil {
			tx.Rollback()
			return err
		}
	} else {
		_, err = tx.Exec(`
			INSERT INTO buckets(token, measure, source, time, vals)
			VALUES($1, $2, $3, $4, $5::FLOAT8[])`,
			bucket.Key.Token, bucket.Key.Name, bucket.Key.Source,
			bucket.Key.Time, vals)
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	err = tx.Commit()
	if err != nil {
		return err
	}
	return nil
}
Exemplo n.º 2
0
func (b *Bucket) Put() (int64, error) {
	b.Lock()
	defer b.Unlock()
	db.PGLocker.Lock()
	defer db.PGLocker.Unlock()
	var err error
	id, _ := b.dbId()
	// Create the bucket if needed.
	if id == 0 {
		fmt.Printf("at=create-bucket name=%s bucket=%s\n",
			b.Name, b.Time)
		_, err := db.PG.Exec("insert into metrics (name, bucket, source, token) values($1,$2,$3,$4)",
			b.Name, b.Time, b.Source, b.Token)
		if err != nil {
			fmt.Printf("at=error error=%s\n", err)
			return 0, err
		}
	}

	res, err := db.PG.Exec("update metrics set vals = vals || $1::float8[] where name = $2 and bucket = $3",
		string(encoding.EncodeArray(b.Vals)), b.Name, b.Time)
	if err != nil {
		fmt.Printf("at=error error=%s\n", err)
		return 0, err
	}

	//Reset the vals on this bucket. It might be used again.
	// It might be used again.
	b.Vals = []float64{}

	var count int64
	count, err = res.RowsAffected()
	if err != nil {
		fmt.Printf("at=error error=%s\n", err)
		count = 0
	}
	return count, nil
}