github.com/matrixorigin/matrixone@v1.2.0/pkg/vm/engine/tae/containers/vector.go (about)

     1  // Copyright 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package containers
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  	"io"
    21  	"sync/atomic"
    22  
    23  	"github.com/RoaringBitmap/roaring"
    24  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    25  	"github.com/matrixorigin/matrixone/pkg/common/mpool"
    26  	"github.com/matrixorigin/matrixone/pkg/container/nulls"
    27  	"github.com/matrixorigin/matrixone/pkg/container/types"
    28  	"github.com/matrixorigin/matrixone/pkg/container/vector"
    29  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/common"
    30  )
    31  
    32  type vectorWrapper struct {
    33  	// wrapped is the vector.Vector that is wrapped by this vectorWrapper.
    34  	wrapped *vector.Vector
    35  
    36  	// mpool is the memory pool used by the wrapped vector.Vector.
    37  	mpool *mpool.MPool
    38  
    39  	// it is used to call Close in an idempotent way
    40  	closed atomic.Bool
    41  
    42  	element *vectorPoolElement
    43  }
    44  
    45  func NewConstFixed[T any](typ types.Type, val T, length int, opts ...Options) *vectorWrapper {
    46  	var (
    47  		alloc *mpool.MPool
    48  	)
    49  	if len(opts) > 0 {
    50  		alloc = opts[0].Allocator
    51  	}
    52  	if alloc == nil {
    53  		alloc = common.DefaultAllocator
    54  	}
    55  
    56  	vc, err := vector.NewConstFixed[T](typ, val, length, alloc)
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	vec := &vectorWrapper{
    61  		wrapped: vc,
    62  	}
    63  	vec.mpool = alloc
    64  	return vec
    65  }
    66  
    67  func NewConstBytes(typ types.Type, val []byte, length int, opts ...Options) *vectorWrapper {
    68  	var (
    69  		alloc *mpool.MPool
    70  	)
    71  	if len(opts) > 0 {
    72  		alloc = opts[0].Allocator
    73  	}
    74  	if alloc == nil {
    75  		alloc = common.DefaultAllocator
    76  	}
    77  
    78  	vc, err := vector.NewConstBytes(typ, val, length, alloc)
    79  	if err != nil {
    80  		panic(err)
    81  	}
    82  	vec := &vectorWrapper{
    83  		wrapped: vc,
    84  	}
    85  	vec.mpool = alloc
    86  	return vec
    87  }
    88  
    89  func NewConstNullVector(
    90  	typ types.Type,
    91  	length int,
    92  	mp *mpool.MPool,
    93  ) *vectorWrapper {
    94  	vec := &vectorWrapper{
    95  		wrapped: vector.NewConstNull(typ, length, mp),
    96  	}
    97  	vec.mpool = mp
    98  	return vec
    99  }
   100  
   101  func NewVector(typ types.Type, opts ...Options) *vectorWrapper {
   102  	vec := &vectorWrapper{
   103  		wrapped: vector.NewVec(typ),
   104  	}
   105  
   106  	// setting mpool variables
   107  	var (
   108  		alloc    *mpool.MPool
   109  		capacity int
   110  	)
   111  	if len(opts) > 0 {
   112  		alloc = opts[0].Allocator
   113  		capacity = opts[0].Capacity
   114  	}
   115  	if alloc == nil {
   116  		alloc = common.DefaultAllocator
   117  	}
   118  	vec.mpool = alloc
   119  	if capacity > 0 {
   120  		if err := vec.wrapped.PreExtend(capacity, vec.mpool); err != nil {
   121  			panic(err)
   122  		}
   123  	}
   124  	return vec
   125  }
   126  
   127  func (vec *vectorWrapper) ApproxSize() int {
   128  	if vec.wrapped.NeedDup() {
   129  		return 0
   130  	} else {
   131  		return vec.wrapped.Size()
   132  	}
   133  }
   134  
   135  func (vec *vectorWrapper) PreExtend(length int) (err error) {
   136  	vec.tryCOW()
   137  	return vec.wrapped.PreExtend(length, vec.mpool)
   138  }
   139  
   140  func (vec *vectorWrapper) Get(i int) any {
   141  	if vec.wrapped.IsConstNull() {
   142  		return nil
   143  	}
   144  	if vec.GetType().IsVarlen() {
   145  		bs := vec.ShallowGet(i).([]byte)
   146  		ret := make([]byte, len(bs))
   147  		copy(ret, bs)
   148  		return any(ret)
   149  	}
   150  
   151  	return getNonNullValue(vec.wrapped, uint32(i))
   152  }
   153  
   154  func (vec *vectorWrapper) ShallowGet(i int) any {
   155  	return getNonNullValue(vec.wrapped, uint32(i))
   156  }
   157  
   158  func (vec *vectorWrapper) Length() int {
   159  	if vec.wrapped == nil {
   160  		return 0
   161  	}
   162  	return vec.wrapped.Length()
   163  }
   164  
   165  func (vec *vectorWrapper) Append(v any, isNull bool) {
   166  	// innsert AppendAny will check IsConst
   167  	vec.tryCOW()
   168  
   169  	var err error
   170  	if isNull {
   171  		err = vector.AppendAny(vec.wrapped, nil, true, vec.mpool)
   172  	} else {
   173  		err = vector.AppendAny(vec.wrapped, v, false, vec.mpool)
   174  	}
   175  	if err != nil {
   176  		panic(err)
   177  	}
   178  }
   179  
   180  func (vec *vectorWrapper) GetAllocator() *mpool.MPool {
   181  	return vec.mpool
   182  }
   183  
   184  func (vec *vectorWrapper) IsNull(i int) bool {
   185  	inner := vec.wrapped
   186  	if inner.IsConstNull() {
   187  		return true
   188  	}
   189  	if inner.IsConst() {
   190  		return false
   191  	}
   192  	return nulls.Contains(inner.GetNulls(), uint64(i))
   193  }
   194  
   195  func (vec *vectorWrapper) NullMask() *nulls.Nulls {
   196  	return vec.wrapped.GetNulls()
   197  }
   198  
   199  func (vec *vectorWrapper) GetType() *types.Type {
   200  	return vec.wrapped.GetType()
   201  }
   202  
   203  func (vec *vectorWrapper) Extend(src Vector) {
   204  	vec.ExtendWithOffset(src, 0, src.Length())
   205  }
   206  
   207  func (vec *vectorWrapper) Update(i int, v any, isNull bool) {
   208  	if vec.wrapped.IsConst() {
   209  		panic(moerr.NewInternalErrorNoCtx("update to const vectorWrapper"))
   210  	}
   211  	vec.tryCOW()
   212  	UpdateValue(vec.wrapped, uint32(i), v, isNull, vec.mpool)
   213  }
   214  
   215  func (vec *vectorWrapper) WriteTo(w io.Writer) (n int64, err error) {
   216  	var bs bytes.Buffer
   217  
   218  	var size int64
   219  	_, _ = bs.Write(types.EncodeInt64(&size))
   220  
   221  	if err = vec.wrapped.MarshalBinaryWithBuffer(&bs); err != nil {
   222  		return
   223  	}
   224  
   225  	size = int64(bs.Len() - 8)
   226  
   227  	buf := bs.Bytes()
   228  	copy(buf[:8], types.EncodeInt64(&size))
   229  
   230  	if _, err = w.Write(buf); err != nil {
   231  		return
   232  	}
   233  
   234  	n = int64(len(buf))
   235  	return
   236  }
   237  
   238  func (vec *vectorWrapper) ReadFrom(r io.Reader) (n int64, err error) {
   239  	buf := make([]byte, 8)
   240  	if _, err = r.Read(buf); err != nil {
   241  		return
   242  	}
   243  
   244  	n += 8
   245  
   246  	// 1. Whole TN Vector
   247  	buf = make([]byte, types.DecodeInt64(buf[:]))
   248  	if _, err = r.Read(buf); err != nil {
   249  		return
   250  	}
   251  
   252  	n += int64(len(buf))
   253  
   254  	t := vec.wrapped.GetType()
   255  	vec.releaseWrapped()
   256  	vec.wrapped = vector.NewVec(*t)
   257  	if err = vec.wrapped.UnmarshalBinary(buf); err != nil {
   258  		return
   259  	}
   260  
   261  	return
   262  }
   263  
   264  func (vec *vectorWrapper) HasNull() bool {
   265  	if vec.wrapped.IsConstNull() {
   266  		return true
   267  	}
   268  	if vec.wrapped.IsConst() {
   269  		return false
   270  	}
   271  	return vec.NullMask() != nil && !vec.NullMask().IsEmpty()
   272  }
   273  
   274  func (vec *vectorWrapper) NullCount() int {
   275  	if vec.wrapped.IsConstNull() {
   276  		return vec.Length()
   277  	}
   278  	if vec.wrapped.IsConst() {
   279  		return 0
   280  	}
   281  	if vec.NullMask() != nil {
   282  		return vec.NullMask().GetCardinality()
   283  	}
   284  	return 0
   285  }
   286  
   287  func (vec *vectorWrapper) IsConst() bool {
   288  	return vec.wrapped.IsConst()
   289  }
   290  
   291  func (vec *vectorWrapper) IsConstNull() bool {
   292  	return vec.wrapped.IsConstNull()
   293  }
   294  
   295  // conver a const vectorWrapper to a normal one, getting ready to edit
   296  func (vec *vectorWrapper) TryConvertConst() Vector {
   297  	if vec.wrapped.IsConstNull() {
   298  		ret := NewVector(*vec.GetType())
   299  		ret.mpool = vec.mpool
   300  		for i := 0; i < vec.Length(); i++ {
   301  			ret.Append(nil, true)
   302  		}
   303  		return ret
   304  	}
   305  
   306  	if vec.wrapped.IsConst() {
   307  		ret := NewVector(*vec.GetType())
   308  		ret.mpool = vec.mpool
   309  		v := vec.Get(0)
   310  		for i := 0; i < vec.Length(); i++ {
   311  			ret.Append(v, false)
   312  		}
   313  		return ret
   314  	}
   315  	return vec
   316  }
   317  
   318  func (vec *vectorWrapper) Foreach(op ItOp, sels *nulls.Bitmap) error {
   319  	return vec.ForeachWindow(0, vec.wrapped.Length(), op, sels)
   320  }
   321  
   322  func (vec *vectorWrapper) ForeachWindow(offset, length int, op ItOp, sels *nulls.Bitmap) (err error) {
   323  	return ForeachVectorWindow(vec, offset, length, nil, op, sels)
   324  }
   325  
   326  func (vec *vectorWrapper) Close() {
   327  	if !vec.closed.CompareAndSwap(false, true) {
   328  		return
   329  	}
   330  	if vec.element != nil {
   331  		vec.element.put()
   332  		vec.element = nil
   333  		vec.wrapped = nil
   334  		return
   335  	}
   336  
   337  	// if this wrapper is not get from a pool, we should release the wrapped vector
   338  	vec.releaseWrapped()
   339  }
   340  
   341  func (vec *vectorWrapper) releaseWrapped() {
   342  	if vec.wrapped == nil {
   343  		return
   344  	}
   345  	if !vec.wrapped.NeedDup() {
   346  		vec.wrapped.Free(vec.mpool)
   347  	}
   348  	vec.wrapped = nil
   349  }
   350  
   351  func (vec *vectorWrapper) Allocated() int {
   352  	if vec.wrapped.NeedDup() {
   353  		return 0
   354  	}
   355  	return vec.wrapped.Allocated()
   356  }
   357  
   358  // When a new Append() is happening on a SharedMemory vectorWrapper, we allocate the data[] from the mpool.
   359  func (vec *vectorWrapper) tryCOW() {
   360  	if !vec.wrapped.NeedDup() {
   361  		return
   362  	}
   363  
   364  	newCnVector, err := vec.wrapped.Dup(vec.mpool)
   365  	if err != nil {
   366  		panic(err)
   367  	}
   368  	vec.wrapped = newCnVector
   369  }
   370  
   371  func (vec *vectorWrapper) Window(offset, length int) Vector {
   372  	var err error
   373  	win := new(vectorWrapper)
   374  	win.mpool = vec.mpool
   375  	win.wrapped, err = vec.wrapped.Window(offset, offset+length)
   376  	if err != nil {
   377  		panic(err)
   378  	}
   379  
   380  	return win
   381  }
   382  
   383  func (vec *vectorWrapper) CloneWindow(offset, length int, allocator ...*mpool.MPool) Vector {
   384  	opts := Options{}
   385  	if len(allocator) == 0 {
   386  		opts.Allocator = vec.GetAllocator()
   387  	} else {
   388  		opts.Allocator = allocator[0]
   389  	}
   390  
   391  	cloned := NewVector(*vec.GetType(), opts)
   392  	v, err := vec.wrapped.CloneWindow(offset, offset+length, cloned.GetAllocator())
   393  	if err != nil {
   394  		panic(err)
   395  	}
   396  	cloned.setDownstreamVector(v)
   397  	return cloned
   398  }
   399  
   400  func (vec *vectorWrapper) CloneWindowWithPool(offset, length int, pool *VectorPool) Vector {
   401  	cloned := pool.GetVector(vec.GetType())
   402  	if err := vec.wrapped.CloneWindowTo(cloned.wrapped, offset, offset+length, cloned.GetAllocator()); err != nil {
   403  		panic(err)
   404  	}
   405  	return cloned
   406  }
   407  
   408  func (vec *vectorWrapper) ExtendWithOffset(src Vector, srcOff, srcLen int) {
   409  	if err := vec.extendWithOffset(src.GetDownstreamVector(), srcOff, srcLen); err != nil {
   410  		panic(err)
   411  	}
   412  }
   413  
   414  func (vec *vectorWrapper) ExtendVec(src *vector.Vector) (err error) {
   415  	return vec.extendWithOffset(src, 0, src.Length())
   416  }
   417  
   418  func (vec *vectorWrapper) extendWithOffset(src *vector.Vector, srcOff, srcLen int) (err error) {
   419  	if vec.wrapped.IsConst() {
   420  		panic(moerr.NewInternalErrorNoCtx("extend to const vectorWrapper"))
   421  	}
   422  	if srcLen <= 0 {
   423  		return
   424  	}
   425  
   426  	if srcOff == 0 && srcLen == src.Length() {
   427  		err = vector.GetUnionAllFunction(
   428  			*vec.GetType(),
   429  			vec.mpool,
   430  		)(vec.wrapped, src)
   431  		return
   432  	}
   433  
   434  	sels := make([]int32, srcLen)
   435  	for j := 0; j < srcLen; j++ {
   436  		sels[j] = int32(j) + int32(srcOff)
   437  	}
   438  	err = vec.wrapped.Union(src, sels, vec.mpool)
   439  	return
   440  }
   441  
   442  func (vec *vectorWrapper) CompactByBitmap(mask *nulls.Bitmap) {
   443  	if mask.IsEmpty() {
   444  		return
   445  	}
   446  	vec.tryCOW()
   447  
   448  	dels := vec.mpool.GetSels()
   449  	mask.Foreach(func(i uint64) bool {
   450  		dels = append(dels, int64(i))
   451  		return true
   452  	})
   453  	vec.wrapped.Shrink(dels, true)
   454  	vec.mpool.PutSels(dels)
   455  }
   456  
   457  func (vec *vectorWrapper) Compact(deletes *roaring.Bitmap) {
   458  	if deletes == nil || deletes.IsEmpty() {
   459  		return
   460  	}
   461  	vec.tryCOW()
   462  
   463  	dels := vec.mpool.GetSels()
   464  	itr := deletes.Iterator()
   465  	for itr.HasNext() {
   466  		r := itr.Next()
   467  		dels = append(dels, int64(r))
   468  	}
   469  
   470  	vec.wrapped.Shrink(dels, true)
   471  	vec.mpool.PutSels(dels)
   472  }
   473  
   474  func (vec *vectorWrapper) GetDownstreamVector() *vector.Vector {
   475  	return vec.wrapped
   476  }
   477  
   478  func (vec *vectorWrapper) setDownstreamVector(dsVec *vector.Vector) {
   479  	vec.wrapped = dsVec
   480  }
   481  
   482  /****** Below functions are not used in critical path. Used mainly for testing */
   483  
   484  // String value of vectorWrapper
   485  // Deprecated: Only use for test functions
   486  func (vec *vectorWrapper) String() string {
   487  	s := fmt.Sprintf("DN Vector: Len=%d[Rows];Allocted:%d[Bytes]", vec.Length(), vec.Allocated())
   488  
   489  	end := 100
   490  	if vec.Length() < end {
   491  		end = vec.Length()
   492  	}
   493  	if end == 0 {
   494  		return s
   495  	}
   496  
   497  	data := "Vals=["
   498  	for i := 0; i < end; i++ {
   499  		data = fmt.Sprintf("%s %v", data, vec.Get(i))
   500  	}
   501  	if vec.Length() > end {
   502  		s = fmt.Sprintf("%s %s...]", s, data)
   503  	} else {
   504  		s = fmt.Sprintf("%s %s]", s, data)
   505  	}
   506  
   507  	return s
   508  }
   509  
   510  // PPString Pretty Print
   511  // Deprecated: Only use for test functions
   512  func (vec *vectorWrapper) PPString(num int) string {
   513  	var w bytes.Buffer
   514  	limit := vec.Length()
   515  	if num > 0 && num < limit {
   516  		limit = num
   517  	}
   518  	_, _ = w.WriteString(fmt.Sprintf("[T=%s]%s", vec.GetType().String(), common.MoVectorToString(vec.GetDownstreamVector(), limit)))
   519  	if vec.Length() > num {
   520  		_, _ = w.WriteString("...")
   521  	}
   522  	_, _ = w.WriteString(fmt.Sprintf("[%v]", vec.element != nil))
   523  	return w.String()
   524  }
   525  
   526  // AppendMany appends multiple values
   527  // Deprecated: Only use for test functions
   528  func (vec *vectorWrapper) AppendMany(vs []any, isNulls []bool) {
   529  	for i, v := range vs {
   530  		vec.Append(v, isNulls[i])
   531  	}
   532  }
   533  
   534  // Delete Deletes an item from vectorWrapper
   535  // Deprecated: Only use for test functions
   536  func (vec *vectorWrapper) Delete(delRowId int) {
   537  	deletes := roaring.BitmapOf(uint32(delRowId))
   538  	vec.Compact(deletes)
   539  }
   540  
   541  // Equals Compares two vectors
   542  // Deprecated: Only use for test functions
   543  func (vec *vectorWrapper) Equals(o Vector) bool {
   544  	if vec.Length() != o.Length() {
   545  		return false
   546  	}
   547  	if *vec.GetType() != *o.GetType() {
   548  		return false
   549  	}
   550  	if vec.HasNull() != o.HasNull() {
   551  		return false
   552  	}
   553  	if vec.HasNull() {
   554  		if !vec.NullMask().IsSame(o.NullMask()) {
   555  			return false
   556  		}
   557  	}
   558  	mask := vec.NullMask()
   559  	typ := vec.wrapped.GetType()
   560  	for i := 0; i < vec.Length(); i++ {
   561  		if mask != nil && mask.Contains(uint64(i)) {
   562  			continue
   563  		}
   564  		if typ.IsVarlen() {
   565  			if !bytes.Equal(vec.ShallowGet(i).([]byte), o.ShallowGet(i).([]byte)) {
   566  				return false
   567  			}
   568  		} else if typ.Oid == types.T_decimal64 {
   569  			d := vec.Get(i).(types.Decimal64)
   570  			od := vec.Get(i).(types.Decimal64)
   571  			if d != od {
   572  				return false
   573  			}
   574  		} else if typ.Oid == types.T_decimal128 {
   575  			d := vec.Get(i).(types.Decimal128)
   576  			od := vec.Get(i).(types.Decimal128)
   577  			if d != od {
   578  				return false
   579  			}
   580  		} else if typ.Oid == types.T_TS {
   581  			d := vec.Get(i).(types.TS)
   582  			od := vec.Get(i).(types.TS)
   583  			if types.CompareTSTSAligned(d, od) != 0 {
   584  				return false
   585  			}
   586  		} else if typ.Oid == types.T_Rowid {
   587  			d := vec.Get(i).(types.Rowid)
   588  			od := vec.Get(i).(types.Rowid)
   589  			if types.CompareRowidRowidAligned(d, od) != 0 {
   590  				return false
   591  			}
   592  		} else {
   593  			if vec.Get(i) != o.Get(i) {
   594  				return false
   595  			}
   596  		}
   597  	}
   598  	return true
   599  }