github.com/gogf/gf/v2@v2.7.4/database/gdb/gdb_result.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gdb
     8  
     9  import (
    10  	"database/sql"
    11  
    12  	"github.com/gogf/gf/v2/errors/gerror"
    13  )
    14  
    15  // SqlResult is execution result for sql operations.
    16  // It also supports batch operation result for rowsAffected.
    17  type SqlResult struct {
    18  	Result   sql.Result
    19  	Affected int64
    20  }
    21  
    22  // MustGetAffected returns the affected rows count, if any error occurs, it panics.
    23  func (r *SqlResult) MustGetAffected() int64 {
    24  	rows, err := r.RowsAffected()
    25  	if err != nil {
    26  		err = gerror.Wrap(err, `sql.Result.RowsAffected failed`)
    27  		panic(err)
    28  	}
    29  	return rows
    30  }
    31  
    32  // MustGetInsertId returns the last insert id, if any error occurs, it panics.
    33  func (r *SqlResult) MustGetInsertId() int64 {
    34  	id, err := r.LastInsertId()
    35  	if err != nil {
    36  		err = gerror.Wrap(err, `sql.Result.LastInsertId failed`)
    37  		panic(err)
    38  	}
    39  	return id
    40  }
    41  
    42  // RowsAffected returns the number of rows affected by an
    43  // update, insert, or delete. Not every database or database
    44  // driver may support this.
    45  // Also, See sql.Result.
    46  func (r *SqlResult) RowsAffected() (int64, error) {
    47  	if r.Affected > 0 {
    48  		return r.Affected, nil
    49  	}
    50  	if r.Result == nil {
    51  		return 0, nil
    52  	}
    53  	return r.Result.RowsAffected()
    54  }
    55  
    56  // LastInsertId returns the integer generated by the database
    57  // in response to a command. Typically, this will be from an
    58  // "auto increment" column when inserting a new row. Not all
    59  // databases support this feature, and the syntax of such
    60  // statements varies.
    61  // Also, See sql.Result.
    62  func (r *SqlResult) LastInsertId() (int64, error) {
    63  	if r.Result == nil {
    64  		return 0, nil
    65  	}
    66  	return r.Result.LastInsertId()
    67  }