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


Golang Tx.Commit方法代碼示例

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


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

示例1:

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

示例2: 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

示例3: doExec

func (self *Source) doExec(terms ...interface{}) (res sql.Result, err error) {
	var tx *sql.Tx

	if self.session == nil {
		return nil, db.ErrNotConnected
	}

	chunks := sqlCompile(terms)

	query := strings.Join(chunks.Query, ` `)

	for i := 0; i < len(chunks.Args); i++ {
		query = strings.Replace(query, `?`, fmt.Sprintf(`$%d`, i+1), 1)
	}

	if debugEnabled() == true {
		debugLogQuery(query, chunks)
	}

	if tx, err = self.session.Begin(); err != nil {
		return nil, err
	}

	if res, err = tx.Exec(query, chunks.Args...); err != nil {
		return nil, err
	}

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

	return res, nil
}
開發者ID:vimdude,項目名稱:db,代碼行數:33,代碼來源:database.go

示例4: BenchmarkAppendTxRawSQL

// Benchmarking raw database/sql.
func BenchmarkAppendTxRawSQL(b *testing.B) {
	var err error
	var sess db.Database
	var tx *sql.Tx

	if sess, err = db.Open(Adapter, settings); err != nil {
		b.Fatal(err)
	}

	defer sess.Close()

	driver := sess.Driver().(*sql.DB)

	if tx, err = driver.Begin(); err != nil {
		b.Fatal(err)
	}

	if _, err = tx.Exec("TRUNCATE TABLE `artist`"); err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if _, err = tx.Exec("INSERT INTO `artist` (`name`) VALUES('Hayao Miyazaki')"); err != nil {
			b.Fatal(err)
		}
	}

	if err = tx.Commit(); err != nil {
		b.Fatal(err)
	}
}
開發者ID:huuzkee-foundation,項目名稱:dbcli,代碼行數:33,代碼來源:database_test.go

示例5: 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

示例6: 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

示例7: EndTx

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

示例8: processLogin

func processLogin(
	w http.ResponseWriter, r *http.Request, tx *sql.Tx, login *Login,
) (bool, error) {
	cEmail := canonEmail(r.Form.Get("email"))
	cPassword := strings.TrimSpace(r.Form.Get("password"))

	login.Email = cEmail

	userID, passwordHash, err := getUserInfo(tx, cEmail)
	switch {
	case err == sql.ErrNoRows:
		login.Error = errBadUserOrPassword
		return false, nil
	case err != nil:
		return false, err
	}

	if !checkPasswordHash(cPassword, passwordHash) {
		login.Error = errBadUserOrPassword
		return false, nil
	}

	err = loginUser(w, r, tx, userID)
	if err != nil {
		return false, err
	}
	err = tx.Commit()
	if err != nil {
		return false, err
	}

	return true, nil
}
開發者ID:hochhaus,項目名稱:mammothmail,代碼行數:33,代碼來源:login.go

示例9: 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

示例10: readData

func readData(client net.Conn) {
	b := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
	i := 0
	var err error
	var tx *sql.Tx
	for {
		if i == 0 {
			tx, err = pg.Begin()
			if err != nil {
				log.Printf("error=true action=begin message=%v", err)
			}
			i += 1
		} else if i == (*checkpoint + 1) {
			//checkpoint is set by flag
			// we inc checkpoint for the case when it is set to 1
			err = tx.Commit()
			if err != nil {
				log.Printf("error=true action=commit message=%v", err)
			}
			log.Printf("action=commit")
			i = 0
		} else {
			line, err := b.ReadString('\n')
			if err != nil {
				break
			}
			handleInput(*tx, line)
			i += 1
		}
	}
}
開發者ID:ryandotsmith,項目名稱:wcld,代碼行數:31,代碼來源:wcld.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: Up_20130702202327

// Up is executed when this migration is applied
func Up_20130702202327(txn *sql.Tx) {
	_, err := txn.Exec("CREATE TABLE projects (project_name TEXT, meta TEXT, PRIMARY KEY (project_name))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE components (project_name TEXT, component_name TEXT, gitrepo TEXT, meta TEXT, PRIMARY KEY (project_name, component_name))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE repositories (project_name TEXT, repository_name TEXT, type TEXT, arch TEXT, state TINYINT UNSIGNED, PRIMARY KEY (project_name, repository_name))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE types (type_name TEXT, display_name TEXT, description TEXT, needsuper BOOL, applsh TEXT, buldsh TEXT, publsh TEXT, PRIMARY KEY (type_name))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE jobs (project_name TEXT, repository_name TEXT, repository_arch TEXT, component_name TEXT, job_id BIGINT AUTO_INCREMENT, time TEXT, state TINYINT UNSIGNED, results TEXT, PRIMARY KEY (project_name, repository_name, repository_arch, component_name, job_id))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE owners (username TEXT, projects TEXT, email TEXT, isgroup BOOL, groupusers TEXT, PRIMARY KEY (username))")
	if err != nil {
		panic(err)
	}
	_, err = txn.Exec("CREATE TABLE authentication (username TEXT, password TEXT, token TEXT, admin TINYINT, PRIMARY KEY (username))")
	if err != nil {
		panic(err)
	}
	err = txn.Commit()
	if err != nil {
		panic(err)
	}
}
開發者ID:robxu9,項目名稱:reservoir,代碼行數:35,代碼來源:001_createtables.go

示例13: 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

示例14: Delete

// Delete will delete all of the configurations whose name is in the list
// of names in the arugment. It will not return an error if the name is not found.
func (cc *ConfigurationController) Delete(names ...string) (err error) {
	var (
		tx   *sql.Tx
		stmt *sql.Stmt
	)
	tx, err = cc.DB.Begin()
	if err != nil {
		tx.Rollback()
		return err
	}

	stmt, err = tx.Prepare("DELETE FROM configurations where config_name = $1")
	if err != nil {
		tx.Rollback()
		return err
	}

	for _, name := range names {
		_, err := stmt.Exec(name)

		if err == sql.ErrNoRows {
			err = nil
		}
		if err != nil {
			tx.Rollback()
			return err
		}
	}

	return tx.Commit()

}
開發者ID:wrrn,項目名稱:restapi,代碼行數:34,代碼來源:configuration.go

示例15: MarkDeleted

func (c *BaseCluster) MarkDeleted() (err error) {
	c.installer.dbMtx.Lock()
	defer c.installer.dbMtx.Unlock()

	var tx *sql.Tx
	tx, err = c.installer.db.Begin()
	if err != nil {
		return
	}

	if _, err = tx.Exec(`UPDATE prompts SET DeletedAt = now() WHERE ID IN (SELECT ResourceID FROM events WHERE ClusterID == $1 AND ResourceType == "prompt")`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE events SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE domains SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE instances SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE clusters SET DeletedAt = now() WHERE ID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE aws_clusters SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE digital_ocean_clusters SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE digital_ocean_droplets SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	if _, err = tx.Exec(`UPDATE ssh_clusters SET DeletedAt = now() WHERE ClusterID == $1`, c.ID); err != nil {
		tx.Rollback()
		return
	}

	c.installer.ClusterDeleted(c.ID)
	err = tx.Commit()
	return
}
開發者ID:leroyg,項目名稱:flynn,代碼行數:59,代碼來源:cluster.go


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