Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new method ApplyTag #317

Merged
merged 13 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
*
* Copyright (c) 2024 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*
*/

package nebula_go

const (
ErrorTagNotFound = "TagNotFound: Tag not existed!"
)
12 changes: 12 additions & 0 deletions label.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,18 @@ func (edge LabelSchema) BuildDropEdgeQL() string {
return q
}

func (field LabelFieldSchema) BuildAddTagFieldQL(labelName string) string {
q := "ALTER TAG " + labelName + " ADD (" + field.Field + " " + field.Type
if !field.Nullable {
q += " NOT NULL"
}
return q + ");"
}

func (field Label) BuildDropTagFieldQL(labelName string) string {
return "ALTER TAG " + labelName + " DROP (" + field.Field + ");"
}

type LabelName struct {
Name string `nebula:"Name"`
}
Expand Down
18 changes: 18 additions & 0 deletions label_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,21 @@ func TestBuildCreateEdgeQL(t *testing.T) {
assert.Equal(t, "CREATE EDGE IF NOT EXISTS account_email (email string NOT NULL);", edge.BuildCreateEdgeQL())
assert.Equal(t, "DROP EDGE IF EXISTS account_email;", edge.BuildDropEdgeQL())
}

func TestBuildAddFieldQL(t *testing.T) {
field := LabelFieldSchema{
Field: "name",
Type: "string",
Nullable: false,
}
assert.Equal(t, "ALTER TAG account ADD (name string NOT NULL);", field.BuildAddTagFieldQL("account"))
field.Nullable = true
assert.Equal(t, "ALTER TAG account ADD (name string);", field.BuildAddTagFieldQL("account"))
}

func TestBuildDropFieldQL(t *testing.T) {
field := Label{
Field: "name",
}
assert.Equal(t, "ALTER TAG account DROP (name);", field.BuildDropTagFieldQL("account"))
}
109 changes: 109 additions & 0 deletions schema_manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
*
* Copyright (c) 2024 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*
*/

package nebula_go

import (
"fmt"
"strings"
)

type SchemaManager struct {
pool *SessionPool
}

func NewSchemaManager(pool *SessionPool) *SchemaManager {
return &SchemaManager{pool: pool}
}

// ApplyTag applies the given tag to the graph.
// 1. If the tag does not exist, it will be created.
// 2. If the tag exists, it will be checked if the fields are the same.
// 2.1 If not, the new fields will be added.
// 2.2 If the field type is different, it will return an error.
// 2.3 If a field exists in the graph but not in the given tag,
// it will be removed.
//
// Notice:
// We won't change the field type because it has
// unexpected behavior for the data.
func (mgr *SchemaManager) ApplyTag(tag LabelSchema) (*ResultSet, error) {
// 1. Check if the tag exists
fields, err := mgr.pool.DescTag(tag.Name)
if err != nil {
// 2. If the tag does not exist, create it
if strings.Contains(err.Error(), ErrorTagNotFound) {
return mgr.pool.CreateTag(tag)
}
return nil, err
}

// 3. If the tag exists, check if the fields are the same
if err != nil {
return nil, err
}

// 4. Add new fields
// 4.1 Prepare the new fields
addFieldQLs := []string{}
for _, expected := range tag.Fields {
found := false
for _, actual := range fields {
if expected.Field == actual.Field {
found = true
// 4.2 Check if the field type is different
if expected.Type != actual.Type {
return nil, fmt.Errorf("field type is different. "+
"Expected: %s, Actual: %s", expected.Type, actual.Type)
}
break
}
}
if !found {
// 4.3 Add the not exists field QL
q := expected.BuildAddTagFieldQL(tag.Name)
addFieldQLs = append(addFieldQLs, q)
}
}
// 4.4 Execute the add field QLs if needed
if len(addFieldQLs) > 0 {
queries := strings.Join(addFieldQLs, "")
_, err = mgr.pool.ExecuteAndCheck(queries)
if err != nil {
return nil, err
}
}

// 5. Remove the not expected field
// 5.1 Prepare the not expected fields
dropFieldQLs := []string{}
for _, actual := range fields {
redundant := true
for _, expected := range tag.Fields {
if expected.Field == actual.Field {
redundant = false
break
}
}
if redundant {
// 5.2 Remove the not expected field
q := actual.BuildDropTagFieldQL(tag.Name)
haoxins marked this conversation as resolved.
Show resolved Hide resolved
dropFieldQLs = append(dropFieldQLs, q)
}
}
// 5.3 Execute the drop field QLs if needed
if len(dropFieldQLs) > 0 {
queries := strings.Join(dropFieldQLs, "")
_, err := mgr.pool.ExecuteAndCheck(queries)
if err != nil {
return nil, err
}
}

return nil, nil
}
160 changes: 160 additions & 0 deletions schema_manager_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
*
* Copyright (c) 2024 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*
*/

