Example #1
0
func (b *Base) DeleteById(tx *sqlx.Tx, id string) (sql.Result, error) {
	var result sql.Result

	if b.table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	query := fmt.Sprintf("DELETE FROM %v WHERE id=$1", b.table)

	result, err = tx.Exec(query, id)

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	if err != nil {
		return nil, err
	}

	return result, err
}
Example #2
0
func (b *BaseStore) DeleteFromTable(tx *sqlx.Tx, where string) (sql.Result, error) {
	var result sql.Result

	if b.Table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	query := fmt.Sprintf("DELETE FROM %v", b.Table)

	if where != "" {
		query = query + " WHERE " + where
	}

	result, err = tx.Exec(query)

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	if err != nil {
		return nil, err
	}

	return result, err
}
Example #3
0
func (s *PeopleStore) DeletePerson(id int64) (err error) {
	var tx *sqlx.Tx

	tx, err = s.db.Beginx()
	if err != nil {
		return
	}

	// Automatically rollback/commit if there's an error.
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	// Remove the given Person
	if _, err = tx.Exec(s.db.Rebind(personDeleteQuery), id); err != nil {
		return
	}

	// Done!
	return nil
}
Example #4
0
func (s *ListStore) DeleteList(id int64) (err error) {
	var tx *sqlx.Tx

	tx, err = s.db.Beginx()
	if err != nil {
		return
	}

	// Automatically rollback/commit if there's an error.
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	// Remove todos in this list.
	if _, err = tx.Exec(s.db.Rebind(listDeleteTodosQuery), id); err != nil {
		return
	}

	// Remove the given List
	if _, err = tx.Exec(s.db.Rebind(listDeleteQuery), id); err != nil {
		return
	}

	// Done!
	return nil
}
Example #5
0
func (db Database) CommitTransaction(tx *sqlx.Tx) error {
	err := tx.Commit()
	if err != nil {
		fmt.Println("Could not commit database transaction:", err)
	}
	return err
}
Example #6
0
func (b *Base) InsertIntoTable(tx *sqlx.Tx, data map[string]interface{}) (sql.Result, error) {
	if b.table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	keys := make([]string, 0)
	dollarMarks := make([]string, 0)
	values := make([]interface{}, 0)

	loopCounter := 1
	for key, value := range data {
		keys = append(keys, key)
		dollarMarks = append(dollarMarks, fmt.Sprintf("$%v", loopCounter))
		values = append(values, value)

		loopCounter++
	}

	query := fmt.Sprintf(
		"INSERT INTO %v (%v) VALUES (%v)",
		b.table,
		strings.Join(keys, ","),
		strings.Join(dollarMarks, ","))

	result := &InsertResult{}
	result.rowsAffected = 1

	if b.hasID {
		query = query + " RETURNING id"

		var lastInsertId int64
		err = tx.QueryRow(query, values...).Scan(&lastInsertId)
		if err != nil {
			return nil, err
		}

		result.lastInsertId = lastInsertId

	} else {
		_, err := tx.Exec(query, values...)
		if err != nil {
			return nil, err
		}
	}

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	return result, err
}
Example #7
0
func (b *Base) UpdateByKeyValueString(tx *sqlx.Tx, data map[string]interface{}, key, value string) (sql.Result, error) {
	var result sql.Result

	if b.table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	keysWithDollarMarks := make([]string, 0)
	values := make([]interface{}, 0)

	loopCounter := 1
	for key, value := range data {
		keysWithDollarMark := fmt.Sprintf("%v=$%v", key, loopCounter)
		keysWithDollarMarks = append(keysWithDollarMarks, keysWithDollarMark)
		values = append(values, value)

		loopCounter++
	}

	// Add value as part of values
	values = append(values, value)

	query := fmt.Sprintf(
		"UPDATE %v SET %v WHERE %v=$%v",
		b.table,
		strings.Join(keysWithDollarMarks, ","),
		key,
		loopCounter)

	result, err = tx.Exec(query, values...)

	if err != nil {
		return nil, err
	}

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	return result, err
}
Example #8
0
// Transaction manages a db transaction, automatically calling commit
// on success or rollback on failure.
func transaction(fn func(*sqlx.Tx) error) (err error) {
	var tx *sqlx.Tx
	tx, err = db.Beginx()
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			err = tx.Commit()
		}
	}()
	return fn(tx)
}
Example #9
0
func (b *BaseStore) UpdateByID(tx *sqlx.Tx, data map[string]interface{}, id int64) (sql.Result, error) {
	var result sql.Result

	if b.Table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	keysWithQuestionMarks := make([]string, 0)
	values := make([]interface{}, 0)

	for key, value := range data {
		keysWithQuestionMark := fmt.Sprintf("%v=?", key)
		keysWithQuestionMarks = append(keysWithQuestionMarks, keysWithQuestionMark)
		values = append(values, value)
	}

	// Add id as part of values
	values = append(values, id)

	query := fmt.Sprintf(
		"UPDATE %v SET %v WHERE id=?",
		b.Table,
		strings.Join(keysWithQuestionMarks, ","))

	result, err = tx.Exec(query, values...)

	if err != nil {
		return nil, err
	}

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	return result, err
}
Example #10
0
func (s *TodoStore) DeleteTodo(id int64) (err error) {
	var tx *sqlx.Tx

	tx, err = s.db.Beginx()
	if err != nil {
		return
	}

	// Automatically rollback/commit if there's an error.
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	// Get the given Todo
	todo := &model.Todo{}
	if err = tx.Get(todo, s.db.Rebind(todoGetQuery), id); err != nil {
		return
	}

	// Remove the given Todo
	if _, err = tx.Exec(s.db.Rebind(todoDeleteQuery), id); err != nil {
		return
	}

	// Fix any previous link - change any `previous_id` that points at our
	// current id to point at what we point at.
	if _, err = tx.Exec(s.db.Rebind(todoRelinkQuery),
		todo.PreviousID, // New previous_id
		id,              // Old previous_id
		todo.ListID,     // List ID
	); err != nil {
		return
	}

	// Done!
	return nil
}
Example #11
0
func (b *BaseStore) InsertIntoTable(tx *sqlx.Tx, data map[string]interface{}) (sql.Result, error) {
	if b.Table == "" {
		return nil, errors.New("Table must not be empty.")
	}

	tx, wrapInSingleTransaction, err := b.newTransactionIfNeeded(tx)
	if tx == nil {
		return nil, errors.New("Transaction struct must not be empty.")
	}
	if err != nil {
		return nil, err
	}

	keys := make([]string, 0)
	qMarks := make([]string, 0)
	values := make([]interface{}, 0)

	for key, value := range data {
		keys = append(keys, key)
		qMarks = append(qMarks, "?")
		values = append(values, value)
	}

	query := fmt.Sprintf(
		"INSERT INTO %v (%v) VALUES (%v)",
		b.Table,
		strings.Join(keys, ","),
		strings.Join(qMarks, ","))

	result, err := tx.Exec(query, values...)
	if err != nil {
		return nil, err
	}

	if wrapInSingleTransaction == true {
		err = tx.Commit()
	}

	return result, err
}
Example #12
0
func (l *Loader) Commit(tx *sqlx.Tx) (err error) {
	if err = tx.Commit(); err != nil {
		return
	}
	return
}
Example #13
0
func (this *Migrator) ApplyAll() error {
	if len(this.scripts) == 0 {
		return errors.New("Nothing to execute")
	}
	storageExists, err := this.storage.StorageExists()
	if err != nil {
		return err
	}
	if !storageExists {
		err = this.storage.CreateStorage()
		if err != nil {
			return err
		}
	}

	executedMigrationsCount := 0
	for _, script := range this.scripts {
		migrationExists, err := this.storage.MigrationExists(script.GetName())
		if err != nil {
			return err
		}
		if migrationExists {
			this.response.AddMessage("Migration '" + script.GetName() + "' exists. Skipping.")
			continue
		}
		this.response.AddMessage("Executing migration " + script.GetName())
		executionContext := script.GetExecutionContext()
		if executionContext.IsEmpty() {
			this.response.AddMessage("Migration " + script.GetName() + " is empty. Skipping")
			continue
		}
		var tx *sqlx.Tx
		tx, err = this.connection.TransactionStart()
		if err != nil {
			return err
		}
		for _, migration := range executionContext.QueriesToApply {
			res, err := tx.NamedExec(migration.sql, migration.args)
			if err != nil {
				this.response.AddError(errors.New("Query failed. Rollbacking."))
				tx.Rollback()
				return err
			} else {
				rowsAffected, _ := res.RowsAffected()
				lastInserted, _ := res.LastInsertId()
				this.response.AddMessage(fmt.Sprintf("Rows affected %d, last inserted id %d", rowsAffected, lastInserted))
			}
		}
		if executionContext.SuccessCallback != nil {
			err := executionContext.SuccessCallback()
			if err != nil {
				this.response.AddError(errors.New("Callback failed. Rollbacking."))
				tx.Rollback()
				return err
			} else {
				this.response.AddMessage("Callback executed successfully")
			}
		}
		err = this.storage.RegisterNewMigration(script.GetName())
		if err != nil {
			tx.Rollback()
			return err
		} else {
			this.response.AddMessage("New migration with name " + script.GetName() + " is registered")
		}
		tx.Commit()
		executedMigrationsCount++
	}

	this.response.AddMessage(fmt.Sprintf("Successfully executed migrations %d", executedMigrationsCount))
	return nil
}