github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/sem/tree/datum.go (about)

     1  // Copyright 2015 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package tree
    12  
    13  import (
    14  	"bytes"
    15  	"fmt"
    16  	"math"
    17  	"math/big"
    18  	"net"
    19  	"regexp"
    20  	"sort"
    21  	"strconv"
    22  	"strings"
    23  	"time"
    24  	"unicode"
    25  	"unsafe"
    26  
    27  	"github.com/cockroachdb/apd"
    28  	"github.com/cockroachdb/cockroach/pkg/geo"
    29  	"github.com/cockroachdb/cockroach/pkg/roachpb"
    30  	"github.com/cockroachdb/cockroach/pkg/sql/lex"
    31  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
    32  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
    33  	"github.com/cockroachdb/cockroach/pkg/sql/types"
    34  	"github.com/cockroachdb/cockroach/pkg/util/bitarray"
    35  	"github.com/cockroachdb/cockroach/pkg/util/duration"
    36  	"github.com/cockroachdb/cockroach/pkg/util/ipaddr"
    37  	"github.com/cockroachdb/cockroach/pkg/util/json"
    38  	"github.com/cockroachdb/cockroach/pkg/util/stringencoding"
    39  	"github.com/cockroachdb/cockroach/pkg/util/timeofday"
    40  	"github.com/cockroachdb/cockroach/pkg/util/timetz"
    41  	"github.com/cockroachdb/cockroach/pkg/util/timeutil"
    42  	"github.com/cockroachdb/cockroach/pkg/util/timeutil/pgdate"
    43  	"github.com/cockroachdb/cockroach/pkg/util/uint128"
    44  	"github.com/cockroachdb/cockroach/pkg/util/uuid"
    45  	"github.com/cockroachdb/errors"
    46  	"github.com/lib/pq/oid"
    47  	"golang.org/x/text/collate"
    48  	"golang.org/x/text/language"
    49  )
    50  
    51  var (
    52  	constDBoolTrue  DBool = true
    53  	constDBoolFalse DBool = false
    54  
    55  	// DBoolTrue is a pointer to the DBool(true) value and can be used in
    56  	// comparisons against Datum types.
    57  	DBoolTrue = &constDBoolTrue
    58  	// DBoolFalse is a pointer to the DBool(false) value and can be used in
    59  	// comparisons against Datum types.
    60  	DBoolFalse = &constDBoolFalse
    61  
    62  	// DNull is the NULL Datum.
    63  	DNull Datum = dNull{}
    64  
    65  	// DZero is the zero-valued integer Datum.
    66  	DZero = NewDInt(0)
    67  
    68  	// DTimeMaxTimeRegex is a compiled regex for parsing the 24:00 time value.
    69  	DTimeMaxTimeRegex = regexp.MustCompile(`^([0-9-]*(\s|T))?\s*24:00(:00(.0+)?)?\s*$`)
    70  
    71  	// The maximum timestamp Golang can represents is represented as UNIX
    72  	// time timeutil.Unix(-9223372028715321601, 0).
    73  	// However, this causes errors as we cannot reliably sort as we use
    74  	// UNIX time in the key encoding, and 9223372036854775807 > -9223372028715321601
    75  	// but timeutil.Unix(9223372036854775807, 0) < timeutil.Unix(-9223372028715321601, 0).
    76  	//
    77  	// To be compatible with pgwire, we only support the published min/max for
    78  	// postgres 4714 BC (JULIAN = 0) - 4713 in their docs - and 294276 AD.
    79  
    80  	// MaxSupportedTime is the maximum time we support parsing.
    81  	MaxSupportedTime = timeutil.Unix(9224318016000-1, 999999000) // 294276-12-31 23:59:59.999999
    82  	// MinSupportedTime is the minimum time we support parsing.
    83  	MinSupportedTime = timeutil.Unix(-210866803200, 0) // 4714-11-24 00:00:00+00 BC
    84  )
    85  
    86  // Datum represents a SQL value.
    87  type Datum interface {
    88  	TypedExpr
    89  
    90  	// AmbiguousFormat indicates whether the result of formatting this Datum can
    91  	// be interpreted into more than one type. Used with
    92  	// fmtFlags.disambiguateDatumTypes.
    93  	AmbiguousFormat() bool
    94  
    95  	// Compare returns -1 if the receiver is less than other, 0 if receiver is
    96  	// equal to other and +1 if receiver is greater than other.
    97  	Compare(ctx *EvalContext, other Datum) int
    98  
    99  	// Prev returns the previous datum and true, if one exists, or nil and false.
   100  	// The previous datum satisfies the following definition: if the receiver is
   101  	// "b" and the returned datum is "a", then for every compatible datum "x", it
   102  	// holds that "x < b" is true if and only if "x <= a" is true.
   103  	//
   104  	// The return value is undefined if IsMin(_ *EvalContext) returns true.
   105  	//
   106  	// TODO(#12022): for DTuple, the contract is actually that "x < b" (SQL order,
   107  	// where NULL < x is unknown for all x) is true only if "x <= a"
   108  	// (.Compare/encoding order, where NULL <= x is true for all x) is true. This
   109  	// is okay for now: the returned datum is used only to construct a span, which
   110  	// uses .Compare/encoding order and is guaranteed to be large enough by this
   111  	// weaker contract. The original filter expression is left in place to catch
   112  	// false positives.
   113  	Prev(ctx *EvalContext) (Datum, bool)
   114  
   115  	// IsMin returns true if the datum is equal to the minimum value the datum
   116  	// type can hold.
   117  	IsMin(ctx *EvalContext) bool
   118  
   119  	// Next returns the next datum and true, if one exists, or nil and false
   120  	// otherwise. The next datum satisfies the following definition: if the
   121  	// receiver is "a" and the returned datum is "b", then for every compatible
   122  	// datum "x", it holds that "x > a" is true if and only if "x >= b" is true.
   123  	//
   124  	// The return value is undefined if IsMax(_ *EvalContext) returns true.
   125  	//
   126  	// TODO(#12022): for DTuple, the contract is actually that "x > a" (SQL order,
   127  	// where x > NULL is unknown for all x) is true only if "x >= b"
   128  	// (.Compare/encoding order, where x >= NULL is true for all x) is true. This
   129  	// is okay for now: the returned datum is used only to construct a span, which
   130  	// uses .Compare/encoding order and is guaranteed to be large enough by this
   131  	// weaker contract. The original filter expression is left in place to catch
   132  	// false positives.
   133  	Next(ctx *EvalContext) (Datum, bool)
   134  
   135  	// IsMax returns true if the datum is equal to the maximum value the datum
   136  	// type can hold.
   137  	IsMax(ctx *EvalContext) bool
   138  
   139  	// Max returns the upper value and true, if one exists, otherwise
   140  	// nil and false. Used By Prev().
   141  	Max(ctx *EvalContext) (Datum, bool)
   142  
   143  	// Min returns the lower value, if one exists, otherwise nil and
   144  	// false. Used by Next().
   145  	Min(ctx *EvalContext) (Datum, bool)
   146  
   147  	// Size returns a lower bound on the total size of the receiver in bytes,
   148  	// including memory that is pointed at (even if shared between Datum
   149  	// instances) but excluding allocation overhead.
   150  	//
   151  	// It holds for every Datum d that d.Size().
   152  	Size() uintptr
   153  }
   154  
   155  // Datums is a slice of Datum values.
   156  type Datums []Datum
   157  
   158  // Len returns the number of Datum values.
   159  func (d Datums) Len() int { return len(d) }
   160  
   161  // Format implements the NodeFormatter interface.
   162  func (d *Datums) Format(ctx *FmtCtx) {
   163  	ctx.WriteByte('(')
   164  	for i, v := range *d {
   165  		if i > 0 {
   166  			ctx.WriteString(", ")
   167  		}
   168  		ctx.FormatNode(v)
   169  	}
   170  	ctx.WriteByte(')')
   171  }
   172  
   173  // Compare does a lexicographical comparison and returns -1 if the receiver
   174  // is less than other, 0 if receiver is equal to other and +1 if receiver is
   175  // greater than other.
   176  func (d Datums) Compare(evalCtx *EvalContext, other Datums) int {
   177  	if len(d) == 0 {
   178  		panic(errors.AssertionFailedf("empty Datums being compared to other"))
   179  	}
   180  
   181  	for i := range d {
   182  		if i >= len(other) {
   183  			return 1
   184  		}
   185  
   186  		compareDatum := d[i].Compare(evalCtx, other[i])
   187  		if compareDatum != 0 {
   188  			return compareDatum
   189  		}
   190  	}
   191  
   192  	if len(d) < len(other) {
   193  		return -1
   194  	}
   195  	return 0
   196  }
   197  
   198  // IsDistinctFrom checks to see if two datums are distinct from each other. Any
   199  // change in value is considered distinct, however, a NULL value is NOT
   200  // considered distinct from another NULL value.
   201  func (d Datums) IsDistinctFrom(evalCtx *EvalContext, other Datums) bool {
   202  	if len(d) != len(other) {
   203  		return true
   204  	}
   205  	for i, val := range d {
   206  		if val == DNull {
   207  			if other[i] != DNull {
   208  				return true
   209  			}
   210  		} else {
   211  			if val.Compare(evalCtx, other[i]) != 0 {
   212  				return true
   213  			}
   214  		}
   215  	}
   216  	return false
   217  }
   218  
   219  // CompositeDatum is a Datum that may require composite encoding in
   220  // indexes. Any Datum implementing this interface must also add itself to
   221  // sqlbase/HasCompositeKeyEncoding.
   222  type CompositeDatum interface {
   223  	Datum
   224  	// IsComposite returns true if this datum is not round-tripable in a key
   225  	// encoding.
   226  	IsComposite() bool
   227  }
   228  
   229  // DBool is the boolean Datum.
   230  type DBool bool
   231  
   232  // MakeDBool converts its argument to a *DBool, returning either DBoolTrue or
   233  // DBoolFalse.
   234  func MakeDBool(d DBool) *DBool {
   235  	if d {
   236  		return DBoolTrue
   237  	}
   238  	return DBoolFalse
   239  }
   240  
   241  // MustBeDBool attempts to retrieve a DBool from an Expr, panicking if the
   242  // assertion fails.
   243  func MustBeDBool(e Expr) DBool {
   244  	b, ok := AsDBool(e)
   245  	if !ok {
   246  		panic(errors.AssertionFailedf("expected *DBool, found %T", e))
   247  	}
   248  	return b
   249  }
   250  
   251  // AsDBool attempts to retrieve a *DBool from an Expr, returning a *DBool and
   252  // a flag signifying whether the assertion was successful. The function should
   253  // be used instead of direct type assertions.
   254  func AsDBool(e Expr) (DBool, bool) {
   255  	switch t := e.(type) {
   256  	case *DBool:
   257  		return *t, true
   258  	}
   259  	return false, false
   260  }
   261  
   262  // makeParseError returns a parse error using the provided string and type. An
   263  // optional error can be provided, which will be appended to the end of the
   264  // error string.
   265  func makeParseError(s string, typ *types.T, err error) error {
   266  	if err != nil {
   267  		return pgerror.Wrapf(err, pgcode.InvalidTextRepresentation,
   268  			"could not parse %q as type %s", s, typ)
   269  	}
   270  	return pgerror.Newf(pgcode.InvalidTextRepresentation,
   271  		"could not parse %q as type %s", s, typ)
   272  }
   273  
   274  func makeUnsupportedComparisonMessage(d1, d2 Datum) error {
   275  	return errors.AssertionFailedWithDepthf(1,
   276  		"unsupported comparison: %s to %s", errors.Safe(d1.ResolvedType()), errors.Safe(d2.ResolvedType()))
   277  }
   278  
   279  func isCaseInsensitivePrefix(prefix, s string) bool {
   280  	if len(prefix) > len(s) {
   281  		return false
   282  	}
   283  	return strings.EqualFold(prefix, s[:len(prefix)])
   284  }
   285  
   286  // ParseDBool parses and returns the *DBool Datum value represented by the provided
   287  // string, or an error if parsing is unsuccessful.
   288  // See https://github.com/postgres/postgres/blob/90627cf98a8e7d0531789391fd798c9bfcc3bc1a/src/backend/utils/adt/bool.c#L36
   289  func ParseDBool(s string) (*DBool, error) {
   290  	s = strings.TrimSpace(s)
   291  	if len(s) >= 1 {
   292  		switch s[0] {
   293  		case 't', 'T':
   294  			if isCaseInsensitivePrefix(s, "true") {
   295  				return DBoolTrue, nil
   296  			}
   297  		case 'f', 'F':
   298  			if isCaseInsensitivePrefix(s, "false") {
   299  				return DBoolFalse, nil
   300  			}
   301  		case 'y', 'Y':
   302  			if isCaseInsensitivePrefix(s, "yes") {
   303  				return DBoolTrue, nil
   304  			}
   305  		case 'n', 'N':
   306  			if isCaseInsensitivePrefix(s, "no") {
   307  				return DBoolFalse, nil
   308  			}
   309  		case '1':
   310  			if s == "1" {
   311  				return DBoolTrue, nil
   312  			}
   313  		case '0':
   314  			if s == "0" {
   315  				return DBoolFalse, nil
   316  			}
   317  		case 'o', 'O':
   318  			// Just 'o' is ambiguous between 'on' and 'off'.
   319  			if len(s) > 1 {
   320  				if isCaseInsensitivePrefix(s, "on") {
   321  					return DBoolTrue, nil
   322  				}
   323  				if isCaseInsensitivePrefix(s, "off") {
   324  					return DBoolFalse, nil
   325  				}
   326  			}
   327  		}
   328  	}
   329  	return nil, makeParseError(s, types.Bool, pgerror.New(pgcode.InvalidTextRepresentation, "invalid bool value"))
   330  }
   331  
   332  // ParseDByte parses a string representation of hex encoded binary
   333  // data. It supports both the hex format, with "\x" followed by a
   334  // string of hexadecimal digits (the "\x" prefix occurs just once at
   335  // the beginning), and the escaped format, which supports "\\" and
   336  // octal escapes.
   337  func ParseDByte(s string) (*DBytes, error) {
   338  	res, err := lex.DecodeRawBytesToByteArrayAuto([]byte(s))
   339  	if err != nil {
   340  		return nil, makeParseError(s, types.Bytes, err)
   341  	}
   342  	return NewDBytes(DBytes(res)), nil
   343  }
   344  
   345  // ParseDUuidFromString parses and returns the *DUuid Datum value represented
   346  // by the provided input string, or an error.
   347  func ParseDUuidFromString(s string) (*DUuid, error) {
   348  	uv, err := uuid.FromString(s)
   349  	if err != nil {
   350  		return nil, makeParseError(s, types.Uuid, err)
   351  	}
   352  	return NewDUuid(DUuid{uv}), nil
   353  }
   354  
   355  // ParseDUuidFromBytes parses and returns the *DUuid Datum value represented
   356  // by the provided input bytes, or an error.
   357  func ParseDUuidFromBytes(b []byte) (*DUuid, error) {
   358  	uv, err := uuid.FromBytes(b)
   359  	if err != nil {
   360  		return nil, makeParseError(string(b), types.Uuid, err)
   361  	}
   362  	return NewDUuid(DUuid{uv}), nil
   363  }
   364  
   365  // ParseDIPAddrFromINetString parses and returns the *DIPAddr Datum value
   366  // represented by the provided input INet string, or an error.
   367  func ParseDIPAddrFromINetString(s string) (*DIPAddr, error) {
   368  	var d DIPAddr
   369  	err := ipaddr.ParseINet(s, &d.IPAddr)
   370  	if err != nil {
   371  		return nil, err
   372  	}
   373  	return &d, nil
   374  }
   375  
   376  // GetBool gets DBool or an error (also treats NULL as false, not an error).
   377  func GetBool(d Datum) (DBool, error) {
   378  	if v, ok := d.(*DBool); ok {
   379  		return *v, nil
   380  	}
   381  	if d == DNull {
   382  		return DBool(false), nil
   383  	}
   384  	return false, errors.AssertionFailedf("cannot convert %s to type %s", d.ResolvedType(), types.Bool)
   385  }
   386  
   387  // ResolvedType implements the TypedExpr interface.
   388  func (*DBool) ResolvedType() *types.T {
   389  	return types.Bool
   390  }
   391  
   392  // Compare implements the Datum interface.
   393  func (d *DBool) Compare(ctx *EvalContext, other Datum) int {
   394  	if other == DNull {
   395  		// NULL is less than any non-NULL value.
   396  		return 1
   397  	}
   398  	v, ok := UnwrapDatum(ctx, other).(*DBool)
   399  	if !ok {
   400  		panic(makeUnsupportedComparisonMessage(d, other))
   401  	}
   402  	return CompareBools(bool(*d), bool(*v))
   403  }
   404  
   405  // CompareBools compares the input bools according to the SQL comparison rules.
   406  func CompareBools(d, v bool) int {
   407  	if !d && v {
   408  		return -1
   409  	}
   410  	if d && !v {
   411  		return 1
   412  	}
   413  	return 0
   414  }
   415  
   416  // Prev implements the Datum interface.
   417  func (*DBool) Prev(_ *EvalContext) (Datum, bool) {
   418  	return DBoolFalse, true
   419  }
   420  
   421  // Next implements the Datum interface.
   422  func (*DBool) Next(_ *EvalContext) (Datum, bool) {
   423  	return DBoolTrue, true
   424  }
   425  
   426  // IsMax implements the Datum interface.
   427  func (d *DBool) IsMax(_ *EvalContext) bool {
   428  	return bool(*d)
   429  }
   430  
   431  // IsMin implements the Datum interface.
   432  func (d *DBool) IsMin(_ *EvalContext) bool {
   433  	return !bool(*d)
   434  }
   435  
   436  // Min implements the Datum interface.
   437  func (d *DBool) Min(_ *EvalContext) (Datum, bool) {
   438  	return DBoolFalse, true
   439  }
   440  
   441  // Max implements the Datum interface.
   442  func (d *DBool) Max(_ *EvalContext) (Datum, bool) {
   443  	return DBoolTrue, true
   444  }
   445  
   446  // AmbiguousFormat implements the Datum interface.
   447  func (*DBool) AmbiguousFormat() bool { return false }
   448  
   449  // Format implements the NodeFormatter interface.
   450  func (d *DBool) Format(ctx *FmtCtx) {
   451  	if ctx.HasFlags(fmtPgwireFormat) {
   452  		if bool(*d) {
   453  			ctx.WriteByte('t')
   454  		} else {
   455  			ctx.WriteByte('f')
   456  		}
   457  		return
   458  	}
   459  	ctx.WriteString(strconv.FormatBool(bool(*d)))
   460  }
   461  
   462  // Size implements the Datum interface.
   463  func (d *DBool) Size() uintptr {
   464  	return unsafe.Sizeof(*d)
   465  }
   466  
   467  // DBitArray is the BIT/VARBIT Datum.
   468  type DBitArray struct {
   469  	bitarray.BitArray
   470  }
   471  
   472  // ParseDBitArray parses a string representation of binary digits.
   473  func ParseDBitArray(s string) (*DBitArray, error) {
   474  	var a DBitArray
   475  	var err error
   476  	a.BitArray, err = bitarray.Parse(s)
   477  	if err != nil {
   478  		return nil, err
   479  	}
   480  	return &a, nil
   481  }
   482  
   483  // NewDBitArray returns a DBitArray.
   484  func NewDBitArray(bitLen uint) *DBitArray {
   485  	a := MakeDBitArray(bitLen)
   486  	return &a
   487  }
   488  
   489  // MakeDBitArray returns a DBitArray.
   490  func MakeDBitArray(bitLen uint) DBitArray {
   491  	return DBitArray{BitArray: bitarray.MakeZeroBitArray(bitLen)}
   492  }
   493  
   494  // MustBeDBitArray attempts to retrieve a DBitArray from an Expr, panicking if the
   495  // assertion fails.
   496  func MustBeDBitArray(e Expr) *DBitArray {
   497  	b, ok := AsDBitArray(e)
   498  	if !ok {
   499  		panic(errors.AssertionFailedf("expected *DBitArray, found %T", e))
   500  	}
   501  	return b
   502  }
   503  
   504  // AsDBitArray attempts to retrieve a *DBitArray from an Expr, returning a *DBitArray and
   505  // a flag signifying whether the assertion was successful. The function should
   506  // be used instead of direct type assertions.
   507  func AsDBitArray(e Expr) (*DBitArray, bool) {
   508  	switch t := e.(type) {
   509  	case *DBitArray:
   510  		return t, true
   511  	}
   512  	return nil, false
   513  }
   514  
   515  var errCannotCastNegativeIntToBitArray = pgerror.Newf(pgcode.CannotCoerce,
   516  	"cannot cast negative integer to bit varying with unbounded width")
   517  
   518  // NewDBitArrayFromInt creates a bit array from the specified integer
   519  // at the specified width.
   520  // If the width is zero, only positive integers can be converted.
   521  // If the width is nonzero, the value is truncated to that width.
   522  // Negative values are encoded using two's complement.
   523  func NewDBitArrayFromInt(i int64, width uint) (*DBitArray, error) {
   524  	if width == 0 && i < 0 {
   525  		return nil, errCannotCastNegativeIntToBitArray
   526  	}
   527  	return &DBitArray{
   528  		BitArray: bitarray.MakeBitArrayFromInt64(width, i, 64),
   529  	}, nil
   530  }
   531  
   532  // AsDInt computes the integer value of the given bit array.
   533  // The value is assumed to be encoded using two's complement.
   534  // The result is truncated to the given integer number of bits,
   535  // if specified.
   536  // The given width must be 64 or smaller. The results are undefined
   537  // if n is greater than 64.
   538  func (d *DBitArray) AsDInt(n uint) *DInt {
   539  	if n == 0 {
   540  		n = 64
   541  	}
   542  	return NewDInt(DInt(d.BitArray.AsInt64(n)))
   543  }
   544  
   545  // ResolvedType implements the TypedExpr interface.
   546  func (*DBitArray) ResolvedType() *types.T {
   547  	return types.VarBit
   548  }
   549  
   550  // Compare implements the Datum interface.
   551  func (d *DBitArray) Compare(ctx *EvalContext, other Datum) int {
   552  	if other == DNull {
   553  		// NULL is less than any non-NULL value.
   554  		return 1
   555  	}
   556  	v, ok := UnwrapDatum(ctx, other).(*DBitArray)
   557  	if !ok {
   558  		panic(makeUnsupportedComparisonMessage(d, other))
   559  	}
   560  	return bitarray.Compare(d.BitArray, v.BitArray)
   561  }
   562  
   563  // Prev implements the Datum interface.
   564  func (d *DBitArray) Prev(_ *EvalContext) (Datum, bool) {
   565  	return nil, false
   566  }
   567  
   568  // Next implements the Datum interface.
   569  func (d *DBitArray) Next(_ *EvalContext) (Datum, bool) {
   570  	a := bitarray.Next(d.BitArray)
   571  	return &DBitArray{BitArray: a}, true
   572  }
   573  
   574  // IsMax implements the Datum interface.
   575  func (d *DBitArray) IsMax(_ *EvalContext) bool {
   576  	return false
   577  }
   578  
   579  // IsMin implements the Datum interface.
   580  func (d *DBitArray) IsMin(_ *EvalContext) bool {
   581  	return d.BitArray.IsEmpty()
   582  }
   583  
   584  var bitArrayZero = NewDBitArray(0)
   585  
   586  // Min implements the Datum interface.
   587  func (d *DBitArray) Min(_ *EvalContext) (Datum, bool) {
   588  	return bitArrayZero, true
   589  }
   590  
   591  // Max implements the Datum interface.
   592  func (d *DBitArray) Max(_ *EvalContext) (Datum, bool) {
   593  	return nil, false
   594  }
   595  
   596  // AmbiguousFormat implements the Datum interface.
   597  func (*DBitArray) AmbiguousFormat() bool { return false }
   598  
   599  // Format implements the NodeFormatter interface.
   600  func (d *DBitArray) Format(ctx *FmtCtx) {
   601  	f := ctx.flags
   602  	if f.HasFlags(fmtPgwireFormat) {
   603  		d.BitArray.Format(&ctx.Buffer)
   604  	} else {
   605  		withQuotes := !f.HasFlags(FmtFlags(lex.EncBareStrings))
   606  		if withQuotes {
   607  			ctx.WriteString("B'")
   608  		}
   609  		d.BitArray.Format(&ctx.Buffer)
   610  		if withQuotes {
   611  			ctx.WriteByte('\'')
   612  		}
   613  	}
   614  }
   615  
   616  // Size implements the Datum interface.
   617  func (d *DBitArray) Size() uintptr {
   618  	return d.BitArray.Sizeof()
   619  }
   620  
   621  // DInt is the int Datum.
   622  type DInt int64
   623  
   624  // NewDInt is a helper routine to create a *DInt initialized from its argument.
   625  func NewDInt(d DInt) *DInt {
   626  	return &d
   627  }
   628  
   629  // ParseDInt parses and returns the *DInt Datum value represented by the provided
   630  // string, or an error if parsing is unsuccessful.
   631  func ParseDInt(s string) (*DInt, error) {
   632  	i, err := strconv.ParseInt(s, 0, 64)
   633  	if err != nil {
   634  		return nil, makeParseError(s, types.Int, err)
   635  	}
   636  	return NewDInt(DInt(i)), nil
   637  }
   638  
   639  // AsDInt attempts to retrieve a DInt from an Expr, returning a DInt and
   640  // a flag signifying whether the assertion was successful. The function should
   641  // be used instead of direct type assertions wherever a *DInt wrapped by a
   642  // *DOidWrapper is possible.
   643  func AsDInt(e Expr) (DInt, bool) {
   644  	switch t := e.(type) {
   645  	case *DInt:
   646  		return *t, true
   647  	case *DOidWrapper:
   648  		return AsDInt(t.Wrapped)
   649  	}
   650  	return 0, false
   651  }
   652  
   653  // MustBeDInt attempts to retrieve a DInt from an Expr, panicking if the
   654  // assertion fails.
   655  func MustBeDInt(e Expr) DInt {
   656  	i, ok := AsDInt(e)
   657  	if !ok {
   658  		panic(errors.AssertionFailedf("expected *DInt, found %T", e))
   659  	}
   660  	return i
   661  }
   662  
   663  // ResolvedType implements the TypedExpr interface.
   664  func (*DInt) ResolvedType() *types.T {
   665  	return types.Int
   666  }
   667  
   668  // Compare implements the Datum interface.
   669  func (d *DInt) Compare(ctx *EvalContext, other Datum) int {
   670  	if other == DNull {
   671  		// NULL is less than any non-NULL value.
   672  		return 1
   673  	}
   674  	var v DInt
   675  	switch t := UnwrapDatum(ctx, other).(type) {
   676  	case *DInt:
   677  		v = *t
   678  	case *DFloat, *DDecimal:
   679  		return -t.Compare(ctx, d)
   680  	default:
   681  		panic(makeUnsupportedComparisonMessage(d, other))
   682  	}
   683  	if *d < v {
   684  		return -1
   685  	}
   686  	if *d > v {
   687  		return 1
   688  	}
   689  	return 0
   690  }
   691  
   692  // Prev implements the Datum interface.
   693  func (d *DInt) Prev(_ *EvalContext) (Datum, bool) {
   694  	return NewDInt(*d - 1), true
   695  }
   696  
   697  // Next implements the Datum interface.
   698  func (d *DInt) Next(_ *EvalContext) (Datum, bool) {
   699  	return NewDInt(*d + 1), true
   700  }
   701  
   702  // IsMax implements the Datum interface.
   703  func (d *DInt) IsMax(_ *EvalContext) bool {
   704  	return *d == math.MaxInt64
   705  }
   706  
   707  // IsMin implements the Datum interface.
   708  func (d *DInt) IsMin(_ *EvalContext) bool {
   709  	return *d == math.MinInt64
   710  }
   711  
   712  var dMaxInt = NewDInt(math.MaxInt64)
   713  var dMinInt = NewDInt(math.MinInt64)
   714  
   715  // Max implements the Datum interface.
   716  func (d *DInt) Max(_ *EvalContext) (Datum, bool) {
   717  	return dMaxInt, true
   718  }
   719  
   720  // Min implements the Datum interface.
   721  func (d *DInt) Min(_ *EvalContext) (Datum, bool) {
   722  	return dMinInt, true
   723  }
   724  
   725  // AmbiguousFormat implements the Datum interface.
   726  func (*DInt) AmbiguousFormat() bool { return true }
   727  
   728  // Format implements the NodeFormatter interface.
   729  func (d *DInt) Format(ctx *FmtCtx) {
   730  	// If the number is negative, we need to use parens or the `:::INT` type hint
   731  	// will take precedence over the negation sign.
   732  	disambiguate := ctx.flags.HasFlags(fmtDisambiguateDatumTypes)
   733  	parsable := ctx.flags.HasFlags(FmtParsableNumerics)
   734  	needParens := (disambiguate || parsable) && *d < 0
   735  	if needParens {
   736  		ctx.WriteByte('(')
   737  	}
   738  	ctx.WriteString(strconv.FormatInt(int64(*d), 10))
   739  	if needParens {
   740  		ctx.WriteByte(')')
   741  	}
   742  }
   743  
   744  // Size implements the Datum interface.
   745  func (d *DInt) Size() uintptr {
   746  	return unsafe.Sizeof(*d)
   747  }
   748  
   749  // DFloat is the float Datum.
   750  type DFloat float64
   751  
   752  // MustBeDFloat attempts to retrieve a DFloat from an Expr, panicking if the
   753  // assertion fails.
   754  func MustBeDFloat(e Expr) DFloat {
   755  	switch t := e.(type) {
   756  	case *DFloat:
   757  		return *t
   758  	}
   759  	panic(errors.AssertionFailedf("expected *DFloat, found %T", e))
   760  }
   761  
   762  // NewDFloat is a helper routine to create a *DFloat initialized from its
   763  // argument.
   764  func NewDFloat(d DFloat) *DFloat {
   765  	return &d
   766  }
   767  
   768  // ParseDFloat parses and returns the *DFloat Datum value represented by the provided
   769  // string, or an error if parsing is unsuccessful.
   770  func ParseDFloat(s string) (*DFloat, error) {
   771  	f, err := strconv.ParseFloat(s, 64)
   772  	if err != nil {
   773  		return nil, makeParseError(s, types.Float, err)
   774  	}
   775  	return NewDFloat(DFloat(f)), nil
   776  }
   777  
   778  // ResolvedType implements the TypedExpr interface.
   779  func (*DFloat) ResolvedType() *types.T {
   780  	return types.Float
   781  }
   782  
   783  // Compare implements the Datum interface.
   784  func (d *DFloat) Compare(ctx *EvalContext, other Datum) int {
   785  	if other == DNull {
   786  		// NULL is less than any non-NULL value.
   787  		return 1
   788  	}
   789  	var v DFloat
   790  	switch t := UnwrapDatum(ctx, other).(type) {
   791  	case *DFloat:
   792  		v = *t
   793  	case *DInt:
   794  		v = DFloat(MustBeDInt(t))
   795  	case *DDecimal:
   796  		return -t.Compare(ctx, d)
   797  	default:
   798  		panic(makeUnsupportedComparisonMessage(d, other))
   799  	}
   800  	if *d < v {
   801  		return -1
   802  	}
   803  	if *d > v {
   804  		return 1
   805  	}
   806  	// NaN sorts before non-NaN (#10109).
   807  	if *d == v {
   808  		return 0
   809  	}
   810  	if math.IsNaN(float64(*d)) {
   811  		if math.IsNaN(float64(v)) {
   812  			return 0
   813  		}
   814  		return -1
   815  	}
   816  	return 1
   817  }
   818  
   819  // Prev implements the Datum interface.
   820  func (d *DFloat) Prev(_ *EvalContext) (Datum, bool) {
   821  	f := float64(*d)
   822  	if math.IsNaN(f) {
   823  		return nil, false
   824  	}
   825  	if f == math.Inf(-1) {
   826  		return dNaNFloat, true
   827  	}
   828  	return NewDFloat(DFloat(math.Nextafter(f, math.Inf(-1)))), true
   829  }
   830  
   831  // Next implements the Datum interface.
   832  func (d *DFloat) Next(_ *EvalContext) (Datum, bool) {
   833  	f := float64(*d)
   834  	if math.IsNaN(f) {
   835  		return dNegInfFloat, true
   836  	}
   837  	if f == math.Inf(+1) {
   838  		return nil, false
   839  	}
   840  	return NewDFloat(DFloat(math.Nextafter(f, math.Inf(+1)))), true
   841  }
   842  
   843  var dZeroFloat = NewDFloat(0.0)
   844  var dPosInfFloat = NewDFloat(DFloat(math.Inf(+1)))
   845  var dNegInfFloat = NewDFloat(DFloat(math.Inf(-1)))
   846  var dNaNFloat = NewDFloat(DFloat(math.NaN()))
   847  
   848  // IsMax implements the Datum interface.
   849  func (d *DFloat) IsMax(_ *EvalContext) bool {
   850  	return *d == *dPosInfFloat
   851  }
   852  
   853  // IsMin implements the Datum interface.
   854  func (d *DFloat) IsMin(_ *EvalContext) bool {
   855  	return math.IsNaN(float64(*d))
   856  }
   857  
   858  // Max implements the Datum interface.
   859  func (d *DFloat) Max(_ *EvalContext) (Datum, bool) {
   860  	return dPosInfFloat, true
   861  }
   862  
   863  // Min implements the Datum interface.
   864  func (d *DFloat) Min(_ *EvalContext) (Datum, bool) {
   865  	return dNaNFloat, true
   866  }
   867  
   868  // AmbiguousFormat implements the Datum interface.
   869  func (*DFloat) AmbiguousFormat() bool { return true }
   870  
   871  // Format implements the NodeFormatter interface.
   872  func (d *DFloat) Format(ctx *FmtCtx) {
   873  	fl := float64(*d)
   874  
   875  	disambiguate := ctx.flags.HasFlags(fmtDisambiguateDatumTypes)
   876  	parsable := ctx.flags.HasFlags(FmtParsableNumerics)
   877  	quote := parsable && (math.IsNaN(fl) || math.IsInf(fl, 0))
   878  	// We need to use Signbit here and not just fl < 0 because of -0.
   879  	needParens := !quote && (disambiguate || parsable) && math.Signbit(fl)
   880  	// If the number is negative, we need to use parens or the `:::INT` type hint
   881  	// will take precedence over the negation sign.
   882  	if quote {
   883  		ctx.WriteByte('\'')
   884  	} else if needParens {
   885  		ctx.WriteByte('(')
   886  	}
   887  	if _, frac := math.Modf(fl); frac == 0 && -1000000 < *d && *d < 1000000 {
   888  		// d is a small whole number. Ensure it is printed using a decimal point.
   889  		ctx.Printf("%.1f", fl)
   890  	} else {
   891  		ctx.Printf("%g", fl)
   892  	}
   893  	if quote {
   894  		ctx.WriteByte('\'')
   895  	} else if needParens {
   896  		ctx.WriteByte(')')
   897  	}
   898  }
   899  
   900  // Size implements the Datum interface.
   901  func (d *DFloat) Size() uintptr {
   902  	return unsafe.Sizeof(*d)
   903  }
   904  
   905  // IsComposite implements the CompositeDatum interface.
   906  func (d *DFloat) IsComposite() bool {
   907  	// -0 is composite.
   908  	return math.Float64bits(float64(*d)) == 1<<63
   909  }
   910  
   911  // DDecimal is the decimal Datum.
   912  type DDecimal struct {
   913  	apd.Decimal
   914  }
   915  
   916  // MustBeDDecimal attempts to retrieve a DDecimal from an Expr, panicking if the
   917  // assertion fails.
   918  func MustBeDDecimal(e Expr) DDecimal {
   919  	switch t := e.(type) {
   920  	case *DDecimal:
   921  		return *t
   922  	}
   923  	panic(errors.AssertionFailedf("expected *DDecimal, found %T", e))
   924  }
   925  
   926  // ParseDDecimal parses and returns the *DDecimal Datum value represented by the
   927  // provided string, or an error if parsing is unsuccessful.
   928  func ParseDDecimal(s string) (*DDecimal, error) {
   929  	dd := &DDecimal{}
   930  	err := dd.SetString(s)
   931  	return dd, err
   932  }
   933  
   934  // SetString sets d to s. Any non-standard NaN values are converted to a
   935  // normal NaN. Any negative zero is converted to positive.
   936  func (d *DDecimal) SetString(s string) error {
   937  	// ExactCtx should be able to handle any decimal, but if there is any rounding
   938  	// or other inexact conversion, it will result in an error.
   939  	//_, res, err := HighPrecisionCtx.SetString(&d.Decimal, s)
   940  	_, res, err := ExactCtx.SetString(&d.Decimal, s)
   941  	if res != 0 || err != nil {
   942  		return makeParseError(s, types.Decimal, nil)
   943  	}
   944  	switch d.Form {
   945  	case apd.NaNSignaling:
   946  		d.Form = apd.NaN
   947  		d.Negative = false
   948  	case apd.NaN:
   949  		d.Negative = false
   950  	case apd.Finite:
   951  		if d.IsZero() && d.Negative {
   952  			d.Negative = false
   953  		}
   954  	}
   955  	return nil
   956  }
   957  
   958  // ResolvedType implements the TypedExpr interface.
   959  func (*DDecimal) ResolvedType() *types.T {
   960  	return types.Decimal
   961  }
   962  
   963  // Compare implements the Datum interface.
   964  func (d *DDecimal) Compare(ctx *EvalContext, other Datum) int {
   965  	if other == DNull {
   966  		// NULL is less than any non-NULL value.
   967  		return 1
   968  	}
   969  	v := ctx.getTmpDec()
   970  	switch t := UnwrapDatum(ctx, other).(type) {
   971  	case *DDecimal:
   972  		v = &t.Decimal
   973  	case *DInt:
   974  		v.SetFinite(int64(*t), 0)
   975  	case *DFloat:
   976  		if _, err := v.SetFloat64(float64(*t)); err != nil {
   977  			panic(errors.NewAssertionErrorWithWrappedErrf(err, "decimal compare, unexpected error"))
   978  		}
   979  	default:
   980  		panic(makeUnsupportedComparisonMessage(d, other))
   981  	}
   982  	return CompareDecimals(&d.Decimal, v)
   983  }
   984  
   985  // CompareDecimals compares 2 apd.Decimals according to the SQL comparison
   986  // rules, making sure that NaNs sort first.
   987  func CompareDecimals(d *apd.Decimal, v *apd.Decimal) int {
   988  	// NaNs sort first in SQL.
   989  	if dn, vn := d.Form == apd.NaN, v.Form == apd.NaN; dn && !vn {
   990  		return -1
   991  	} else if !dn && vn {
   992  		return 1
   993  	} else if dn && vn {
   994  		return 0
   995  	}
   996  	return d.Cmp(v)
   997  }
   998  
   999  // Prev implements the Datum interface.
  1000  func (d *DDecimal) Prev(_ *EvalContext) (Datum, bool) {
  1001  	return nil, false
  1002  }
  1003  
  1004  // Next implements the Datum interface.
  1005  func (d *DDecimal) Next(_ *EvalContext) (Datum, bool) {
  1006  	return nil, false
  1007  }
  1008  
  1009  var dZeroDecimal = &DDecimal{Decimal: apd.Decimal{}}
  1010  var dPosInfDecimal = &DDecimal{Decimal: apd.Decimal{Form: apd.Infinite, Negative: false}}
  1011  var dNaNDecimal = &DDecimal{Decimal: apd.Decimal{Form: apd.NaN}}
  1012  
  1013  // IsMax implements the Datum interface.
  1014  func (d *DDecimal) IsMax(_ *EvalContext) bool {
  1015  	return d.Form == apd.Infinite && !d.Negative
  1016  }
  1017  
  1018  // IsMin implements the Datum interface.
  1019  func (d *DDecimal) IsMin(_ *EvalContext) bool {
  1020  	return d.Form == apd.NaN
  1021  }
  1022  
  1023  // Max implements the Datum interface.
  1024  func (d *DDecimal) Max(_ *EvalContext) (Datum, bool) {
  1025  	return dPosInfDecimal, true
  1026  }
  1027  
  1028  // Min implements the Datum interface.
  1029  func (d *DDecimal) Min(_ *EvalContext) (Datum, bool) {
  1030  	return dNaNDecimal, true
  1031  }
  1032  
  1033  // AmbiguousFormat implements the Datum interface.
  1034  func (*DDecimal) AmbiguousFormat() bool { return true }
  1035  
  1036  // Format implements the NodeFormatter interface.
  1037  func (d *DDecimal) Format(ctx *FmtCtx) {
  1038  	// If the number is negative, we need to use parens or the `:::INT` type hint
  1039  	// will take precedence over the negation sign.
  1040  	disambiguate := ctx.flags.HasFlags(fmtDisambiguateDatumTypes)
  1041  	parsable := ctx.flags.HasFlags(FmtParsableNumerics)
  1042  	quote := parsable && d.Decimal.Form != apd.Finite
  1043  	needParens := !quote && (disambiguate || parsable) && d.Negative
  1044  	if needParens {
  1045  		ctx.WriteByte('(')
  1046  	}
  1047  	if quote {
  1048  		ctx.WriteByte('\'')
  1049  	}
  1050  	ctx.WriteString(d.Decimal.String())
  1051  	if quote {
  1052  		ctx.WriteByte('\'')
  1053  	}
  1054  	if needParens {
  1055  		ctx.WriteByte(')')
  1056  	}
  1057  }
  1058  
  1059  // SizeOfDecimal returns the size in bytes of an apd.Decimal.
  1060  func SizeOfDecimal(d apd.Decimal) uintptr {
  1061  	return uintptr(cap(d.Coeff.Bits())) * unsafe.Sizeof(big.Word(0))
  1062  }
  1063  
  1064  // Size implements the Datum interface.
  1065  func (d *DDecimal) Size() uintptr {
  1066  	return unsafe.Sizeof(*d) + SizeOfDecimal(d.Decimal)
  1067  }
  1068  
  1069  var (
  1070  	decimalNegativeZero = &apd.Decimal{Negative: true}
  1071  	bigTen              = big.NewInt(10)
  1072  )
  1073  
  1074  // IsComposite implements the CompositeDatum interface.
  1075  func (d *DDecimal) IsComposite() bool {
  1076  	// -0 is composite.
  1077  	if d.Decimal.CmpTotal(decimalNegativeZero) == 0 {
  1078  		return true
  1079  	}
  1080  
  1081  	// Check if d is divisible by 10.
  1082  	var r big.Int
  1083  	r.Rem(&d.Decimal.Coeff, bigTen)
  1084  	return r.Sign() == 0
  1085  }
  1086  
  1087  // DString is the string Datum.
  1088  type DString string
  1089  
  1090  // NewDString is a helper routine to create a *DString initialized from its
  1091  // argument.
  1092  func NewDString(d string) *DString {
  1093  	r := DString(d)
  1094  	return &r
  1095  }
  1096  
  1097  // AsDString attempts to retrieve a DString from an Expr, returning a DString and
  1098  // a flag signifying whether the assertion was successful. The function should
  1099  // be used instead of direct type assertions wherever a *DString wrapped by a
  1100  // *DOidWrapper is possible.
  1101  func AsDString(e Expr) (DString, bool) {
  1102  	switch t := e.(type) {
  1103  	case *DString:
  1104  		return *t, true
  1105  	case *DOidWrapper:
  1106  		return AsDString(t.Wrapped)
  1107  	}
  1108  	return "", false
  1109  }
  1110  
  1111  // MustBeDString attempts to retrieve a DString from an Expr, panicking if the
  1112  // assertion fails.
  1113  func MustBeDString(e Expr) DString {
  1114  	i, ok := AsDString(e)
  1115  	if !ok {
  1116  		panic(errors.AssertionFailedf("expected *DString, found %T", e))
  1117  	}
  1118  	return i
  1119  }
  1120  
  1121  // ResolvedType implements the TypedExpr interface.
  1122  func (*DString) ResolvedType() *types.T {
  1123  	return types.String
  1124  }
  1125  
  1126  // Compare implements the Datum interface.
  1127  func (d *DString) Compare(ctx *EvalContext, other Datum) int {
  1128  	if other == DNull {
  1129  		// NULL is less than any non-NULL value.
  1130  		return 1
  1131  	}
  1132  	v, ok := UnwrapDatum(ctx, other).(*DString)
  1133  	if !ok {
  1134  		panic(makeUnsupportedComparisonMessage(d, other))
  1135  	}
  1136  	if *d < *v {
  1137  		return -1
  1138  	}
  1139  	if *d > *v {
  1140  		return 1
  1141  	}
  1142  	return 0
  1143  }
  1144  
  1145  // Prev implements the Datum interface.
  1146  func (d *DString) Prev(_ *EvalContext) (Datum, bool) {
  1147  	return nil, false
  1148  }
  1149  
  1150  // Next implements the Datum interface.
  1151  func (d *DString) Next(_ *EvalContext) (Datum, bool) {
  1152  	return NewDString(string(roachpb.Key(*d).Next())), true
  1153  }
  1154  
  1155  // IsMax implements the Datum interface.
  1156  func (*DString) IsMax(_ *EvalContext) bool {
  1157  	return false
  1158  }
  1159  
  1160  // IsMin implements the Datum interface.
  1161  func (d *DString) IsMin(_ *EvalContext) bool {
  1162  	return len(*d) == 0
  1163  }
  1164  
  1165  var dEmptyString = NewDString("")
  1166  
  1167  // Min implements the Datum interface.
  1168  func (d *DString) Min(_ *EvalContext) (Datum, bool) {
  1169  	return dEmptyString, true
  1170  }
  1171  
  1172  // Max implements the Datum interface.
  1173  func (d *DString) Max(_ *EvalContext) (Datum, bool) {
  1174  	return nil, false
  1175  }
  1176  
  1177  // AmbiguousFormat implements the Datum interface.
  1178  func (*DString) AmbiguousFormat() bool { return true }
  1179  
  1180  // Format implements the NodeFormatter interface.
  1181  func (d *DString) Format(ctx *FmtCtx) {
  1182  	buf, f := &ctx.Buffer, ctx.flags
  1183  	if f.HasFlags(fmtRawStrings) {
  1184  		buf.WriteString(string(*d))
  1185  	} else {
  1186  		lex.EncodeSQLStringWithFlags(buf, string(*d), f.EncodeFlags())
  1187  	}
  1188  }
  1189  
  1190  // Size implements the Datum interface.
  1191  func (d *DString) Size() uintptr {
  1192  	return unsafe.Sizeof(*d) + uintptr(len(*d))
  1193  }
  1194  
  1195  // DCollatedString is the Datum for strings with a locale. The struct members
  1196  // are intended to be immutable.
  1197  type DCollatedString struct {
  1198  	Contents string
  1199  	Locale   string
  1200  	// Key is the collation key.
  1201  	Key []byte
  1202  }
  1203  
  1204  // CollationEnvironment stores the state needed by NewDCollatedString to
  1205  // construct collation keys efficiently.
  1206  type CollationEnvironment struct {
  1207  	cache  map[string]collationEnvironmentCacheEntry
  1208  	buffer *collate.Buffer
  1209  }
  1210  
  1211  type collationEnvironmentCacheEntry struct {
  1212  	// locale is interned.
  1213  	locale string
  1214  	// collator is an expensive factory.
  1215  	collator *collate.Collator
  1216  }
  1217  
  1218  func (env *CollationEnvironment) getCacheEntry(
  1219  	locale string,
  1220  ) (collationEnvironmentCacheEntry, error) {
  1221  	entry, ok := env.cache[locale]
  1222  	if !ok {
  1223  		if env.cache == nil {
  1224  			env.cache = make(map[string]collationEnvironmentCacheEntry)
  1225  		}
  1226  		tag, err := language.Parse(locale)
  1227  		if err != nil {
  1228  			err = errors.NewAssertionErrorWithWrappedErrf(err, "failed to parse locale %q", locale)
  1229  			return collationEnvironmentCacheEntry{}, err
  1230  		}
  1231  
  1232  		entry = collationEnvironmentCacheEntry{locale, collate.New(tag)}
  1233  		env.cache[locale] = entry
  1234  	}
  1235  	return entry, nil
  1236  }
  1237  
  1238  // NewDCollatedString is a helper routine to create a *DCollatedString. Panics
  1239  // if locale is invalid. Not safe for concurrent use.
  1240  func NewDCollatedString(
  1241  	contents string, locale string, env *CollationEnvironment,
  1242  ) (*DCollatedString, error) {
  1243  	entry, err := env.getCacheEntry(locale)
  1244  	if err != nil {
  1245  		return nil, err
  1246  	}
  1247  	if env.buffer == nil {
  1248  		env.buffer = &collate.Buffer{}
  1249  	}
  1250  	key := entry.collator.KeyFromString(env.buffer, contents)
  1251  	d := DCollatedString{contents, entry.locale, make([]byte, len(key))}
  1252  	copy(d.Key, key)
  1253  	env.buffer.Reset()
  1254  	return &d, nil
  1255  }
  1256  
  1257  // AmbiguousFormat implements the Datum interface.
  1258  func (*DCollatedString) AmbiguousFormat() bool { return false }
  1259  
  1260  // Format implements the NodeFormatter interface.
  1261  func (d *DCollatedString) Format(ctx *FmtCtx) {
  1262  	lex.EncodeSQLString(&ctx.Buffer, d.Contents)
  1263  	ctx.WriteString(" COLLATE ")
  1264  	lex.EncodeLocaleName(&ctx.Buffer, d.Locale)
  1265  }
  1266  
  1267  // ResolvedType implements the TypedExpr interface.
  1268  func (d *DCollatedString) ResolvedType() *types.T {
  1269  	return types.MakeCollatedString(types.String, d.Locale)
  1270  }
  1271  
  1272  // Compare implements the Datum interface.
  1273  func (d *DCollatedString) Compare(ctx *EvalContext, other Datum) int {
  1274  	if other == DNull {
  1275  		// NULL is less than any non-NULL value.
  1276  		return 1
  1277  	}
  1278  	v, ok := UnwrapDatum(ctx, other).(*DCollatedString)
  1279  	if !ok || d.Locale != v.Locale {
  1280  		panic(makeUnsupportedComparisonMessage(d, other))
  1281  	}
  1282  	return bytes.Compare(d.Key, v.Key)
  1283  }
  1284  
  1285  // Prev implements the Datum interface.
  1286  func (d *DCollatedString) Prev(_ *EvalContext) (Datum, bool) {
  1287  	return nil, false
  1288  }
  1289  
  1290  // Next implements the Datum interface.
  1291  func (d *DCollatedString) Next(_ *EvalContext) (Datum, bool) {
  1292  	return nil, false
  1293  }
  1294  
  1295  // IsMax implements the Datum interface.
  1296  func (*DCollatedString) IsMax(_ *EvalContext) bool {
  1297  	return false
  1298  }
  1299  
  1300  // IsMin implements the Datum interface.
  1301  func (d *DCollatedString) IsMin(_ *EvalContext) bool {
  1302  	return d.Contents == ""
  1303  }
  1304  
  1305  // Min implements the Datum interface.
  1306  func (d *DCollatedString) Min(_ *EvalContext) (Datum, bool) {
  1307  	return &DCollatedString{"", d.Locale, nil}, true
  1308  }
  1309  
  1310  // Max implements the Datum interface.
  1311  func (d *DCollatedString) Max(_ *EvalContext) (Datum, bool) {
  1312  	return nil, false
  1313  }
  1314  
  1315  // Size implements the Datum interface.
  1316  func (d *DCollatedString) Size() uintptr {
  1317  	return unsafe.Sizeof(*d) + uintptr(len(d.Contents)) + uintptr(len(d.Locale)) + uintptr(len(d.Key))
  1318  }
  1319  
  1320  // IsComposite implements the CompositeDatum interface.
  1321  func (d *DCollatedString) IsComposite() bool {
  1322  	return true
  1323  }
  1324  
  1325  // DBytes is the bytes Datum. The underlying type is a string because we want
  1326  // the immutability, but this may contain arbitrary bytes.
  1327  type DBytes string
  1328  
  1329  // NewDBytes is a helper routine to create a *DBytes initialized from its
  1330  // argument.
  1331  func NewDBytes(d DBytes) *DBytes {
  1332  	return &d
  1333  }
  1334  
  1335  // MustBeDBytes attempts to convert an Expr into a DBytes, panicking if unsuccessful.
  1336  func MustBeDBytes(e Expr) DBytes {
  1337  	i, ok := AsDBytes(e)
  1338  	if !ok {
  1339  		panic(errors.AssertionFailedf("expected *DBytes, found %T", e))
  1340  	}
  1341  	return i
  1342  }
  1343  
  1344  // AsDBytes attempts to convert an Expr into a DBytes, returning a flag indicating
  1345  // whether it was successful.
  1346  func AsDBytes(e Expr) (DBytes, bool) {
  1347  	switch t := e.(type) {
  1348  	case *DBytes:
  1349  		return *t, true
  1350  	}
  1351  	return "", false
  1352  }
  1353  
  1354  // ResolvedType implements the TypedExpr interface.
  1355  func (*DBytes) ResolvedType() *types.T {
  1356  	return types.Bytes
  1357  }
  1358  
  1359  // Compare implements the Datum interface.
  1360  func (d *DBytes) Compare(ctx *EvalContext, other Datum) int {
  1361  	if other == DNull {
  1362  		// NULL is less than any non-NULL value.
  1363  		return 1
  1364  	}
  1365  	v, ok := UnwrapDatum(ctx, other).(*DBytes)
  1366  	if !ok {
  1367  		panic(makeUnsupportedComparisonMessage(d, other))
  1368  	}
  1369  	if *d < *v {
  1370  		return -1
  1371  	}
  1372  	if *d > *v {
  1373  		return 1
  1374  	}
  1375  	return 0
  1376  }
  1377  
  1378  // Prev implements the Datum interface.
  1379  func (d *DBytes) Prev(_ *EvalContext) (Datum, bool) {
  1380  	return nil, false
  1381  }
  1382  
  1383  // Next implements the Datum interface.
  1384  func (d *DBytes) Next(_ *EvalContext) (Datum, bool) {
  1385  	return NewDBytes(DBytes(roachpb.Key(*d).Next())), true
  1386  }
  1387  
  1388  // IsMax implements the Datum interface.
  1389  func (*DBytes) IsMax(_ *EvalContext) bool {
  1390  	return false
  1391  }
  1392  
  1393  // IsMin implements the Datum interface.
  1394  func (d *DBytes) IsMin(_ *EvalContext) bool {
  1395  	return len(*d) == 0
  1396  }
  1397  
  1398  var dEmptyBytes = NewDBytes(DBytes(""))
  1399  
  1400  // Min implements the Datum interface.
  1401  func (d *DBytes) Min(_ *EvalContext) (Datum, bool) {
  1402  	return dEmptyBytes, true
  1403  }
  1404  
  1405  // Max implements the Datum interface.
  1406  func (d *DBytes) Max(_ *EvalContext) (Datum, bool) {
  1407  	return nil, false
  1408  }
  1409  
  1410  // AmbiguousFormat implements the Datum interface.
  1411  func (*DBytes) AmbiguousFormat() bool { return true }
  1412  
  1413  func writeAsHexString(ctx *FmtCtx, d *DBytes) {
  1414  	b := string(*d)
  1415  	for i := 0; i < len(b); i++ {
  1416  		ctx.Write(stringencoding.RawHexMap[b[i]])
  1417  	}
  1418  }
  1419  
  1420  // Format implements the NodeFormatter interface.
  1421  func (d *DBytes) Format(ctx *FmtCtx) {
  1422  	f := ctx.flags
  1423  	if f.HasFlags(fmtPgwireFormat) {
  1424  		ctx.WriteString(`"\\x`)
  1425  		writeAsHexString(ctx, d)
  1426  		ctx.WriteString(`"`)
  1427  	} else {
  1428  		withQuotes := !f.HasFlags(FmtFlags(lex.EncBareStrings))
  1429  		if withQuotes {
  1430  			if f.HasFlags(fmtFormatByteLiterals) {
  1431  				ctx.WriteByte('b')
  1432  			}
  1433  			ctx.WriteByte('\'')
  1434  		}
  1435  		ctx.WriteString("\\x")
  1436  		writeAsHexString(ctx, d)
  1437  		if withQuotes {
  1438  			ctx.WriteByte('\'')
  1439  		}
  1440  	}
  1441  }
  1442  
  1443  // Size implements the Datum interface.
  1444  func (d *DBytes) Size() uintptr {
  1445  	return unsafe.Sizeof(*d) + uintptr(len(*d))
  1446  }
  1447  
  1448  // DUuid is the UUID Datum.
  1449  type DUuid struct {
  1450  	uuid.UUID
  1451  }
  1452  
  1453  // NewDUuid is a helper routine to create a *DUuid initialized from its
  1454  // argument.
  1455  func NewDUuid(d DUuid) *DUuid {
  1456  	return &d
  1457  }
  1458  
  1459  // ResolvedType implements the TypedExpr interface.
  1460  func (*DUuid) ResolvedType() *types.T {
  1461  	return types.Uuid
  1462  }
  1463  
  1464  // Compare implements the Datum interface.
  1465  func (d *DUuid) Compare(ctx *EvalContext, other Datum) int {
  1466  	if other == DNull {
  1467  		// NULL is less than any non-NULL value.
  1468  		return 1
  1469  	}
  1470  	v, ok := UnwrapDatum(ctx, other).(*DUuid)
  1471  	if !ok {
  1472  		panic(makeUnsupportedComparisonMessage(d, other))
  1473  	}
  1474  	return bytes.Compare(d.GetBytes(), v.GetBytes())
  1475  }
  1476  
  1477  func (d *DUuid) equal(other *DUuid) bool {
  1478  	return bytes.Equal(d.GetBytes(), other.GetBytes())
  1479  }
  1480  
  1481  // Prev implements the Datum interface.
  1482  func (d *DUuid) Prev(_ *EvalContext) (Datum, bool) {
  1483  	i := d.ToUint128()
  1484  	u := uuid.FromUint128(i.Sub(1))
  1485  	return NewDUuid(DUuid{u}), true
  1486  }
  1487  
  1488  // Next implements the Datum interface.
  1489  func (d *DUuid) Next(_ *EvalContext) (Datum, bool) {
  1490  	i := d.ToUint128()
  1491  	u := uuid.FromUint128(i.Add(1))
  1492  	return NewDUuid(DUuid{u}), true
  1493  }
  1494  
  1495  // IsMax implements the Datum interface.
  1496  func (d *DUuid) IsMax(_ *EvalContext) bool {
  1497  	return d.equal(DMaxUUID)
  1498  }
  1499  
  1500  // IsMin implements the Datum interface.
  1501  func (d *DUuid) IsMin(_ *EvalContext) bool {
  1502  	return d.equal(DMinUUID)
  1503  }
  1504  
  1505  // DMinUUID is the min UUID.
  1506  var DMinUUID = NewDUuid(DUuid{uuid.UUID{}})
  1507  
  1508  // DMaxUUID is the max UUID.
  1509  var DMaxUUID = NewDUuid(DUuid{uuid.UUID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  1510  	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}})
  1511  
  1512  // Min implements the Datum interface.
  1513  func (*DUuid) Min(_ *EvalContext) (Datum, bool) {
  1514  	return DMinUUID, true
  1515  }
  1516  
  1517  // Max implements the Datum interface.
  1518  func (*DUuid) Max(_ *EvalContext) (Datum, bool) {
  1519  	return DMaxUUID, true
  1520  }
  1521  
  1522  // AmbiguousFormat implements the Datum interface.
  1523  func (*DUuid) AmbiguousFormat() bool { return true }
  1524  
  1525  // Format implements the NodeFormatter interface.
  1526  func (d *DUuid) Format(ctx *FmtCtx) {
  1527  	f := ctx.flags
  1528  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  1529  	if !bareStrings {
  1530  		ctx.WriteByte('\'')
  1531  	}
  1532  	ctx.WriteString(d.UUID.String())
  1533  	if !bareStrings {
  1534  		ctx.WriteByte('\'')
  1535  	}
  1536  }
  1537  
  1538  // Size implements the Datum interface.
  1539  func (d *DUuid) Size() uintptr {
  1540  	return unsafe.Sizeof(*d)
  1541  }
  1542  
  1543  // DIPAddr is the IPAddr Datum.
  1544  type DIPAddr struct {
  1545  	ipaddr.IPAddr
  1546  }
  1547  
  1548  // NewDIPAddr is a helper routine to create a *DIPAddr initialized from its
  1549  // argument.
  1550  func NewDIPAddr(d DIPAddr) *DIPAddr {
  1551  	return &d
  1552  }
  1553  
  1554  // AsDIPAddr attempts to retrieve a *DIPAddr from an Expr, returning a *DIPAddr and
  1555  // a flag signifying whether the assertion was successful. The function should
  1556  // be used instead of direct type assertions wherever a *DIPAddr wrapped by a
  1557  // *DOidWrapper is possible.
  1558  func AsDIPAddr(e Expr) (DIPAddr, bool) {
  1559  	switch t := e.(type) {
  1560  	case *DIPAddr:
  1561  		return *t, true
  1562  	case *DOidWrapper:
  1563  		return AsDIPAddr(t.Wrapped)
  1564  	}
  1565  	return DIPAddr{}, false
  1566  }
  1567  
  1568  // MustBeDIPAddr attempts to retrieve a DIPAddr from an Expr, panicking if the
  1569  // assertion fails.
  1570  func MustBeDIPAddr(e Expr) DIPAddr {
  1571  	i, ok := AsDIPAddr(e)
  1572  	if !ok {
  1573  		panic(errors.AssertionFailedf("expected *DIPAddr, found %T", e))
  1574  	}
  1575  	return i
  1576  }
  1577  
  1578  // ResolvedType implements the TypedExpr interface.
  1579  func (*DIPAddr) ResolvedType() *types.T {
  1580  	return types.INet
  1581  }
  1582  
  1583  // Compare implements the Datum interface.
  1584  func (d *DIPAddr) Compare(ctx *EvalContext, other Datum) int {
  1585  	if other == DNull {
  1586  		// NULL is less than any non-NULL value.
  1587  		return 1
  1588  	}
  1589  	v, ok := UnwrapDatum(ctx, other).(*DIPAddr)
  1590  	if !ok {
  1591  		panic(makeUnsupportedComparisonMessage(d, other))
  1592  	}
  1593  
  1594  	return d.IPAddr.Compare(&v.IPAddr)
  1595  }
  1596  
  1597  func (d DIPAddr) equal(other *DIPAddr) bool {
  1598  	return d.IPAddr.Equal(&other.IPAddr)
  1599  }
  1600  
  1601  // Prev implements the Datum interface.
  1602  func (d *DIPAddr) Prev(_ *EvalContext) (Datum, bool) {
  1603  	// We will do one of the following to get the Prev IPAddr:
  1604  	//	- Decrement IP address if we won't underflow the IP.
  1605  	//	- Decrement mask and set the IP to max in family if we will underflow.
  1606  	//	- Jump down from IPv6 to IPv4 if we will underflow both IP and mask.
  1607  	if d.Family == ipaddr.IPv6family && d.Addr.Equal(dIPv6min) {
  1608  		if d.Mask == 0 {
  1609  			// Jump down IP family.
  1610  			return dMaxIPv4Addr, true
  1611  		}
  1612  		// Decrease mask size, wrap IPv6 IP address.
  1613  		return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv6family, Addr: dIPv6max, Mask: d.Mask - 1}}), true
  1614  	} else if d.Family == ipaddr.IPv4family && d.Addr.Equal(dIPv4min) {
  1615  		// Decrease mask size, wrap IPv4 IP address.
  1616  		return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv4family, Addr: dIPv4max, Mask: d.Mask - 1}}), true
  1617  	}
  1618  	// Decrement IP address.
  1619  	return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: d.Family, Addr: d.Addr.Sub(1), Mask: d.Mask}}), true
  1620  }
  1621  
  1622  // Next implements the Datum interface.
  1623  func (d *DIPAddr) Next(_ *EvalContext) (Datum, bool) {
  1624  	// We will do one of a few things to get the Next IP address:
  1625  	//	- Increment IP address if we won't overflow the IP.
  1626  	//	- Increment mask and set the IP to min in family if we will overflow.
  1627  	//	- Jump up from IPv4 to IPv6 if we will overflow both IP and mask.
  1628  	if d.Family == ipaddr.IPv4family && d.Addr.Equal(dIPv4max) {
  1629  		if d.Mask == 32 {
  1630  			// Jump up IP family.
  1631  			return dMinIPv6Addr, true
  1632  		}
  1633  		// Increase mask size, wrap IPv4 IP address.
  1634  		return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv4family, Addr: dIPv4min, Mask: d.Mask + 1}}), true
  1635  	} else if d.Family == ipaddr.IPv6family && d.Addr.Equal(dIPv6max) {
  1636  		// Increase mask size, wrap IPv6 IP address.
  1637  		return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv6family, Addr: dIPv6min, Mask: d.Mask + 1}}), true
  1638  	}
  1639  	// Increment IP address.
  1640  	return NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: d.Family, Addr: d.Addr.Add(1), Mask: d.Mask}}), true
  1641  }
  1642  
  1643  // IsMax implements the Datum interface.
  1644  func (d *DIPAddr) IsMax(_ *EvalContext) bool {
  1645  	return d.equal(DMaxIPAddr)
  1646  }
  1647  
  1648  // IsMin implements the Datum interface.
  1649  func (d *DIPAddr) IsMin(_ *EvalContext) bool {
  1650  	return d.equal(DMinIPAddr)
  1651  }
  1652  
  1653  // dIPv4 and dIPv6 min and maxes use ParseIP because the actual byte constant is
  1654  // no equal to solely zeros or ones. For IPv4 there is a 0xffff prefix. Without
  1655  // this prefix this makes IP arithmetic invalid.
  1656  var dIPv4min = ipaddr.Addr(uint128.FromBytes([]byte(net.ParseIP("0.0.0.0"))))
  1657  var dIPv4max = ipaddr.Addr(uint128.FromBytes([]byte(net.ParseIP("255.255.255.255"))))
  1658  var dIPv6min = ipaddr.Addr(uint128.FromBytes([]byte(net.ParseIP("::"))))
  1659  var dIPv6max = ipaddr.Addr(uint128.FromBytes([]byte(net.ParseIP("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"))))
  1660  
  1661  // dMaxIPv4Addr and dMinIPv6Addr are used as global constants to prevent extra
  1662  // heap extra allocation
  1663  var dMaxIPv4Addr = NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv4family, Addr: dIPv4max, Mask: 32}})
  1664  var dMinIPv6Addr = NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv6family, Addr: dIPv6min, Mask: 0}})
  1665  
  1666  // DMinIPAddr is the min DIPAddr.
  1667  var DMinIPAddr = NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv4family, Addr: dIPv4min, Mask: 0}})
  1668  
  1669  // DMaxIPAddr is the max DIPaddr.
  1670  var DMaxIPAddr = NewDIPAddr(DIPAddr{ipaddr.IPAddr{Family: ipaddr.IPv6family, Addr: dIPv6max, Mask: 128}})
  1671  
  1672  // Min implements the Datum interface.
  1673  func (*DIPAddr) Min(_ *EvalContext) (Datum, bool) {
  1674  	return DMinIPAddr, true
  1675  }
  1676  
  1677  // Max implements the Datum interface.
  1678  func (*DIPAddr) Max(_ *EvalContext) (Datum, bool) {
  1679  	return DMaxIPAddr, true
  1680  }
  1681  
  1682  // AmbiguousFormat implements the Datum interface.
  1683  func (*DIPAddr) AmbiguousFormat() bool {
  1684  	return true
  1685  }
  1686  
  1687  // Format implements the NodeFormatter interface.
  1688  func (d *DIPAddr) Format(ctx *FmtCtx) {
  1689  	f := ctx.flags
  1690  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  1691  	if !bareStrings {
  1692  		ctx.WriteByte('\'')
  1693  	}
  1694  	ctx.WriteString(d.IPAddr.String())
  1695  	if !bareStrings {
  1696  		ctx.WriteByte('\'')
  1697  	}
  1698  }
  1699  
  1700  // Size implements the Datum interface.
  1701  func (d *DIPAddr) Size() uintptr {
  1702  	return unsafe.Sizeof(*d)
  1703  }
  1704  
  1705  // DDate is the date Datum represented as the number of days after
  1706  // the Unix epoch.
  1707  type DDate struct {
  1708  	pgdate.Date
  1709  }
  1710  
  1711  // NewDDate is a helper routine to create a *DDate initialized from its
  1712  // argument.
  1713  func NewDDate(d pgdate.Date) *DDate {
  1714  	return &DDate{Date: d}
  1715  }
  1716  
  1717  // MakeDDate makes a DDate from a pgdate.Date.
  1718  func MakeDDate(d pgdate.Date) DDate {
  1719  	return DDate{Date: d}
  1720  }
  1721  
  1722  // NewDDateFromTime constructs a *DDate from a time.Time.
  1723  func NewDDateFromTime(t time.Time) (*DDate, error) {
  1724  	d, err := pgdate.MakeDateFromTime(t)
  1725  	return NewDDate(d), err
  1726  }
  1727  
  1728  // ParseTimeContext provides the information necessary for
  1729  // parsing dates, times, and timestamps. A nil value is generally
  1730  // acceptable and will result in reasonable defaults being applied.
  1731  type ParseTimeContext interface {
  1732  	// GetRelativeParseTime returns the transaction time in the session's
  1733  	// timezone (i.e. now()). This is used to calculate relative dates,
  1734  	// like "tomorrow", and also provides a default time.Location for
  1735  	// parsed times.
  1736  	GetRelativeParseTime() time.Time
  1737  }
  1738  
  1739  var _ ParseTimeContext = &EvalContext{}
  1740  var _ ParseTimeContext = &SemaContext{}
  1741  var _ ParseTimeContext = &simpleParseTimeContext{}
  1742  
  1743  // NewParseTimeContext constructs a ParseTimeContext that returns
  1744  // the given values.
  1745  func NewParseTimeContext(relativeParseTime time.Time) ParseTimeContext {
  1746  	return &simpleParseTimeContext{
  1747  		RelativeParseTime: relativeParseTime,
  1748  	}
  1749  }
  1750  
  1751  type simpleParseTimeContext struct {
  1752  	RelativeParseTime time.Time
  1753  }
  1754  
  1755  // GetRelativeParseTime implements ParseTimeContext.
  1756  func (ctx simpleParseTimeContext) GetRelativeParseTime() time.Time {
  1757  	return ctx.RelativeParseTime
  1758  }
  1759  
  1760  // relativeParseTime chooses a reasonable "now" value for
  1761  // performing date parsing.
  1762  func relativeParseTime(ctx ParseTimeContext) time.Time {
  1763  	if ctx == nil {
  1764  		return timeutil.Now()
  1765  	}
  1766  	return ctx.GetRelativeParseTime()
  1767  }
  1768  
  1769  // ParseDDate parses and returns the *DDate Datum value represented by the provided
  1770  // string in the provided location, or an error if parsing is unsuccessful.
  1771  func ParseDDate(ctx ParseTimeContext, s string) (*DDate, error) {
  1772  	now := relativeParseTime(ctx)
  1773  	t, err := pgdate.ParseDate(now, 0 /* mode */, s)
  1774  	return NewDDate(t), err
  1775  }
  1776  
  1777  // ResolvedType implements the TypedExpr interface.
  1778  func (*DDate) ResolvedType() *types.T {
  1779  	return types.Date
  1780  }
  1781  
  1782  // Compare implements the Datum interface.
  1783  func (d *DDate) Compare(ctx *EvalContext, other Datum) int {
  1784  	if other == DNull {
  1785  		// NULL is less than any non-NULL value.
  1786  		return 1
  1787  	}
  1788  	var v DDate
  1789  	switch t := UnwrapDatum(ctx, other).(type) {
  1790  	case *DDate:
  1791  		v = *t
  1792  	case *DTimestamp, *DTimestampTZ:
  1793  		return compareTimestamps(ctx, d, other)
  1794  	default:
  1795  		panic(makeUnsupportedComparisonMessage(d, other))
  1796  	}
  1797  	return d.Date.Compare(v.Date)
  1798  }
  1799  
  1800  var (
  1801  	epochDate, _ = pgdate.MakeDateFromPGEpoch(0)
  1802  	dEpochDate   = NewDDate(epochDate)
  1803  	dMaxDate     = NewDDate(pgdate.PosInfDate)
  1804  	dMinDate     = NewDDate(pgdate.NegInfDate)
  1805  	dLowDate     = NewDDate(pgdate.LowDate)
  1806  	dHighDate    = NewDDate(pgdate.HighDate)
  1807  )
  1808  
  1809  // Prev implements the Datum interface.
  1810  func (d *DDate) Prev(_ *EvalContext) (Datum, bool) {
  1811  	switch d.Date {
  1812  	case pgdate.PosInfDate:
  1813  		return dHighDate, true
  1814  	case pgdate.LowDate:
  1815  		return dMinDate, true
  1816  	case pgdate.NegInfDate:
  1817  		return nil, false
  1818  	}
  1819  	n, err := d.AddDays(-1)
  1820  	if err != nil {
  1821  		return nil, false
  1822  	}
  1823  	return NewDDate(n), true
  1824  }
  1825  
  1826  // Next implements the Datum interface.
  1827  func (d *DDate) Next(_ *EvalContext) (Datum, bool) {
  1828  	switch d.Date {
  1829  	case pgdate.NegInfDate:
  1830  		return dLowDate, true
  1831  	case pgdate.HighDate:
  1832  		return dMaxDate, true
  1833  	case pgdate.PosInfDate:
  1834  		return nil, false
  1835  	}
  1836  	n, err := d.AddDays(1)
  1837  	if err != nil {
  1838  		return nil, false
  1839  	}
  1840  	return NewDDate(n), true
  1841  }
  1842  
  1843  // IsMax implements the Datum interface.
  1844  func (d *DDate) IsMax(_ *EvalContext) bool {
  1845  	return d.Date == pgdate.PosInfDate
  1846  }
  1847  
  1848  // IsMin implements the Datum interface.
  1849  func (d *DDate) IsMin(_ *EvalContext) bool {
  1850  	return d.Date == pgdate.NegInfDate
  1851  }
  1852  
  1853  // Max implements the Datum interface.
  1854  func (d *DDate) Max(_ *EvalContext) (Datum, bool) {
  1855  	return dMaxDate, true
  1856  }
  1857  
  1858  // Min implements the Datum interface.
  1859  func (d *DDate) Min(_ *EvalContext) (Datum, bool) {
  1860  	return dMinDate, true
  1861  }
  1862  
  1863  // AmbiguousFormat implements the Datum interface.
  1864  func (*DDate) AmbiguousFormat() bool { return true }
  1865  
  1866  // Format implements the NodeFormatter interface.
  1867  func (d *DDate) Format(ctx *FmtCtx) {
  1868  	f := ctx.flags
  1869  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  1870  	if !bareStrings {
  1871  		ctx.WriteByte('\'')
  1872  	}
  1873  	d.Date.Format(&ctx.Buffer)
  1874  	if !bareStrings {
  1875  		ctx.WriteByte('\'')
  1876  	}
  1877  }
  1878  
  1879  // Size implements the Datum interface.
  1880  func (d *DDate) Size() uintptr {
  1881  	return unsafe.Sizeof(*d)
  1882  }
  1883  
  1884  // DTime is the time Datum.
  1885  type DTime timeofday.TimeOfDay
  1886  
  1887  // MakeDTime creates a DTime from a TimeOfDay.
  1888  func MakeDTime(t timeofday.TimeOfDay) *DTime {
  1889  	d := DTime(t)
  1890  	return &d
  1891  }
  1892  
  1893  // ParseDTime parses and returns the *DTime Datum value represented by the
  1894  // provided string, or an error if parsing is unsuccessful.
  1895  func ParseDTime(ctx ParseTimeContext, s string, precision time.Duration) (*DTime, error) {
  1896  	now := relativeParseTime(ctx)
  1897  
  1898  	// Special case on 24:00 and 24:00:00 as the parser
  1899  	// does not handle these correctly.
  1900  	if DTimeMaxTimeRegex.MatchString(s) {
  1901  		return MakeDTime(timeofday.Time2400), nil
  1902  	}
  1903  
  1904  	s = timeutil.ReplaceLibPQTimePrefix(s)
  1905  
  1906  	t, err := pgdate.ParseTime(now, pgdate.ParseModeYMD, s)
  1907  	if err != nil {
  1908  		// Build our own error message to avoid exposing the dummy date.
  1909  		return nil, makeParseError(s, types.Time, nil)
  1910  	}
  1911  	return MakeDTime(timeofday.FromTime(t).Round(precision)), nil
  1912  }
  1913  
  1914  // ResolvedType implements the TypedExpr interface.
  1915  func (*DTime) ResolvedType() *types.T {
  1916  	return types.Time
  1917  }
  1918  
  1919  // Compare implements the Datum interface.
  1920  func (d *DTime) Compare(ctx *EvalContext, other Datum) int {
  1921  	if other == DNull {
  1922  		// NULL is less than any non-NULL value.
  1923  		return 1
  1924  	}
  1925  	return compareTimestamps(ctx, d, other)
  1926  }
  1927  
  1928  // Prev implements the Datum interface.
  1929  func (d *DTime) Prev(ctx *EvalContext) (Datum, bool) {
  1930  	if d.IsMin(ctx) {
  1931  		return nil, false
  1932  	}
  1933  	prev := *d - 1
  1934  	return &prev, true
  1935  }
  1936  
  1937  // Round returns a new DTime to the specified precision.
  1938  func (d *DTime) Round(precision time.Duration) *DTime {
  1939  	return MakeDTime(timeofday.TimeOfDay(*d).Round(precision))
  1940  }
  1941  
  1942  // Next implements the Datum interface.
  1943  func (d *DTime) Next(ctx *EvalContext) (Datum, bool) {
  1944  	if d.IsMax(ctx) {
  1945  		return nil, false
  1946  	}
  1947  	next := *d + 1
  1948  	return &next, true
  1949  }
  1950  
  1951  var dTimeMin = MakeDTime(timeofday.Min)
  1952  var dTimeMax = MakeDTime(timeofday.Max)
  1953  
  1954  // IsMax implements the Datum interface.
  1955  func (d *DTime) IsMax(_ *EvalContext) bool {
  1956  	return *d == *dTimeMax
  1957  }
  1958  
  1959  // IsMin implements the Datum interface.
  1960  func (d *DTime) IsMin(_ *EvalContext) bool {
  1961  	return *d == *dTimeMin
  1962  }
  1963  
  1964  // Max implements the Datum interface.
  1965  func (d *DTime) Max(_ *EvalContext) (Datum, bool) {
  1966  	return dTimeMax, true
  1967  }
  1968  
  1969  // Min implements the Datum interface.
  1970  func (d *DTime) Min(_ *EvalContext) (Datum, bool) {
  1971  	return dTimeMin, true
  1972  }
  1973  
  1974  // AmbiguousFormat implements the Datum interface.
  1975  func (*DTime) AmbiguousFormat() bool { return true }
  1976  
  1977  // Format implements the NodeFormatter interface.
  1978  func (d *DTime) Format(ctx *FmtCtx) {
  1979  	f := ctx.flags
  1980  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  1981  	if !bareStrings {
  1982  		ctx.WriteByte('\'')
  1983  	}
  1984  	ctx.WriteString(timeofday.TimeOfDay(*d).String())
  1985  	if !bareStrings {
  1986  		ctx.WriteByte('\'')
  1987  	}
  1988  }
  1989  
  1990  // Size implements the Datum interface.
  1991  func (d *DTime) Size() uintptr {
  1992  	return unsafe.Sizeof(*d)
  1993  }
  1994  
  1995  // DTimeTZ is the time with time zone Datum.
  1996  type DTimeTZ struct {
  1997  	timetz.TimeTZ
  1998  }
  1999  
  2000  var (
  2001  	dZeroTimeTZ = NewDTimeTZFromOffset(timeofday.Min, 0)
  2002  	// DMinTimeTZ is the min TimeTZ.
  2003  	DMinTimeTZ = NewDTimeTZFromOffset(timeofday.Min, timetz.MinTimeTZOffsetSecs)
  2004  	// DMaxTimeTZ is the max TimeTZ.
  2005  	DMaxTimeTZ = NewDTimeTZFromOffset(timeofday.Max, timetz.MaxTimeTZOffsetSecs)
  2006  )
  2007  
  2008  // NewDTimeTZ creates a DTimeTZ from a timetz.TimeTZ.
  2009  func NewDTimeTZ(t timetz.TimeTZ) *DTimeTZ {
  2010  	return &DTimeTZ{t}
  2011  }
  2012  
  2013  // NewDTimeTZFromTime creates a DTimeTZ from time.Time.
  2014  func NewDTimeTZFromTime(t time.Time) *DTimeTZ {
  2015  	return &DTimeTZ{timetz.MakeTimeTZFromTime(t)}
  2016  }
  2017  
  2018  // NewDTimeTZFromOffset creates a DTimeTZ from a TimeOfDay and offset.
  2019  func NewDTimeTZFromOffset(t timeofday.TimeOfDay, offsetSecs int32) *DTimeTZ {
  2020  	return &DTimeTZ{timetz.MakeTimeTZ(t, offsetSecs)}
  2021  }
  2022  
  2023  // NewDTimeTZFromLocation creates a DTimeTZ from a TimeOfDay and time.Location.
  2024  func NewDTimeTZFromLocation(t timeofday.TimeOfDay, loc *time.Location) *DTimeTZ {
  2025  	return &DTimeTZ{timetz.MakeTimeTZFromLocation(t, loc)}
  2026  }
  2027  
  2028  // ParseDTimeTZ parses and returns the *DTime Datum value represented by the
  2029  // provided string, or an error if parsing is unsuccessful.
  2030  func ParseDTimeTZ(ctx ParseTimeContext, s string, precision time.Duration) (*DTimeTZ, error) {
  2031  	now := relativeParseTime(ctx)
  2032  	d, err := timetz.ParseTimeTZ(now, s, precision)
  2033  	if err != nil {
  2034  		return nil, err
  2035  	}
  2036  	return NewDTimeTZ(d), nil
  2037  }
  2038  
  2039  // ResolvedType implements the TypedExpr interface.
  2040  func (*DTimeTZ) ResolvedType() *types.T {
  2041  	return types.TimeTZ
  2042  }
  2043  
  2044  // Compare implements the Datum interface.
  2045  func (d *DTimeTZ) Compare(ctx *EvalContext, other Datum) int {
  2046  	if other == DNull {
  2047  		// NULL is less than any non-NULL value.
  2048  		return 1
  2049  	}
  2050  	return compareTimestamps(ctx, d, other)
  2051  }
  2052  
  2053  // Prev implements the Datum interface.
  2054  func (d *DTimeTZ) Prev(ctx *EvalContext) (Datum, bool) {
  2055  	if d.IsMin(ctx) {
  2056  		return nil, false
  2057  	}
  2058  	return NewDTimeTZFromOffset(d.TimeOfDay-1, d.OffsetSecs), true
  2059  }
  2060  
  2061  // Next implements the Datum interface.
  2062  func (d *DTimeTZ) Next(ctx *EvalContext) (Datum, bool) {
  2063  	if d.IsMax(ctx) {
  2064  		return nil, false
  2065  	}
  2066  	return NewDTimeTZFromOffset(d.TimeOfDay+1, d.OffsetSecs), true
  2067  }
  2068  
  2069  // IsMax implements the Datum interface.
  2070  func (d *DTimeTZ) IsMax(_ *EvalContext) bool {
  2071  	return d.TimeOfDay == DMaxTimeTZ.TimeOfDay && d.OffsetSecs == timetz.MaxTimeTZOffsetSecs
  2072  }
  2073  
  2074  // IsMin implements the Datum interface.
  2075  func (d *DTimeTZ) IsMin(_ *EvalContext) bool {
  2076  	return d.TimeOfDay == DMinTimeTZ.TimeOfDay && d.OffsetSecs == timetz.MinTimeTZOffsetSecs
  2077  }
  2078  
  2079  // Max implements the Datum interface.
  2080  func (d *DTimeTZ) Max(_ *EvalContext) (Datum, bool) {
  2081  	return DMaxTimeTZ, true
  2082  }
  2083  
  2084  // Round returns a new DTimeTZ to the specified precision.
  2085  func (d *DTimeTZ) Round(precision time.Duration) *DTimeTZ {
  2086  	return NewDTimeTZ(d.TimeTZ.Round(precision))
  2087  }
  2088  
  2089  // Min implements the Datum interface.
  2090  func (d *DTimeTZ) Min(_ *EvalContext) (Datum, bool) {
  2091  	return DMinTimeTZ, true
  2092  }
  2093  
  2094  // AmbiguousFormat implements the Datum interface.
  2095  func (*DTimeTZ) AmbiguousFormat() bool { return true }
  2096  
  2097  // Format implements the NodeFormatter interface.
  2098  func (d *DTimeTZ) Format(ctx *FmtCtx) {
  2099  	f := ctx.flags
  2100  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2101  	if !bareStrings {
  2102  		ctx.WriteByte('\'')
  2103  	}
  2104  	ctx.WriteString(d.TimeTZ.String())
  2105  	if !bareStrings {
  2106  		ctx.WriteByte('\'')
  2107  	}
  2108  }
  2109  
  2110  // Size implements the Datum interface.
  2111  func (d *DTimeTZ) Size() uintptr {
  2112  	return unsafe.Sizeof(*d)
  2113  }
  2114  
  2115  // DTimestamp is the timestamp Datum.
  2116  type DTimestamp struct {
  2117  	time.Time
  2118  }
  2119  
  2120  // MakeDTimestamp creates a DTimestamp with specified precision.
  2121  func MakeDTimestamp(t time.Time, precision time.Duration) (*DTimestamp, error) {
  2122  	ret := t.Round(precision)
  2123  	if ret.After(MaxSupportedTime) || ret.Before(MinSupportedTime) {
  2124  		return nil, errors.Newf("timestamp %q exceeds supported timestamp bounds", ret.Format(time.RFC3339))
  2125  	}
  2126  	return &DTimestamp{Time: ret}, nil
  2127  }
  2128  
  2129  // MustMakeDTimestamp wraps MakeDTimestamp but panics if there is an error.
  2130  // This is intended for testing applications only.
  2131  func MustMakeDTimestamp(t time.Time, precision time.Duration) *DTimestamp {
  2132  	ret, err := MakeDTimestamp(t, precision)
  2133  	if err != nil {
  2134  		panic(err)
  2135  	}
  2136  	return ret
  2137  }
  2138  
  2139  var dZeroTimestamp = &DTimestamp{}
  2140  
  2141  // time.Time formats.
  2142  const (
  2143  	// TimestampOutputFormat is used to output all timestamps.
  2144  	TimestampOutputFormat = "2006-01-02 15:04:05.999999-07:00"
  2145  )
  2146  
  2147  // ParseDTimestamp parses and returns the *DTimestamp Datum value represented by
  2148  // the provided string in UTC, or an error if parsing is unsuccessful.
  2149  func ParseDTimestamp(ctx ParseTimeContext, s string, precision time.Duration) (*DTimestamp, error) {
  2150  	now := relativeParseTime(ctx)
  2151  	t, err := pgdate.ParseTimestamp(now, pgdate.ParseModeYMD, s)
  2152  	if err != nil {
  2153  		return nil, err
  2154  	}
  2155  	// Truncate the timezone. DTimestamp doesn't carry its timezone around.
  2156  	_, offset := t.Zone()
  2157  	t = t.Add(time.Duration(offset) * time.Second).UTC()
  2158  	return MakeDTimestamp(t, precision)
  2159  }
  2160  
  2161  // AsDTimestamp attempts to retrieve a DTimestamp from an Expr, returning a DTimestamp and
  2162  // a flag signifying whether the assertion was successful. The function should
  2163  // be used instead of direct type assertions wherever a *DTimestamp wrapped by a
  2164  // *DOidWrapper is possible.
  2165  func AsDTimestamp(e Expr) (DTimestamp, bool) {
  2166  	switch t := e.(type) {
  2167  	case *DTimestamp:
  2168  		return *t, true
  2169  	case *DOidWrapper:
  2170  		return AsDTimestamp(t.Wrapped)
  2171  	}
  2172  	return DTimestamp{}, false
  2173  }
  2174  
  2175  // MustBeDTimestamp attempts to retrieve a DTimestamp from an Expr, panicking if the
  2176  // assertion fails.
  2177  func MustBeDTimestamp(e Expr) DTimestamp {
  2178  	t, ok := AsDTimestamp(e)
  2179  	if !ok {
  2180  		panic(errors.AssertionFailedf("expected *DTimestamp, found %T", e))
  2181  	}
  2182  	return t
  2183  }
  2184  
  2185  // Round returns a new DTimestamp to the specified precision.
  2186  func (d *DTimestamp) Round(precision time.Duration) (*DTimestamp, error) {
  2187  	return MakeDTimestamp(d.Time, precision)
  2188  }
  2189  
  2190  // ResolvedType implements the TypedExpr interface.
  2191  func (*DTimestamp) ResolvedType() *types.T {
  2192  	return types.Timestamp
  2193  }
  2194  
  2195  // timeFromDatumForComparison gets the time from a datum object to use
  2196  // strictly for comparison usage.
  2197  func timeFromDatumForComparison(ctx *EvalContext, d Datum) (time.Time, bool) {
  2198  	d = UnwrapDatum(ctx, d)
  2199  	switch t := d.(type) {
  2200  	case *DDate:
  2201  		ts, err := MakeDTimestampTZFromDate(ctx.GetLocation(), t)
  2202  		if err != nil {
  2203  			return time.Time{}, false
  2204  		}
  2205  		return ts.Time, true
  2206  	case *DTimestampTZ:
  2207  		return t.Time, true
  2208  	case *DTimestamp:
  2209  		// Normalize to the timezone of the context.
  2210  		_, zoneOffset := t.Time.In(ctx.GetLocation()).Zone()
  2211  		ts := t.Time.In(ctx.GetLocation()).Add(-time.Duration(zoneOffset) * time.Second)
  2212  		return ts, true
  2213  	case *DTime:
  2214  		// Normalize to the timezone of the context.
  2215  		toTime := timeofday.TimeOfDay(*t).ToTime()
  2216  		_, zoneOffsetSecs := toTime.In(ctx.GetLocation()).Zone()
  2217  		return toTime.In(ctx.GetLocation()).Add(-time.Duration(zoneOffsetSecs) * time.Second), true
  2218  	case *DTimeTZ:
  2219  		return t.ToTime(), true
  2220  	default:
  2221  		return time.Time{}, false
  2222  	}
  2223  }
  2224  
  2225  func compareTimestamps(ctx *EvalContext, l Datum, r Datum) int {
  2226  	lTime, lOk := timeFromDatumForComparison(ctx, l)
  2227  	rTime, rOk := timeFromDatumForComparison(ctx, r)
  2228  	if !lOk || !rOk {
  2229  		panic(makeUnsupportedComparisonMessage(l, r))
  2230  	}
  2231  	if lTime.Before(rTime) {
  2232  		return -1
  2233  	}
  2234  	if rTime.Before(lTime) {
  2235  		return 1
  2236  	}
  2237  
  2238  	// If either side is a TimeTZ, then we must compare timezones before
  2239  	// when comparing. If comparing a non-TimeTZ value, and the times are
  2240  	// equal, then we must compare relative to the current zone we are at.
  2241  	//
  2242  	// This is a special quirk of TimeTZ and does not apply to TimestampTZ,
  2243  	// as TimestampTZ does not store a timezone offset and is based on
  2244  	// the current zone.
  2245  	_, leftIsTimeTZ := l.(*DTimeTZ)
  2246  	_, rightIsTimeTZ := r.(*DTimeTZ)
  2247  
  2248  	// If neither side is TimeTZ, this is always equal at this point.
  2249  	if !leftIsTimeTZ && !rightIsTimeTZ {
  2250  		return 0
  2251  	}
  2252  
  2253  	_, zoneOffset := ctx.GetRelativeParseTime().Zone()
  2254  	lOffset := int32(-zoneOffset)
  2255  	rOffset := int32(-zoneOffset)
  2256  
  2257  	if leftIsTimeTZ {
  2258  		lOffset = l.(*DTimeTZ).OffsetSecs
  2259  	}
  2260  	if rightIsTimeTZ {
  2261  		rOffset = r.(*DTimeTZ).OffsetSecs
  2262  	}
  2263  
  2264  	if lOffset > rOffset {
  2265  		return 1
  2266  	}
  2267  	if lOffset < rOffset {
  2268  		return -1
  2269  	}
  2270  	return 0
  2271  }
  2272  
  2273  // Compare implements the Datum interface.
  2274  func (d *DTimestamp) Compare(ctx *EvalContext, other Datum) int {
  2275  	if other == DNull {
  2276  		// NULL is less than any non-NULL value.
  2277  		return 1
  2278  	}
  2279  	return compareTimestamps(ctx, d, other)
  2280  }
  2281  
  2282  // Prev implements the Datum interface.
  2283  func (d *DTimestamp) Prev(ctx *EvalContext) (Datum, bool) {
  2284  	if d.IsMin(ctx) {
  2285  		return nil, false
  2286  	}
  2287  	return &DTimestamp{Time: d.Add(-time.Microsecond)}, true
  2288  }
  2289  
  2290  // Next implements the Datum interface.
  2291  func (d *DTimestamp) Next(ctx *EvalContext) (Datum, bool) {
  2292  	if d.IsMax(ctx) {
  2293  		return nil, false
  2294  	}
  2295  	return &DTimestamp{Time: d.Add(time.Microsecond)}, true
  2296  }
  2297  
  2298  // IsMax implements the Datum interface.
  2299  func (d *DTimestamp) IsMax(_ *EvalContext) bool {
  2300  	return d.Equal(MaxSupportedTime)
  2301  }
  2302  
  2303  // IsMin implements the Datum interface.
  2304  func (d *DTimestamp) IsMin(_ *EvalContext) bool {
  2305  	return d.Equal(MinSupportedTime)
  2306  }
  2307  
  2308  // Min implements the Datum interface.
  2309  func (d *DTimestamp) Min(_ *EvalContext) (Datum, bool) {
  2310  	return &DTimestamp{Time: MinSupportedTime}, true
  2311  }
  2312  
  2313  // Max implements the Datum interface.
  2314  func (d *DTimestamp) Max(_ *EvalContext) (Datum, bool) {
  2315  	return &DTimestamp{Time: MaxSupportedTime}, true
  2316  }
  2317  
  2318  // AmbiguousFormat implements the Datum interface.
  2319  func (*DTimestamp) AmbiguousFormat() bool { return true }
  2320  
  2321  // Format implements the NodeFormatter interface.
  2322  func (d *DTimestamp) Format(ctx *FmtCtx) {
  2323  	f := ctx.flags
  2324  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2325  	if !bareStrings {
  2326  		ctx.WriteByte('\'')
  2327  	}
  2328  	ctx.WriteString(d.UTC().Format(TimestampOutputFormat))
  2329  	if !bareStrings {
  2330  		ctx.WriteByte('\'')
  2331  	}
  2332  }
  2333  
  2334  // Size implements the Datum interface.
  2335  func (d *DTimestamp) Size() uintptr {
  2336  	return unsafe.Sizeof(*d)
  2337  }
  2338  
  2339  // DTimestampTZ is the timestamp Datum that is rendered with session offset.
  2340  type DTimestampTZ struct {
  2341  	time.Time
  2342  }
  2343  
  2344  // MakeDTimestampTZ creates a DTimestampTZ with specified precision.
  2345  func MakeDTimestampTZ(t time.Time, precision time.Duration) (*DTimestampTZ, error) {
  2346  	ret := t.Round(precision)
  2347  	if ret.After(MaxSupportedTime) || ret.Before(MinSupportedTime) {
  2348  		return nil, errors.Newf("timestamp %q exceeds supported timestamp bounds", ret.Format(time.RFC3339))
  2349  	}
  2350  	return &DTimestampTZ{Time: ret}, nil
  2351  }
  2352  
  2353  // MustMakeDTimestampTZ wraps MakeDTimestampTZ but panics if there is an error.
  2354  // This is intended for testing applications only.
  2355  func MustMakeDTimestampTZ(t time.Time, precision time.Duration) *DTimestampTZ {
  2356  	ret, err := MakeDTimestampTZ(t, precision)
  2357  	if err != nil {
  2358  		panic(err)
  2359  	}
  2360  	return ret
  2361  }
  2362  
  2363  // MakeDTimestampTZFromDate creates a DTimestampTZ from a DDate.
  2364  // This will be equivalent to the midnight of the given zone.
  2365  func MakeDTimestampTZFromDate(loc *time.Location, d *DDate) (*DTimestampTZ, error) {
  2366  	t, err := d.ToTime()
  2367  	if err != nil {
  2368  		return nil, err
  2369  	}
  2370  	// Normalize to the correct zone.
  2371  	t = t.In(loc)
  2372  	_, offset := t.Zone()
  2373  	return MakeDTimestampTZ(t.Add(time.Duration(-offset)*time.Second), time.Microsecond)
  2374  }
  2375  
  2376  // ParseDTimestampTZ parses and returns the *DTimestampTZ Datum value represented by
  2377  // the provided string in the provided location, or an error if parsing is unsuccessful.
  2378  func ParseDTimestampTZ(
  2379  	ctx ParseTimeContext, s string, precision time.Duration,
  2380  ) (*DTimestampTZ, error) {
  2381  	now := relativeParseTime(ctx)
  2382  	t, err := pgdate.ParseTimestamp(now, pgdate.ParseModeYMD, s)
  2383  	if err != nil {
  2384  		return nil, err
  2385  	}
  2386  	// Always normalize time to the current location.
  2387  	return MakeDTimestampTZ(t, precision)
  2388  }
  2389  
  2390  var dZeroTimestampTZ = &DTimestampTZ{}
  2391  
  2392  // AsDTimestampTZ attempts to retrieve a DTimestampTZ from an Expr, returning a
  2393  // DTimestampTZ and a flag signifying whether the assertion was successful. The
  2394  // function should be used instead of direct type assertions wherever a
  2395  // *DTimestamp wrapped by a *DOidWrapper is possible.
  2396  func AsDTimestampTZ(e Expr) (DTimestampTZ, bool) {
  2397  	switch t := e.(type) {
  2398  	case *DTimestampTZ:
  2399  		return *t, true
  2400  	case *DOidWrapper:
  2401  		return AsDTimestampTZ(t.Wrapped)
  2402  	}
  2403  	return DTimestampTZ{}, false
  2404  }
  2405  
  2406  // MustBeDTimestampTZ attempts to retrieve a DTimestampTZ from an Expr,
  2407  // panicking if the assertion fails.
  2408  func MustBeDTimestampTZ(e Expr) DTimestampTZ {
  2409  	t, ok := AsDTimestampTZ(e)
  2410  	if !ok {
  2411  		panic(errors.AssertionFailedf("expected *DTimestampTZ, found %T", e))
  2412  	}
  2413  	return t
  2414  }
  2415  
  2416  // Round returns a new DTimestampTZ to the specified precision.
  2417  func (d *DTimestampTZ) Round(precision time.Duration) (*DTimestampTZ, error) {
  2418  	return MakeDTimestampTZ(d.Time, precision)
  2419  }
  2420  
  2421  // ResolvedType implements the TypedExpr interface.
  2422  func (*DTimestampTZ) ResolvedType() *types.T {
  2423  	return types.TimestampTZ
  2424  }
  2425  
  2426  // Compare implements the Datum interface.
  2427  func (d *DTimestampTZ) Compare(ctx *EvalContext, other Datum) int {
  2428  	if other == DNull {
  2429  		// NULL is less than any non-NULL value.
  2430  		return 1
  2431  	}
  2432  	return compareTimestamps(ctx, d, other)
  2433  }
  2434  
  2435  // Prev implements the Datum interface.
  2436  func (d *DTimestampTZ) Prev(ctx *EvalContext) (Datum, bool) {
  2437  	if d.IsMin(ctx) {
  2438  		return nil, false
  2439  	}
  2440  	return &DTimestampTZ{Time: d.Add(-time.Microsecond)}, true
  2441  }
  2442  
  2443  // Next implements the Datum interface.
  2444  func (d *DTimestampTZ) Next(ctx *EvalContext) (Datum, bool) {
  2445  	if d.IsMax(ctx) {
  2446  		return nil, false
  2447  	}
  2448  	return &DTimestampTZ{Time: d.Add(time.Microsecond)}, true
  2449  }
  2450  
  2451  // IsMax implements the Datum interface.
  2452  func (d *DTimestampTZ) IsMax(_ *EvalContext) bool {
  2453  	return d.Equal(MaxSupportedTime)
  2454  }
  2455  
  2456  // IsMin implements the Datum interface.
  2457  func (d *DTimestampTZ) IsMin(_ *EvalContext) bool {
  2458  	return d.Equal(MinSupportedTime)
  2459  }
  2460  
  2461  // Min implements the Datum interface.
  2462  func (d *DTimestampTZ) Min(_ *EvalContext) (Datum, bool) {
  2463  	return &DTimestampTZ{Time: MinSupportedTime}, true
  2464  }
  2465  
  2466  // Max implements the Datum interface.
  2467  func (d *DTimestampTZ) Max(_ *EvalContext) (Datum, bool) {
  2468  	return &DTimestampTZ{Time: MaxSupportedTime}, true
  2469  }
  2470  
  2471  // AmbiguousFormat implements the Datum interface.
  2472  func (*DTimestampTZ) AmbiguousFormat() bool { return true }
  2473  
  2474  // Format implements the NodeFormatter interface.
  2475  func (d *DTimestampTZ) Format(ctx *FmtCtx) {
  2476  	f := ctx.flags
  2477  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2478  	if !bareStrings {
  2479  		ctx.WriteByte('\'')
  2480  	}
  2481  	ctx.WriteString(d.Time.Format(TimestampOutputFormat))
  2482  	if !bareStrings {
  2483  		ctx.WriteByte('\'')
  2484  	}
  2485  }
  2486  
  2487  // Size implements the Datum interface.
  2488  func (d *DTimestampTZ) Size() uintptr {
  2489  	return unsafe.Sizeof(*d)
  2490  }
  2491  
  2492  // stripTimeZone removes the time zone from this TimestampTZ. For example, a
  2493  // TimestampTZ '2012-01-01 12:00:00 +02:00' would become
  2494  //             '2012-01-01 12:00:00'.
  2495  func (d *DTimestampTZ) stripTimeZone(ctx *EvalContext) (*DTimestamp, error) {
  2496  	return d.EvalAtTimeZone(ctx, ctx.GetLocation())
  2497  }
  2498  
  2499  // EvalAtTimeZone evaluates this TimestampTZ as if it were in the supplied
  2500  // location, returning a timestamp without a timezone.
  2501  func (d *DTimestampTZ) EvalAtTimeZone(ctx *EvalContext, loc *time.Location) (*DTimestamp, error) {
  2502  	_, locOffset := d.Time.In(loc).Zone()
  2503  	t := d.Time.UTC().Add(time.Duration(locOffset) * time.Second).UTC()
  2504  	return MakeDTimestamp(t, time.Microsecond)
  2505  }
  2506  
  2507  // DInterval is the interval Datum.
  2508  type DInterval struct {
  2509  	duration.Duration
  2510  }
  2511  
  2512  // MustBeDInterval attempts to retrieve a DInterval from an Expr, panicking if the
  2513  // assertion fails.
  2514  func MustBeDInterval(e Expr) *DInterval {
  2515  	switch t := e.(type) {
  2516  	case *DInterval:
  2517  		return t
  2518  	}
  2519  	panic(errors.AssertionFailedf("expected *DInterval, found %T", e))
  2520  }
  2521  
  2522  // NewDInterval creates a new DInterval.
  2523  func NewDInterval(d duration.Duration, itm types.IntervalTypeMetadata) *DInterval {
  2524  	ret := &DInterval{Duration: d}
  2525  	truncateDInterval(ret, itm)
  2526  	return ret
  2527  }
  2528  
  2529  // ParseDInterval parses and returns the *DInterval Datum value represented by the provided
  2530  // string, or an error if parsing is unsuccessful.
  2531  func ParseDInterval(s string) (*DInterval, error) {
  2532  	return ParseDIntervalWithTypeMetadata(s, types.DefaultIntervalTypeMetadata)
  2533  }
  2534  
  2535  // truncateDInterval truncates the input DInterval downward to the nearest
  2536  // interval quantity specified by the DurationField input.
  2537  // If precision is set for seconds, this will instead round at the second layer.
  2538  func truncateDInterval(d *DInterval, itm types.IntervalTypeMetadata) {
  2539  	switch itm.DurationField.DurationType {
  2540  	case types.IntervalDurationType_YEAR:
  2541  		d.Duration.Months = d.Duration.Months - d.Duration.Months%12
  2542  		d.Duration.Days = 0
  2543  		d.Duration.SetNanos(0)
  2544  	case types.IntervalDurationType_MONTH:
  2545  		d.Duration.Days = 0
  2546  		d.Duration.SetNanos(0)
  2547  	case types.IntervalDurationType_DAY:
  2548  		d.Duration.SetNanos(0)
  2549  	case types.IntervalDurationType_HOUR:
  2550  		d.Duration.SetNanos(d.Duration.Nanos() - d.Duration.Nanos()%time.Hour.Nanoseconds())
  2551  	case types.IntervalDurationType_MINUTE:
  2552  		d.Duration.SetNanos(d.Duration.Nanos() - d.Duration.Nanos()%time.Minute.Nanoseconds())
  2553  	case types.IntervalDurationType_SECOND, types.IntervalDurationType_UNSET:
  2554  		if itm.PrecisionIsSet || itm.Precision > 0 {
  2555  			prec := TimeFamilyPrecisionToRoundDuration(itm.Precision)
  2556  			d.Duration.SetNanos(time.Duration(d.Duration.Nanos()).Round(prec).Nanoseconds())
  2557  		}
  2558  	}
  2559  }
  2560  
  2561  // ParseDIntervalWithTypeMetadata is like ParseDInterval, but it also takes a
  2562  // types.IntervalTypeMetadata that both specifies the units for unitless, numeric intervals
  2563  // and also specifies the precision of the interval.
  2564  func ParseDIntervalWithTypeMetadata(s string, itm types.IntervalTypeMetadata) (*DInterval, error) {
  2565  	d, err := parseDInterval(s, itm)
  2566  	if err != nil {
  2567  		return nil, err
  2568  	}
  2569  	truncateDInterval(d, itm)
  2570  	return d, nil
  2571  }
  2572  
  2573  func parseDInterval(s string, itm types.IntervalTypeMetadata) (*DInterval, error) {
  2574  	// At this time the only supported interval formats are:
  2575  	// - SQL standard.
  2576  	// - Postgres compatible.
  2577  	// - iso8601 format (with designators only), see interval.go for
  2578  	//   sources of documentation.
  2579  	// - Golang time.parseDuration compatible.
  2580  
  2581  	// If it's a blank string, exit early.
  2582  	if len(s) == 0 {
  2583  		return nil, makeParseError(s, types.Interval, nil)
  2584  	}
  2585  	if s[0] == 'P' {
  2586  		// If it has a leading P we're most likely working with an iso8601
  2587  		// interval.
  2588  		dur, err := iso8601ToDuration(s)
  2589  		if err != nil {
  2590  			return nil, makeParseError(s, types.Interval, err)
  2591  		}
  2592  		return &DInterval{Duration: dur}, nil
  2593  	}
  2594  	if strings.IndexFunc(s, unicode.IsLetter) == -1 {
  2595  		// If it has no letter, then we're most likely working with a SQL standard
  2596  		// interval, as both postgres and golang have letter(s) and iso8601 has been tested.
  2597  		dur, err := sqlStdToDuration(s, itm)
  2598  		if err != nil {
  2599  			return nil, makeParseError(s, types.Interval, err)
  2600  		}
  2601  		return &DInterval{Duration: dur}, nil
  2602  	}
  2603  
  2604  	// We're either a postgres string or a Go duration.
  2605  	// Our postgres syntax parser also supports golang, so just use that for both.
  2606  	dur, err := parseDuration(s, itm)
  2607  	if err != nil {
  2608  		return nil, makeParseError(s, types.Interval, err)
  2609  	}
  2610  	return &DInterval{Duration: dur}, nil
  2611  }
  2612  
  2613  // ResolvedType implements the TypedExpr interface.
  2614  func (*DInterval) ResolvedType() *types.T {
  2615  	return types.Interval
  2616  }
  2617  
  2618  // Compare implements the Datum interface.
  2619  func (d *DInterval) Compare(ctx *EvalContext, other Datum) int {
  2620  	if other == DNull {
  2621  		// NULL is less than any non-NULL value.
  2622  		return 1
  2623  	}
  2624  	v, ok := UnwrapDatum(ctx, other).(*DInterval)
  2625  	if !ok {
  2626  		panic(makeUnsupportedComparisonMessage(d, other))
  2627  	}
  2628  	return d.Duration.Compare(v.Duration)
  2629  }
  2630  
  2631  // Prev implements the Datum interface.
  2632  func (d *DInterval) Prev(_ *EvalContext) (Datum, bool) {
  2633  	return nil, false
  2634  }
  2635  
  2636  // Next implements the Datum interface.
  2637  func (d *DInterval) Next(_ *EvalContext) (Datum, bool) {
  2638  	return nil, false
  2639  }
  2640  
  2641  // IsMax implements the Datum interface.
  2642  func (d *DInterval) IsMax(_ *EvalContext) bool {
  2643  	return d.Duration == dMaxInterval.Duration
  2644  }
  2645  
  2646  // IsMin implements the Datum interface.
  2647  func (d *DInterval) IsMin(_ *EvalContext) bool {
  2648  	return d.Duration == dMinInterval.Duration
  2649  }
  2650  
  2651  var (
  2652  	dZeroInterval = &DInterval{}
  2653  	dMaxInterval  = &DInterval{duration.MakeDuration(math.MaxInt64, math.MaxInt64, math.MaxInt64)}
  2654  	dMinInterval  = &DInterval{duration.MakeDuration(math.MinInt64, math.MinInt64, math.MinInt64)}
  2655  )
  2656  
  2657  // Max implements the Datum interface.
  2658  func (d *DInterval) Max(_ *EvalContext) (Datum, bool) {
  2659  	return dMaxInterval, true
  2660  }
  2661  
  2662  // Min implements the Datum interface.
  2663  func (d *DInterval) Min(_ *EvalContext) (Datum, bool) {
  2664  	return dMinInterval, true
  2665  }
  2666  
  2667  // ValueAsString returns the interval as a string (e.g. "1h2m").
  2668  func (d *DInterval) ValueAsString() string {
  2669  	return d.Duration.String()
  2670  }
  2671  
  2672  // AmbiguousFormat implements the Datum interface.
  2673  func (*DInterval) AmbiguousFormat() bool { return true }
  2674  
  2675  // Format implements the NodeFormatter interface.
  2676  func (d *DInterval) Format(ctx *FmtCtx) {
  2677  	f := ctx.flags
  2678  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2679  	if !bareStrings {
  2680  		ctx.WriteByte('\'')
  2681  	}
  2682  	d.Duration.Format(&ctx.Buffer)
  2683  	if !bareStrings {
  2684  		ctx.WriteByte('\'')
  2685  	}
  2686  }
  2687  
  2688  // Size implements the Datum interface.
  2689  func (d *DInterval) Size() uintptr {
  2690  	return unsafe.Sizeof(*d)
  2691  }
  2692  
  2693  // DGeography is the Geometry Datum.
  2694  type DGeography struct {
  2695  	*geo.Geography
  2696  }
  2697  
  2698  // NewDGeography returns a new Geography Datum.
  2699  func NewDGeography(g *geo.Geography) *DGeography {
  2700  	return &DGeography{Geography: g}
  2701  }
  2702  
  2703  // AsDGeography attempts to retrieve a *DGeography from an Expr, returning a
  2704  // *DGeography and a flag signifying whether the assertion was successful. The
  2705  // function should be used instead of direct type assertions wherever a
  2706  // *DGeography wrapped by a *DOidWrapper is possible.
  2707  func AsDGeography(e Expr) (*DGeography, bool) {
  2708  	switch t := e.(type) {
  2709  	case *DGeography:
  2710  		return t, true
  2711  	case *DOidWrapper:
  2712  		return AsDGeography(t.Wrapped)
  2713  	}
  2714  	return nil, false
  2715  }
  2716  
  2717  // MustBeDGeography attempts to retrieve a *DGeography from an Expr, panicking
  2718  // if the assertion fails.
  2719  func MustBeDGeography(e Expr) *DGeography {
  2720  	i, ok := AsDGeography(e)
  2721  	if !ok {
  2722  		panic(errors.AssertionFailedf("expected *DGeography, found %T", e))
  2723  	}
  2724  	return i
  2725  }
  2726  
  2727  // ParseDGeography attempts to pass `str` as a Geography type.
  2728  func ParseDGeography(str string) (*DGeography, error) {
  2729  	g, err := geo.ParseGeography(str)
  2730  	if err != nil {
  2731  		return nil, errors.Wrapf(err, "could not parse geography")
  2732  	}
  2733  	return &DGeography{Geography: g}, nil
  2734  }
  2735  
  2736  // ResolvedType implements the TypedExpr interface.
  2737  func (*DGeography) ResolvedType() *types.T {
  2738  	return types.Geography
  2739  }
  2740  
  2741  // Compare implements the Datum interface.
  2742  func (d *DGeography) Compare(ctx *EvalContext, other Datum) int {
  2743  	if other == DNull {
  2744  		// NULL is less than any non-NULL value.
  2745  		return 1
  2746  	}
  2747  	return bytes.Compare(d.EWKB(), other.(*DGeography).EWKB())
  2748  }
  2749  
  2750  // Prev implements the Datum interface.
  2751  func (d *DGeography) Prev(ctx *EvalContext) (Datum, bool) {
  2752  	return nil, false
  2753  }
  2754  
  2755  // Next implements the Datum interface.
  2756  func (d *DGeography) Next(ctx *EvalContext) (Datum, bool) {
  2757  	return nil, false
  2758  }
  2759  
  2760  // IsMax implements the Datum interface.
  2761  func (d *DGeography) IsMax(_ *EvalContext) bool {
  2762  	return false
  2763  }
  2764  
  2765  // IsMin implements the Datum interface.
  2766  func (d *DGeography) IsMin(_ *EvalContext) bool {
  2767  	return false
  2768  }
  2769  
  2770  // Max implements the Datum interface.
  2771  func (d *DGeography) Max(_ *EvalContext) (Datum, bool) {
  2772  	return nil, false
  2773  }
  2774  
  2775  // Min implements the Datum interface.
  2776  func (d *DGeography) Min(_ *EvalContext) (Datum, bool) {
  2777  	return nil, false
  2778  }
  2779  
  2780  // AmbiguousFormat implements the Datum interface.
  2781  func (*DGeography) AmbiguousFormat() bool { return true }
  2782  
  2783  // Format implements the NodeFormatter interface.
  2784  func (d *DGeography) Format(ctx *FmtCtx) {
  2785  	f := ctx.flags
  2786  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2787  	if !bareStrings {
  2788  		ctx.WriteByte('\'')
  2789  	}
  2790  	ctx.WriteString(d.Geography.EWKBHex())
  2791  	if !bareStrings {
  2792  		ctx.WriteByte('\'')
  2793  	}
  2794  }
  2795  
  2796  // Size implements the Datum interface.
  2797  func (d *DGeography) Size() uintptr {
  2798  	return unsafe.Sizeof(*d)
  2799  }
  2800  
  2801  // DGeometry is the Geometry Datum.
  2802  type DGeometry struct {
  2803  	*geo.Geometry
  2804  }
  2805  
  2806  // NewDGeometry returns a new Geometry Datum.
  2807  func NewDGeometry(g *geo.Geometry) *DGeometry {
  2808  	return &DGeometry{Geometry: g}
  2809  }
  2810  
  2811  // AsDGeometry attempts to retrieve a *DGeometry from an Expr, returning a
  2812  // *DGeometry and a flag signifying whether the assertion was successful. The
  2813  // function should be used instead of direct type assertions wherever a
  2814  // *DGeometry wrapped by a *DOidWrapper is possible.
  2815  func AsDGeometry(e Expr) (*DGeometry, bool) {
  2816  	switch t := e.(type) {
  2817  	case *DGeometry:
  2818  		return t, true
  2819  	case *DOidWrapper:
  2820  		return AsDGeometry(t.Wrapped)
  2821  	}
  2822  	return nil, false
  2823  }
  2824  
  2825  // MustBeDGeometry attempts to retrieve a *DGeometry from an Expr, panicking
  2826  // if the assertion fails.
  2827  func MustBeDGeometry(e Expr) *DGeometry {
  2828  	i, ok := AsDGeometry(e)
  2829  	if !ok {
  2830  		panic(errors.AssertionFailedf("expected *DGeometry, found %T", e))
  2831  	}
  2832  	return i
  2833  }
  2834  
  2835  // ParseDGeometry attempts to pass `str` as a Geometry type.
  2836  func ParseDGeometry(str string) (*DGeometry, error) {
  2837  	g, err := geo.ParseGeometry(str)
  2838  	if err != nil {
  2839  		return nil, errors.Wrapf(err, "could not parse geometry")
  2840  	}
  2841  	return &DGeometry{Geometry: g}, nil
  2842  }
  2843  
  2844  // ResolvedType implements the TypedExpr interface.
  2845  func (*DGeometry) ResolvedType() *types.T {
  2846  	return types.Geometry
  2847  }
  2848  
  2849  // Compare implements the Datum interface.
  2850  func (d *DGeometry) Compare(ctx *EvalContext, other Datum) int {
  2851  	if other == DNull {
  2852  		// NULL is less than any non-NULL value.
  2853  		return 1
  2854  	}
  2855  	return bytes.Compare(d.EWKB(), other.(*DGeometry).EWKB())
  2856  }
  2857  
  2858  // Prev implements the Datum interface.
  2859  func (d *DGeometry) Prev(ctx *EvalContext) (Datum, bool) {
  2860  	return nil, false
  2861  }
  2862  
  2863  // Next implements the Datum interface.
  2864  func (d *DGeometry) Next(ctx *EvalContext) (Datum, bool) {
  2865  	return nil, false
  2866  }
  2867  
  2868  // IsMax implements the Datum interface.
  2869  func (d *DGeometry) IsMax(_ *EvalContext) bool {
  2870  	return false
  2871  }
  2872  
  2873  // IsMin implements the Datum interface.
  2874  func (d *DGeometry) IsMin(_ *EvalContext) bool {
  2875  	return false
  2876  }
  2877  
  2878  // Max implements the Datum interface.
  2879  func (d *DGeometry) Max(_ *EvalContext) (Datum, bool) {
  2880  	return nil, false
  2881  }
  2882  
  2883  // Min implements the Datum interface.
  2884  func (d *DGeometry) Min(_ *EvalContext) (Datum, bool) {
  2885  	return nil, false
  2886  }
  2887  
  2888  // AmbiguousFormat implements the Datum interface.
  2889  func (*DGeometry) AmbiguousFormat() bool { return true }
  2890  
  2891  // Format implements the NodeFormatter interface.
  2892  func (d *DGeometry) Format(ctx *FmtCtx) {
  2893  	f := ctx.flags
  2894  	bareStrings := f.HasFlags(FmtFlags(lex.EncBareStrings))
  2895  	if !bareStrings {
  2896  		ctx.WriteByte('\'')
  2897  	}
  2898  	ctx.WriteString(d.Geometry.EWKBHex())
  2899  	if !bareStrings {
  2900  		ctx.WriteByte('\'')
  2901  	}
  2902  }
  2903  
  2904  // Size implements the Datum interface.
  2905  func (d *DGeometry) Size() uintptr {
  2906  	return unsafe.Sizeof(*d)
  2907  }
  2908  
  2909  // DJSON is the JSON Datum.
  2910  type DJSON struct{ json.JSON }
  2911  
  2912  // NewDJSON is a helper routine to create a DJSON initialized from its argument.
  2913  func NewDJSON(j json.JSON) *DJSON {
  2914  	return &DJSON{j}
  2915  }
  2916  
  2917  // ParseDJSON takes a string of JSON and returns a DJSON value.
  2918  func ParseDJSON(s string) (Datum, error) {
  2919  	j, err := json.ParseJSON(s)
  2920  	if err != nil {
  2921  		return nil, pgerror.Wrapf(err, pgcode.Syntax, "could not parse JSON")
  2922  	}
  2923  	return NewDJSON(j), nil
  2924  }
  2925  
  2926  // MakeDJSON returns a JSON value given a Go-style representation of JSON.
  2927  // * JSON null is Go `nil`,
  2928  // * JSON true is Go `true`,
  2929  // * JSON false is Go `false`,
  2930  // * JSON numbers are json.Number | int | int64 | float64,
  2931  // * JSON string is a Go string,
  2932  // * JSON array is a Go []interface{},
  2933  // * JSON object is a Go map[string]interface{}.
  2934  func MakeDJSON(d interface{}) (Datum, error) {
  2935  	j, err := json.MakeJSON(d)
  2936  	if err != nil {
  2937  		return nil, err
  2938  	}
  2939  	return &DJSON{j}, nil
  2940  }
  2941  
  2942  var dNullJSON = NewDJSON(json.NullJSONValue)
  2943  
  2944  // AsDJSON attempts to retrieve a *DJSON from an Expr, returning a *DJSON and
  2945  // a flag signifying whether the assertion was successful. The function should
  2946  // be used instead of direct type assertions wherever a *DJSON wrapped by a
  2947  // *DOidWrapper is possible.
  2948  func AsDJSON(e Expr) (*DJSON, bool) {
  2949  	switch t := e.(type) {
  2950  	case *DJSON:
  2951  		return t, true
  2952  	case *DOidWrapper:
  2953  		return AsDJSON(t.Wrapped)
  2954  	}
  2955  	return nil, false
  2956  }
  2957  
  2958  // MustBeDJSON attempts to retrieve a DJSON from an Expr, panicking if the
  2959  // assertion fails.
  2960  func MustBeDJSON(e Expr) DJSON {
  2961  	i, ok := AsDJSON(e)
  2962  	if !ok {
  2963  		panic(errors.AssertionFailedf("expected *DJSON, found %T", e))
  2964  	}
  2965  	return *i
  2966  }
  2967  
  2968  // AsJSON converts a datum into our standard json representation.
  2969  func AsJSON(d Datum, loc *time.Location) (json.JSON, error) {
  2970  	switch t := d.(type) {
  2971  	case *DBool:
  2972  		return json.FromBool(bool(*t)), nil
  2973  	case *DInt:
  2974  		return json.FromInt(int(*t)), nil
  2975  	case *DFloat:
  2976  		return json.FromFloat64(float64(*t))
  2977  	case *DDecimal:
  2978  		return json.FromDecimal(t.Decimal), nil
  2979  	case *DString:
  2980  		return json.FromString(string(*t)), nil
  2981  	case *DCollatedString:
  2982  		return json.FromString(t.Contents), nil
  2983  	case *DJSON:
  2984  		return t.JSON, nil
  2985  	case *DArray:
  2986  		builder := json.NewArrayBuilder(t.Len())
  2987  		for _, e := range t.Array {
  2988  			j, err := AsJSON(e, loc)
  2989  			if err != nil {
  2990  				return nil, err
  2991  			}
  2992  			builder.Add(j)
  2993  		}
  2994  		return builder.Build(), nil
  2995  	case *DTuple:
  2996  		builder := json.NewObjectBuilder(len(t.D))
  2997  		// We need to make sure that t.typ is initialized before getting the tuple
  2998  		// labels (it is valid for t.typ be left uninitialized when instantiating a
  2999  		// DTuple).
  3000  		t.maybePopulateType()
  3001  		labels := t.typ.TupleLabels()
  3002  		for i, e := range t.D {
  3003  			j, err := AsJSON(e, loc)
  3004  			if err != nil {
  3005  				return nil, err
  3006  			}
  3007  			var key string
  3008  			if i >= len(labels) {
  3009  				key = fmt.Sprintf("f%d", i+1)
  3010  			} else {
  3011  				key = labels[i]
  3012  			}
  3013  			builder.Add(key, j)
  3014  		}
  3015  		return builder.Build(), nil
  3016  	case *DTimestampTZ:
  3017  		// Our normal timestamp-formatting code uses a variation on RFC 3339,
  3018  		// without the T separator. This causes some compatibility problems
  3019  		// with certain JSON consumers, so we'll use an alternate formatting
  3020  		// path here to maintain consistency with PostgreSQL.
  3021  		return json.FromString(t.Time.In(loc).Format(time.RFC3339Nano)), nil
  3022  	case *DTimestamp:
  3023  		// This is RFC3339Nano, but without the TZ fields.
  3024  		return json.FromString(t.UTC().Format("2006-01-02T15:04:05.999999999")), nil
  3025  	case *DDate, *DUuid, *DOid, *DInterval, *DBytes, *DIPAddr, *DTime, *DTimeTZ, *DBitArray,
  3026  		*DGeography, *DGeometry:
  3027  		return json.FromString(AsStringWithFlags(t, FmtBareStrings)), nil
  3028  	default:
  3029  		if d == DNull {
  3030  			return json.NullJSONValue, nil
  3031  		}
  3032  
  3033  		return nil, errors.AssertionFailedf("unexpected type %T for AsJSON", d)
  3034  	}
  3035  }
  3036  
  3037  // ResolvedType implements the TypedExpr interface.
  3038  func (*DJSON) ResolvedType() *types.T {
  3039  	return types.Jsonb
  3040  }
  3041  
  3042  // Compare implements the Datum interface.
  3043  func (d *DJSON) Compare(ctx *EvalContext, other Datum) int {
  3044  	if other == DNull {
  3045  		// NULL is less than any non-NULL value.
  3046  		return 1
  3047  	}
  3048  	v, ok := UnwrapDatum(ctx, other).(*DJSON)
  3049  	if !ok {
  3050  		panic(makeUnsupportedComparisonMessage(d, other))
  3051  	}
  3052  	// No avenue for us to pass up this error here at the moment, but Compare
  3053  	// only errors for invalid encoded data.
  3054  	// TODO(justin): modify Compare to allow passing up errors.
  3055  	c, err := d.JSON.Compare(v.JSON)
  3056  	if err != nil {
  3057  		panic(err)
  3058  	}
  3059  	return c
  3060  }
  3061  
  3062  // Prev implements the Datum interface.
  3063  func (d *DJSON) Prev(_ *EvalContext) (Datum, bool) {
  3064  	return nil, false
  3065  }
  3066  
  3067  // Next implements the Datum interface.
  3068  func (d *DJSON) Next(_ *EvalContext) (Datum, bool) {
  3069  	return nil, false
  3070  }
  3071  
  3072  // IsMax implements the Datum interface.
  3073  func (d *DJSON) IsMax(_ *EvalContext) bool {
  3074  	return false
  3075  }
  3076  
  3077  // IsMin implements the Datum interface.
  3078  func (d *DJSON) IsMin(_ *EvalContext) bool {
  3079  	return d.JSON == json.NullJSONValue
  3080  }
  3081  
  3082  // Max implements the Datum interface.
  3083  func (d *DJSON) Max(_ *EvalContext) (Datum, bool) {
  3084  	return nil, false
  3085  }
  3086  
  3087  // Min implements the Datum interface.
  3088  func (d *DJSON) Min(_ *EvalContext) (Datum, bool) {
  3089  	return &DJSON{json.NullJSONValue}, true
  3090  }
  3091  
  3092  // AmbiguousFormat implements the Datum interface.
  3093  func (*DJSON) AmbiguousFormat() bool { return true }
  3094  
  3095  // Format implements the NodeFormatter interface.
  3096  func (d *DJSON) Format(ctx *FmtCtx) {
  3097  	// TODO(justin): ideally the JSON string encoder should know it needs to
  3098  	// escape things to be inside SQL strings in order to avoid this allocation.
  3099  	s := d.JSON.String()
  3100  	if ctx.flags.HasFlags(fmtRawStrings) {
  3101  		ctx.WriteString(s)
  3102  	} else {
  3103  		lex.EncodeSQLStringWithFlags(&ctx.Buffer, s, ctx.flags.EncodeFlags())
  3104  	}
  3105  }
  3106  
  3107  // Size implements the Datum interface.
  3108  // TODO(justin): is this a frequently-called method? Should we be caching the computed size?
  3109  func (d *DJSON) Size() uintptr {
  3110  	return unsafe.Sizeof(*d) + d.JSON.Size()
  3111  }
  3112  
  3113  // DTuple is the tuple Datum.
  3114  type DTuple struct {
  3115  	D Datums
  3116  
  3117  	// sorted indicates that the values in D are pre-sorted.
  3118  	// This is used to accelerate IN comparisons.
  3119  	sorted bool
  3120  
  3121  	// typ is the tuple's type.
  3122  	//
  3123  	// The Types sub-field can be initially uninitialized, and is then
  3124  	// populated upon first invocation of ResolvedTypes(). If
  3125  	// initialized it must have the same arity as D.
  3126  	//
  3127  	// The Labels sub-field can be left nil. If populated, it must have
  3128  	// the same arity as D.
  3129  	typ *types.T
  3130  }
  3131  
  3132  // NewDTuple creates a *DTuple with the provided datums. When creating a new
  3133  // DTuple with Datums that are known to be sorted in ascending order, chain
  3134  // this call with DTuple.SetSorted.
  3135  func NewDTuple(typ *types.T, d ...Datum) *DTuple {
  3136  	return &DTuple{D: d, typ: typ}
  3137  }
  3138  
  3139  // NewDTupleWithLen creates a *DTuple with the provided length.
  3140  func NewDTupleWithLen(typ *types.T, l int) *DTuple {
  3141  	return &DTuple{D: make(Datums, l), typ: typ}
  3142  }
  3143  
  3144  // AsDTuple attempts to retrieve a *DTuple from an Expr, returning a *DTuple and
  3145  // a flag signifying whether the assertion was successful. The function should
  3146  // be used instead of direct type assertions wherever a *DTuple wrapped by a
  3147  // *DOidWrapper is possible.
  3148  func AsDTuple(e Expr) (*DTuple, bool) {
  3149  	switch t := e.(type) {
  3150  	case *DTuple:
  3151  		return t, true
  3152  	case *DOidWrapper:
  3153  		return AsDTuple(t.Wrapped)
  3154  	}
  3155  	return nil, false
  3156  }
  3157  
  3158  // maybePopulateType populates the tuple's type if it hasn't yet been
  3159  // populated.
  3160  func (d *DTuple) maybePopulateType() {
  3161  	if d.typ == nil {
  3162  		contents := make([]*types.T, len(d.D))
  3163  		for i, v := range d.D {
  3164  			contents[i] = v.ResolvedType()
  3165  		}
  3166  		d.typ = types.MakeTuple(contents)
  3167  	}
  3168  }
  3169  
  3170  // ResolvedType implements the TypedExpr interface.
  3171  func (d *DTuple) ResolvedType() *types.T {
  3172  	d.maybePopulateType()
  3173  	return d.typ
  3174  }
  3175  
  3176  // Compare implements the Datum interface.
  3177  func (d *DTuple) Compare(ctx *EvalContext, other Datum) int {
  3178  	if other == DNull {
  3179  		// NULL is less than any non-NULL value.
  3180  		return 1
  3181  	}
  3182  	v, ok := UnwrapDatum(ctx, other).(*DTuple)
  3183  	if !ok {
  3184  		panic(makeUnsupportedComparisonMessage(d, other))
  3185  	}
  3186  	n := len(d.D)
  3187  	if n > len(v.D) {
  3188  		n = len(v.D)
  3189  	}
  3190  	for i := 0; i < n; i++ {
  3191  		c := d.D[i].Compare(ctx, v.D[i])
  3192  		if c != 0 {
  3193  			return c
  3194  		}
  3195  	}
  3196  	if len(d.D) < len(v.D) {
  3197  		return -1
  3198  	}
  3199  	if len(d.D) > len(v.D) {
  3200  		return 1
  3201  	}
  3202  	return 0
  3203  }
  3204  
  3205  // Prev implements the Datum interface.
  3206  func (d *DTuple) Prev(ctx *EvalContext) (Datum, bool) {
  3207  	// Note: (a:decimal, b:int, c:int) has a prev value; that's (a, b,
  3208  	// c-1). With an exception if c is MinInt64, in which case the prev
  3209  	// value is (a, b-1, max(_ *EvalContext)). However, (a:int, b:decimal) does not
  3210  	// have a prev value, because decimal doesn't have one.
  3211  	//
  3212  	// In general, a tuple has a prev value if and only if it ends with
  3213  	// zero or more values that are a minimum and a maximum value of the
  3214  	// same type exists, and the first element before that has a prev
  3215  	// value.
  3216  	res := NewDTupleWithLen(d.typ, len(d.D))
  3217  	copy(res.D, d.D)
  3218  	for i := len(res.D) - 1; i >= 0; i-- {
  3219  		if !res.D[i].IsMin(ctx) {
  3220  			prevVal, ok := res.D[i].Prev(ctx)
  3221  			if !ok {
  3222  				return nil, false
  3223  			}
  3224  			res.D[i] = prevVal
  3225  			break
  3226  		}
  3227  		maxVal, ok := res.D[i].Max(ctx)
  3228  		if !ok {
  3229  			return nil, false
  3230  		}
  3231  		res.D[i] = maxVal
  3232  	}
  3233  	return res, true
  3234  }
  3235  
  3236  // Next implements the Datum interface.
  3237  func (d *DTuple) Next(ctx *EvalContext) (Datum, bool) {
  3238  	// Note: (a:decimal, b:int, c:int) has a next value; that's (a, b,
  3239  	// c+1). With an exception if c is MaxInt64, in which case the next
  3240  	// value is (a, b+1, min(_ *EvalContext)). However, (a:int, b:decimal) does not
  3241  	// have a next value, because decimal doesn't have one.
  3242  	//
  3243  	// In general, a tuple has a next value if and only if it ends with
  3244  	// zero or more values that are a maximum and a minimum value of the
  3245  	// same type exists, and the first element before that has a next
  3246  	// value.
  3247  	res := NewDTupleWithLen(d.typ, len(d.D))
  3248  	copy(res.D, d.D)
  3249  	for i := len(res.D) - 1; i >= 0; i-- {
  3250  		if !res.D[i].IsMax(ctx) {
  3251  			nextVal, ok := res.D[i].Next(ctx)
  3252  			if !ok {
  3253  				return nil, false
  3254  			}
  3255  			res.D[i] = nextVal
  3256  			break
  3257  		}
  3258  		// TODO(#12022): temporary workaround; see the interface comment.
  3259  		res.D[i] = DNull
  3260  	}
  3261  	return res, true
  3262  }
  3263  
  3264  // Max implements the Datum interface.
  3265  func (d *DTuple) Max(ctx *EvalContext) (Datum, bool) {
  3266  	res := NewDTupleWithLen(d.typ, len(d.D))
  3267  	for i, v := range d.D {
  3268  		m, ok := v.Max(ctx)
  3269  		if !ok {
  3270  			return nil, false
  3271  		}
  3272  		res.D[i] = m
  3273  	}
  3274  	return res, true
  3275  }
  3276  
  3277  // Min implements the Datum interface.
  3278  func (d *DTuple) Min(ctx *EvalContext) (Datum, bool) {
  3279  	res := NewDTupleWithLen(d.typ, len(d.D))
  3280  	for i, v := range d.D {
  3281  		m, ok := v.Min(ctx)
  3282  		if !ok {
  3283  			return nil, false
  3284  		}
  3285  		res.D[i] = m
  3286  	}
  3287  	return res, true
  3288  }
  3289  
  3290  // IsMax implements the Datum interface.
  3291  func (d *DTuple) IsMax(ctx *EvalContext) bool {
  3292  	for _, v := range d.D {
  3293  		if !v.IsMax(ctx) {
  3294  			return false
  3295  		}
  3296  	}
  3297  	return true
  3298  }
  3299  
  3300  // IsMin implements the Datum interface.
  3301  func (d *DTuple) IsMin(ctx *EvalContext) bool {
  3302  	for _, v := range d.D {
  3303  		if !v.IsMin(ctx) {
  3304  			return false
  3305  		}
  3306  	}
  3307  	return true
  3308  }
  3309  
  3310  // AmbiguousFormat implements the Datum interface.
  3311  func (*DTuple) AmbiguousFormat() bool { return false }
  3312  
  3313  // Format implements the NodeFormatter interface.
  3314  func (d *DTuple) Format(ctx *FmtCtx) {
  3315  	if ctx.HasFlags(fmtPgwireFormat) {
  3316  		d.pgwireFormat(ctx)
  3317  		return
  3318  	}
  3319  
  3320  	typ := d.ResolvedType()
  3321  	showLabels := len(typ.TupleLabels()) > 0
  3322  	if showLabels {
  3323  		ctx.WriteByte('(')
  3324  	}
  3325  	ctx.WriteByte('(')
  3326  	comma := ""
  3327  	parsable := ctx.HasFlags(FmtParsable)
  3328  	for i, v := range d.D {
  3329  		ctx.WriteString(comma)
  3330  		ctx.FormatNode(v)
  3331  		if parsable && (v == DNull) && len(typ.TupleContents()) > i {
  3332  			// If Tuple has types.Unknown for this slot, then we can't determine
  3333  			// the column type to write this annotation. Somebody else will provide
  3334  			// an error message in this case, if necessary, so just skip the
  3335  			// annotation and continue.
  3336  			if typ.TupleContents()[i].Family() != types.UnknownFamily {
  3337  				ctx.WriteString("::")
  3338  				ctx.WriteString(typ.TupleContents()[i].SQLString())
  3339  			}
  3340  		}
  3341  		comma = ", "
  3342  	}
  3343  	if len(d.D) == 1 {
  3344  		// Ensure the pretty-printed 1-value tuple is not ambiguous with
  3345  		// the equivalent value enclosed in grouping parentheses.
  3346  		ctx.WriteByte(',')
  3347  	}
  3348  	ctx.WriteByte(')')
  3349  	if showLabels {
  3350  		ctx.WriteString(" AS ")
  3351  		comma := ""
  3352  		for i := range typ.TupleLabels() {
  3353  			ctx.WriteString(comma)
  3354  			ctx.FormatNode((*Name)(&typ.TupleLabels()[i]))
  3355  			comma = ", "
  3356  		}
  3357  		ctx.WriteByte(')')
  3358  	}
  3359  }
  3360  
  3361  // Sorted returns true if the tuple is known to be sorted (and contains no
  3362  // NULLs).
  3363  func (d *DTuple) Sorted() bool {
  3364  	return d.sorted
  3365  }
  3366  
  3367  // SetSorted sets the sorted flag on the DTuple. This should be used when a
  3368  // DTuple is known to be sorted based on the datums added to it.
  3369  func (d *DTuple) SetSorted() *DTuple {
  3370  	if d.ContainsNull() {
  3371  		// A DTuple that contains a NULL (see ContainsNull) cannot be marked as sorted.
  3372  		return d
  3373  	}
  3374  	d.sorted = true
  3375  	return d
  3376  }
  3377  
  3378  // AssertSorted asserts that the DTuple is sorted.
  3379  func (d *DTuple) AssertSorted() {
  3380  	if !d.sorted {
  3381  		panic(errors.AssertionFailedf("expected sorted tuple, found %#v", d))
  3382  	}
  3383  }
  3384  
  3385  // SearchSorted searches the tuple for the target Datum, returning an int with
  3386  // the same contract as sort.Search and a boolean flag signifying whether the datum
  3387  // was found. It assumes that the DTuple is sorted and panics if it is not.
  3388  //
  3389  // The target Datum cannot be NULL or a DTuple that contains NULLs (we cannot
  3390  // binary search in this case; for example `(1, NULL) IN ((1, 2), ..)` needs to
  3391  // be
  3392  func (d *DTuple) SearchSorted(ctx *EvalContext, target Datum) (int, bool) {
  3393  	d.AssertSorted()
  3394  	if target == DNull {
  3395  		panic(errors.AssertionFailedf("NULL target (d: %s)", d))
  3396  	}
  3397  	if t, ok := target.(*DTuple); ok && t.ContainsNull() {
  3398  		panic(errors.AssertionFailedf("target containing NULLs: %#v (d: %s)", target, d))
  3399  	}
  3400  	i := sort.Search(len(d.D), func(i int) bool {
  3401  		return d.D[i].Compare(ctx, target) >= 0
  3402  	})
  3403  	found := i < len(d.D) && d.D[i].Compare(ctx, target) == 0
  3404  	return i, found
  3405  }
  3406  
  3407  // Normalize sorts and uniques the datum tuple.
  3408  func (d *DTuple) Normalize(ctx *EvalContext) {
  3409  	d.sort(ctx)
  3410  	d.makeUnique(ctx)
  3411  }
  3412  
  3413  func (d *DTuple) sort(ctx *EvalContext) {
  3414  	if !d.sorted {
  3415  		sort.Slice(d.D, func(i, j int) bool {
  3416  			return d.D[i].Compare(ctx, d.D[j]) < 0
  3417  		})
  3418  		d.SetSorted()
  3419  	}
  3420  }
  3421  
  3422  func (d *DTuple) makeUnique(ctx *EvalContext) {
  3423  	n := 0
  3424  	for i := 0; i < len(d.D); i++ {
  3425  		if n == 0 || d.D[n-1].Compare(ctx, d.D[i]) < 0 {
  3426  			d.D[n] = d.D[i]
  3427  			n++
  3428  		}
  3429  	}
  3430  	d.D = d.D[:n]
  3431  }
  3432  
  3433  // Size implements the Datum interface.
  3434  func (d *DTuple) Size() uintptr {
  3435  	sz := unsafe.Sizeof(*d)
  3436  	for _, e := range d.D {
  3437  		dsz := e.Size()
  3438  		sz += dsz
  3439  	}
  3440  	return sz
  3441  }
  3442  
  3443  // ContainsNull returns true if the tuple contains NULL, possibly nested inside
  3444  // other tuples. For example, all the following tuples contain NULL:
  3445  //  (1, 2, NULL)
  3446  //  ((1, 1), (2, NULL))
  3447  //  (((1, 1), (2, 2)), ((3, 3), (4, NULL)))
  3448  func (d *DTuple) ContainsNull() bool {
  3449  	for _, r := range d.D {
  3450  		if r == DNull {
  3451  			return true
  3452  		}
  3453  		if t, ok := r.(*DTuple); ok {
  3454  			if t.ContainsNull() {
  3455  				return true
  3456  			}
  3457  		}
  3458  	}
  3459  	return false
  3460  }
  3461  
  3462  type dNull struct{}
  3463  
  3464  // ResolvedType implements the TypedExpr interface.
  3465  func (dNull) ResolvedType() *types.T {
  3466  	return types.Unknown
  3467  }
  3468  
  3469  // Compare implements the Datum interface.
  3470  func (d dNull) Compare(ctx *EvalContext, other Datum) int {
  3471  	if other == DNull {
  3472  		return 0
  3473  	}
  3474  	return -1
  3475  }
  3476  
  3477  // Prev implements the Datum interface.
  3478  func (d dNull) Prev(_ *EvalContext) (Datum, bool) {
  3479  	return nil, false
  3480  }
  3481  
  3482  // Next implements the Datum interface.
  3483  func (d dNull) Next(_ *EvalContext) (Datum, bool) {
  3484  	return nil, false
  3485  }
  3486  
  3487  // IsMax implements the Datum interface.
  3488  func (dNull) IsMax(_ *EvalContext) bool {
  3489  	return true
  3490  }
  3491  
  3492  // IsMin implements the Datum interface.
  3493  func (dNull) IsMin(_ *EvalContext) bool {
  3494  	return true
  3495  }
  3496  
  3497  // Max implements the Datum interface.
  3498  func (dNull) Max(_ *EvalContext) (Datum, bool) {
  3499  	return DNull, true
  3500  }
  3501  
  3502  // Min implements the Datum interface.
  3503  func (dNull) Min(_ *EvalContext) (Datum, bool) {
  3504  	return DNull, true
  3505  }
  3506  
  3507  // AmbiguousFormat implements the Datum interface.
  3508  func (dNull) AmbiguousFormat() bool { return false }
  3509  
  3510  // Format implements the NodeFormatter interface.
  3511  func (dNull) Format(ctx *FmtCtx) {
  3512  	if ctx.HasFlags(fmtPgwireFormat) {
  3513  		// NULL sub-expressions in pgwire text values are represented with
  3514  		// the empty string.
  3515  		return
  3516  	}
  3517  	ctx.WriteString("NULL")
  3518  }
  3519  
  3520  // Size implements the Datum interface.
  3521  func (d dNull) Size() uintptr {
  3522  	return unsafe.Sizeof(d)
  3523  }
  3524  
  3525  // DArray is the array Datum. Any Datum inserted into a DArray are treated as
  3526  // text during serialization.
  3527  type DArray struct {
  3528  	ParamTyp *types.T
  3529  	Array    Datums
  3530  	// HasNulls is set to true if any of the datums within the array are null.
  3531  	// This is used in the binary array serialization format.
  3532  	HasNulls bool
  3533  	// HasNonNulls is set to true if any of the datums within the are non-null.
  3534  	// This is used in expression serialization (FmtParsable).
  3535  	HasNonNulls bool
  3536  
  3537  	// customOid, if non-0, is the oid of this array datum.
  3538  	customOid oid.Oid
  3539  }
  3540  
  3541  // NewDArray returns a DArray containing elements of the specified type.
  3542  func NewDArray(paramTyp *types.T) *DArray {
  3543  	return &DArray{ParamTyp: paramTyp}
  3544  }
  3545  
  3546  // AsDArray attempts to retrieve a *DArray from an Expr, returning a *DArray and
  3547  // a flag signifying whether the assertion was successful. The function should
  3548  // be used instead of direct type assertions wherever a *DArray wrapped by a
  3549  // *DOidWrapper is possible.
  3550  func AsDArray(e Expr) (*DArray, bool) {
  3551  	switch t := e.(type) {
  3552  	case *DArray:
  3553  		return t, true
  3554  	case *DOidWrapper:
  3555  		return AsDArray(t.Wrapped)
  3556  	}
  3557  	return nil, false
  3558  }
  3559  
  3560  // MustBeDArray attempts to retrieve a *DArray from an Expr, panicking if the
  3561  // assertion fails.
  3562  func MustBeDArray(e Expr) *DArray {
  3563  	i, ok := AsDArray(e)
  3564  	if !ok {
  3565  		panic(errors.AssertionFailedf("expected *DArray, found %T", e))
  3566  	}
  3567  	return i
  3568  }
  3569  
  3570  // ResolvedType implements the TypedExpr interface.
  3571  func (d *DArray) ResolvedType() *types.T {
  3572  	switch d.customOid {
  3573  	case oid.T_int2vector:
  3574  		return types.Int2Vector
  3575  	case oid.T_oidvector:
  3576  		return types.OidVector
  3577  	}
  3578  	return types.MakeArray(d.ParamTyp)
  3579  }
  3580  
  3581  // IsComposite implements the CompositeDatum interface.
  3582  func (d *DArray) IsComposite() bool {
  3583  	for _, elem := range d.Array {
  3584  		if cdatum, ok := elem.(CompositeDatum); ok && cdatum.IsComposite() {
  3585  			return true
  3586  		}
  3587  	}
  3588  	return false
  3589  }
  3590  
  3591  // FirstIndex returns the first index of the array. 1 for normal SQL arrays,
  3592  // which are 1-indexed, and 0 for the special Postgers vector types which are
  3593  // 0-indexed.
  3594  func (d *DArray) FirstIndex() int {
  3595  	switch d.customOid {
  3596  	case oid.T_int2vector, oid.T_oidvector:
  3597  		return 0
  3598  	}
  3599  	return 1
  3600  }
  3601  
  3602  // Compare implements the Datum interface.
  3603  func (d *DArray) Compare(ctx *EvalContext, other Datum) int {
  3604  	if other == DNull {
  3605  		// NULL is less than any non-NULL value.
  3606  		return 1
  3607  	}
  3608  	v, ok := UnwrapDatum(ctx, other).(*DArray)
  3609  	if !ok {
  3610  		panic(makeUnsupportedComparisonMessage(d, other))
  3611  	}
  3612  	n := d.Len()
  3613  	if n > v.Len() {
  3614  		n = v.Len()
  3615  	}
  3616  	for i := 0; i < n; i++ {
  3617  		c := d.Array[i].Compare(ctx, v.Array[i])
  3618  		if c != 0 {
  3619  			return c
  3620  		}
  3621  	}
  3622  	if d.Len() < v.Len() {
  3623  		return -1
  3624  	}
  3625  	if d.Len() > v.Len() {
  3626  		return 1
  3627  	}
  3628  	return 0
  3629  }
  3630  
  3631  // Prev implements the Datum interface.
  3632  func (d *DArray) Prev(_ *EvalContext) (Datum, bool) {
  3633  	return nil, false
  3634  }
  3635  
  3636  // Next implements the Datum interface.
  3637  func (d *DArray) Next(_ *EvalContext) (Datum, bool) {
  3638  	a := DArray{ParamTyp: d.ParamTyp, Array: make(Datums, d.Len()+1)}
  3639  	copy(a.Array, d.Array)
  3640  	a.Array[len(a.Array)-1] = DNull
  3641  	return &a, true
  3642  }
  3643  
  3644  // Max implements the Datum interface.
  3645  func (d *DArray) Max(_ *EvalContext) (Datum, bool) {
  3646  	return nil, false
  3647  }
  3648  
  3649  // Min implements the Datum interface.
  3650  func (d *DArray) Min(_ *EvalContext) (Datum, bool) {
  3651  	return &DArray{ParamTyp: d.ParamTyp}, true
  3652  }
  3653  
  3654  // IsMax implements the Datum interface.
  3655  func (d *DArray) IsMax(_ *EvalContext) bool {
  3656  	return false
  3657  }
  3658  
  3659  // IsMin implements the Datum interface.
  3660  func (d *DArray) IsMin(_ *EvalContext) bool {
  3661  	return d.Len() == 0
  3662  }
  3663  
  3664  // AmbiguousFormat implements the Datum interface.
  3665  func (d *DArray) AmbiguousFormat() bool {
  3666  	// The type of the array is ambiguous if it is empty or all-null; when
  3667  	// serializing we need to annotate it with the type.
  3668  	if d.ParamTyp.Family() == types.UnknownFamily {
  3669  		// If the array's type is unknown, marking it as ambiguous would cause the
  3670  		// expression formatter to try to annotate it with UNKNOWN[], which is not
  3671  		// a valid type. So an array of unknown type is (paradoxically) unambiguous.
  3672  		return false
  3673  	}
  3674  	return !d.HasNonNulls
  3675  }
  3676  
  3677  // Format implements the NodeFormatter interface.
  3678  func (d *DArray) Format(ctx *FmtCtx) {
  3679  	if ctx.HasFlags(fmtPgwireFormat) {
  3680  		d.pgwireFormat(ctx)
  3681  		return
  3682  	}
  3683  
  3684  	// If we want to export arrays, we need to ensure that
  3685  	// the datums within the arrays are formatted with enclosing quotes etc.
  3686  	if ctx.HasFlags(FmtExport) {
  3687  		oldFlags := ctx.flags
  3688  		ctx.flags = oldFlags & ^FmtExport | FmtParsable
  3689  		defer func() { ctx.flags = oldFlags }()
  3690  	}
  3691  
  3692  	ctx.WriteString("ARRAY[")
  3693  	comma := ""
  3694  	for _, v := range d.Array {
  3695  		ctx.WriteString(comma)
  3696  		ctx.FormatNode(v)
  3697  		comma = ","
  3698  	}
  3699  	ctx.WriteByte(']')
  3700  }
  3701  
  3702  const maxArrayLength = math.MaxInt32
  3703  
  3704  var errArrayTooLongError = errors.New("ARRAYs can be at most 2^31-1 elements long")
  3705  
  3706  // Validate checks that the given array is valid,
  3707  // for example, that it's not too big.
  3708  func (d *DArray) Validate() error {
  3709  	if d.Len() > maxArrayLength {
  3710  		return errors.WithStack(errArrayTooLongError)
  3711  	}
  3712  	return nil
  3713  }
  3714  
  3715  // Len returns the length of the Datum array.
  3716  func (d *DArray) Len() int {
  3717  	return len(d.Array)
  3718  }
  3719  
  3720  // Size implements the Datum interface.
  3721  func (d *DArray) Size() uintptr {
  3722  	sz := unsafe.Sizeof(*d)
  3723  	for _, e := range d.Array {
  3724  		dsz := e.Size()
  3725  		sz += dsz
  3726  	}
  3727  	return sz
  3728  }
  3729  
  3730  var errNonHomogeneousArray = pgerror.New(pgcode.ArraySubscript, "multidimensional arrays must have array expressions with matching dimensions")
  3731  
  3732  // Append appends a Datum to the array, whose parameterized type must be
  3733  // consistent with the type of the Datum.
  3734  func (d *DArray) Append(v Datum) error {
  3735  	if v != DNull && !d.ParamTyp.Equivalent(v.ResolvedType()) {
  3736  		return errors.AssertionFailedf("cannot append %s to array containing %s", d.ParamTyp,
  3737  			v.ResolvedType())
  3738  	}
  3739  	if d.Len() >= maxArrayLength {
  3740  		return errors.WithStack(errArrayTooLongError)
  3741  	}
  3742  	if d.ParamTyp.Family() == types.ArrayFamily {
  3743  		if v == DNull {
  3744  			return errNonHomogeneousArray
  3745  		}
  3746  		if d.Len() > 0 {
  3747  			prevItem := d.Array[d.Len()-1]
  3748  			if prevItem == DNull {
  3749  				return errNonHomogeneousArray
  3750  			}
  3751  			expectedLen := MustBeDArray(prevItem).Len()
  3752  			if MustBeDArray(v).Len() != expectedLen {
  3753  				return errNonHomogeneousArray
  3754  			}
  3755  		}
  3756  	}
  3757  	if v == DNull {
  3758  		d.HasNulls = true
  3759  	} else {
  3760  		d.HasNonNulls = true
  3761  	}
  3762  	d.Array = append(d.Array, v)
  3763  	return d.Validate()
  3764  }
  3765  
  3766  // DEnum represents an ENUM value.
  3767  type DEnum struct {
  3768  	// EnumType is the hydrated type of this enum.
  3769  	EnumTyp *types.T
  3770  	// PhysicalRep is a slice containing the encodable and ordered physical
  3771  	// representation of this datum. It is used for comparisons and encoding.
  3772  	PhysicalRep []byte
  3773  	// LogicalRep is a string containing the user visible value of the enum.
  3774  	LogicalRep string
  3775  }
  3776  
  3777  // Size implements the Datum interface.
  3778  func (d *DEnum) Size() uintptr {
  3779  	// When creating DEnums, we store pointers back into the type enum
  3780  	// metadata, so enums themselves don't pay for the memory of their
  3781  	// physical and logical representations.
  3782  	return unsafe.Sizeof(d.EnumTyp) +
  3783  		unsafe.Sizeof(d.PhysicalRep) +
  3784  		unsafe.Sizeof(d.LogicalRep)
  3785  }
  3786  
  3787  // GetEnumComponentsFromPhysicalRep returns the physical and logical components
  3788  // for an enum of the requested type. It returns an error if it cannot find a
  3789  // matching physical representation.
  3790  func GetEnumComponentsFromPhysicalRep(typ *types.T, rep []byte) ([]byte, string, error) {
  3791  	idx, err := typ.EnumGetIdxOfPhysical(rep)
  3792  	if err != nil {
  3793  		return nil, "", err
  3794  	}
  3795  	meta := typ.TypeMeta.EnumData
  3796  	// Take a pointer into the enum metadata rather than holding on
  3797  	// to a pointer to the input bytes.
  3798  	return meta.PhysicalRepresentations[idx], meta.LogicalRepresentations[idx], nil
  3799  }
  3800  
  3801  // MakeDEnumFromPhysicalRepresentation creates a DEnum of the input type
  3802  // and the input physical representation.
  3803  func MakeDEnumFromPhysicalRepresentation(typ *types.T, rep []byte) (*DEnum, error) {
  3804  	// Return a nice error if the input requested type is types.AnyEnum.
  3805  	if typ.Oid() == oid.T_anyenum {
  3806  		return nil, errors.New("cannot create enum of unspecified type")
  3807  	}
  3808  	phys, log, err := GetEnumComponentsFromPhysicalRep(typ, rep)
  3809  	if err != nil {
  3810  		return nil, err
  3811  	}
  3812  	return &DEnum{
  3813  		EnumTyp:     typ,
  3814  		PhysicalRep: phys,
  3815  		LogicalRep:  log,
  3816  	}, nil
  3817  }
  3818  
  3819  // MakeDEnumFromLogicalRepresentation creates a DEnum of the input type
  3820  // and input logical representation. It returns an error if the input
  3821  // logical representation is invalid.
  3822  func MakeDEnumFromLogicalRepresentation(typ *types.T, rep string) (*DEnum, error) {
  3823  	// Return a nice error if the input requested type is types.AnyEnum.
  3824  	if typ.Oid() == oid.T_anyenum {
  3825  		return nil, errors.New("cannot create enum of unspecified type")
  3826  	}
  3827  	// Take a pointer into the enum metadata rather than holding on
  3828  	// to a pointer to the input string.
  3829  	idx, err := typ.EnumGetIdxOfLogical(rep)
  3830  	if err != nil {
  3831  		return nil, err
  3832  	}
  3833  	return &DEnum{
  3834  		EnumTyp:     typ,
  3835  		PhysicalRep: typ.TypeMeta.EnumData.PhysicalRepresentations[idx],
  3836  		LogicalRep:  typ.TypeMeta.EnumData.LogicalRepresentations[idx],
  3837  	}, nil
  3838  }
  3839  
  3840  // Format implements the NodeFormatter interface.
  3841  func (d *DEnum) Format(ctx *FmtCtx) {
  3842  	if ctx.HasFlags(fmtStaticallyFormatUserDefinedTypes) {
  3843  		s := DBytes(d.PhysicalRep)
  3844  		// We use the fmtFormatByteLiterals flag here so that the bytes
  3845  		// get formatted as byte literals. Consider an enum of type t with physical
  3846  		// representation \x80. If we don't format this as a bytes literal then
  3847  		// it gets emitted as '\x80':::t. '\x80' is scanned as a string, and we try
  3848  		// to find a logical representation matching '\x80', which won't exist.
  3849  		// Instead, we want to emit b'\x80'::: so that '\x80' is scanned as bytes,
  3850  		// triggering the logic to cast the bytes \x80 to t.
  3851  		ctx.WithFlags(ctx.flags|fmtFormatByteLiterals, func() {
  3852  			s.Format(ctx)
  3853  		})
  3854  	} else {
  3855  		s := DString(d.LogicalRep)
  3856  		s.Format(ctx)
  3857  	}
  3858  }
  3859  
  3860  func (d *DEnum) String() string {
  3861  	return AsString(d)
  3862  }
  3863  
  3864  // ResolvedType implements the Datum interface.
  3865  func (d *DEnum) ResolvedType() *types.T {
  3866  	return d.EnumTyp
  3867  }
  3868  
  3869  // Compare implements the Datum interface.
  3870  func (d *DEnum) Compare(ctx *EvalContext, other Datum) int {
  3871  	if other == DNull {
  3872  		return 1
  3873  	}
  3874  	v, ok := UnwrapDatum(ctx, other).(*DEnum)
  3875  	if !ok {
  3876  		panic(makeUnsupportedComparisonMessage(d, other))
  3877  	}
  3878  	return bytes.Compare(d.PhysicalRep, v.PhysicalRep)
  3879  }
  3880  
  3881  // Prev implements the Datum interface.
  3882  func (d *DEnum) Prev(ctx *EvalContext) (Datum, bool) {
  3883  	idx, err := d.EnumTyp.EnumGetIdxOfPhysical(d.PhysicalRep)
  3884  	if err != nil {
  3885  		panic(err)
  3886  	}
  3887  	if idx == 0 {
  3888  		return nil, false
  3889  	}
  3890  	enumData := d.EnumTyp.TypeMeta.EnumData
  3891  	return &DEnum{
  3892  		EnumTyp:     d.EnumTyp,
  3893  		PhysicalRep: enumData.PhysicalRepresentations[idx-1],
  3894  		LogicalRep:  enumData.LogicalRepresentations[idx-1],
  3895  	}, true
  3896  }
  3897  
  3898  // Next implements the Datum interface.
  3899  func (d *DEnum) Next(ctx *EvalContext) (Datum, bool) {
  3900  	idx, err := d.EnumTyp.EnumGetIdxOfPhysical(d.PhysicalRep)
  3901  	if err != nil {
  3902  		panic(err)
  3903  	}
  3904  	enumData := d.EnumTyp.TypeMeta.EnumData
  3905  	if idx == len(enumData.PhysicalRepresentations)-1 {
  3906  		return nil, false
  3907  	}
  3908  	return &DEnum{
  3909  		EnumTyp:     d.EnumTyp,
  3910  		PhysicalRep: enumData.PhysicalRepresentations[idx+1],
  3911  		LogicalRep:  enumData.LogicalRepresentations[idx+1],
  3912  	}, true
  3913  }
  3914  
  3915  // Max implements the Datum interface.
  3916  func (d *DEnum) Max(ctx *EvalContext) (Datum, bool) {
  3917  	enumData := d.EnumTyp.TypeMeta.EnumData
  3918  	if len(enumData.PhysicalRepresentations) == 0 {
  3919  		return nil, false
  3920  	}
  3921  	idx := len(enumData.PhysicalRepresentations) - 1
  3922  	return &DEnum{
  3923  		EnumTyp:     d.EnumTyp,
  3924  		PhysicalRep: enumData.PhysicalRepresentations[idx],
  3925  		LogicalRep:  enumData.LogicalRepresentations[idx],
  3926  	}, true
  3927  }
  3928  
  3929  // Min implements the Datum interface.
  3930  func (d *DEnum) Min(ctx *EvalContext) (Datum, bool) {
  3931  	enumData := d.EnumTyp.TypeMeta.EnumData
  3932  	if len(enumData.PhysicalRepresentations) == 0 {
  3933  		return nil, false
  3934  	}
  3935  	return &DEnum{
  3936  		EnumTyp:     d.EnumTyp,
  3937  		PhysicalRep: enumData.PhysicalRepresentations[0],
  3938  		LogicalRep:  enumData.LogicalRepresentations[0],
  3939  	}, true
  3940  }
  3941  
  3942  // IsMax implements the Datum interface.
  3943  func (d *DEnum) IsMax(_ *EvalContext) bool {
  3944  	physReps := d.EnumTyp.TypeMeta.EnumData.PhysicalRepresentations
  3945  	idx, err := d.EnumTyp.EnumGetIdxOfPhysical(d.PhysicalRep)
  3946  	if err != nil {
  3947  		panic(err)
  3948  	}
  3949  	return idx == len(physReps)-1
  3950  }
  3951  
  3952  // IsMin implements the Datum interface.
  3953  func (d *DEnum) IsMin(_ *EvalContext) bool {
  3954  	idx, err := d.EnumTyp.EnumGetIdxOfPhysical(d.PhysicalRep)
  3955  	if err != nil {
  3956  		panic(err)
  3957  	}
  3958  	return idx == 0
  3959  }
  3960  
  3961  // AmbiguousFormat implements the Datum interface.
  3962  func (d *DEnum) AmbiguousFormat() bool {
  3963  	return true
  3964  }
  3965  
  3966  // DOid is the Postgres OID datum. It can represent either an OID type or any
  3967  // of the reg* types, such as regproc or regclass.
  3968  type DOid struct {
  3969  	// A DOid embeds a DInt, the underlying integer OID for this OID datum.
  3970  	DInt
  3971  	// semanticType indicates the particular variety of OID this datum is, whether raw
  3972  	// oid or a reg* type.
  3973  	semanticType *types.T
  3974  	// name is set to the resolved name of this OID, if available.
  3975  	name string
  3976  }
  3977  
  3978  // MakeDOid is a helper routine to create a DOid initialized from a DInt.
  3979  func MakeDOid(d DInt) DOid {
  3980  	return DOid{DInt: d, semanticType: types.Oid, name: ""}
  3981  }
  3982  
  3983  // NewDOid is a helper routine to create a *DOid initialized from a DInt.
  3984  func NewDOid(d DInt) *DOid {
  3985  	oid := MakeDOid(d)
  3986  	return &oid
  3987  }
  3988  
  3989  // AsDOid attempts to retrieve a DOid from an Expr, returning a DOid and
  3990  // a flag signifying whether the assertion was successful. The function should
  3991  // be used instead of direct type assertions wherever a *DOid wrapped by a
  3992  // *DOidWrapper is possible.
  3993  func AsDOid(e Expr) (*DOid, bool) {
  3994  	switch t := e.(type) {
  3995  	case *DOid:
  3996  		return t, true
  3997  	case *DOidWrapper:
  3998  		return AsDOid(t.Wrapped)
  3999  	}
  4000  	return NewDOid(0), false
  4001  }
  4002  
  4003  // MustBeDOid attempts to retrieve a DOid from an Expr, panicking if the
  4004  // assertion fails.
  4005  func MustBeDOid(e Expr) *DOid {
  4006  	i, ok := AsDOid(e)
  4007  	if !ok {
  4008  		panic(errors.AssertionFailedf("expected *DOid, found %T", e))
  4009  	}
  4010  	return i
  4011  }
  4012  
  4013  // NewDOidWithName is a helper routine to create a *DOid initialized from a DInt
  4014  // and a string.
  4015  func NewDOidWithName(d DInt, typ *types.T, name string) *DOid {
  4016  	return &DOid{
  4017  		DInt:         d,
  4018  		semanticType: typ,
  4019  		name:         name,
  4020  	}
  4021  }
  4022  
  4023  // AsRegProc changes the input DOid into a regproc with the given name and
  4024  // returns it.
  4025  func (d *DOid) AsRegProc(name string) *DOid {
  4026  	d.name = name
  4027  	d.semanticType = types.RegProc
  4028  	return d
  4029  }
  4030  
  4031  // AmbiguousFormat implements the Datum interface.
  4032  func (*DOid) AmbiguousFormat() bool { return true }
  4033  
  4034  // Compare implements the Datum interface.
  4035  func (d *DOid) Compare(ctx *EvalContext, other Datum) int {
  4036  	if other == DNull {
  4037  		// NULL is less than any non-NULL value.
  4038  		return 1
  4039  	}
  4040  	v, ok := UnwrapDatum(ctx, other).(*DOid)
  4041  	if !ok {
  4042  		panic(makeUnsupportedComparisonMessage(d, other))
  4043  	}
  4044  	if d.DInt < v.DInt {
  4045  		return -1
  4046  	}
  4047  	if d.DInt > v.DInt {
  4048  		return 1
  4049  	}
  4050  	return 0
  4051  }
  4052  
  4053  // Format implements the Datum interface.
  4054  func (d *DOid) Format(ctx *FmtCtx) {
  4055  	if d.semanticType.Oid() == oid.T_oid || d.name == "" {
  4056  		// If we call FormatNode directly when the disambiguateDatumTypes flag
  4057  		// is set, then we get something like 123:::INT:::OID. This is the
  4058  		// important flag set by FmtParsable which is supposed to be
  4059  		// roundtrippable. Since in this branch, a DOid is a thin wrapper around
  4060  		// a DInt, I _think_ it's correct to just delegate to the DInt's Format.
  4061  		d.DInt.Format(ctx)
  4062  	} else if ctx.HasFlags(fmtDisambiguateDatumTypes) {
  4063  		ctx.WriteString("crdb_internal.create_")
  4064  		ctx.WriteString(d.semanticType.SQLStandardName())
  4065  		ctx.WriteByte('(')
  4066  		d.DInt.Format(ctx)
  4067  		ctx.WriteByte(',')
  4068  		lex.EncodeSQLStringWithFlags(&ctx.Buffer, d.name, lex.EncNoFlags)
  4069  		ctx.WriteByte(')')
  4070  	} else {
  4071  		// This is used to print the name of pseudo-procedures in e.g.
  4072  		// pg_catalog.pg_type.typinput
  4073  		lex.EncodeSQLStringWithFlags(&ctx.Buffer, d.name, lex.EncBareStrings)
  4074  	}
  4075  }
  4076  
  4077  // IsMax implements the Datum interface.
  4078  func (d *DOid) IsMax(ctx *EvalContext) bool { return d.DInt.IsMax(ctx) }
  4079  
  4080  // IsMin implements the Datum interface.
  4081  func (d *DOid) IsMin(ctx *EvalContext) bool { return d.DInt.IsMin(ctx) }
  4082  
  4083  // Next implements the Datum interface.
  4084  func (d *DOid) Next(ctx *EvalContext) (Datum, bool) {
  4085  	next, ok := d.DInt.Next(ctx)
  4086  	return &DOid{*next.(*DInt), d.semanticType, ""}, ok
  4087  }
  4088  
  4089  // Prev implements the Datum interface.
  4090  func (d *DOid) Prev(ctx *EvalContext) (Datum, bool) {
  4091  	prev, ok := d.DInt.Prev(ctx)
  4092  	return &DOid{*prev.(*DInt), d.semanticType, ""}, ok
  4093  }
  4094  
  4095  // ResolvedType implements the Datum interface.
  4096  func (d *DOid) ResolvedType() *types.T {
  4097  	return d.semanticType
  4098  }
  4099  
  4100  // Size implements the Datum interface.
  4101  func (d *DOid) Size() uintptr { return unsafe.Sizeof(*d) }
  4102  
  4103  // Max implements the Datum interface.
  4104  func (d *DOid) Max(ctx *EvalContext) (Datum, bool) {
  4105  	max, ok := d.DInt.Max(ctx)
  4106  	return &DOid{*max.(*DInt), d.semanticType, ""}, ok
  4107  }
  4108  
  4109  // Min implements the Datum interface.
  4110  func (d *DOid) Min(ctx *EvalContext) (Datum, bool) {
  4111  	min, ok := d.DInt.Min(ctx)
  4112  	return &DOid{*min.(*DInt), d.semanticType, ""}, ok
  4113  }
  4114  
  4115  // DOidWrapper is a Datum implementation which is a wrapper around a Datum, allowing
  4116  // custom Oid values to be attached to the Datum and its types.T.
  4117  // The reason the Datum type was introduced was to permit the introduction of Datum
  4118  // types with new Object IDs while maintaining identical behavior to current Datum
  4119  // types. Specifically, it obviates the need to define a new tree.Datum type for
  4120  // each possible Oid value.
  4121  //
  4122  // Instead, DOidWrapper allows a standard Datum to be wrapped with a new Oid.
  4123  // This approach provides two major advantages:
  4124  // - performance of the existing Datum types are not affected because they
  4125  //   do not need to have custom oid.Oids added to their structure.
  4126  // - the introduction of new Datum aliases is straightforward and does not require
  4127  //   additions to typing rules or type-dependent evaluation behavior.
  4128  //
  4129  // Types that currently benefit from DOidWrapper are:
  4130  // - DName => DOidWrapper(*DString, oid.T_name)
  4131  //
  4132  type DOidWrapper struct {
  4133  	Wrapped Datum
  4134  	Oid     oid.Oid
  4135  }
  4136  
  4137  // wrapWithOid wraps a Datum with a custom Oid.
  4138  func wrapWithOid(d Datum, oid oid.Oid) Datum {
  4139  	switch v := d.(type) {
  4140  	case nil:
  4141  		return nil
  4142  	case *DInt:
  4143  	case *DString:
  4144  	case *DArray:
  4145  	case dNull, *DOidWrapper:
  4146  		panic(errors.AssertionFailedf("cannot wrap %T with an Oid", v))
  4147  	default:
  4148  		// Currently only *DInt, *DString, *DArray are hooked up to work with
  4149  		// *DOidWrapper. To support another base Datum type, replace all type
  4150  		// assertions to that type with calls to functions like AsDInt and
  4151  		// MustBeDInt.
  4152  		panic(errors.AssertionFailedf("unsupported Datum type passed to wrapWithOid: %T", d))
  4153  	}
  4154  	return &DOidWrapper{
  4155  		Wrapped: d,
  4156  		Oid:     oid,
  4157  	}
  4158  }
  4159  
  4160  // UnwrapDatum returns the base Datum type for a provided datum, stripping
  4161  // an *DOidWrapper if present. This is useful for cases like type switches,
  4162  // where type aliases should be ignored.
  4163  func UnwrapDatum(evalCtx *EvalContext, d Datum) Datum {
  4164  	if w, ok := d.(*DOidWrapper); ok {
  4165  		return w.Wrapped
  4166  	}
  4167  	if p, ok := d.(*Placeholder); ok && evalCtx != nil && evalCtx.HasPlaceholders() {
  4168  		ret, err := p.Eval(evalCtx)
  4169  		if err != nil {
  4170  			// If we fail to evaluate the placeholder, it's because we don't have
  4171  			// a placeholder available. Just return the placeholder and someone else
  4172  			// will handle this problem.
  4173  			return d
  4174  		}
  4175  		return ret
  4176  	}
  4177  	return d
  4178  }
  4179  
  4180  // ResolvedType implements the TypedExpr interface.
  4181  func (d *DOidWrapper) ResolvedType() *types.T {
  4182  	return types.OidToType[d.Oid]
  4183  }
  4184  
  4185  // Compare implements the Datum interface.
  4186  func (d *DOidWrapper) Compare(ctx *EvalContext, other Datum) int {
  4187  	if other == DNull {
  4188  		// NULL is less than any non-NULL value.
  4189  		return 1
  4190  	}
  4191  	if v, ok := other.(*DOidWrapper); ok {
  4192  		return d.Wrapped.Compare(ctx, v.Wrapped)
  4193  	}
  4194  	return d.Wrapped.Compare(ctx, other)
  4195  }
  4196  
  4197  // Prev implements the Datum interface.
  4198  func (d *DOidWrapper) Prev(ctx *EvalContext) (Datum, bool) {
  4199  	prev, ok := d.Wrapped.Prev(ctx)
  4200  	return wrapWithOid(prev, d.Oid), ok
  4201  }
  4202  
  4203  // Next implements the Datum interface.
  4204  func (d *DOidWrapper) Next(ctx *EvalContext) (Datum, bool) {
  4205  	next, ok := d.Wrapped.Next(ctx)
  4206  	return wrapWithOid(next, d.Oid), ok
  4207  }
  4208  
  4209  // IsMax implements the Datum interface.
  4210  func (d *DOidWrapper) IsMax(ctx *EvalContext) bool {
  4211  	return d.Wrapped.IsMax(ctx)
  4212  }
  4213  
  4214  // IsMin implements the Datum interface.
  4215  func (d *DOidWrapper) IsMin(ctx *EvalContext) bool {
  4216  	return d.Wrapped.IsMin(ctx)
  4217  }
  4218  
  4219  // Max implements the Datum interface.
  4220  func (d *DOidWrapper) Max(ctx *EvalContext) (Datum, bool) {
  4221  	max, ok := d.Wrapped.Max(ctx)
  4222  	return wrapWithOid(max, d.Oid), ok
  4223  }
  4224  
  4225  // Min implements the Datum interface.
  4226  func (d *DOidWrapper) Min(ctx *EvalContext) (Datum, bool) {
  4227  	min, ok := d.Wrapped.Min(ctx)
  4228  	return wrapWithOid(min, d.Oid), ok
  4229  }
  4230  
  4231  // AmbiguousFormat implements the Datum interface.
  4232  func (d *DOidWrapper) AmbiguousFormat() bool {
  4233  	return d.Wrapped.AmbiguousFormat()
  4234  }
  4235  
  4236  // Format implements the NodeFormatter interface.
  4237  func (d *DOidWrapper) Format(ctx *FmtCtx) {
  4238  	// Custom formatting based on d.OID could go here.
  4239  	ctx.FormatNode(d.Wrapped)
  4240  }
  4241  
  4242  // Size implements the Datum interface.
  4243  func (d *DOidWrapper) Size() uintptr {
  4244  	return unsafe.Sizeof(*d) + d.Wrapped.Size()
  4245  }
  4246  
  4247  // AmbiguousFormat implements the Datum interface.
  4248  func (d *Placeholder) AmbiguousFormat() bool {
  4249  	return true
  4250  }
  4251  
  4252  func (d *Placeholder) mustGetValue(ctx *EvalContext) Datum {
  4253  	e, ok := ctx.Placeholders.Value(d.Idx)
  4254  	if !ok {
  4255  		panic(errors.AssertionFailedf("fail"))
  4256  	}
  4257  	out, err := e.Eval(ctx)
  4258  	if err != nil {
  4259  		panic(errors.NewAssertionErrorWithWrappedErrf(err, "fail"))
  4260  	}
  4261  	return out
  4262  }
  4263  
  4264  // Compare implements the Datum interface.
  4265  func (d *Placeholder) Compare(ctx *EvalContext, other Datum) int {
  4266  	return d.mustGetValue(ctx).Compare(ctx, other)
  4267  }
  4268  
  4269  // Prev implements the Datum interface.
  4270  func (d *Placeholder) Prev(ctx *EvalContext) (Datum, bool) {
  4271  	return d.mustGetValue(ctx).Prev(ctx)
  4272  }
  4273  
  4274  // IsMin implements the Datum interface.
  4275  func (d *Placeholder) IsMin(ctx *EvalContext) bool {
  4276  	return d.mustGetValue(ctx).IsMin(ctx)
  4277  }
  4278  
  4279  // Next implements the Datum interface.
  4280  func (d *Placeholder) Next(ctx *EvalContext) (Datum, bool) {
  4281  	return d.mustGetValue(ctx).Next(ctx)
  4282  }
  4283  
  4284  // IsMax implements the Datum interface.
  4285  func (d *Placeholder) IsMax(ctx *EvalContext) bool {
  4286  	return d.mustGetValue(ctx).IsMax(ctx)
  4287  }
  4288  
  4289  // Max implements the Datum interface.
  4290  func (d *Placeholder) Max(ctx *EvalContext) (Datum, bool) {
  4291  	return d.mustGetValue(ctx).Max(ctx)
  4292  }
  4293  
  4294  // Min implements the Datum interface.
  4295  func (d *Placeholder) Min(ctx *EvalContext) (Datum, bool) {
  4296  	return d.mustGetValue(ctx).Min(ctx)
  4297  }
  4298  
  4299  // Size implements the Datum interface.
  4300  func (d *Placeholder) Size() uintptr {
  4301  	panic(errors.AssertionFailedf("shouldn't get called"))
  4302  }
  4303  
  4304  // NewDNameFromDString is a helper routine to create a *DName (implemented as
  4305  // a *DOidWrapper) initialized from an existing *DString.
  4306  func NewDNameFromDString(d *DString) Datum {
  4307  	return wrapWithOid(d, oid.T_name)
  4308  }
  4309  
  4310  // NewDName is a helper routine to create a *DName (implemented as a *DOidWrapper)
  4311  // initialized from a string.
  4312  func NewDName(d string) Datum {
  4313  	return NewDNameFromDString(NewDString(d))
  4314  }
  4315  
  4316  // NewDIntVectorFromDArray is a helper routine to create a *DIntVector
  4317  // (implemented as a *DOidWrapper) initialized from an existing *DArray.
  4318  func NewDIntVectorFromDArray(d *DArray) Datum {
  4319  	ret := new(DArray)
  4320  	*ret = *d
  4321  	ret.customOid = oid.T_int2vector
  4322  	return ret
  4323  }
  4324  
  4325  // NewDOidVectorFromDArray is a helper routine to create a *DOidVector
  4326  // (implemented as a *DOidWrapper) initialized from an existing *DArray.
  4327  func NewDOidVectorFromDArray(d *DArray) Datum {
  4328  	ret := new(DArray)
  4329  	*ret = *d
  4330  	ret.customOid = oid.T_oidvector
  4331  	return ret
  4332  }
  4333  
  4334  // NewDefaultDatum returns a default non-NULL datum value for the given type.
  4335  // This is used when updating non-NULL columns that are being added or dropped
  4336  // from a table, and there is no user-defined DEFAULT value available.
  4337  func NewDefaultDatum(evalCtx *EvalContext, t *types.T) (d Datum, err error) {
  4338  	switch t.Family() {
  4339  	case types.BoolFamily:
  4340  		return DBoolFalse, nil
  4341  	case types.IntFamily:
  4342  		return DZero, nil
  4343  	case types.FloatFamily:
  4344  		return dZeroFloat, nil
  4345  	case types.DecimalFamily:
  4346  		return dZeroDecimal, nil
  4347  	case types.DateFamily:
  4348  		return dEpochDate, nil
  4349  	case types.TimestampFamily:
  4350  		return dZeroTimestamp, nil
  4351  	case types.IntervalFamily:
  4352  		return dZeroInterval, nil
  4353  	case types.StringFamily:
  4354  		return dEmptyString, nil
  4355  	case types.BytesFamily:
  4356  		return dEmptyBytes, nil
  4357  	case types.TimestampTZFamily:
  4358  		return dZeroTimestampTZ, nil
  4359  	case types.CollatedStringFamily:
  4360  		return NewDCollatedString("", t.Locale(), &evalCtx.CollationEnv)
  4361  	case types.OidFamily:
  4362  		return NewDOidWithName(DInt(t.Oid()), t, t.SQLStandardName()), nil
  4363  	case types.UnknownFamily:
  4364  		return DNull, nil
  4365  	case types.UuidFamily:
  4366  		return DMinUUID, nil
  4367  	case types.ArrayFamily:
  4368  		return NewDArray(t.ArrayContents()), nil
  4369  	case types.INetFamily:
  4370  		return DMinIPAddr, nil
  4371  	case types.TimeFamily:
  4372  		return dTimeMin, nil
  4373  	case types.JsonFamily:
  4374  		return dNullJSON, nil
  4375  	case types.TimeTZFamily:
  4376  		return dZeroTimeTZ, nil
  4377  	case types.GeometryFamily, types.GeographyFamily:
  4378  		// TODO(otan): force Geometry/Geography to not allow `NOT NULL` columns to
  4379  		// make this impossible.
  4380  		return nil, pgerror.Newf(
  4381  			pgcode.FeatureNotSupported,
  4382  			"%s must be set or be NULL",
  4383  			t.Name(),
  4384  		)
  4385  	case types.TupleFamily:
  4386  		contents := t.TupleContents()
  4387  		datums := make([]Datum, len(contents))
  4388  		for i, subT := range contents {
  4389  			datums[i], err = NewDefaultDatum(evalCtx, subT)
  4390  			if err != nil {
  4391  				return nil, err
  4392  			}
  4393  		}
  4394  		return NewDTuple(t, datums...), nil
  4395  	case types.BitFamily:
  4396  		return bitArrayZero, nil
  4397  	default:
  4398  		return nil, errors.AssertionFailedf("unhandled type %v", t.SQLString())
  4399  	}
  4400  }
  4401  
  4402  // DatumTypeSize returns a lower bound on the total size of a Datum
  4403  // of the given type in bytes, including memory that is
  4404  // pointed at (even if shared between Datum instances) but excluding
  4405  // allocation overhead.
  4406  //
  4407  // The second return value indicates whether data of this type have different
  4408  // sizes.
  4409  //
  4410  // It holds for every Datum d that d.Size() >= DatumSize(d.ResolvedType())
  4411  func DatumTypeSize(t *types.T) (size uintptr, isVarlen bool) {
  4412  	// The following are composite types or types that support multiple widths.
  4413  	switch t.Family() {
  4414  	case types.TupleFamily:
  4415  		if types.IsWildcardTupleType(t) {
  4416  			return uintptr(0), false
  4417  		}
  4418  		sz := uintptr(0)
  4419  		variable := false
  4420  		for i := range t.TupleContents() {
  4421  			typsz, typvariable := DatumTypeSize(t.TupleContents()[i])
  4422  			sz += typsz
  4423  			variable = variable || typvariable
  4424  		}
  4425  		return sz, variable
  4426  	case types.IntFamily, types.FloatFamily:
  4427  		return uintptr(t.Width() / 8), false
  4428  
  4429  	case types.StringFamily:
  4430  		// T_char is a special string type that has a fixed size of 1. We have to
  4431  		// report its size accurately, and that it's not a variable-length datatype.
  4432  		if t.Oid() == oid.T_char {
  4433  			return 1, false
  4434  		}
  4435  	}
  4436  
  4437  	// All the primary types have fixed size information.
  4438  	if bSzInfo, ok := baseDatumTypeSizes[t.Family()]; ok {
  4439  		return bSzInfo.sz, bSzInfo.variable
  4440  	}
  4441  
  4442  	panic(errors.AssertionFailedf("unknown type: %T", t))
  4443  }
  4444  
  4445  const (
  4446  	fixedSize    = false
  4447  	variableSize = true
  4448  )
  4449  
  4450  var baseDatumTypeSizes = map[types.Family]struct {
  4451  	sz       uintptr
  4452  	variable bool
  4453  }{
  4454  	types.UnknownFamily:        {unsafe.Sizeof(dNull{}), fixedSize},
  4455  	types.BoolFamily:           {unsafe.Sizeof(DBool(false)), fixedSize},
  4456  	types.BitFamily:            {unsafe.Sizeof(DBitArray{}), variableSize},
  4457  	types.IntFamily:            {unsafe.Sizeof(DInt(0)), fixedSize},
  4458  	types.FloatFamily:          {unsafe.Sizeof(DFloat(0.0)), fixedSize},
  4459  	types.DecimalFamily:        {unsafe.Sizeof(DDecimal{}), variableSize},
  4460  	types.StringFamily:         {unsafe.Sizeof(DString("")), variableSize},
  4461  	types.CollatedStringFamily: {unsafe.Sizeof(DCollatedString{"", "", nil}), variableSize},
  4462  	types.BytesFamily:          {unsafe.Sizeof(DBytes("")), variableSize},
  4463  	types.DateFamily:           {unsafe.Sizeof(DDate{}), fixedSize},
  4464  	types.GeographyFamily:      {unsafe.Sizeof(DGeography{}), variableSize},
  4465  	types.GeometryFamily:       {unsafe.Sizeof(DGeometry{}), variableSize},
  4466  	types.TimeFamily:           {unsafe.Sizeof(DTime(0)), fixedSize},
  4467  	types.TimeTZFamily:         {unsafe.Sizeof(DTimeTZ{}), fixedSize},
  4468  	types.TimestampFamily:      {unsafe.Sizeof(DTimestamp{}), fixedSize},
  4469  	types.TimestampTZFamily:    {unsafe.Sizeof(DTimestampTZ{}), fixedSize},
  4470  	types.IntervalFamily:       {unsafe.Sizeof(DInterval{}), fixedSize},
  4471  	types.JsonFamily:           {unsafe.Sizeof(DJSON{}), variableSize},
  4472  	types.UuidFamily:           {unsafe.Sizeof(DUuid{}), fixedSize},
  4473  	types.INetFamily:           {unsafe.Sizeof(DIPAddr{}), fixedSize},
  4474  	types.OidFamily:            {unsafe.Sizeof(DInt(0)), fixedSize},
  4475  	types.EnumFamily:           {unsafe.Sizeof(DEnum{}), variableSize},
  4476  
  4477  	// TODO(jordan,justin): This seems suspicious.
  4478  	types.ArrayFamily: {unsafe.Sizeof(DString("")), variableSize},
  4479  
  4480  	// TODO(jordan,justin): This seems suspicious.
  4481  	types.AnyFamily: {unsafe.Sizeof(DString("")), variableSize},
  4482  }