github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/internal/rows/data_rows.go (about)

     1  // Copyright 2021 ecodeclub
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package rows
    16  
    17  import (
    18  	"database/sql"
    19  
    20  	"github.com/ecodeclub/eorm/internal/errs"
    21  )
    22  
    23  var _ Rows = (*DataRows)(nil)
    24  
    25  // DataRows 直接传入数据,伪装成了一个 Rows
    26  // 非线程安全实现
    27  type DataRows struct {
    28  	data        [][]any
    29  	len         int
    30  	columns     []string
    31  	columnTypes []*sql.ColumnType
    32  	// 第几行
    33  	idx int
    34  }
    35  
    36  func (*DataRows) NextResultSet() bool {
    37  	return false
    38  }
    39  
    40  func (d *DataRows) ColumnTypes() ([]*sql.ColumnType, error) {
    41  	return d.columnTypes, nil
    42  }
    43  
    44  func NewDataRows(data [][]any, columns []string, columnTypes []*sql.ColumnType) *DataRows {
    45  	// 这里并没有什么必要检查 data 和 columns 的输入
    46  	// 因为只有在很故意的情况下,data 和 columns 才可能会有问题
    47  	return &DataRows{
    48  		data:        data,
    49  		len:         len(data),
    50  		columns:     columns,
    51  		idx:         -1,
    52  		columnTypes: columnTypes,
    53  	}
    54  }
    55  
    56  func (d *DataRows) Next() bool {
    57  	if d.idx >= d.len-1 {
    58  		return false
    59  	}
    60  	d.idx++
    61  	return true
    62  }
    63  
    64  func (d *DataRows) Scan(dest ...any) error {
    65  	// 不需要检测,作为内部代码我们可以预期用户会主动控制
    66  	data := d.data[d.idx]
    67  	if len(data) != len(dest) {
    68  		return errs.NewErrScanWrongDestinationArguments(len(data), len(dest))
    69  	}
    70  	for idx, dst := range dest {
    71  		if err := ConvertAssign(dst, data[idx]); err != nil {
    72  			return err
    73  		}
    74  	}
    75  	return nil
    76  }
    77  
    78  func (*DataRows) Close() error {
    79  	return nil
    80  }
    81  
    82  func (d *DataRows) Columns() ([]string, error) {
    83  	return d.columns, nil
    84  }
    85  
    86  func (*DataRows) Err() error {
    87  	return nil
    88  }