Beispiel #1
0
func (db *DB) GetConfig(inst flux.InstanceID) (instance.Config, error) {
	var c string
	err := db.conn.QueryRow(`SELECT config FROM config WHERE instance = $1`, string(inst)).Scan(&c)
	switch err {
	case nil:
		break
	case sql.ErrNoRows:
		return instance.MakeConfig(), nil
	default:
		return instance.Config{}, err
	}
	var conf instance.Config
	return conf, json.Unmarshal([]byte(c), &conf)
}
Beispiel #2
0
func (db *DB) UpdateConfig(inst flux.InstanceID, update instance.UpdateFunc) error {
	tx, err := db.conn.Begin()
	if err != nil {
		return err
	}

	var (
		currentConfig instance.Config
		confString    string
	)
	switch tx.QueryRow(`SELECT config FROM config WHERE instance = $1`, string(inst)).Scan(&confString) {
	case sql.ErrNoRows:
		currentConfig = instance.MakeConfig()
	case nil:
		if err = json.Unmarshal([]byte(confString), &currentConfig); err != nil {
			return err
		}
	default:
		return err
	}

	newConfig, err := update(currentConfig)
	if err != nil {
		err2 := tx.Rollback()
		if err2 != nil {
			return errors.Wrapf(err, "transaction rollback failed: %s", err2)
		}
		return err
	}

	newConfigBytes, err := json.Marshal(newConfig)
	if err != nil {
		return err
	}

	_, err = tx.Exec(`DELETE FROM config WHERE instance = $1`, string(inst))
	if err == nil {
		_, err = tx.Exec(`INSERT INTO config (instance, config, stamp) VALUES
                       ($1, $2, now())`, string(inst), string(newConfigBytes))
	}
	if err == nil {
		err = tx.Commit()
	}
	return err
}