github.com/dolthub/go-mysql-server@v0.18.0/sql/table_iter.go (about)

     1  // Copyright 2020-2021 Dolthub, Inc.
     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 sql
    16  
    17  import (
    18  	"io"
    19  )
    20  
    21  // TableRowIter is an iterator over the partitions in a table.
    22  type TableRowIter struct {
    23  	table      Table
    24  	partitions PartitionIter
    25  	partition  Partition
    26  	rows       RowIter
    27  }
    28  
    29  var _ RowIter = (*TableRowIter)(nil)
    30  
    31  // NewTableRowIter returns a new iterator over the rows in the partitions of the table given.
    32  func NewTableRowIter(ctx *Context, table Table, partitions PartitionIter) *TableRowIter {
    33  	return &TableRowIter{table: table, partitions: partitions}
    34  }
    35  
    36  func (i *TableRowIter) Next(ctx *Context) (Row, error) {
    37  	if ctx.Err() != nil {
    38  		return nil, ctx.Err()
    39  	}
    40  
    41  	if i.partition == nil {
    42  		partition, err := i.partitions.Next(ctx)
    43  		if err != nil {
    44  			if err == io.EOF {
    45  				if e := i.partitions.Close(ctx); e != nil {
    46  					return nil, e
    47  				}
    48  			}
    49  
    50  			return nil, err
    51  		}
    52  
    53  		i.partition = partition
    54  	}
    55  
    56  	if i.rows == nil {
    57  		rows, err := i.table.PartitionRows(ctx, i.partition)
    58  		if err != nil {
    59  			return nil, err
    60  		}
    61  
    62  		i.rows = rows
    63  	}
    64  
    65  	row, err := i.rows.Next(ctx)
    66  	if err != nil && err == io.EOF {
    67  		if err = i.rows.Close(ctx); err != nil {
    68  			return nil, err
    69  		}
    70  
    71  		i.partition = nil
    72  		i.rows = nil
    73  		row, err = i.Next(ctx)
    74  	}
    75  	select {
    76  	case <-ctx.Done():
    77  		return nil, ctx.Err()
    78  	default:
    79  	}
    80  	return row, err
    81  }
    82  
    83  func (i *TableRowIter) Close(ctx *Context) error {
    84  	if i.rows != nil {
    85  		if err := i.rows.Close(ctx); err != nil {
    86  			_ = i.partitions.Close(ctx)
    87  			return err
    88  		}
    89  	}
    90  	return i.partitions.Close(ctx)
    91  }