vitess.io/vitess@v0.16.2/go/vt/vtadmin/vtsql/fakevtsql/rows.go (about)

     1  /*
     2  Copyright 2020 The Vitess Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package fakevtsql
    18  
    19  import (
    20  	"database/sql/driver"
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  )
    25  
    26  var (
    27  	// ErrBadRow is returned from Next() when a row has an incorrect number of
    28  	// fields.
    29  	ErrBadRow = errors.New("bad sql row")
    30  	// ErrRowsClosed is returned when attempting to operate on an already-closed
    31  	// Rows.
    32  	ErrRowsClosed = errors.New("err rows closed")
    33  )
    34  
    35  type rows struct {
    36  	cols []string
    37  	vals [][]any
    38  	pos  int
    39  
    40  	closed bool
    41  }
    42  
    43  var _ driver.Rows = (*rows)(nil)
    44  
    45  func (r *rows) Close() error {
    46  	r.closed = true
    47  	return nil
    48  }
    49  
    50  func (r *rows) Columns() []string {
    51  	return r.cols
    52  }
    53  
    54  func (r *rows) Next(dest []driver.Value) error {
    55  	if r.closed {
    56  		return ErrRowsClosed
    57  	}
    58  
    59  	if r.pos >= len(r.vals) {
    60  		return io.EOF
    61  	}
    62  
    63  	row := r.vals[r.pos]
    64  	r.pos++
    65  
    66  	if len(row) != len(r.cols) {
    67  		return fmt.Errorf("%w: row %d has %d fields but %d cols", ErrBadRow, r.pos-1, len(row), len(r.cols))
    68  	}
    69  
    70  	for i := 0; i < len(r.cols); i++ {
    71  		dest[i] = row[i]
    72  	}
    73  
    74  	return nil
    75  }