github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/aggregation/window/lag.go (about)

     1  // Copyright 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 window
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/dolthub/go-mysql-server/sql/transform"
    22  
    23  	"github.com/dolthub/go-mysql-server/sql"
    24  	"github.com/dolthub/go-mysql-server/sql/expression"
    25  	"github.com/dolthub/go-mysql-server/sql/expression/function/aggregation"
    26  )
    27  
    28  type Lag struct {
    29  	window *sql.WindowDefinition
    30  	expression.NaryExpression
    31  	offset int
    32  	pos    int
    33  	id     sql.ColumnId
    34  }
    35  
    36  var _ sql.FunctionExpression = (*Lag)(nil)
    37  var _ sql.WindowAggregation = (*Lag)(nil)
    38  var _ sql.WindowAdaptableExpression = (*Lag)(nil)
    39  var _ sql.CollationCoercible = (*Lag)(nil)
    40  
    41  // NewLag accepts variadic arguments to create a new Lag node:
    42  // If 1 expression, use default values for [default] and [offset]
    43  // If 2 expressions, use default value for [default]
    44  // 3 input expression match to [child], [offset], and [default] arguments
    45  // The offset is constrained to a non-negative integer expression.Literal.
    46  // TODO: support user-defined variable offset
    47  func NewLag(e ...sql.Expression) (*Lag, error) {
    48  	switch len(e) {
    49  	case 1:
    50  		return &Lag{NaryExpression: expression.NaryExpression{ChildExpressions: e[:1]}, offset: 1}, nil
    51  	case 2:
    52  		offset, err := expression.LiteralToInt(e[1])
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		return &Lag{NaryExpression: expression.NaryExpression{ChildExpressions: e[:1]}, offset: offset}, nil
    57  	case 3:
    58  		offset, err := expression.LiteralToInt(e[1])
    59  		if err != nil {
    60  			return nil, err
    61  		}
    62  		return &Lag{NaryExpression: expression.NaryExpression{ChildExpressions: []sql.Expression{e[0], e[2]}}, offset: offset}, nil
    63  	}
    64  	return nil, sql.ErrInvalidArgumentNumber.New("LAG", "1, 2, or 3", len(e))
    65  }
    66  
    67  // Id implements the Aggregation interface
    68  func (l *Lag) Id() sql.ColumnId {
    69  	return l.id
    70  }
    71  
    72  // WithId implements the Aggregation interface
    73  func (l *Lag) WithId(id sql.ColumnId) sql.IdExpression {
    74  	ret := *l
    75  	ret.id = id
    76  	return &ret
    77  }
    78  
    79  // Description implements sql.FunctionExpression
    80  func (l *Lag) Description() string {
    81  	return "returns the value of the expression evaluated at the lag offset row"
    82  }
    83  
    84  // Window implements sql.WindowExpression
    85  func (l *Lag) Window() *sql.WindowDefinition {
    86  	return l.window
    87  }
    88  
    89  // IsNullable implements sql.Expression
    90  func (l *Lag) Resolved() bool {
    91  	childrenResolved := true
    92  	for _, c := range l.ChildExpressions {
    93  		childrenResolved = childrenResolved && c.Resolved()
    94  	}
    95  	return childrenResolved && windowResolved(l.window)
    96  }
    97  
    98  func (l *Lag) String() string {
    99  	sb := strings.Builder{}
   100  	if len(l.ChildExpressions) > 1 {
   101  		sb.WriteString(fmt.Sprintf("lag(%s, %d, %s)", l.ChildExpressions[0].String(), l.offset, l.ChildExpressions[1]))
   102  	} else {
   103  		sb.WriteString(fmt.Sprintf("lag(%s, %d)", l.ChildExpressions[0].String(), l.offset))
   104  	}
   105  	if l.window != nil {
   106  		sb.WriteString(" ")
   107  		sb.WriteString(l.window.String())
   108  	}
   109  	return sb.String()
   110  }
   111  
   112  func (l *Lag) DebugString() string {
   113  	sb := strings.Builder{}
   114  	if len(l.ChildExpressions) > 1 {
   115  		sb.WriteString(fmt.Sprintf("lag(%s, %d, %s)", l.ChildExpressions[0].String(), l.offset, l.ChildExpressions[1]))
   116  	} else {
   117  		sb.WriteString(fmt.Sprintf("lag(%s, %d)", l.ChildExpressions[0].String(), l.offset))
   118  	}
   119  	if l.window != nil {
   120  		sb.WriteString(" ")
   121  		sb.WriteString(sql.DebugString(l.window))
   122  	}
   123  	return sb.String()
   124  }
   125  
   126  // FunctionName implements sql.FunctionExpression
   127  func (l *Lag) FunctionName() string {
   128  	return "LAG"
   129  }
   130  
   131  // Type implements sql.Expression
   132  func (l *Lag) Type() sql.Type {
   133  	return l.ChildExpressions[0].Type()
   134  }
   135  
   136  // CollationCoercibility implements the interface sql.CollationCoercible.
   137  func (l *Lag) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
   138  	// We're returning the type of the first child, so we'll return the coercibility of the first child
   139  	// as well
   140  	if l == nil || len(l.ChildExpressions) == 0 {
   141  		return sql.Collation_binary, 6
   142  	}
   143  	return sql.GetCoercibility(ctx, l.ChildExpressions[0])
   144  }
   145  
   146  // IsNullable implements sql.Expression
   147  func (l *Lag) IsNullable() bool {
   148  	return true
   149  }
   150  
   151  // Eval implements sql.Expression
   152  func (l *Lag) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
   153  	return nil, sql.ErrWindowUnsupported.New(l.FunctionName())
   154  }
   155  
   156  // Children implements sql.Expression
   157  func (l *Lag) Children() []sql.Expression {
   158  	if l == nil {
   159  		return nil
   160  	}
   161  	return append(l.window.ToExpressions(), l.ChildExpressions...)
   162  }
   163  
   164  // WithChildren implements sql.Expression
   165  func (l *Lag) WithChildren(children ...sql.Expression) (sql.Expression, error) {
   166  	if len(children) < 2 {
   167  		return nil, sql.ErrInvalidChildrenNumber.New(l, len(children), 2)
   168  	}
   169  
   170  	nl := *l
   171  	numWindowExpr := len(children) - len(l.ChildExpressions)
   172  	window, err := l.window.FromExpressions(children[:numWindowExpr])
   173  	if err != nil {
   174  		return nil, err
   175  	}
   176  
   177  	nl.ChildExpressions = children[numWindowExpr:]
   178  	nl.window = window
   179  
   180  	return &nl, nil
   181  }
   182  
   183  // WithWindow implements sql.WindowAggregation
   184  func (l *Lag) WithWindow(window *sql.WindowDefinition) sql.WindowAdaptableExpression {
   185  	nl := *l
   186  	nl.window = window
   187  	return &nl
   188  }
   189  
   190  func (l *Lag) NewWindowFunction() (sql.WindowFunction, error) {
   191  	c, err := transform.Clone(l.ChildExpressions[0])
   192  	if err != nil {
   193  		return nil, err
   194  	}
   195  	var def sql.Expression
   196  	if len(l.ChildExpressions) > 1 {
   197  		def, err = transform.Clone(l.ChildExpressions[1])
   198  		if err != nil {
   199  			return nil, err
   200  		}
   201  	}
   202  	return aggregation.NewLag(c, def, l.offset), nil
   203  }