package nebula_go

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestSchemaManagerApplyTag(t *testing.T) {
spaceName := "test_space_apply_tag"
err := prepareSpace(spaceName)
if err != nil {
t.Fatal(err)
}
defer dropSpace(spaceName)

hostAddress := HostAddress{Host: address, Port: port}
config, err := NewSessionPoolConf(
"root",
"nebula",
[]HostAddress{hostAddress},
spaceName)
if err != nil {
t.Errorf("failed to create session pool config, %s", err.Error())
}

// allow only one session in the pool so it is easier to test
config.maxSize = 1

// create session pool
sessionPool, err := NewSessionPool(*config, DefaultLogger{})
if err != nil {
t.Fatal(err)
}
defer sessionPool.Close()

schemaManager := NewSchemaManager(sessionPool)

spaces, err := sessionPool.ShowSpaces()
if err != nil {
t.Fatal(err)
}
assert.LessOrEqual(t, 1, len(spaces))
var spaceNames []string
for _, space := range spaces {
spaceNames = append(spaceNames, space.Name)
}
assert.Contains(t, spaceNames, spaceName)

tagSchema := LabelSchema{
Name: "account",
Fields: []LabelFieldSchema{
{
Field: "name",
Nullable: false,
},
},
}
_, err = schemaManager.ApplyTag(tagSchema)
if err != nil {
t.Fatal(err)
}
tags, err := sessionPool.ShowTags()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 1, len(tags))
assert.Equal(t, "account", tags[0].Name)
labels, err := sessionPool.DescTag("account")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 1, len(labels))
assert.Equal(t, "name", labels[0].Field)
assert.Equal(t, "string", labels[0].Type)

tagSchema = LabelSchema{
Name: "account",
Fields: []LabelFieldSchema{
{
Field: "name",
Type: "string",
Nullable: false,
},
{
Field: "email",
Type: "string",
Nullable: true,
},
{
Field: "phone",
Type: "int64",
Nullable: true,
},
},
}
_, err = schemaManager.ApplyTag(tagSchema)
if err != nil {
t.Fatal(err)
}
tags, err = sessionPool.ShowTags()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 1, len(tags))
assert.Equal(t, "account", tags[0].Name)
labels, err = sessionPool.DescTag("account")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 3, len(labels))
assert.Equal(t, "name", labels[0].Field)
assert.Equal(t, "string", labels[0].Type)
assert.Equal(t, "email", labels[1].Field)
assert.Equal(t, "string", labels[1].Type)
assert.Equal(t, "phone", labels[2].Field)
assert.Equal(t, "int64", labels[2].Type)
tagSchema = LabelSchema{
Name: "account",
Fields: []LabelFieldSchema{
{
Field: "name",
Type: "string",
Nullable: false,
},
{
Field: "phone",
Type: "int64",
Nullable: true,
},
},
}
_, err = schemaManager.ApplyTag(tagSchema)
if err != nil {
t.Fatal(err)
}
tags, err = sessionPool.ShowTags()
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 1, len(tags))
assert.Equal(t, "account", tags[0].Name)
labels, err = sessionPool.DescTag("account")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 2, len(labels))
assert.Equal(t, "name", labels[0].Field)
assert.Equal(t, "string", labels[0].Type)
assert.Equal(t, "phone", labels[1].Field)
assert.Equal(t, "int64", labels[1].Type)
}
9 changes: 5 additions & 4 deletions session_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,18 +359,19 @@ func TestSessionPoolSpaceChange(t *testing.T) {
}

func TestSessionPoolApplySchema(t *testing.T) {
err := prepareSpace("test_space_schema")
spaceName := "test_space_schema"
err := prepareSpace(spaceName)
if err != nil {
t.Fatal(err)
}
defer dropSpace("test_space_schema")
defer dropSpace(spaceName)

hostAddress := HostAddress{Host: address, Port: port}
config, err := NewSessionPoolConf(
"root",
"nebula",
[]HostAddress{hostAddress},
"test_space_schema")
spaceName)
if err != nil {
t.Errorf("failed to create session pool config, %s", err.Error())
}
Expand All @@ -394,7 +395,7 @@ func TestSessionPoolApplySchema(t *testing.T) {
for _, space := range spaces {
spaceNames = append(spaceNames, space.Name)
}
assert.Contains(t, spaceNames, "test_space_schema", "should have test_space_schema")
assert.Contains(t, spaceNames, spaceName)

tagSchema := LabelSchema{
Name: "account",
Expand Down