github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/expression/property.go (about)

     1  // Copyright 2023 zGraph Authors. All rights reserved.
     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 expression
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/vescale/zgraph/datum"
    21  	"github.com/vescale/zgraph/parser/model"
    22  	"github.com/vescale/zgraph/stmtctx"
    23  	"github.com/vescale/zgraph/types"
    24  )
    25  
    26  var _ Expression = &PropertyAccess{}
    27  
    28  // PropertyAccess represents a property access expression.
    29  type PropertyAccess struct {
    30  	Expr         Expression
    31  	VariableName model.CIStr
    32  	PropertyName model.CIStr
    33  }
    34  
    35  func (p *PropertyAccess) String() string {
    36  	return p.VariableName.O + "." + p.PropertyName.O
    37  }
    38  
    39  func (p *PropertyAccess) ReturnType() types.T {
    40  	// Property types are unknown until runtime.
    41  	return types.Unknown
    42  }
    43  
    44  func (p *PropertyAccess) Eval(stmtCtx *stmtctx.Context, input datum.Row) (datum.Datum, error) {
    45  	d, err := p.Expr.Eval(stmtCtx, input)
    46  	if err != nil || d == datum.Null {
    47  		return d, err
    48  	}
    49  
    50  	v, ok := d.(*datum.Vertex)
    51  	if ok {
    52  		d, ok := v.Props[p.PropertyName.L]
    53  		if !ok {
    54  			return datum.Null, nil
    55  		}
    56  		return d, nil
    57  	}
    58  
    59  	e, ok := d.(*datum.Edge)
    60  	if ok {
    61  		d, ok := e.Props[p.PropertyName.L]
    62  		if !ok {
    63  			return datum.Null, nil
    64  		}
    65  		return d, nil
    66  	}
    67  
    68  	return nil, fmt.Errorf("cannot access property on non-vertex or non-edge type %T", d)
    69  }