func upsertBaseComponentTx(tx *sqlx.Tx, deviceID types.DeviceID, name string, c types.Component) (int64, error) { base := c.GetBaseComponent() existingBaseComp, found := getBaseComponentTx(tx, deviceID, name) if !found { // not found: do insert q := "INSERT INTO component (device_id, name, make, model, type) VALUES (?, ?, ?, ?, ?)" res, err := tx.Exec(q, deviceID, name, base.Make, base.Model, c.Type()) if err != nil { return 0, fmt.Errorf("error inserting component: %v", err) } id, err := res.LastInsertId() // Get ID from insert if err != nil || id == 0 { return 0, fmt.Errorf("error or zero-value ID (id: %v, err: %v)", id, err) } Log.Debug("inserted component", "id", id, "base_component", base, "stmt", q) return id, nil } // found: do update q := "UPDATE component SET make=?, model=?, type=? WHERE id=?;" _, err := tx.Exec(q, base.Make, base.Model, c.Type(), existingBaseComp.ID) if err != nil { return 0, fmt.Errorf("error updating base component: %v", err) } Log.Debug("updated component", "base", base, "query", q, "update_err", err) return existingBaseComp.ID, err }