From 68d39e75f8d4075353f5581c7fffcceb6d77649c Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Thu, 16 Jul 2026 11:38:50 +0800 Subject: [PATCH] feat(product): migrate category images to image_ids array --- internal/repository/product_repository.go | 97 +++++++++++++--------- internal/server/category_image_ids_test.go | 31 +++++++ internal/server/product_server.go | 65 ++++++++------- scripts/sql/migrate-category-image-ids.sql | 35 ++++++++ scripts/sql/recreate-product-tables.sql | 4 +- 5 files changed, 161 insertions(+), 71 deletions(-) create mode 100644 internal/server/category_image_ids_test.go create mode 100644 scripts/sql/migrate-category-image-ids.sql diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index bef4b2a..71eeec9 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -103,14 +103,14 @@ type CategoryProductRecord struct { // CategoryRecord is the persistence model for product.product_category. type CategoryRecord struct { - ID string - NodeType int32 - Name string - ParentID string - Level int32 - ImageJSON string - SortNum int32 - Status int32 + ID string + NodeType int32 + Name string + ParentID string + Level int32 + ImageIDs []string + SortNum int32 + Status int32 } // ProductRepository provides CRUD access to product tables only [ARC-PROD-001]. @@ -132,6 +132,36 @@ ALTER TABLE product.products ALTER TABLE product.product_category_bindings ALTER COLUMN id DROP DEFAULT; +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'product' + AND table_name = 'product_category' + AND column_name = 'image_json' + ) THEN + EXECUTE $migration$ + UPDATE product.product_category + SET image_ids = CASE + WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( + (SELECT array_agg(image_id) + FROM jsonb_array_elements_text(image_json) AS image_id), + '{}'::VARCHAR[] + ) + ELSE '{}'::VARCHAR[] + END + WHERE image_json IS NOT NULL + $migration$; + END IF; +END $$; + +ALTER TABLE product.product_category + DROP COLUMN IF EXISTS image_json; + CREATE TABLE IF NOT EXISTS product.product_items ( id BIGINT PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE, @@ -563,7 +593,7 @@ SELECT id, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status FROM product.product_category @@ -599,7 +629,7 @@ SELECT id, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status FROM product.product_category @@ -927,11 +957,6 @@ func insertCategoryNode(ctx context.Context, tx *sql.Tx, category CategoryRecord parentID = sql.NullInt64{Int64: parsedParentID, Valid: true} } - imageJSON, err := normalizeCategoryImageJSON(category.ImageJSON) - if err != nil { - return nil, err - } - row := tx.QueryRowContext(ctx, ` INSERT INTO product.product_category ( id, @@ -939,20 +964,20 @@ INSERT INTO product.product_category ( name, parent_id, level, - image_json, + image_ids, sort_num, status ) -VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, node_type, name, parent_id, level, - image_json, + COALESCE(to_json(image_ids)::text, '[]'), sort_num, status -`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), imageJSON, category.SortNum, int16(category.Status)) +`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status)) createdCategory, err := scanCategory(row) if err != nil { @@ -1251,16 +1276,16 @@ func scanInventory(scanner rowScanner) (*InventoryRecord, error) { func scanCategory(scanner rowScanner) (*CategoryRecord, error) { var ( - rec CategoryRecord - id int64 - parentID sql.NullInt64 - imageJSON []byte - nodeType int16 - level int16 - status int16 + rec CategoryRecord + id int64 + parentID sql.NullInt64 + imageIDsJSON []byte + nodeType int16 + level int16 + status int16 ) if err := scanner.Scan( - &id, &nodeType, &rec.Name, &parentID, &level, &imageJSON, &rec.SortNum, &status, + &id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, ); err != nil { return nil, fmt.Errorf("scan category: %w", err) } @@ -1271,10 +1296,11 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) { rec.ParentID = formatID(parentID.Int64) } rec.Level = int32(level) - rec.ImageJSON = string(imageJSON) - if rec.ImageJSON == "" { - rec.ImageJSON = "[]" + imageIDs, err := parseStringArrayJSON(string(imageIDsJSON)) + if err != nil { + return nil, fmt.Errorf("unmarshal category image_ids: %w", err) } + rec.ImageIDs = imageIDs rec.Status = int32(status) return &rec, nil } @@ -1289,17 +1315,6 @@ func normalizeAttributesJSON(raw string) ([]byte, error) { return []byte(raw), nil } -func normalizeCategoryImageJSON(raw string) ([]byte, error) { - raw = strings.TrimSpace(raw) - if raw == "" { - return []byte("[]"), nil - } - if !json.Valid([]byte(raw)) { - return nil, fmt.Errorf("invalid image_json") - } - return []byte(raw), nil -} - func productCrossBorderJSON(product ProductRecord) ([]byte, error) { if strings.TrimSpace(product.CrossBorderJSON) != "" { attrs := []byte(product.CrossBorderJSON) diff --git a/internal/server/category_image_ids_test.go b/internal/server/category_image_ids_test.go new file mode 100644 index 0000000..e148ee9 --- /dev/null +++ b/internal/server/category_image_ids_test.go @@ -0,0 +1,31 @@ +package server + +import ( + "testing" + + "google.golang.org/protobuf/encoding/protojson" + + "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" +) + +func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) { + imageIDs, err := normalizeNodeImageIDs(`[" image-1 ", "image-1", "image-2"]`) + if err != nil { + t.Fatalf("normalizeNodeImageIDs: %v", err) + } + if len(imageIDs) != 2 || imageIDs[0] != "image-1" || imageIDs[1] != "image-2" { + t.Fatalf("image ids = %#v", imageIDs) + } + + node := toProtoCategoryNode(&repository.CategoryRecord{ImageIDs: imageIDs}) + if got := node.GetImageJson(); got != `["image-1","image-2"]` { + t.Fatalf("image_json = %q", got) + } + if _, err := protojson.Marshal(node); err != nil { + t.Fatalf("marshal category node: %v", err) + } + + if _, err := normalizeNodeImageIDs(`{"image_id":"image-1"}`); err == nil { + t.Fatal("expected non-array image_json to be rejected") + } +} diff --git a/internal/server/product_server.go b/internal/server/product_server.go index f218816..6d31926 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -350,7 +350,7 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re if err != nil { return repository.CategoryRecord{}, nil, err } - imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } @@ -360,12 +360,12 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } parent := repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: name, - Level: 1, - ImageJSON: imageJSON, - SortNum: req.GetSortNum(), - Status: statusValue, + NodeType: categoryNodeType, + Name: name, + Level: 1, + ImageIDs: imageIDs, + SortNum: req.GetSortNum(), + Status: statusValue, } children := make([]repository.CategoryRecord, 0, len(req.GetChildren())) @@ -383,7 +383,7 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } childNames[childName] = struct{}{} - childImageJSON, err := normalizeNodeImageJSON(child.GetImageJson()) + childImageIDs, err := normalizeNodeImageIDs(child.GetImageJson()) if err != nil { return repository.CategoryRecord{}, nil, err } @@ -393,12 +393,12 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re } children = append(children, repository.CategoryRecord{ - NodeType: categoryNodeType, - Name: childName, - Level: 2, - ImageJSON: childImageJSON, - SortNum: child.GetSortNum(), - Status: childStatus, + NodeType: categoryNodeType, + Name: childName, + Level: 2, + ImageIDs: childImageIDs, + SortNum: child.GetSortNum(), + Status: childStatus, }) } @@ -410,7 +410,7 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ if err != nil { return repository.CategoryRecord{}, err } - imageJSON, err := normalizeNodeImageJSON(req.GetImageJson()) + imageIDs, err := normalizeNodeImageIDs(req.GetImageJson()) if err != nil { return repository.CategoryRecord{}, err } @@ -420,12 +420,12 @@ func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.Categ } return repository.CategoryRecord{ - NodeType: groupNodeType, - Name: name, - Level: 1, - ImageJSON: imageJSON, - SortNum: req.GetSortNum(), - Status: statusValue, + NodeType: groupNodeType, + Name: name, + Level: 1, + ImageIDs: imageIDs, + SortNum: req.GetSortNum(), + Status: statusValue, }, nil } @@ -440,15 +440,16 @@ func normalizeNodeName(raw, field string) (string, error) { return name, nil } -func normalizeNodeImageJSON(raw string) (string, error) { +func normalizeNodeImageIDs(raw string) ([]string, error) { raw = strings.TrimSpace(raw) if raw == "" { - return "[]", nil + return []string{}, nil } - if !json.Valid([]byte(raw)) { - return "", errors.New("image_json must be valid json") + var imageIDs []string + if err := json.Unmarshal([]byte(raw), &imageIDs); err != nil { + return nil, errors.New("image_json must be a json string array") } - return raw, nil + return normalizeStringList(imageIDs), nil } func normalizeNodeStatus(statusValue *int32) (int32, error) { @@ -839,7 +840,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor Name: category.Name, ParentId: category.ParentID, Level: category.Level, - ImageJson: category.ImageJSON, + ImageJson: categoryImageIDsJSON(category.ImageIDs), SortNum: category.SortNum, Status: category.Status, Children: []*productv1.CategoryNode{}, @@ -856,8 +857,16 @@ func toProtoGroupNode(group *repository.CategoryRecord) *productv1.GroupNode { Name: group.Name, ParentId: group.ParentID, Level: group.Level, - ImageJson: group.ImageJSON, + ImageJson: categoryImageIDsJSON(group.ImageIDs), SortNum: group.SortNum, Status: group.Status, } } + +func categoryImageIDsJSON(imageIDs []string) string { + encoded, err := json.Marshal(imageIDs) + if err != nil { + return "[]" + } + return string(encoded) +} diff --git a/scripts/sql/migrate-category-image-ids.sql b/scripts/sql/migrate-category-image-ids.sql new file mode 100644 index 0000000..7285382 --- /dev/null +++ b/scripts/sql/migrate-category-image-ids.sql @@ -0,0 +1,35 @@ +-- Migrate product.product_category.image_json (JSONB) to image_ids (VARCHAR[]). +-- Safe to run multiple times. The ids-svc-product startup schema check performs +-- the same migration for service-managed deployments. + +ALTER TABLE product.product_category + ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = 'product' + AND table_name = 'product_category' + AND column_name = 'image_json' + ) THEN + EXECUTE $migration$ + UPDATE product.product_category + SET image_ids = CASE + WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE( + (SELECT array_agg(image_id) + FROM jsonb_array_elements_text(image_json) AS image_id), + '{}'::VARCHAR[] + ) + ELSE '{}'::VARCHAR[] + END + WHERE image_json IS NOT NULL + $migration$; + END IF; +END $$; + +ALTER TABLE product.product_category + DROP COLUMN IF EXISTS image_json; + +COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index f798124..61d462a 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -111,7 +111,7 @@ CREATE TABLE IF NOT EXISTS product.product_category ( name VARCHAR(100) NOT NULL, parent_id BIGINT REFERENCES product.product_category(id), level SMALLINT NOT NULL, - image_json JSONB NOT NULL DEFAULT '[]'::JSONB, + image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[], sort_num INTEGER NOT NULL DEFAULT 0, status SMALLINT NOT NULL DEFAULT 1, CONSTRAINT chk_product_category_node_type @@ -128,7 +128,7 @@ COMMENT ON COLUMN product.product_category.node_type IS '节点类型:0 分类 COMMENT ON COLUMN product.product_category.name IS '节点展示名称'; COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询'; COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3'; -COMMENT ON COLUMN product.product_category.image_json IS '图片列表,用于小程序分类入口、分组入口展示'; +COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示'; COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前'; COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示';