github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/doltcore/sqle/dfunctions/active_branch.go (about) 1 // Copyright 2021 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package dfunctions 16 17 import ( 18 "fmt" 19 20 "github.com/dolthub/go-mysql-server/sql" 21 22 "github.com/dolthub/dolt/go/libraries/doltcore/ref" 23 "github.com/dolthub/dolt/go/libraries/doltcore/sqle" 24 ) 25 26 const ActiveBranchFuncName = "active_branch" 27 28 type ActiveBranchFunc struct { 29 } 30 31 // NewActiveBranchFunc creates a new ActiveBranchFunc expression. 32 func NewActiveBranchFunc(ctx *sql.Context) sql.Expression { 33 return &ActiveBranchFunc{} 34 } 35 36 // Eval implements the Expression interface. 37 func (cf *ActiveBranchFunc) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { 38 dbName := ctx.GetCurrentDatabase() 39 dSess := sqle.DSessFromSess(ctx.Session) 40 41 ddb, ok := dSess.GetDoltDB(dbName) 42 43 if !ok { 44 return nil, sql.ErrDatabaseNotFound.New(dbName) 45 } 46 47 rsr, ok := dSess.GetDoltDBRepoStateReader(dbName) 48 49 if !ok { 50 return nil, sql.ErrDatabaseNotFound.New(dbName) 51 } 52 53 currentBranch := rsr.CWBHeadRef() 54 55 branches, err := ddb.GetBranches(ctx) 56 57 if err != nil { 58 return nil, err 59 } 60 61 for _, br := range branches { 62 if ref.Equals(br, currentBranch) { 63 return br.GetPath(), nil 64 } 65 } 66 67 return nil, fmt.Errorf("active branch not found") 68 } 69 70 // String implements the Stringer interface. 71 func (cf *ActiveBranchFunc) String() string { 72 return fmt.Sprint("ACTIVE_BRANCH()") 73 } 74 75 // IsNullable implements the Expression interface. 76 func (cf *ActiveBranchFunc) IsNullable() bool { 77 return false 78 } 79 80 // Resolved implements the Expression interface. 81 func (*ActiveBranchFunc) Resolved() bool { 82 return true 83 } 84 85 func (cf *ActiveBranchFunc) Type() sql.Type { 86 return sql.Text 87 } 88 89 // Children implements the Expression interface. 90 func (*ActiveBranchFunc) Children() []sql.Expression { 91 return nil 92 } 93 94 // WithChildren implements the Expression interface. 95 func (v *ActiveBranchFunc) WithChildren(ctx *sql.Context, children ...sql.Expression) (sql.Expression, error) { 96 if len(children) != 0 { 97 return nil, sql.ErrInvalidChildrenNumber.New(v, len(children), 0) 98 } 99 return NewActiveBranchFunc(ctx), nil 100 }