github.com/gogf/gf@v1.16.9/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 "database/sql"
    10  
    11  // SqlResult is execution result for sql operations.
    12  // It also supports batch operation result for rowsAffected.
    13  type SqlResult struct {
    14  	result   sql.Result
    15  	affected int64
    16  }
    17  
    18  // MustGetAffected returns the affected rows count, if any error occurs, it panics.
    19  func (r *SqlResult) MustGetAffected() int64 {
    20  	rows, err := r.RowsAffected()
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	return rows
    25  }
    26  
    27  // MustGetInsertId returns the last insert id, if any error occurs, it panics.
    28  func (r *SqlResult) MustGetInsertId() int64 {
    29  	id, err := r.LastInsertId()
    30  	if err != nil {
    31  		panic(err)
    32  	}
    33  	return id
    34  }
    35  
    36  // RowsAffected returns the number of rows affected by an
    37  // update, insert, or delete. Not every database or database
    38  // driver may support this.
    39  // Also See sql.Result.
    40  func (r *SqlResult) RowsAffected() (int64, error) {
    41  	if r.affected > 0 {
    42  		return r.affected, nil
    43  	}
    44  	if r.result == nil {
    45  		return 0, nil
    46  	}
    47  	return r.result.RowsAffected()
    48  }
    49  
    50  // LastInsertId returns the integer generated by the database
    51  // in response to a command. Typically this will be from an
    52  // "auto increment" column when inserting a new row. Not all
    53  // databases support this feature, and the syntax of such
    54  // statements varies.
    55  // Also See sql.Result.
    56  func (r *SqlResult) LastInsertId() (int64, error) {
    57  	if r.result == nil {
    58  		return 0, nil
    59  	}
    60  	return r.result.LastInsertId()
    61  }