Example #1
0
func dataCompletenessDelete(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	v := r.URL.Query()

	siteID := v.Get("siteID")
	typeID := v.Get("typeID")

	var txn *sql.Tx
	var err error

	if txn, err = db.Begin(); err != nil {
		return weft.InternalServerError(err)
	}

	for _, table := range []string{"data.completeness", "data.completeness_summary", "data.completeness_tag"} {
		if _, err = txn.Exec(`DELETE FROM `+table+` WHERE
				sitePK = (SELECT sitePK FROM data.site WHERE siteID = $1)
				AND typePK = (SELECT typePK FROM data.completeness_type WHERE typeID = $2)`,
			siteID, typeID); err != nil {
			txn.Rollback()
			return weft.InternalServerError(err)
		}
	}

	if err = txn.Commit(); err != nil {
		return weft.InternalServerError(err)
	}

	return &weft.StatusOK
}
Example #2
0
// 打印并抛出异常
func perrorWithRollBack(e error, errMsg string, tx *sql.Tx) {
	if e != nil {
		tx.Rollback()
		log.Println(e)
		panic(errMsg)
	}
}
Example #3
0
func EndTx(tx *sql.Tx, err *error) {
	if *err == nil {
		tx.Commit()
	} else {
		tx.Rollback()
	}
}
// Down is executed when this migration is rolled back
func Down_20150712142846(txn *sql.Tx) {
	log.Println("Drop Table Places")
	if _, err := txn.Exec("DROP TABLE places;"); err != nil {
		txn.Rollback()
		log.Println("Error dropping table places", err)
	}
}
Example #5
0
func rollbackAndError(tx *sql.Tx, err error) error {
	new_err := tx.Rollback()
	if new_err != nil {
		return fmt.Errorf("Rollback error (%v); previous error (%v)", new_err, err)
	}
	return err
}
// Insert saves the options to the database
func (m *ProfileOptionType) Insert(tx *sql.Tx) (int, error) {

	_, err := tx.Exec(`
INSERT INTO profile_options (
    profile_id
   ,show_dob_year
   ,show_dob_date
   ,send_email
   ,send_sms
   ,is_discouraged
) VALUES (
    $1
   ,$2
   ,$3
   ,$4
   ,$5
   ,$6
)`,
		m.ProfileID,
		m.ShowDOBYear,
		m.ShowDOB,
		m.SendEMail,
		m.SendSMS,
		m.IsDiscouraged,
	)
	if err != nil {
		tx.Rollback()
		return http.StatusInternalServerError,
			fmt.Errorf("Error inserting data: %v", err.Error())
	}

	go PurgeCacheByScope(c.CacheOptions, h.ItemTypes[h.ItemTypeProfile], m.ProfileID)

	return http.StatusOK, nil
}
Example #7
0
func (self *DBRcs) Upgrade(patch_root string, verbose bool) (err error) {
	// 1. Read the version file passed in.
	// 2. Verify the previous version exists and matches the *current*
	//    version of the database.
	// 3. Start transactional schema upgrade
	// 4. Update version code in schema
	// 5. Rollback on failure, commit if no errors

	var curr_db_ver string
	var curr_patch_dir string
	var node *versionNode
	var sql_cmd string
	var txn *sql.Tx
	var upgrade_bytes []byte

	if err = self.ComputeHistory(patch_root); err != nil {
		return err
	}

	if curr_db_ver, err = self.CurrentDBVersion(); err != nil {
		if err == sql.ErrNoRows {
			return fmt.Errorf("No version code has been set yet.  You need to initialize the versioning system.")
		}
		return err
	}

	// walk the nodes from back to front
	for i := len(self.revisions) - 1; i >= 0; i-- {
		node = self.revisions[i]
		// Process this node
		curr_patch_dir, err = GetPatchDirectory(patch_root, node.version)
		if node.prev == curr_db_ver {
			upgrade_sql := filepath.Join(curr_patch_dir, "upgrade.sql")
			fmt.Printf("Reading from :[%v]\n", upgrade_sql)
			upgrade_bytes, err = ioutil.ReadFile(upgrade_sql)

			sql_cmd = string(upgrade_bytes)
			fmt.Printf("Attempting SQL is: [%v]\n", sql_cmd)
			txn, err = self.Db.Begin()
			if _, err = txn.Exec(sql_cmd); err != nil {
				fmt.Printf("Failed to execute: [%s]\n", sql_cmd)
				txn.Rollback()
				return err
			}

			// Roll the version forward
			_, err = txn.Exec("update meta set value = $1 where key = 'db.hash';", node.version)
			if err != nil {
				txn.Rollback()
				return err
			}
			fmt.Printf("Version switched from : [%v]\n", curr_db_ver)
			curr_db_ver = node.version
			fmt.Printf("Version switched to   : [%v]\n", curr_db_ver)
			txn.Commit()
			fmt.Printf("Success!  Executed [%v]\n", sql_cmd)
		}
	}
	return err
}
func tryRollback(lbl Label, tx *sql.Tx, err error) (Label, error) {
	rbErr := tx.Rollback()
	if rbErr != nil {
		return lbl, rbErr
	}
	return lbl, err
}
Example #9
0
func truncateAllTables(svc *Services) error {
	var tx *sql.Tx
	done := func(err error) error {
		if err == nil {
			err = tx.Commit()
		}
		if err != nil {
			tx.Rollback()
			return fmt.Errorf("truncateAllTables failed: %v", err)
		} else {
			return nil
		}
	}

	tx, err := svc.db.Begin()
	if err != nil {
		return done(err)
	}
	names, err := getTableNames(tx)
	if err != nil {
		return done(err)
	}

	for _, name := range names {
		stmt := fmt.Sprintf("TRUNCATE TABLE %v CASCADE", name)
		if _, err := tx.Exec(stmt); err != nil {
			return done(err)
		}
	}

	return done(nil)
}
Example #10
0
func (ø *db) DeletePackage(pkgPath string) (err error) {
	var tx *sql.Tx
	defer func() {
		if err != nil && tx != nil {
			tx.Rollback()
		}
	}()
	tx, err = ø.Begin()
	if err != nil {
		return
	}
	err = _deleteExports(pkgPath, tx)
	if err != nil {
		return
	}
	err = _deleteImports(pkgPath, tx)
	if err != nil {
		return
	}

	err = _deletePackage(pkgPath, tx)
	if err != nil {
		return
	}
	tx.Commit()
	fmt.Printf("deleted: %s\n", pkgPath)
	return
}
Example #11
0
func (r *Runner) invokeMigration(isTest bool, m Migration, c *spiffy.DbConnection, optionalTx ...*sql.Tx) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", err)
		}
	}()

	if m.IsTransactionIsolated() {
		err = m.Apply(c, spiffy.OptionalTx(optionalTx...))
		return
	}

	var tx *sql.Tx
	tx, err = c.Begin()
	if err != nil {
		return err
	}
	defer func() {
		if err == nil {
			err = exception.Wrap(tx.Commit())
		} else {
			err = exception.WrapMany(err, exception.New(tx.Rollback()))
		}
	}()
	err = m.Apply(c, tx)
	return
}
Example #12
0
func fieldMetricDelete(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result {
	v := r.URL.Query()

	deviceID := v.Get("deviceID")
	typeID := v.Get("typeID")

	var err error
	var txn *sql.Tx

	if txn, err = db.Begin(); err != nil {
		return weft.InternalServerError(err)
	}

	for _, table := range []string{"field.metric", "field.metric_summary", "field.metric_tag", "field.threshold"} {
		if _, err = txn.Exec(`DELETE FROM `+table+` WHERE
				devicePK = (SELECT devicePK FROM field.device WHERE deviceID = $1)
				 AND typePK = (SELECT typePK from field.type WHERE typeID = $2)`,
			deviceID, typeID); err != nil {
			txn.Rollback()
			return weft.InternalServerError(err)
		}
	}

	if err = txn.Commit(); err != nil {
		return weft.InternalServerError(err)
	}

	return &weft.StatusOK
}
Example #13
0
// UpdateAttendees updates the number of attendees for an event
func (m *EventType) UpdateAttendees(tx *sql.Tx) (int, error) {
	_, err := tx.Exec(`
UPDATE events
   SET rsvp_attending = att.attending
      ,rsvp_spaces = CASE rsvp_limit WHEN 0 THEN 0 ELSE (rsvp_limit - att.attending) END
  FROM (
        SELECT e.event_id
              ,a.state_id
              ,COUNT(a.*) as attending
          FROM events e
               LEFT OUTER JOIN (
                     SELECT *
                       FROM attendees
                      WHERE state_id = 1
               ) a ON e.event_id = a.event_id
         WHERE e.event_id = $1
         GROUP BY e.event_id
                 ,a.state_id
       ) AS att
 WHERE events.event_id = att.event_id`,
		m.ID,
	)
	if err != nil {
		tx.Rollback()
		return http.StatusInternalServerError,
			fmt.Errorf("Update of event attendees failed: %v", err.Error())
	}

	return http.StatusOK, nil
}
Example #14
0
// RollbackErr does a rollback on the transaction and returns either the error
// from the rollback if there was one or the alternative.
// This is useful if you have multiple statments in a row but don't want to
// call rollback and check for errors every time.
func RollbackErr(tx *sql.Tx, alt error) error {
	if err := tx.Rollback(); err != nil {
		return err
	}

	return alt
}
Example #15
0
// AddParent adds a parent. Uses passed transaction or a new one if one is not provided
func AddParent(familyID int, name string, email string, password string, tx *sql.Tx) (int, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	needCommit := false
	if tx == nil {
		tx, err = db.Begin()
		if err != nil {
			return 0, err
		}
		needCommit = true
		defer tx.Rollback()
	}

	// Create the parent
	if _, err := tx.Exec("INSERT INTO parents VALUES(NULL, ?, ?, ?, ?, NULL, NULL)", familyID, name, email, hashedPassword); err != nil {
		return 0, err
	}
	// Get the ID
	var ID int
	row := tx.QueryRow("SELECT LAST_INSERT_ID()")
	err = row.Scan(&ID)
	if needCommit {
		tx.Commit()
	}

	return ID, err
}
Example #16
0
// Migrate executes the required migration of the database on startup.
// For each successful migration, an entry will be written into the "version"
// table, that states when a certain version was reached.
func Migrate(db *sql.DB) error {
	var err error

	if db == nil {
		return errs.Errorf("Database handle is nil\n")
	}

	m := getMigrations()

	var tx *sql.Tx
	for nextVersion := int64(0); nextVersion < int64(len(m)) && err == nil; nextVersion++ {

		tx, err = db.Begin()
		if err != nil {
			return errs.Errorf("Failed to start transaction: %s\n", err)
		}

		err = migrateToNextVersion(tx, &nextVersion, m)

		if err != nil {
			oldErr := err
			log.Info(nil, map[string]interface{}{
				"pkg":         "migration",
				"nextVersion": nextVersion,
				"migrations":  m,
				"err":         err,
			}, "Rolling back transaction due to: ", err)

			if err = tx.Rollback(); err != nil {
				log.Error(nil, map[string]interface{}{
					"nextVersion": nextVersion,
					"migrations":  m,
					"err":         err,
				}, "error while rolling back transaction: ", err)
				return errs.Errorf("Error while rolling back transaction: %s\n", err)
			}
			return oldErr
		}

		if err = tx.Commit(); err != nil {
			log.Error(nil, map[string]interface{}{
				"migrations": m,
				"err":        err,
			}, "error during transaction commit: ", err)
			return errs.Errorf("Error during transaction commit: %s\n", err)
		}

	}

	if err != nil {
		log.Error(nil, map[string]interface{}{
			"migrations": m,
			"err":        err,
		}, "migration failed with error: ", err)
		return errs.Errorf("Migration failed with error: %s\n", err)
	}

	return nil
}
Example #17
0
func Rollback(tx *sql.Tx) {
	err := tx.Rollback()

	// roll back error is a serious error
	if err != nil {
		panic(err)
	}
}
Example #18
0
// 回滚事务
// tx:事务对象
// playerObj:玩家对象
// rollbackPlayer:回滚玩家数据的方法
func RollbackTransaction(tx *sql.Tx, playerObj *player.Player, rollbackPlayer func(*player.Player)) {
	err := tx.Rollback()
	if err != nil && err != sql.ErrTxDone {
		logUtil.Log(fmt.Sprintf("回滚事务失败,错误信息:%s", err), logUtil.Error, true)
	}

	// 并且回滚玩家数据
	rollbackPlayer(playerObj)
}
Example #19
0
func (s *Storage) saveRefresh(tx *sql.Tx, refresh, access string) (err error) {
	_, err = tx.Exec("INSERT INTO refresh (token, access) VALUES ($1, $2)", refresh, access)
	if err != nil {
		if rbe := tx.Rollback(); rbe != nil {
			return rbe
		}
	}
	return err
}
Example #20
0
func TxRollback(tx *sql.Tx) error {
	err := tx.Rollback()
	if err != nil {
		DFErrorLog("Transaction Rollback Error:" + err.Error())
		return err
	}
	DFLog("Transaction Rollback")
	return err
}
Example #21
0
//////////////////////////////////////////////////////////////////////////////
/// private interface related to database
//////////////////////////////////////////////////////////////////////////////
// transaction rollback according to the error status
func rollback(err *error, tx *sql.Tx) {
	if *err != nil {
		log.Infof("error occured rollback:err[%v]", *err)
		newErr := tx.Rollback()
		if newErr != nil {
			log.Errorf("rollback failed:err[%v]", newErr)
		}
	}
}
Example #22
0
func (s *cleansrv) cleanOldEntries() (err error) {
	var tx *sql.Tx
	tx, err = s.db.Begin()
	if err != nil {
		return err
	}

	defer func() {
		if err == nil {
			err = tx.Commit()
		} else {
			tx.Rollback()
		}
	}()

	res, err := tx.Stmt(s.prep["cleanAddress"]).Exec()
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows > 0 {
		log.Printf("Clean: %d old addresses", rows)
	}

	res, err = tx.Stmt(s.prep["cleanRelay"]).Exec()
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows > 0 {
		log.Printf("Clean: %d old relays", rows)
	}

	res, err = tx.Stmt(s.prep["cleanDevice"]).Exec()
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows > 0 {
		log.Printf("Clean: %d old devices", rows)
	}

	var devs, addrs, relays int
	row := tx.Stmt(s.prep["countDevice"]).QueryRow()
	if err = row.Scan(&devs); err != nil {
		return err
	}
	row = tx.Stmt(s.prep["countAddress"]).QueryRow()
	if err = row.Scan(&addrs); err != nil {
		return err
	}
	row = tx.Stmt(s.prep["countRelay"]).QueryRow()
	if err = row.Scan(&relays); err != nil {
		return err
	}

	log.Printf("Database: %d devices, %d addresses, %d relays", devs, addrs, relays)
	return nil
}
Example #23
0
func applyMigration(c *Config, m Migration, direction int) error {
	var tx *sql.Tx
	var exec execer

	rollback := func() {
		if tx != nil {
			tx.Rollback()
		}
	}

	contents, err := ioutil.ReadFile(filepath.Join(c.MigrationFolder, m.Filename))
	if err != nil {
		return err
	}

	db, err := openConnection(c)
	defer db.Close()
	if err != nil {
		return err
	}
	exec = db

	if m.WrapInTransaction() {
		tx, err = db.Begin()
		if err != nil {
			return err
		}
		exec = tx
	}

	if _, err = exec.Exec(string(contents)); err != nil {
		rollback()
		return errors.New(formatPgErr(&contents, err.(*pq.Error)))
	}

	if direction == UP {
		if err = insertSchemaVersion(c, exec, m.Version); err != nil {
			rollback()
			return errors.New(formatPgErr(&contents, err.(*pq.Error)))
		}
	} else {
		if err = deleteSchemaVersion(c, exec, m.Version); err != nil {
			rollback()
			return errors.New(formatPgErr(&contents, err.(*pq.Error)))
		}
	}

	if tx != nil {
		err = tx.Commit()
		if err != nil {
			return err
		}
	}

	return nil
}
Example #24
0
func (p *Provider) StoreProviderAddress(providerId int64, transaction *sql.Tx) bool {
	_, err := transaction.Exec("INSERT INTO addresses (addressed_id, addressed_type, street, street2, city, state, zip_code, created_at, updated_at) VALUES (?,'CareProvider',?,?,?,?,?,NOW(),NOW())", providerId, *p.Street, NilorValueString(p.Street2), *p.City, *p.State, *p.Zip)

	if err != nil {
		fmt.Println(err.Error())
		transaction.Rollback()
		return false
	}
	return true
}
Example #25
0
func (library *Library) Flush() (err error) {
	var (
		tx     *sql.Tx
		stmt1  *sql.Stmt
		stmt2  *sql.Stmt
		res    sql.Result
		lastId int64
	)

	tx, err = library.db.Begin()
	if err != nil {
		return
	}

	stmt1, err = tx.Prepare("INSERT INTO songs (path, title, artist, albumartist, album, track, year, genre, composer, copyright) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
	if err != nil {
		tx.Rollback()
		return
	}

	stmt2, err = tx.Prepare("INSERT INTO comments (data, song_id) VALUES (?, ?)")
	if err != nil {
		tx.Rollback()
		return
	}

	for _, song := range library.queue {
		res, err = stmt1.Exec(song.Path, song.Title, song.Artist, song.AlbumArtist, song.Album, song.Track, song.Year, song.Genre, song.Composer, song.Copyright)
		if err != nil {
			tx.Rollback()
			return
		}

		if len(song.Comments) > 0 {
			lastId, err = res.LastInsertId()
			if err != nil {
				tx.Rollback()
				return
			}

			for _, comment := range song.Comments {
				_, err = stmt2.Exec(comment, lastId)
				if err != nil {
					tx.Rollback()
					return
				}
			}
		}
	}

	err = tx.Commit()
	library.queue = nil
	return
}
Example #26
0
// Update the version table for the given migration,
// and finalize the transaction.
func FinalizeMigration(conf *DBConf, txn *sql.Tx, direction bool, v int64) error {

	// XXX: drop goose_db_version table on some minimum version number?
	stmt := conf.Driver.Dialect.insertVersionSql()
	if _, err := txn.Exec(stmt, v, direction); err != nil {
		txn.Rollback()
		return err
	}

	return txn.Commit()
}
Example #27
0
func completeTransaction(tx *sql.Tx, errResult error) error {
	if errResult != nil {
		err := tx.Rollback()
		if err != nil {
			log.Printf("warning: failed to rollback: %v", err)
		}
	} else {
		errResult = tx.Commit()
	}
	return errResult
}
Example #28
0
File: db.go Project: postfix/arx
// Finalise handles transaction rollback and commit.
func Finalise(tx *sql.Tx, err error) {
	if err != nil {
		if err = tx.Rollback(); err != nil {
			log.Printf("database transaction rollback failed (%v)", err)
		}
	} else {
		if err = tx.Commit(); err != nil {
			log.Printf("failed to commit transaction (%v)", err)
		}
	}
}
Example #29
0
// insertVulnerabilityFixedInFeatureVersions populates Vulnerability_FixedIn_Feature for the given
// vulnerability with the specified database.FeatureVersion list and uses
// linkVulnerabilityToFeatureVersions to propagate the changes on Vulnerability_FixedIn_Feature to
// Vulnerability_Affects_FeatureVersion.
func (pgSQL *pgSQL) insertVulnerabilityFixedInFeatureVersions(tx *sql.Tx, vulnerabilityID int, fixedIn []database.FeatureVersion) error {
	defer observeQueryTime("insertVulnerabilityFixedInFeatureVersions", "all", time.Now())

	// Insert or find the Features.
	// TODO(Quentin-M): Batch me.
	var err error
	var features []*database.Feature
	for i := 0; i < len(fixedIn); i++ {
		features = append(features, &fixedIn[i].Feature)
	}
	for _, feature := range features {
		if feature.ID == 0 {
			if feature.ID, err = pgSQL.insertFeature(*feature); err != nil {
				return err
			}
		}
	}

	// Lock Vulnerability_Affects_FeatureVersion exclusively.
	// We want to prevent InsertFeatureVersion to modify it.
	promConcurrentLockVAFV.Inc()
	defer promConcurrentLockVAFV.Dec()
	t := time.Now()
	_, err = tx.Exec(lockVulnerabilityAffects)
	observeQueryTime("insertVulnerability", "lock", t)

	if err != nil {
		tx.Rollback()
		return handleError("insertVulnerability.lockVulnerabilityAffects", err)
	}

	for _, fv := range fixedIn {
		var fixedInID int

		// Insert Vulnerability_FixedIn_Feature.
		err = tx.QueryRow(
			insertVulnerabilityFixedInFeature,
			vulnerabilityID, fv.Feature.ID,
			&fv.Version,
		).Scan(&fixedInID)

		if err != nil {
			return handleError("insertVulnerabilityFixedInFeature", err)
		}

		// Insert Vulnerability_Affects_FeatureVersion.
		err = linkVulnerabilityToFeatureVersions(tx, fixedInID, vulnerabilityID, fv.Feature.ID, fv.Version)
		if err != nil {
			return err
		}
	}

	return nil
}
Example #30
0
func DelDataset(log *logging.Logger, db *DB, section, grace string, dataset int) error {
	var tx *sql.Tx
	var stmt *sql.Stmt
	var err error

	var tables = []string{"attrs", "acls"}
	var queries = []string{
		"DELETE FROM " + tables[0] + " WHERE grace = $1 AND dataset = $2",
		"DELETE FROM " + tables[1] + " WHERE grace = $1 AND dataset = $2",
	}

	var geterror = func(debugmessage, message string) error {
		tx.Rollback()

		log.Debug(debugmessage)
		return errors.New(message)
	}

	if section != "" {
		queries[0] = queries[0] + " AND area = $3"
		queries[1] = queries[1] + " AND area = $3"
	}

	tx, err = db.Conn.Begin()
	if err != nil {
		return geterror("Transaction error: "+err.Error(), "Problems with opening transaction")
	}

	for item, query := range queries {
		log.Debug("Delete table " + tables[item])

		stmt, err = tx.Prepare(query)
		if err != nil {
			return geterror("Error in prepare: "+err.Error(), "Problems when preparing query")
		}

		if section != "" {
			_, err = stmt.Exec(grace, dataset, section)
		} else {
			_, err = stmt.Exec(grace, dataset)
		}

		if err != nil {
			return geterror("Exec error: "+err.Error(), "Delete of dataset "+tables[item]+" wasn't possible")
		}
		stmt.Close()
	}
	tx.Commit()

	return nil
}