From c3470584e228a189f7e81ca3bc4ea4b96054927c Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 01:17:07 +0800 Subject: [PATCH 01/11] make delete node works --- nested_set.go | 61 ++++++++++++++++++++++++++++++++++++++++++++-- nested_set_test.go | 20 +++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/nested_set.go b/nested_set.go index 4377171..ffea8bf 100644 --- a/nested_set.go +++ b/nested_set.go @@ -99,7 +99,7 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err } // Create a new node by parent with Gorm original Create() -// ```nestedset.Create(db, &Category{...}, nil)```` will create a new category in root level +// ```nestedset.Create(db, &Category{...}, nil)``` will create a new category in root level // ```nestedset.Create(db, &Category{...}, &parent)``` will create a new category under parent node as its last child func Create(db *gorm.DB, source, parent interface{}) error { return db.Transaction(func(db *gorm.DB) (err error) { @@ -149,7 +149,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { return err } - // UPDATE tree SET children_count = children_count + 1 WHERE is = parent.id; + // UPDATE tree SET children_count = children_count + 1 WHERE id = parent.id; err = db.Model(parent).Update( dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), ).Error @@ -184,6 +184,63 @@ func Create(db *gorm.DB, source, parent interface{}) error { }) } +// Delete a node from scoped list and its all descendent +// ```nestedset.Delete(db, &Category{...})``` +func Delete(db *gorm.DB, source interface{}) error { + return db.Transaction(func(tx *gorm.DB) (err error) { + tx.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}) + + // load node from locked DB to avoid override + rst := db.First(source) + if rst.Error != nil { + return rst.Error + } + + tx, target, err := parseNode(tx, source) + if err != nil { + return err + } + + tableName, dbNames := target.TableName, target.DbNames + // Batch Delete Method in GORM requires an instance of current source type without ID + // to avoid GORM style Delete interface, we hacked here by set source ID to 0 + v := reflect.Indirect(reflect.ValueOf(source)) + t := v.Type() + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("nestedset") == "id" { + f := v.FieldByName(f.Name) + f.SetInt(0) + break + } + } + + tx, _, _ = parseNode(tx, source) + err = tx. + Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). + Delete(source).Error + if err != nil { + return err + } + + // UPDATE tree SET rgt = rgt - width WHERE rgt > target_rgt; + // UPDATE tree SET lft = lft - width WHERE lft > target_rgt; + width := target.Rgt - target.Lft + 1 + for _, d := range []string{"rgt", "lft"} { + tx, _, _ = parseNode(db, source) + err = tx.Table(tableName). + Where(formatSQL(":"+d+" > ?", target), target.Rgt). + Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). + Error + if err != nil { + return err + } + } + + return nil + }) +} + // MoveTo move node to a position which is related a target node // ```nestedset.MoveTo(db, &node, &to, nestedset.MoveDirectionInner)``` will move [&node] to [&to] node's child_list as its first child func MoveTo(db *gorm.DB, node, to interface{}, direction MoveDirection) error { diff --git a/nested_set_test.go b/nested_set_test.go index bfe27af..374d87f 100644 --- a/nested_set_test.go +++ b/nested_set_test.go @@ -130,6 +130,26 @@ func TestCreateSource(t *testing.T) { assert.Equal(t, c2.ChildrenCount, 1) } +func TestDeleteSource(t *testing.T) { + initData() + + c1 := Category{Title: "c1s"} + Create(db, &c1, nil) + + cp := Category{Title: "cp"} + Create(db, &cp, c1) + + c2 := Category{Title: "c2"} + Create(db, &c2, nil) + + db.First(&c1) + Delete(db, &c1) + + db.Model(&c2).First(&c2) + assert.Equal(t, c2.Lft, 1) + assert.Equal(t, c2.Rgt, 2) +} + func TestMoveToRight(t *testing.T) { // case 1 initData() From 892052b8465a5cc3643431c68442a74a795161bb Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 01:51:32 +0800 Subject: [PATCH 02/11] update delete logic --- nested_set.go | 15 +++++++++------ nested_set_test.go | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/nested_set.go b/nested_set.go index ffea8bf..e89bf3e 100644 --- a/nested_set.go +++ b/nested_set.go @@ -187,8 +187,12 @@ func Create(db *gorm.DB, source, parent interface{}) error { // Delete a node from scoped list and its all descendent // ```nestedset.Delete(db, &Category{...})``` func Delete(db *gorm.DB, source interface{}) error { - return db.Transaction(func(tx *gorm.DB) (err error) { - tx.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}) + return db.Transaction(func(db *gorm.DB) (err error) { + // lock table + err = db.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}).Find(source).Error + if err != nil { + return nil + } // load node from locked DB to avoid override rst := db.First(source) @@ -196,14 +200,14 @@ func Delete(db *gorm.DB, source interface{}) error { return rst.Error } - tx, target, err := parseNode(tx, source) + tx, target, err := parseNode(db, source) if err != nil { return err } - tableName, dbNames := target.TableName, target.DbNames // Batch Delete Method in GORM requires an instance of current source type without ID // to avoid GORM style Delete interface, we hacked here by set source ID to 0 + tableName, dbNames := target.TableName, target.DbNames v := reflect.Indirect(reflect.ValueOf(source)) t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -214,8 +218,6 @@ func Delete(db *gorm.DB, source interface{}) error { break } } - - tx, _, _ = parseNode(tx, source) err = tx. Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). Delete(source).Error @@ -227,6 +229,7 @@ func Delete(db *gorm.DB, source interface{}) error { // UPDATE tree SET lft = lft - width WHERE lft > target_rgt; width := target.Rgt - target.Lft + 1 for _, d := range []string{"rgt", "lft"} { + // recreate db session for get rid of previous clauses tx, _, _ = parseNode(db, source) err = tx.Table(tableName). Where(formatSQL(":"+d+" > ?", target), target.Rgt). diff --git a/nested_set_test.go b/nested_set_test.go index 374d87f..3116266 100644 --- a/nested_set_test.go +++ b/nested_set_test.go @@ -139,7 +139,7 @@ func TestDeleteSource(t *testing.T) { cp := Category{Title: "cp"} Create(db, &cp, c1) - c2 := Category{Title: "c2"} + c2 := Category{Title: "c2s"} Create(db, &c2, nil) db.First(&c1) From eaa4b3e8593f2aa3b7fc7ee82879e6a290817da1 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 02:14:38 +0800 Subject: [PATCH 03/11] add lock in create node --- nested_set.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/nested_set.go b/nested_set.go index e89bf3e..1729c7b 100644 --- a/nested_set.go +++ b/nested_set.go @@ -103,6 +103,13 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err // ```nestedset.Create(db, &Category{...}, &parent)``` will create a new category under parent node as its last child func Create(db *gorm.DB, source, parent interface{}) error { return db.Transaction(func(db *gorm.DB) (err error) { + // lock table + lockRst := make(map[string]interface{}, 0) + err = db.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}).Find(&lockRst).Error + if err != nil { + return nil + } + tx, target, err := parseNode(db, source) if err != nil { return err From 0abcbfddf4808784d16b5a5f309cebf7602418f3 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 02:19:39 +0800 Subject: [PATCH 04/11] fix tx issue when create node --- nested_set.go | 1 + 1 file changed, 1 insertion(+) diff --git a/nested_set.go b/nested_set.go index 1729c7b..311f3f9 100644 --- a/nested_set.go +++ b/nested_set.go @@ -147,6 +147,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { return err } + tx, _, _ := parseNode(db, source) // UPDATE tree SET lft = lft + 2 WHERE lft > new_lft; err = tx.Table(tableName). Where(formatSQL(":lft > ?", target), setToLft). From 5bdd7a39b8870e9f2dfec9a792ebff401214427d Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 10:26:45 +0800 Subject: [PATCH 05/11] rename dbNames to columnMap --- nested_set.go | 54 +++++++++++++++++++++++----------------------- nested_set_test.go | 28 ++++++++++++------------ 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/nested_set.go b/nested_set.go index 311f3f9..0537371 100644 --- a/nested_set.go +++ b/nested_set.go @@ -33,7 +33,7 @@ type nodeItem struct { Lft int ChildrenCount int TableName string - DbNames map[string]string + ColumnMap map[string]string } // parseNode parse a gorm structure into an internal source structure @@ -53,7 +53,7 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err return } - item = nodeItem{TableName: stmt.Table, DbNames: map[string]string{}} + item = nodeItem{TableName: stmt.Table, ColumnMap: map[string]string{}} sourceValue := reflect.Indirect(reflect.ValueOf(source)) sourceType := sourceValue.Type() for i := 0; i < sourceType.NumField(); i++ { @@ -66,27 +66,27 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err switch t.Tag.Get("nestedset") { case "id": item.ID = v.Int() - item.DbNames["id"] = dbName + item.ColumnMap["id"] = dbName break case "parent_id": item.ParentID = v.Interface().(sql.NullInt64) - item.DbNames["parent_id"] = dbName + item.ColumnMap["parent_id"] = dbName break case "depth": item.Depth = int(v.Int()) - item.DbNames["depth"] = dbName + item.ColumnMap["depth"] = dbName break case "rgt": item.Rgt = int(v.Int()) - item.DbNames["rgt"] = dbName + item.ColumnMap["rgt"] = dbName break case "lft": item.Lft = int(v.Int()) - item.DbNames["lft"] = dbName + item.ColumnMap["lft"] = dbName break case "children_count": item.ChildrenCount = int(v.Int()) - item.DbNames["children_count"] = dbName + item.ColumnMap["children_count"] = dbName break case "scope": rawVal, _ := schemaField.ValueOf(sourceValue) @@ -117,15 +117,15 @@ func Create(db *gorm.DB, source, parent interface{}) error { // for totally blank table / scope default init root would be [1 - 2] setDepth, setToLft, setToRgt := 0, 1, 2 - tableName, dbNames := target.TableName, target.DbNames + tableName, ColumnMap := target.TableName, target.ColumnMap // put node into root level when parent is nil if parent == nil { lastNode := make(map[string]interface{}) orderSQL := formatSQL(":rgt desc", target) - rst := tx.Model(source).Select(dbNames["rgt"]).Order(orderSQL).First(&lastNode) + rst := tx.Model(source).Select(ColumnMap["rgt"]).Order(orderSQL).First(&lastNode) if rst.Error == nil { - setToLft = lastNode[dbNames["rgt"]].(int) + 1 + setToLft = lastNode[ColumnMap["rgt"]].(int) + 1 setToRgt = setToLft + 1 } } else { @@ -141,7 +141,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET rgt = rgt + 2 WHERE rgt >= new_lft; err = tx.Table(tableName). Where(formatSQL(":rgt >= ?", target), setToLft). - UpdateColumn(dbNames["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))). + UpdateColumn(ColumnMap["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))). Error if err != nil { return err @@ -151,7 +151,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET lft = lft + 2 WHERE lft > new_lft; err = tx.Table(tableName). Where(formatSQL(":lft > ?", target), setToLft). - UpdateColumn(dbNames["lft"], gorm.Expr(formatSQL(":lft + 2", target))). + UpdateColumn(ColumnMap["lft"], gorm.Expr(formatSQL(":lft + 2", target))). Error if err != nil { return err @@ -159,7 +159,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET children_count = children_count + 1 WHERE id = parent.id; err = db.Model(parent).Update( - dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), + ColumnMap["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), ).Error if err != nil { return err @@ -215,7 +215,7 @@ func Delete(db *gorm.DB, source interface{}) error { // Batch Delete Method in GORM requires an instance of current source type without ID // to avoid GORM style Delete interface, we hacked here by set source ID to 0 - tableName, dbNames := target.TableName, target.DbNames + tableName, ColumeMap := target.TableName, target.ColumnMap v := reflect.Indirect(reflect.ValueOf(source)) t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -241,7 +241,7 @@ func Delete(db *gorm.DB, source interface{}) error { tx, _, _ = parseNode(db, source) err = tx.Table(tableName). Where(formatSQL(":"+d+" > ?", target), target.Rgt). - Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). + Update(ColumeMap[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). Error if err != nil { return err @@ -337,7 +337,7 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI if err != nil { return } - err = tx.Where(formatSQL(":id = ?", targetNode), oldParentID).Update(targetNode.DbNames["children_count"], oldParentCount).Error + err = tx.Where(formatSQL(":id = ?", targetNode), oldParentID).Update(targetNode.ColumnMap["children_count"], oldParentCount).Error if err != nil { return } @@ -348,7 +348,7 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI if err != nil { return } - err = tx.Where(formatSQL(":id = ?", targetNode), newParentID).Update(targetNode.DbNames["children_count"], newParentCount).Error + err = tx.Where(formatSQL(":id = ?", targetNode), newParentID).Update(targetNode.ColumnMap["children_count"], newParentCount).Error if err != nil { return } @@ -358,30 +358,30 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI } func moveTarget(tx *gorm.DB, targetNode nodeItem, targetID int64, targetIds []int64, step, depthChange int, newParentID sql.NullInt64) (err error) { - dbNames := targetNode.DbNames + cm := targetNode.ColumnMap if len(targetIds) > 0 { err = tx.Where(formatSQL(":id IN (?)", targetNode), targetIds). Updates(map[string]interface{}{ - dbNames["lft"]: gorm.Expr(formatSQL(":lft + ?", targetNode), step), - dbNames["rgt"]: gorm.Expr(formatSQL(":rgt + ?", targetNode), step), - dbNames["depth"]: gorm.Expr(formatSQL(":depth + ?", targetNode), depthChange), + cm["lft"]: gorm.Expr(formatSQL(":lft + ?", targetNode), step), + cm["rgt"]: gorm.Expr(formatSQL(":rgt + ?", targetNode), step), + cm["depth"]: gorm.Expr(formatSQL(":depth + ?", targetNode), depthChange), }).Error if err != nil { return } } - return tx.Where(formatSQL(":id = ?", targetNode), targetID).Update(dbNames["parent_id"], newParentID).Error + return tx.Where(formatSQL(":id = ?", targetNode), targetID).Update(cm["parent_id"], newParentID).Error } func moveAffected(tx *gorm.DB, targetNode nodeItem, gte, lte, step int) (err error) { - dbNames := targetNode.DbNames + cm := targetNode.ColumnMap return tx.Where(formatSQL("(:lft BETWEEN ? AND ?) OR (:rgt BETWEEN ? AND ?)", targetNode), gte, lte, gte, lte). Updates(map[string]interface{}{ - dbNames["lft"]: gorm.Expr(formatSQL("(CASE WHEN :lft >= ? THEN :lft + ? ELSE :lft END)", targetNode), gte, step), - dbNames["rgt"]: gorm.Expr(formatSQL("(CASE WHEN :rgt <= ? THEN :rgt + ? ELSE :rgt END)", targetNode), lte, step), + cm["lft"]: gorm.Expr(formatSQL("(CASE WHEN :lft >= ? THEN :lft + ? ELSE :lft END)", targetNode), gte, step), + cm["rgt"]: gorm.Expr(formatSQL("(CASE WHEN :rgt <= ? THEN :rgt + ? ELSE :rgt END)", targetNode), lte, step), }).Error } @@ -389,7 +389,7 @@ func formatSQL(placeHolderSQL string, node nodeItem) (out string) { out = placeHolderSQL out = strings.ReplaceAll(out, ":table_name", node.TableName) - for k, v := range node.DbNames { + for k, v := range node.ColumnMap { out = strings.Replace(out, ":"+k, v, -1) } diff --git a/nested_set_test.go b/nested_set_test.go index 3116266..485f286 100644 --- a/nested_set_test.go +++ b/nested_set_test.go @@ -49,13 +49,13 @@ func TestNewNodeItem(t *testing.T) { stmt.Build(clause.Where{}.Name()) assert.Equal(t, "WHERE user_id = $1 AND user_type = $2", stmt.SQL.String()) - dbNames := node.DbNames - assert.Equal(t, "id", dbNames["id"]) - assert.Equal(t, "parent_id", dbNames["parent_id"]) - assert.Equal(t, "depth", dbNames["depth"]) - assert.Equal(t, "rgt", dbNames["rgt"]) - assert.Equal(t, "lft", dbNames["lft"]) - assert.Equal(t, "children_count", dbNames["children_count"]) + columnMap := node.ColumnMap + assert.Equal(t, "id", columnMap["id"]) + assert.Equal(t, "parent_id", columnMap["parent_id"]) + assert.Equal(t, "depth", columnMap["depth"]) + assert.Equal(t, "rgt", columnMap["rgt"]) + assert.Equal(t, "lft", columnMap["lft"]) + assert.Equal(t, "children_count", columnMap["children_count"]) // Test for difference column names specialItem := SpecialItem{ @@ -80,13 +80,13 @@ func TestNewNodeItem(t *testing.T) { stmt.Build(clause.Where{}.Name()) assert.Equal(t, "", stmt.SQL.String()) - dbNames = node.DbNames - assert.Equal(t, "item_id", dbNames["id"]) - assert.Equal(t, "pid", dbNames["parent_id"]) - assert.Equal(t, "depth1", dbNames["depth"]) - assert.Equal(t, "right", dbNames["rgt"]) - assert.Equal(t, "left", dbNames["lft"]) - assert.Equal(t, "nodes_count", dbNames["children_count"]) + columnMap = node.ColumnMap + assert.Equal(t, "item_id", columnMap["id"]) + assert.Equal(t, "pid", columnMap["parent_id"]) + assert.Equal(t, "depth1", columnMap["depth"]) + assert.Equal(t, "right", columnMap["rgt"]) + assert.Equal(t, "left", columnMap["lft"]) + assert.Equal(t, "nodes_count", columnMap["children_count"]) // formatSQL test assert.Equal(t, "item_id = ? AND left > right AND pid = ?, nodes_count = 1, depth1 = 0", formatSQL(":id = ? AND :lft > :rgt AND :parent_id = ?, :children_count = 1, :depth = 0", node)) From b2426c96ba52151122f366c32b52afea04fe4e42 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 10:28:08 +0800 Subject: [PATCH 06/11] remove lock logic from create & delete, which should be done by caller --- nested_set.go | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/nested_set.go b/nested_set.go index 0537371..a6c0ad1 100644 --- a/nested_set.go +++ b/nested_set.go @@ -103,13 +103,6 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err // ```nestedset.Create(db, &Category{...}, &parent)``` will create a new category under parent node as its last child func Create(db *gorm.DB, source, parent interface{}) error { return db.Transaction(func(db *gorm.DB) (err error) { - // lock table - lockRst := make(map[string]interface{}, 0) - err = db.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}).Find(&lockRst).Error - if err != nil { - return nil - } - tx, target, err := parseNode(db, source) if err != nil { return err @@ -196,12 +189,6 @@ func Create(db *gorm.DB, source, parent interface{}) error { // ```nestedset.Delete(db, &Category{...})``` func Delete(db *gorm.DB, source interface{}) error { return db.Transaction(func(db *gorm.DB) (err error) { - // lock table - err = db.Model(source).Clauses(clause.Locking{Strength: "UPDATE"}).Find(source).Error - if err != nil { - return nil - } - // load node from locked DB to avoid override rst := db.First(source) if rst.Error != nil { From a72e045eafe5209a2e8343448727b3a1f3bce24d Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 10:47:18 +0800 Subject: [PATCH 07/11] Revert "rename dbNames to columnMap" This reverts commit 5bdd7a39b8870e9f2dfec9a792ebff401214427d. --- nested_set.go | 54 +++++++++++++++++++++++----------------------- nested_set_test.go | 28 ++++++++++++------------ 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/nested_set.go b/nested_set.go index a6c0ad1..cf767ca 100644 --- a/nested_set.go +++ b/nested_set.go @@ -33,7 +33,7 @@ type nodeItem struct { Lft int ChildrenCount int TableName string - ColumnMap map[string]string + DbNames map[string]string } // parseNode parse a gorm structure into an internal source structure @@ -53,7 +53,7 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err return } - item = nodeItem{TableName: stmt.Table, ColumnMap: map[string]string{}} + item = nodeItem{TableName: stmt.Table, DbNames: map[string]string{}} sourceValue := reflect.Indirect(reflect.ValueOf(source)) sourceType := sourceValue.Type() for i := 0; i < sourceType.NumField(); i++ { @@ -66,27 +66,27 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err switch t.Tag.Get("nestedset") { case "id": item.ID = v.Int() - item.ColumnMap["id"] = dbName + item.DbNames["id"] = dbName break case "parent_id": item.ParentID = v.Interface().(sql.NullInt64) - item.ColumnMap["parent_id"] = dbName + item.DbNames["parent_id"] = dbName break case "depth": item.Depth = int(v.Int()) - item.ColumnMap["depth"] = dbName + item.DbNames["depth"] = dbName break case "rgt": item.Rgt = int(v.Int()) - item.ColumnMap["rgt"] = dbName + item.DbNames["rgt"] = dbName break case "lft": item.Lft = int(v.Int()) - item.ColumnMap["lft"] = dbName + item.DbNames["lft"] = dbName break case "children_count": item.ChildrenCount = int(v.Int()) - item.ColumnMap["children_count"] = dbName + item.DbNames["children_count"] = dbName break case "scope": rawVal, _ := schemaField.ValueOf(sourceValue) @@ -110,15 +110,15 @@ func Create(db *gorm.DB, source, parent interface{}) error { // for totally blank table / scope default init root would be [1 - 2] setDepth, setToLft, setToRgt := 0, 1, 2 - tableName, ColumnMap := target.TableName, target.ColumnMap + tableName, dbNames := target.TableName, target.DbNames // put node into root level when parent is nil if parent == nil { lastNode := make(map[string]interface{}) orderSQL := formatSQL(":rgt desc", target) - rst := tx.Model(source).Select(ColumnMap["rgt"]).Order(orderSQL).First(&lastNode) + rst := tx.Model(source).Select(dbNames["rgt"]).Order(orderSQL).First(&lastNode) if rst.Error == nil { - setToLft = lastNode[ColumnMap["rgt"]].(int) + 1 + setToLft = lastNode[dbNames["rgt"]].(int) + 1 setToRgt = setToLft + 1 } } else { @@ -134,7 +134,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET rgt = rgt + 2 WHERE rgt >= new_lft; err = tx.Table(tableName). Where(formatSQL(":rgt >= ?", target), setToLft). - UpdateColumn(ColumnMap["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))). + UpdateColumn(dbNames["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))). Error if err != nil { return err @@ -144,7 +144,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET lft = lft + 2 WHERE lft > new_lft; err = tx.Table(tableName). Where(formatSQL(":lft > ?", target), setToLft). - UpdateColumn(ColumnMap["lft"], gorm.Expr(formatSQL(":lft + 2", target))). + UpdateColumn(dbNames["lft"], gorm.Expr(formatSQL(":lft + 2", target))). Error if err != nil { return err @@ -152,7 +152,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET children_count = children_count + 1 WHERE id = parent.id; err = db.Model(parent).Update( - ColumnMap["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), + dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), ).Error if err != nil { return err @@ -202,7 +202,7 @@ func Delete(db *gorm.DB, source interface{}) error { // Batch Delete Method in GORM requires an instance of current source type without ID // to avoid GORM style Delete interface, we hacked here by set source ID to 0 - tableName, ColumeMap := target.TableName, target.ColumnMap + tableName, dbNames := target.TableName, target.DbNames v := reflect.Indirect(reflect.ValueOf(source)) t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -228,7 +228,7 @@ func Delete(db *gorm.DB, source interface{}) error { tx, _, _ = parseNode(db, source) err = tx.Table(tableName). Where(formatSQL(":"+d+" > ?", target), target.Rgt). - Update(ColumeMap[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). + Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). Error if err != nil { return err @@ -324,7 +324,7 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI if err != nil { return } - err = tx.Where(formatSQL(":id = ?", targetNode), oldParentID).Update(targetNode.ColumnMap["children_count"], oldParentCount).Error + err = tx.Where(formatSQL(":id = ?", targetNode), oldParentID).Update(targetNode.DbNames["children_count"], oldParentCount).Error if err != nil { return } @@ -335,7 +335,7 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI if err != nil { return } - err = tx.Where(formatSQL(":id = ?", targetNode), newParentID).Update(targetNode.ColumnMap["children_count"], newParentCount).Error + err = tx.Where(formatSQL(":id = ?", targetNode), newParentID).Update(targetNode.DbNames["children_count"], newParentCount).Error if err != nil { return } @@ -345,30 +345,30 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI } func moveTarget(tx *gorm.DB, targetNode nodeItem, targetID int64, targetIds []int64, step, depthChange int, newParentID sql.NullInt64) (err error) { - cm := targetNode.ColumnMap + dbNames := targetNode.DbNames if len(targetIds) > 0 { err = tx.Where(formatSQL(":id IN (?)", targetNode), targetIds). Updates(map[string]interface{}{ - cm["lft"]: gorm.Expr(formatSQL(":lft + ?", targetNode), step), - cm["rgt"]: gorm.Expr(formatSQL(":rgt + ?", targetNode), step), - cm["depth"]: gorm.Expr(formatSQL(":depth + ?", targetNode), depthChange), + dbNames["lft"]: gorm.Expr(formatSQL(":lft + ?", targetNode), step), + dbNames["rgt"]: gorm.Expr(formatSQL(":rgt + ?", targetNode), step), + dbNames["depth"]: gorm.Expr(formatSQL(":depth + ?", targetNode), depthChange), }).Error if err != nil { return } } - return tx.Where(formatSQL(":id = ?", targetNode), targetID).Update(cm["parent_id"], newParentID).Error + return tx.Where(formatSQL(":id = ?", targetNode), targetID).Update(dbNames["parent_id"], newParentID).Error } func moveAffected(tx *gorm.DB, targetNode nodeItem, gte, lte, step int) (err error) { - cm := targetNode.ColumnMap + dbNames := targetNode.DbNames return tx.Where(formatSQL("(:lft BETWEEN ? AND ?) OR (:rgt BETWEEN ? AND ?)", targetNode), gte, lte, gte, lte). Updates(map[string]interface{}{ - cm["lft"]: gorm.Expr(formatSQL("(CASE WHEN :lft >= ? THEN :lft + ? ELSE :lft END)", targetNode), gte, step), - cm["rgt"]: gorm.Expr(formatSQL("(CASE WHEN :rgt <= ? THEN :rgt + ? ELSE :rgt END)", targetNode), lte, step), + dbNames["lft"]: gorm.Expr(formatSQL("(CASE WHEN :lft >= ? THEN :lft + ? ELSE :lft END)", targetNode), gte, step), + dbNames["rgt"]: gorm.Expr(formatSQL("(CASE WHEN :rgt <= ? THEN :rgt + ? ELSE :rgt END)", targetNode), lte, step), }).Error } @@ -376,7 +376,7 @@ func formatSQL(placeHolderSQL string, node nodeItem) (out string) { out = placeHolderSQL out = strings.ReplaceAll(out, ":table_name", node.TableName) - for k, v := range node.ColumnMap { + for k, v := range node.DbNames { out = strings.Replace(out, ":"+k, v, -1) } diff --git a/nested_set_test.go b/nested_set_test.go index 485f286..3116266 100644 --- a/nested_set_test.go +++ b/nested_set_test.go @@ -49,13 +49,13 @@ func TestNewNodeItem(t *testing.T) { stmt.Build(clause.Where{}.Name()) assert.Equal(t, "WHERE user_id = $1 AND user_type = $2", stmt.SQL.String()) - columnMap := node.ColumnMap - assert.Equal(t, "id", columnMap["id"]) - assert.Equal(t, "parent_id", columnMap["parent_id"]) - assert.Equal(t, "depth", columnMap["depth"]) - assert.Equal(t, "rgt", columnMap["rgt"]) - assert.Equal(t, "lft", columnMap["lft"]) - assert.Equal(t, "children_count", columnMap["children_count"]) + dbNames := node.DbNames + assert.Equal(t, "id", dbNames["id"]) + assert.Equal(t, "parent_id", dbNames["parent_id"]) + assert.Equal(t, "depth", dbNames["depth"]) + assert.Equal(t, "rgt", dbNames["rgt"]) + assert.Equal(t, "lft", dbNames["lft"]) + assert.Equal(t, "children_count", dbNames["children_count"]) // Test for difference column names specialItem := SpecialItem{ @@ -80,13 +80,13 @@ func TestNewNodeItem(t *testing.T) { stmt.Build(clause.Where{}.Name()) assert.Equal(t, "", stmt.SQL.String()) - columnMap = node.ColumnMap - assert.Equal(t, "item_id", columnMap["id"]) - assert.Equal(t, "pid", columnMap["parent_id"]) - assert.Equal(t, "depth1", columnMap["depth"]) - assert.Equal(t, "right", columnMap["rgt"]) - assert.Equal(t, "left", columnMap["lft"]) - assert.Equal(t, "nodes_count", columnMap["children_count"]) + dbNames = node.DbNames + assert.Equal(t, "item_id", dbNames["id"]) + assert.Equal(t, "pid", dbNames["parent_id"]) + assert.Equal(t, "depth1", dbNames["depth"]) + assert.Equal(t, "right", dbNames["rgt"]) + assert.Equal(t, "left", dbNames["lft"]) + assert.Equal(t, "nodes_count", dbNames["children_count"]) // formatSQL test assert.Equal(t, "item_id = ? AND left > right AND pid = ?, nodes_count = 1, depth1 = 0", formatSQL(":id = ? AND :lft > :rgt AND :parent_id = ?, :children_count = 1, :depth = 0", node)) From 0718d9b003efd4f33e687f7b1c232b29518f3e23 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 11:15:11 +0800 Subject: [PATCH 08/11] fix tx scope issue --- nested_set.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nested_set.go b/nested_set.go index cf767ca..0f0337b 100644 --- a/nested_set.go +++ b/nested_set.go @@ -202,7 +202,7 @@ func Delete(db *gorm.DB, source interface{}) error { // Batch Delete Method in GORM requires an instance of current source type without ID // to avoid GORM style Delete interface, we hacked here by set source ID to 0 - tableName, dbNames := target.TableName, target.DbNames + dbNames := target.DbNames v := reflect.Indirect(reflect.ValueOf(source)) t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -213,7 +213,7 @@ func Delete(db *gorm.DB, source interface{}) error { break } } - err = tx. + err = tx.Model(source). Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). Delete(source).Error if err != nil { @@ -226,7 +226,7 @@ func Delete(db *gorm.DB, source interface{}) error { for _, d := range []string{"rgt", "lft"} { // recreate db session for get rid of previous clauses tx, _, _ = parseNode(db, source) - err = tx.Table(tableName). + err = tx.Model(source). Where(formatSQL(":"+d+" > ?", target), target.Rgt). Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). Error @@ -252,7 +252,7 @@ func MoveTo(db *gorm.DB, node, to interface{}, direction MoveDirection) error { return err } - tx = db.Table(targetNode.TableName) + tx = tx.Table(targetNode.TableName) var right, depthChange int var newParentID sql.NullInt64 From 442690d2212e0a875ca1d6f544669e0a6df0b535 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sat, 26 Dec 2020 22:13:53 +0800 Subject: [PATCH 09/11] move tx out of transaction scope, to make sure scope will be reset after finish again --- nested_set.go | 60 ++++++++++++++++++++++----------------------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/nested_set.go b/nested_set.go index 0f0337b..4389a26 100644 --- a/nested_set.go +++ b/nested_set.go @@ -102,16 +102,16 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err // ```nestedset.Create(db, &Category{...}, nil)``` will create a new category in root level // ```nestedset.Create(db, &Category{...}, &parent)``` will create a new category under parent node as its last child func Create(db *gorm.DB, source, parent interface{}) error { - return db.Transaction(func(db *gorm.DB) (err error) { - tx, target, err := parseNode(db, source) - if err != nil { - return err - } + tx, target, err := parseNode(db, source) + if err != nil { + return err + } - // for totally blank table / scope default init root would be [1 - 2] - setDepth, setToLft, setToRgt := 0, 1, 2 - tableName, dbNames := target.TableName, target.DbNames + // for totally blank table / scope default init root would be [1 - 2] + setDepth, setToLft, setToRgt := 0, 1, 2 + tableName, dbNames := target.TableName, target.DbNames + return tx.Transaction(func(tx *gorm.DB) (err error) { // put node into root level when parent is nil if parent == nil { lastNode := make(map[string]interface{}) @@ -140,7 +140,6 @@ func Create(db *gorm.DB, source, parent interface{}) error { return err } - tx, _, _ := parseNode(db, source) // UPDATE tree SET lft = lft + 2 WHERE lft > new_lft; err = tx.Table(tableName). Where(formatSQL(":lft > ?", target), setToLft). @@ -151,7 +150,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { } // UPDATE tree SET children_count = children_count + 1 WHERE id = parent.id; - err = db.Model(parent).Update( + err = tx.Model(parent).Update( dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), ).Error if err != nil { @@ -188,31 +187,26 @@ func Create(db *gorm.DB, source, parent interface{}) error { // Delete a node from scoped list and its all descendent // ```nestedset.Delete(db, &Category{...})``` func Delete(db *gorm.DB, source interface{}) error { - return db.Transaction(func(db *gorm.DB) (err error) { - // load node from locked DB to avoid override - rst := db.First(source) - if rst.Error != nil { - return rst.Error - } + tx, target, err := parseNode(db, source) + if err != nil { + return err + } - tx, target, err := parseNode(db, source) - if err != nil { - return err + // Batch Delete Method in GORM requires an instance of current source type without ID + // to avoid GORM style Delete interface, we hacked here by set source ID to 0 + dbNames := target.DbNames + v := reflect.Indirect(reflect.ValueOf(source)) + t := v.Type() + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Tag.Get("nestedset") == "id" { + f := v.FieldByName(f.Name) + f.SetInt(0) + break } + } - // Batch Delete Method in GORM requires an instance of current source type without ID - // to avoid GORM style Delete interface, we hacked here by set source ID to 0 - dbNames := target.DbNames - v := reflect.Indirect(reflect.ValueOf(source)) - t := v.Type() - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Tag.Get("nestedset") == "id" { - f := v.FieldByName(f.Name) - f.SetInt(0) - break - } - } + return tx.Transaction(func(tx *gorm.DB) (err error) { err = tx.Model(source). Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). Delete(source).Error @@ -224,8 +218,6 @@ func Delete(db *gorm.DB, source interface{}) error { // UPDATE tree SET lft = lft - width WHERE lft > target_rgt; width := target.Rgt - target.Lft + 1 for _, d := range []string{"rgt", "lft"} { - // recreate db session for get rid of previous clauses - tx, _, _ = parseNode(db, source) err = tx.Model(source). Where(formatSQL(":"+d+" > ?", target), target.Rgt). Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). From 9189b56239de86d21d5c5285285f373ac819efe4 Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sun, 27 Dec 2020 14:15:28 +0800 Subject: [PATCH 10/11] rename some variables, replace schema loading by schema --- nested_set.go | 69 ++++++++++++++++++++++----------------------------- 1 file changed, 29 insertions(+), 40 deletions(-) diff --git a/nested_set.go b/nested_set.go index 4389a26..3b38885 100644 --- a/nested_set.go +++ b/nested_set.go @@ -1,14 +1,14 @@ package nestedset import ( - "context" "database/sql" "fmt" "reflect" "strings" + "sync" "gorm.io/gorm" - "gorm.io/gorm/clause" + "gorm.io/gorm/schema" ) // MoveDirection means where the node is going to be located @@ -25,7 +25,7 @@ const ( MoveDirectionInner MoveDirection = 0 ) -type nodeItem struct { +type nestedItem struct { ID int64 ParentID sql.NullInt64 Depth int @@ -36,31 +36,25 @@ type nodeItem struct { DbNames map[string]string } -// parseNode parse a gorm structure into an internal source structure -// for bring in all required data attribute like scope, left, righ etc. -func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err error) { - tx = db - stmt := &gorm.Statement{ - DB: tx, - ConnPool: tx.ConnPool, - Context: context.Background(), - Clauses: map[string]clause.Clause{}, - } - - err = stmt.Parse(source) +// parseNode parse a gorm struct into an internal nested item struct +// bring in all required data attribute like scope, left, righ etc. +func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nestedItem, err error) { + scm, err := schema.Parse(source, &sync.Map{}, schema.NamingStrategy{}) if err != nil { err = fmt.Errorf("Invalid source, must be a valid Gorm Model instance, %v", source) return } - item = nodeItem{TableName: stmt.Table, DbNames: map[string]string{}} + tx = db.Table(scm.Table) + + item = nestedItem{TableName: scm.Table, DbNames: map[string]string{}} sourceValue := reflect.Indirect(reflect.ValueOf(source)) sourceType := sourceValue.Type() for i := 0; i < sourceType.NumField(); i++ { t := sourceType.Field(i) v := sourceValue.Field(i) - schemaField := stmt.Schema.LookUpField(t.Name) + schemaField := scm.LookUpField(t.Name) dbName := schemaField.DBName switch t.Tag.Get("nestedset") { @@ -98,7 +92,7 @@ func parseNode(db *gorm.DB, source interface{}) (tx *gorm.DB, item nodeItem, err return } -// Create a new node by parent with Gorm original Create() +// Create a new node within its parent by Gorm original Create() method // ```nestedset.Create(db, &Category{...}, nil)``` will create a new category in root level // ```nestedset.Create(db, &Category{...}, &parent)``` will create a new category under parent node as its last child func Create(db *gorm.DB, source, parent interface{}) error { @@ -108,17 +102,16 @@ func Create(db *gorm.DB, source, parent interface{}) error { } // for totally blank table / scope default init root would be [1 - 2] - setDepth, setToLft, setToRgt := 0, 1, 2 - tableName, dbNames := target.TableName, target.DbNames + var setToDepth, setToLft, setToRgt = 0, 1, 2 + dbNames := target.DbNames return tx.Transaction(func(tx *gorm.DB) (err error) { - // put node into root level when parent is nil + // create node in root level when parent is nil if parent == nil { lastNode := make(map[string]interface{}) - orderSQL := formatSQL(":rgt desc", target) - rst := tx.Model(source).Select(dbNames["rgt"]).Order(orderSQL).First(&lastNode) + rst := tx.Select(dbNames["rgt"]).Order(formatSQL(":rgt desc", target)).Take(&lastNode) if rst.Error == nil { - setToLft = lastNode[dbNames["rgt"]].(int) + 1 + setToLft = int(lastNode[dbNames["rgt"]].(int64) + 1) setToRgt = setToLft + 1 } } else { @@ -129,22 +122,18 @@ func Create(db *gorm.DB, source, parent interface{}) error { setToLft = targetParent.Rgt setToRgt = targetParent.Rgt + 1 - setDepth = targetParent.Depth + 1 + setToDepth = targetParent.Depth + 1 // UPDATE tree SET rgt = rgt + 2 WHERE rgt >= new_lft; - err = tx.Table(tableName). - Where(formatSQL(":rgt >= ?", target), setToLft). - UpdateColumn(dbNames["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))). - Error + err = tx.Where(formatSQL(":rgt >= ?", target), setToLft). + UpdateColumn(dbNames["rgt"], gorm.Expr(formatSQL(":rgt + 2", target))).Error if err != nil { return err } // UPDATE tree SET lft = lft + 2 WHERE lft > new_lft; - err = tx.Table(tableName). - Where(formatSQL(":lft > ?", target), setToLft). - UpdateColumn(dbNames["lft"], gorm.Expr(formatSQL(":lft + 2", target))). - Error + err = tx.Where(formatSQL(":lft > ?", target), setToLft). + UpdateColumn(dbNames["lft"], gorm.Expr(formatSQL(":lft + 2", target))).Error if err != nil { return err } @@ -158,7 +147,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { } } - // Set Lft, Rgt, Depth dynamically by refect + // Set Lft, Rgt, Depth dynamically v := reflect.Indirect(reflect.ValueOf(source)) t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -174,7 +163,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { break case "depth": f := v.FieldByName(f.Name) - f.SetInt(int64(setDepth)) + f.SetInt(int64(setToDepth)) break } } @@ -265,7 +254,7 @@ func MoveTo(db *gorm.DB, node, to interface{}, direction MoveDirection) error { return moveToRightOfPosition(tx, targetNode, right, depthChange, newParentID) } -func moveToRightOfPosition(tx *gorm.DB, targetNode nodeItem, position, depthChange int, newParentID sql.NullInt64) error { +func moveToRightOfPosition(tx *gorm.DB, targetNode nestedItem, position, depthChange int, newParentID sql.NullInt64) error { return tx.Transaction(func(tx *gorm.DB) (err error) { oldParentID := targetNode.ParentID targetRight := targetNode.Rgt @@ -308,7 +297,7 @@ func moveToRightOfPosition(tx *gorm.DB, targetNode nodeItem, position, depthChan }) } -func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentID sql.NullInt64) (err error) { +func syncChildrenCount(tx *gorm.DB, targetNode nestedItem, oldParentID, newParentID sql.NullInt64) (err error) { var oldParentCount, newParentCount int64 if oldParentID.Valid { @@ -336,7 +325,7 @@ func syncChildrenCount(tx *gorm.DB, targetNode nodeItem, oldParentID, newParentI return nil } -func moveTarget(tx *gorm.DB, targetNode nodeItem, targetID int64, targetIds []int64, step, depthChange int, newParentID sql.NullInt64) (err error) { +func moveTarget(tx *gorm.DB, targetNode nestedItem, targetID int64, targetIds []int64, step, depthChange int, newParentID sql.NullInt64) (err error) { dbNames := targetNode.DbNames if len(targetIds) > 0 { @@ -354,7 +343,7 @@ func moveTarget(tx *gorm.DB, targetNode nodeItem, targetID int64, targetIds []in return tx.Where(formatSQL(":id = ?", targetNode), targetID).Update(dbNames["parent_id"], newParentID).Error } -func moveAffected(tx *gorm.DB, targetNode nodeItem, gte, lte, step int) (err error) { +func moveAffected(tx *gorm.DB, targetNode nestedItem, gte, lte, step int) (err error) { dbNames := targetNode.DbNames return tx.Where(formatSQL("(:lft BETWEEN ? AND ?) OR (:rgt BETWEEN ? AND ?)", targetNode), gte, lte, gte, lte). @@ -364,7 +353,7 @@ func moveAffected(tx *gorm.DB, targetNode nodeItem, gte, lte, step int) (err err }).Error } -func formatSQL(placeHolderSQL string, node nodeItem) (out string) { +func formatSQL(placeHolderSQL string, node nestedItem) (out string) { out = placeHolderSQL out = strings.ReplaceAll(out, ":table_name", node.TableName) From 9e32fb74d1dec95a4064da9961a27129292dcd4f Mon Sep 17 00:00:00 2001 From: "caleb.xiang" Date: Sun, 27 Dec 2020 14:27:08 +0800 Subject: [PATCH 11/11] format a littile bit --- nested_set.go | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/nested_set.go b/nested_set.go index 3b38885..d4563c5 100644 --- a/nested_set.go +++ b/nested_set.go @@ -102,14 +102,14 @@ func Create(db *gorm.DB, source, parent interface{}) error { } // for totally blank table / scope default init root would be [1 - 2] - var setToDepth, setToLft, setToRgt = 0, 1, 2 + setToDepth, setToLft, setToRgt := 0, 1, 2 dbNames := target.DbNames return tx.Transaction(func(tx *gorm.DB) (err error) { // create node in root level when parent is nil if parent == nil { lastNode := make(map[string]interface{}) - rst := tx.Select(dbNames["rgt"]).Order(formatSQL(":rgt desc", target)).Take(&lastNode) + rst := tx.Select(dbNames["rgt"]).Order(formatSQL(":rgt DESC", target)).Take(&lastNode) if rst.Error == nil { setToLft = int(lastNode[dbNames["rgt"]].(int64) + 1) setToRgt = setToLft + 1 @@ -140,8 +140,7 @@ func Create(db *gorm.DB, source, parent interface{}) error { // UPDATE tree SET children_count = children_count + 1 WHERE id = parent.id; err = tx.Model(parent).Update( - dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target)), - ).Error + dbNames["children_count"], gorm.Expr(formatSQL(":children_count + 1", target))).Error if err != nil { return err } @@ -196,8 +195,7 @@ func Delete(db *gorm.DB, source interface{}) error { } return tx.Transaction(func(tx *gorm.DB) (err error) { - err = tx.Model(source). - Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). + err = tx.Where(formatSQL(":lft >= ? AND :rgt <= ?", target), target.Lft, target.Rgt). Delete(source).Error if err != nil { return err @@ -207,8 +205,7 @@ func Delete(db *gorm.DB, source interface{}) error { // UPDATE tree SET lft = lft - width WHERE lft > target_rgt; width := target.Rgt - target.Lft + 1 for _, d := range []string{"rgt", "lft"} { - err = tx.Model(source). - Where(formatSQL(":"+d+" > ?", target), target.Rgt). + err = tx.Where(formatSQL(":"+d+" > ?", target), target.Rgt). Update(dbNames[d], gorm.Expr(formatSQL(":"+d+" - ?", target), width)). Error if err != nil { @@ -233,8 +230,6 @@ func MoveTo(db *gorm.DB, node, to interface{}, direction MoveDirection) error { return err } - tx = tx.Table(targetNode.TableName) - var right, depthChange int var newParentID sql.NullInt64 if direction == MoveDirectionLeft || direction == MoveDirectionRight {