當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Tx.Rollback方法代碼示例

本文整理匯總了Golang中database/sql.Tx.Rollback方法的典型用法代碼示例。如果您正苦於以下問題:Golang Tx.Rollback方法的具體用法?Golang Tx.Rollback怎麽用?Golang Tx.Rollback使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在database/sql.Tx的用法示例。


在下文中一共展示了Tx.Rollback方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: dataCompletenessDelete

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
}
開發者ID:GeoNet,項目名稱:mtr,代碼行數:29,代碼來源:data_completeness.go

示例2: perrorWithRollBack

// 打印並拋出異常
func perrorWithRollBack(e error, errMsg string, tx *sql.Tx) {
	if e != nil {
		tx.Rollback()
		log.Println(e)
		panic(errMsg)
	}
}
開發者ID:zxnhl702,項目名稱:xinlanAdminTest,代碼行數:8,代碼來源:constVar.go

示例3: EndTx

func EndTx(tx *sql.Tx, err *error) {
	if *err == nil {
		tx.Commit()
	} else {
		tx.Rollback()
	}
}
開發者ID:henyouqian,項目名稱:lwutil,代碼行數:7,代碼來源:util.go

示例4: Down_20150712142846

// 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)
	}
}
開發者ID:GeorgeMac,項目名稱:outing,代碼行數:8,代碼來源:20150712142846_CreatePlacesTable.go

示例5: rollbackAndError

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
}
開發者ID:hyandell,項目名稱:rs_ingester,代碼行數:7,代碼來源:postgres.go

示例6: Insert

// 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
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:36,代碼來源:profile_options.go

示例7: Upgrade

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
}
開發者ID:michielbdejong,項目名稱:FindMyDevice,代碼行數:60,代碼來源:rcs.go

示例8: tryRollback

func tryRollback(lbl Label, tx *sql.Tx, err error) (Label, error) {
	rbErr := tx.Rollback()
	if rbErr != nil {
		return lbl, rbErr
	}
	return lbl, err
}
開發者ID:voiid,項目名稱:goblog-prototype,代碼行數:7,代碼來源:post_has_labels.go

示例9: truncateAllTables

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)
}
開發者ID:vincentcr,項目名稱:huecontrol,代碼行數:32,代碼來源:test_utils.go

示例10:

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
}
開發者ID:pombredanne,項目名稱:dep,代碼行數:28,代碼來源:db.go

示例11: invokeMigration

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
}
開發者ID:blendlabs,項目名稱:spiffy,代碼行數:27,代碼來源:runner.go

示例12: fieldMetricDelete

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
}
開發者ID:GeoNet,項目名稱:mtr,代碼行數:29,代碼來源:field_metric.go

示例13: UpdateAttendees

// 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
}
開發者ID:riseofthetigers,項目名稱:microcosm,代碼行數:31,代碼來源:events.go

示例14: RollbackErr

// 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
}
開發者ID:bahlo,項目名稱:abutil,代碼行數:11,代碼來源:database.go

示例15: AddParent

// 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
}
開發者ID:jefflub,項目名稱:allowance,代碼行數:27,代碼來源:addparent.go


注:本文中的database/sql.Tx.Rollback方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。