github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/types.go (about)

     1  // Copyright 2021 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 engine
    16  
    17  import (
    18  	"bytes"
    19  	"context"
    20  	"encoding/binary"
    21  	"time"
    22  
    23  	"github.com/matrixorigin/matrixone/pkg/common/mpool"
    24  	"github.com/matrixorigin/matrixone/pkg/compress"
    25  	"github.com/matrixorigin/matrixone/pkg/container/batch"
    26  	"github.com/matrixorigin/matrixone/pkg/container/types"
    27  	logservicepb "github.com/matrixorigin/matrixone/pkg/pb/logservice"
    28  	"github.com/matrixorigin/matrixone/pkg/pb/plan"
    29  	"github.com/matrixorigin/matrixone/pkg/pb/timestamp"
    30  	"github.com/matrixorigin/matrixone/pkg/txn/client"
    31  )
    32  
    33  type Nodes []Node
    34  
    35  type Node struct {
    36  	Mcpu int
    37  	Id   string   `json:"id"`
    38  	Addr string   `json:"address"`
    39  	Data [][]byte `json:"payload"`
    40  	Rel  Relation // local relation
    41  }
    42  
    43  // Attribute is a column
    44  type Attribute struct {
    45  	// IsHide whether the attribute is hidden or not
    46  	IsHidden bool
    47  	// IsRowId whether the attribute is rowid or not
    48  	IsRowId bool
    49  	// Column ID
    50  	ID uint64
    51  	// Name name of attribute
    52  	Name string
    53  	// Alg compression algorithm
    54  	Alg compress.T
    55  	// Type attribute's type
    56  	Type types.Type
    57  	// DefaultExpr default value of this attribute
    58  	Default *plan.Default
    59  	// to update col when define in create table
    60  	OnUpdate *plan.OnUpdate
    61  	// Primary is primary key or not
    62  	Primary bool
    63  	// Clusterby means sort by this column
    64  	ClusterBy bool
    65  	// Comment of attribute
    66  	Comment string
    67  	// AutoIncrement is auto incr or not
    68  	AutoIncrement bool
    69  }
    70  
    71  type PropertiesDef struct {
    72  	Properties []Property
    73  }
    74  
    75  type Property struct {
    76  	Key   string
    77  	Value string
    78  }
    79  
    80  type ClusterByDef struct {
    81  	Name string
    82  }
    83  
    84  type Statistics interface {
    85  	Stats(ctx context.Context, expr *plan.Expr) (*plan.Stats, error)
    86  	Rows(ctx context.Context) (int64, error)
    87  	Size(ctx context.Context, columnName string) (int64, error)
    88  }
    89  
    90  type IndexTableDef struct {
    91  	Typ      IndexT
    92  	ColNames []string
    93  	Name     string
    94  }
    95  
    96  type IndexT int
    97  
    98  func (node IndexT) ToString() string {
    99  	switch node {
   100  	case ZoneMap:
   101  		return "ZONEMAP"
   102  	case BsiIndex:
   103  		return "BSI"
   104  	default:
   105  		return "INVAILD"
   106  	}
   107  }
   108  
   109  const (
   110  	Invalid IndexT = iota
   111  	ZoneMap
   112  	BsiIndex
   113  )
   114  
   115  type AttributeDef struct {
   116  	Attr Attribute
   117  }
   118  
   119  type CommentDef struct {
   120  	Comment string
   121  }
   122  
   123  type PartitionDef struct {
   124  	Partition string
   125  }
   126  
   127  type ViewDef struct {
   128  	View string
   129  }
   130  
   131  type IndexDef struct {
   132  	Indexes []*plan.IndexDef
   133  }
   134  
   135  type ForeignKeyDef struct {
   136  	Fkeys []*plan.ForeignKeyDef
   137  }
   138  
   139  type PrimaryKeyDef struct {
   140  	Pkey *plan.PrimaryKeyDef
   141  }
   142  
   143  type RefChildTableDef struct {
   144  	Tables []uint64
   145  }
   146  
   147  type TableDef interface {
   148  	tableDef()
   149  }
   150  
   151  func (*CommentDef) tableDef()    {}
   152  func (*PartitionDef) tableDef()  {}
   153  func (*ViewDef) tableDef()       {}
   154  func (*AttributeDef) tableDef()  {}
   155  func (*IndexTableDef) tableDef() {}
   156  func (*PropertiesDef) tableDef() {}
   157  func (*ClusterByDef) tableDef()  {}
   158  func (*ConstraintDef) tableDef() {}
   159  
   160  type ConstraintDef struct {
   161  	Cts []Constraint
   162  }
   163  
   164  type ConstraintType int8
   165  
   166  const (
   167  	Index ConstraintType = iota
   168  	RefChildTable
   169  	ForeignKey
   170  	PrimaryKey
   171  )
   172  
   173  func (c *ConstraintDef) MarshalBinary() (data []byte, err error) {
   174  	buf := bytes.NewBuffer(make([]byte, 0))
   175  	for _, ct := range c.Cts {
   176  		switch def := ct.(type) {
   177  		case *IndexDef:
   178  			if err := binary.Write(buf, binary.BigEndian, Index); err != nil {
   179  				return nil, err
   180  			}
   181  			if err := binary.Write(buf, binary.BigEndian, uint64(len(def.Indexes))); err != nil {
   182  				return nil, err
   183  			}
   184  
   185  			for _, indexdef := range def.Indexes {
   186  				bytes, err := indexdef.Marshal()
   187  				if err != nil {
   188  					return nil, err
   189  				}
   190  				if err := binary.Write(buf, binary.BigEndian, uint64(len(bytes))); err != nil {
   191  					return nil, err
   192  				}
   193  				buf.Write(bytes)
   194  			}
   195  		case *RefChildTableDef:
   196  			if err := binary.Write(buf, binary.BigEndian, RefChildTable); err != nil {
   197  				return nil, err
   198  			}
   199  			if err := binary.Write(buf, binary.BigEndian, uint64(len(def.Tables))); err != nil {
   200  				return nil, err
   201  			}
   202  			for _, tblId := range def.Tables {
   203  				if err := binary.Write(buf, binary.BigEndian, tblId); err != nil {
   204  					return nil, err
   205  				}
   206  			}
   207  
   208  		case *ForeignKeyDef:
   209  			if err := binary.Write(buf, binary.BigEndian, ForeignKey); err != nil {
   210  				return nil, err
   211  			}
   212  			if err := binary.Write(buf, binary.BigEndian, uint64(len(def.Fkeys))); err != nil {
   213  				return nil, err
   214  			}
   215  			for _, fk := range def.Fkeys {
   216  				bytes, err := fk.Marshal()
   217  				if err != nil {
   218  					return nil, err
   219  				}
   220  
   221  				if err := binary.Write(buf, binary.BigEndian, uint64(len(bytes))); err != nil {
   222  					return nil, err
   223  				}
   224  				buf.Write(bytes)
   225  			}
   226  		case *PrimaryKeyDef:
   227  			if err := binary.Write(buf, binary.BigEndian, PrimaryKey); err != nil {
   228  				return nil, err
   229  			}
   230  			bytes, err := def.Pkey.Marshal()
   231  			if err != nil {
   232  				return nil, err
   233  			}
   234  			if err := binary.Write(buf, binary.BigEndian, uint64((len(bytes)))); err != nil {
   235  				return nil, err
   236  			}
   237  			buf.Write(bytes)
   238  		}
   239  	}
   240  	return buf.Bytes(), nil
   241  }
   242  
   243  func (c *ConstraintDef) UnmarshalBinary(data []byte) error {
   244  	l := 0
   245  	var length uint64
   246  	for l < len(data) {
   247  		typ := ConstraintType(data[l])
   248  		l += 1
   249  		switch typ {
   250  		case Index:
   251  			length = binary.BigEndian.Uint64(data[l : l+8])
   252  			l += 8
   253  			indexes := make([]*plan.IndexDef, length)
   254  
   255  			for i := 0; i < int(length); i++ {
   256  				dataLength := binary.BigEndian.Uint64(data[l : l+8])
   257  				l += 8
   258  				indexdef := &plan.IndexDef{}
   259  				err := indexdef.Unmarshal(data[l : l+int(dataLength)])
   260  				if err != nil {
   261  					return err
   262  				}
   263  				l += int(dataLength)
   264  				indexes[i] = indexdef
   265  			}
   266  			c.Cts = append(c.Cts, &IndexDef{indexes})
   267  		case RefChildTable:
   268  			length = binary.BigEndian.Uint64(data[l : l+8])
   269  			l += 8
   270  			tables := make([]uint64, length)
   271  			for i := 0; i < int(length); i++ {
   272  				tblId := binary.BigEndian.Uint64(data[l : l+8])
   273  				l += 8
   274  				tables[i] = tblId
   275  			}
   276  			c.Cts = append(c.Cts, &RefChildTableDef{tables})
   277  
   278  		case ForeignKey:
   279  			length = binary.BigEndian.Uint64(data[l : l+8])
   280  			l += 8
   281  			fKeys := make([]*plan.ForeignKeyDef, length)
   282  
   283  			for i := 0; i < int(length); i++ {
   284  				dataLength := binary.BigEndian.Uint64(data[l : l+8])
   285  				l += 8
   286  				fKey := &plan.ForeignKeyDef{}
   287  				err := fKey.Unmarshal(data[l : l+int(dataLength)])
   288  				if err != nil {
   289  					return err
   290  				}
   291  				l += int(dataLength)
   292  				fKeys[i] = fKey
   293  			}
   294  			c.Cts = append(c.Cts, &ForeignKeyDef{fKeys})
   295  
   296  		case PrimaryKey:
   297  			length = binary.BigEndian.Uint64(data[l : l+8])
   298  			l += 8
   299  			pkey := &plan.PrimaryKeyDef{}
   300  			err := pkey.Unmarshal(data[l : l+int(length)])
   301  			if err != nil {
   302  				return err
   303  			}
   304  			l += int(length)
   305  			c.Cts = append(c.Cts, &PrimaryKeyDef{pkey})
   306  		}
   307  	}
   308  	return nil
   309  }
   310  
   311  // get the primary key definition in the constraint, and return null if there is no primary key
   312  func (c *ConstraintDef) GetPrimaryKeyDef() *PrimaryKeyDef {
   313  	for _, ct := range c.Cts {
   314  		if ctVal, ok := ct.(*PrimaryKeyDef); ok {
   315  			return ctVal
   316  		}
   317  	}
   318  	return nil
   319  }
   320  
   321  type Constraint interface {
   322  	constraint()
   323  }
   324  
   325  // TODO: UniqueIndexDef, SecondaryIndexDef will not be tabledef and need to be moved in Constraint to be able modified
   326  func (*ForeignKeyDef) constraint()    {}
   327  func (*PrimaryKeyDef) constraint()    {}
   328  func (*RefChildTableDef) constraint() {}
   329  func (*IndexDef) constraint()         {}
   330  
   331  type Relation interface {
   332  	Statistics
   333  
   334  	Ranges(context.Context, *plan.Expr) ([][]byte, error)
   335  
   336  	TableDefs(context.Context) ([]TableDef, error)
   337  
   338  	GetPrimaryKeys(context.Context) ([]*Attribute, error)
   339  
   340  	GetHideKeys(context.Context) ([]*Attribute, error)
   341  
   342  	Write(context.Context, *batch.Batch) error
   343  
   344  	Update(context.Context, *batch.Batch) error
   345  
   346  	// Delete(context.Context, *vector.Vector, string) error
   347  	Delete(context.Context, *batch.Batch, string) error
   348  
   349  	AddTableDef(context.Context, TableDef) error
   350  	DelTableDef(context.Context, TableDef) error
   351  
   352  	// only ConstraintDef can be modified
   353  	UpdateConstraint(context.Context, *ConstraintDef) error
   354  
   355  	GetTableID(context.Context) uint64
   356  
   357  	// second argument is the number of reader, third argument is the filter extend, foruth parameter is the payload required by the engine
   358  	NewReader(context.Context, int, *plan.Expr, [][]byte) ([]Reader, error)
   359  
   360  	TableColumns(ctx context.Context) ([]*Attribute, error)
   361  
   362  	//max and min values
   363  	MaxAndMinValues(ctx context.Context) ([][2]any, []uint8, error)
   364  }
   365  
   366  type Reader interface {
   367  	Close() error
   368  	Read(context.Context, []string, *plan.Expr, *mpool.MPool) (*batch.Batch, error)
   369  }
   370  
   371  type Database interface {
   372  	Relations(context.Context) ([]string, error)
   373  	Relation(context.Context, string) (Relation, error)
   374  
   375  	Delete(context.Context, string) error
   376  	Create(context.Context, string, []TableDef) error // Create Table - (name, table define)
   377  	Truncate(context.Context, string) (uint64, error)
   378  	GetDatabaseId(context.Context) string
   379  }
   380  
   381  type Engine interface {
   382  	// transaction interface
   383  	New(ctx context.Context, op client.TxnOperator) error
   384  	Commit(ctx context.Context, op client.TxnOperator) error
   385  	Rollback(ctx context.Context, op client.TxnOperator) error
   386  
   387  	// Delete deletes a database
   388  	Delete(ctx context.Context, databaseName string, op client.TxnOperator) error
   389  
   390  	// Create creates a database
   391  	Create(ctx context.Context, databaseName string, op client.TxnOperator) error
   392  
   393  	// Databases returns all database names
   394  	Databases(ctx context.Context, op client.TxnOperator) (databaseNames []string, err error)
   395  
   396  	// Database creates a handle for a database
   397  	Database(ctx context.Context, databaseName string, op client.TxnOperator) (Database, error)
   398  
   399  	// Nodes returns all nodes for worker jobs
   400  	Nodes() (cnNodes Nodes, err error)
   401  
   402  	// Hints returns hints of engine features
   403  	// return value should not be cached
   404  	// since implementations may update hints after engine had initialized
   405  	Hints() Hints
   406  
   407  	NewBlockReader(ctx context.Context, num int, ts timestamp.Timestamp,
   408  		expr *plan.Expr, ranges [][]byte, tblDef *plan.TableDef) ([]Reader, error)
   409  
   410  	// Get database name & table name by table id
   411  	GetNameById(ctx context.Context, op client.TxnOperator, tableId uint64) (dbName string, tblName string, err error)
   412  
   413  	// Get relation by table id
   414  	GetRelationById(ctx context.Context, op client.TxnOperator, tableId uint64) (dbName string, tblName string, rel Relation, err error)
   415  }
   416  
   417  type Hints struct {
   418  	CommitOrRollbackTimeout time.Duration
   419  }
   420  
   421  type GetClusterDetailsFunc = func() (logservicepb.ClusterDetails, error)
   422  
   423  // EntireEngine is a wrapper for Engine to support temporary table
   424  type EntireEngine struct {
   425  	Engine     Engine // original engine
   426  	TempEngine Engine // new engine for temporarily table
   427  }