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 }
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 }
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 }
// 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) } }
// 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 }
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) }
func EndTx(tx *sql.Tx, err *error) { if *err == nil { tx.Commit() } else { tx.Rollback() } }
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 }
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 }
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 } } }
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 }
// 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) } }
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 }
// 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() }
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 }
// 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 }
// 提交事务 // tx:事务对象 // 返回值: // 错误对象 func CommitTransaction(tx *sql.Tx) error { err := tx.Commit() if err != nil { logUtil.Log(fmt.Sprintf("提交事务失败,错误信息:%s", err), logUtil.Error, true) } return err }
func TxCommit(tx *sql.Tx) error { err := tx.Commit() if err != nil { DFErrorLog("Transaction Commit Error:" + err.Error()) return err } DFLog("Transaction Commit") return err }
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 }
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 }
//Increments the phone no used count func IncPhoneUsedCount(phoneNo, authID string, tx *sql.Tx) (err error) { _, err = tx.Exec(` UPDATE phone_number SET count = count + 1 WHERE number = $1 AND account_id = (SELECT id FROM account WHERE auth_id = $2) `, phoneNo, authID) tx.Commit() return }
// Down is executed when this migration is rolled back func Down_20130702202327(txn *sql.Tx) { _, err := txn.Exec("DROP TABLE IF EXISTS projects, components, repositories, types, jobs, owners, authentication;") if err != nil { panic(err) } err = txn.Commit() if err != nil { panic(err) } }
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 }
// IoC execution(in transaction) func ExecuteInTx(txCallback func(*sql.Tx)) { var tx *sql.Tx var err error if tx, err = DbForTest.Begin(); err != nil { log.Fatalf("Cannot create transaction: %v", err) } defer tx.Commit() txCallback(tx) }
// 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() }
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 }
// 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) } } }
func Backup(log *logging.Logger, cfg *ini.File, grace string, reload bool) { const POOL = 5 var db database.DB var tx *sql.Tx var c = make(chan bool, POOL) var wg = new(sync.WaitGroup) var dataset, maxdatasets int var sections []*ini.Section sections = cfg.Sections() maxdatasets, _ = cfg.Section("dataset").Key(grace).Int() db.Open(log, cfg) defer db.Close() tx, _ = db.Conn.Begin() dataset = database.GetDataset(log, tx, grace) tx.Commit() if !reload { if nextds := dataset + 1; nextds > maxdatasets { dataset = 1 } else { dataset = dataset + 1 } } log.Info("Dataset processed: " + strconv.Itoa(dataset)) wg.Add(len(sections) - len(SECT_RESERVED)) for _, section := range sections { if !contains(SECT_RESERVED, section.Name()) { if section.Key("type").String() == "file" { // FIXME: useless? sect := common.Section{ Name: section.Name(), Grace: grace, Dataset: dataset, Compressed: section.Key("compress").MustBool(), } go fileBackup(log, §, cfg, c, wg) c <- true } } } wg.Wait() // Wait for all the children to die close(c) tx, _ = db.Conn.Begin() database.SetDataset(log, tx, dataset, grace) tx.Commit() }
func execInsert(db *sql.DB, query string, parameters ...interface{}) { var err error var tx *sql.Tx var stmt *sql.Stmt stmt, err = db.Prepare(query) tx, err = db.Begin() _, err = tx.Stmt(stmt).Exec(parameters...) err = tx.Commit() if err != nil { log.Fatalf("Insert error %q\n", err) } }
func (this *DBAdaptor) CommitTransaction(tx *sql.Tx) error { if this.db == nil { return fmt.Errorf("database object invalid") } err := tx.Commit() if err != nil { //fmt.Printf("提交失败\n") return err } return nil }