mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
Update database schema references from product_schema to product across documentation and codebase, ensuring consistency in environment configurations, repository access, and architectural constraints. Enhance clarity in README and development documents regarding database usage and constraints.
This commit is contained in:
parent
f50ef1a912
commit
f7bb383877
@ -6,7 +6,7 @@
|
||||
|
||||
- 本服务 Go Module 名: `llms.idsbuybuybuy.com/ecommerce/ids-svc-product`
|
||||
- 外部依赖契约: `llms.idsbuybuybuy.com/ecommerce/ids-proto`(已通过 `go.mod` 中的本地 `replace` 关联到 `../ids-proto`)
|
||||
- 数据库命名空间: PostgreSQL 的 `product_schema`
|
||||
- 数据库命名空间: PostgreSQL 的 `product`
|
||||
- Proto 契约路径: `ids-proto/proto/ids/product/v1/product.proto`(包名 `ids.product.v1`,Go 包 `productv1`)
|
||||
|
||||
# Task 1: 依赖对齐与本地拦截 (`go.mod`)
|
||||
@ -29,7 +29,7 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
|
||||
|
||||
```env
|
||||
SERVER_PORT=:50052
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product
|
||||
NATS_URL=nats://localhost:4222
|
||||
```
|
||||
|
||||
@ -45,7 +45,7 @@ NATS_URL=nats://localhost:4222
|
||||
|
||||
## 3.1 `internal/repository/product_repository.go`
|
||||
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD
|
||||
- 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属的 SKU 列表
|
||||
- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用
|
||||
- **【红线 ARC-001】**:严禁在这里编写任何跨 Schema 的 JOIN 查询
|
||||
|
||||
22
README.md
22
README.md
@ -19,7 +19,7 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格
|
||||
|---|---|
|
||||
| 语言 | Go 1.26 |
|
||||
| RPC | gRPC (`google.golang.org/grpc`) |
|
||||
| 数据库 | PostgreSQL `product_schema`(`github.com/jackc/pgx/v5`) |
|
||||
| 数据库 | PostgreSQL `product`(`github.com/jackc/pgx/v5`) |
|
||||
| 配置 | 环境变量 + 可选本地 `.env`(`github.com/joho/godotenv`) |
|
||||
| 契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(本地 `replace ../ids-proto`) |
|
||||
|
||||
@ -30,7 +30,7 @@ ids-svc-product/
|
||||
├── cmd/main.go # 服务入口
|
||||
├── internal/
|
||||
│ ├── config/config.go # 配置加载
|
||||
│ ├── repository/product_repository.go # product_schema 数据访问
|
||||
│ ├── repository/product_repository.go # product 数据访问
|
||||
│ └── server/product_server.go # gRPC 契约实现
|
||||
├── docs/
|
||||
│ ├── ARCHITECTURE.md # 架构白皮书
|
||||
@ -64,7 +64,7 @@ cp .env.example .env
|
||||
| `POSTGRES_USER` | `postgres` | 数据库用户 |
|
||||
| `POSTGRES_PASSWORD` | `postgres` | 数据库密码 |
|
||||
| `POSTGRES_DB` | `ids_ecommerce` | 数据库名 |
|
||||
| `POSTGRES_SCHEMA` | `product_schema` | 搜索路径 |
|
||||
| `POSTGRES_SCHEMA` | `product` | 搜索路径 |
|
||||
| `POSTGRES_SSLMODE` | `disable` | SSL 模式 |
|
||||
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) |
|
||||
|
||||
@ -85,25 +85,25 @@ go run ./cmd
|
||||
grpcurl -plaintext localhost:50052 list
|
||||
|
||||
# 查询单个商品
|
||||
grpcurl -plaintext -d '{"product_id":"<uuid>"}' \
|
||||
grpcurl -plaintext -d '{"product_id":"<snowflake-id>"}' \
|
||||
localhost:50052 ids.product.v1.ProductService/GetProduct
|
||||
|
||||
# 批量查询
|
||||
grpcurl -plaintext -d '{"product_ids":["<uuid-1>","<uuid-2>"]}' \
|
||||
grpcurl -plaintext -d '{"product_ids":["<snowflake-id-1>","<snowflake-id-2>"]}' \
|
||||
localhost:50052 ids.product.v1.ProductService/BatchGetProducts
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
商品域采用 SPU/SKU 分层,**仅读写** `product_schema`:
|
||||
商品域采用 SPU/SKU 分层,**仅读写** `product`:
|
||||
|
||||
| 表 | 职责 |
|
||||
|---|---|
|
||||
| `product_schema.products` | SPU 主表(名称、描述、状态、扩展属性) |
|
||||
| `product_schema.skus` | SKU 明细(规格、价格、库存) |
|
||||
| `product.products` | SPU 主表(名称、描述、状态、扩展属性) |
|
||||
| `product.skus` | SKU 明细(规格、价格、库存) |
|
||||
|
||||
- 价格字段统一为 `BIGINT` / Go `int64`,单位:**分**
|
||||
- 禁止跨 Schema JOIN(`order_schema`、`user_schema` 等)
|
||||
- 禁止跨 Schema JOIN(`trade`、`customer` 等)
|
||||
|
||||
## 架构约束
|
||||
|
||||
@ -116,7 +116,7 @@ grpcurl -plaintext -d '{"product_ids":["<uuid-1>","<uuid-2>"]}' \
|
||||
|
||||
| ID | 约束 |
|
||||
|---|---|
|
||||
| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-003 | `BatchGetProducts` 对重复 ID 去重,缺失 ID 静默跳过 |
|
||||
| ARC-PROD-004 | 价格字段统一 `int64`(分) |
|
||||
| ARC-PROD-005 | 状态枚举强对齐 `productv1.ProductStatus` |
|
||||
@ -127,7 +127,7 @@ grpcurl -plaintext -d '{"product_ids":["<uuid-1>","<uuid-2>"]}' \
|
||||
ids-svc-order (算价) ──BatchGetProducts──▶ ids-svc-product
|
||||
│
|
||||
▼
|
||||
PG product_schema
|
||||
PG product
|
||||
```
|
||||
|
||||
订单服务通过 gRPC 批量拉取 SKU 价格,**不得**跨库查询商品表。
|
||||
|
||||
@ -13,7 +13,7 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres123}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-ids_ecommerce}
|
||||
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product_schema}
|
||||
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product}
|
||||
POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable}
|
||||
NATS_URL: nats://nats:4222
|
||||
GOMODCACHE: /go/pkg/mod
|
||||
|
||||
@ -12,9 +12,9 @@
|
||||
|
||||
### 1.1 数据隔离红线 [ARC-PROD-001]
|
||||
|
||||
- 本服务**仅允许**读写 PostgreSQL 中的 `product_schema`。
|
||||
- 绝对禁止跨 Schema 去 `JOIN` `order_schema`、`user_schema` 或任何其他业务 Schema 的表。
|
||||
- 任何关于订单状态、用户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
||||
- 本服务**仅允许**读写 PostgreSQL 中的 `product`。
|
||||
- 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。
|
||||
- 任何关于订单状态、客户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
||||
|
||||
### 1.2 数据模型 (PostgreSQL)
|
||||
|
||||
@ -22,8 +22,8 @@
|
||||
|
||||
| 表 | 职责 |
|
||||
|---|---|
|
||||
| `product_schema.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 |
|
||||
| `product_schema.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 |
|
||||
| `product.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 |
|
||||
| `product.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 |
|
||||
|
||||
所有价格字段(如 `price`)统一采用 `BIGINT` / Go `int64`,单位为**分**。禁止使用 `float32`、`float64` 或数据库浮点类型表达金额。
|
||||
|
||||
@ -49,7 +49,7 @@
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ PG product_schema │
|
||||
│ PG product │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
@ -59,7 +59,7 @@
|
||||
|---|---|---|
|
||||
| 启动信宿 | `cmd/main.go` | 服务启动信宿,负责加载配置、初始化 PostgreSQL 连接池、创建 repository,并拉起 gRPC 监听端口。 |
|
||||
| 契约实现层 | `internal/server/` | 实现 `ids-proto` 生成的 `ProductServiceServer` 接口。**禁止**在此处编写任何 SQL;主要职责是解析入参、调用 repository、映射 `productv1.Product` 与 `productv1.SKU` 强类型响应。 |
|
||||
| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product_schema.products` 与 `product_schema.skus` 的 CRUD 和批量查询能力。 |
|
||||
| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product.products` 与 `product.skus` 的 CRUD 和批量查询能力。 |
|
||||
| 配置底座 | `internal/config/` | 轻量读取环境变量,优先加载本地 `.env`,生产环境无 `.env` 时静默降级到环境注入。 |
|
||||
|
||||
---
|
||||
@ -77,7 +77,7 @@
|
||||
|
||||
### 3.2 查询实现约束
|
||||
|
||||
1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product_schema.products` 与 `product_schema.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。
|
||||
1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。
|
||||
2. **[ARC-PROD-003] 批量查询必须稳定去重:** `BatchGetProducts` 应对重复 `product_id` 输入做安全处理,避免无意义 DB 放大,并保持返回结果语义清晰。
|
||||
3. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
|
||||
4. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
|
||||
@ -91,7 +91,7 @@
|
||||
| 环境变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `SERVER_PORT` | `:50052` | gRPC Server 监听地址。 |
|
||||
| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema` | PostgreSQL 连接字符串,必须包含 `product_schema` 搜索路径或由 SQL 显式限定 Schema。 |
|
||||
| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product` | PostgreSQL 连接字符串,必须包含 `product` 搜索路径或由 SQL 显式限定 Schema。 |
|
||||
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址;当前商品查询主链路不依赖 NATS。 |
|
||||
|
||||
### 4.1 `.env` 加载策略 [ARC-PROD-006]
|
||||
@ -124,7 +124,7 @@
|
||||
3. 数据库操作必须收敛在 `internal/repository` 层,**严禁**在 `internal/server` 抛出 naked SQL。
|
||||
4. 严格按照 `ids-proto` 中 `ids.product.v1` / `productv1` 的结构体定义进行序列化与反序列化。
|
||||
5. 商品状态枚举必须强对齐 `productv1.ProductStatus`,不得在 gRPC 响应中暴露内部字符串状态。
|
||||
6. 跨域数据(订单、用户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。
|
||||
6. 跨域数据(订单、客户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。
|
||||
7. `BatchGetProducts` 是订单算价链路的关键接口,应优先保证低延迟、批量查询与清晰错误语义。
|
||||
|
||||
---
|
||||
@ -133,7 +133,7 @@
|
||||
|
||||
| ID | 约束 |
|
||||
|---|---|
|
||||
| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-002 | SPU/SKU 只允许在商品域 Schema 内关联 |
|
||||
| ARC-PROD-003 | `BatchGetProducts` 必须对重复输入做稳定处理 |
|
||||
| ARC-PROD-004 | 价格字段统一 `int64`,单位为分 |
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
|---|---|
|
||||
| Go Module | `llms.idsbuybuybuy.com/ecommerce/ids-svc-product` |
|
||||
| 外部依赖契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(通过 `go.mod` 中 `replace` 关联到 `../ids-proto`) |
|
||||
| 数据库命名空间 | PostgreSQL `product_schema` |
|
||||
| 数据库命名空间 | PostgreSQL `product` |
|
||||
| Go 工具链 | **Go 1.26** |
|
||||
| Proto 契约路径 | `ids-proto/proto/ids/product/v1/product.proto` |
|
||||
| Proto 包名 | `ids.product.v1` |
|
||||
@ -59,7 +59,7 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
|
||||
|
||||
```env
|
||||
SERVER_PORT=:50052
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product
|
||||
NATS_URL=nats://localhost:4222
|
||||
```
|
||||
|
||||
@ -111,13 +111,13 @@ ids-svc-product/
|
||||
|
||||
### 3.1 `internal/repository/product_repository.go`
|
||||
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD。
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.skus` 的底座 CRUD。
|
||||
- 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属 SKU 列表。
|
||||
- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用。
|
||||
- `BatchGetProducts` 必须对重复 `product_id` 输入做稳定去重,避免 DB 查询放大。
|
||||
- 单商品不存在时应返回明确 not found 语义,便于 gRPC 层映射为 `codes.NotFound`。
|
||||
- **【红线 ARC-PROD-001】**:严禁编写任何跨 Schema 的 JOIN 查询。
|
||||
- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product_schema` 内关联或分步查询。
|
||||
- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product` 内关联或分步查询。
|
||||
|
||||
---
|
||||
|
||||
@ -164,7 +164,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository
|
||||
|---|---|
|
||||
| 1 | 价格字段一律 `int64`(单位:分),**禁止** `float64` |
|
||||
| 2 | 状态枚举强对齐 `productv1.ProductStatus` |
|
||||
| 3 | repository 仅操作 `product_schema.products` 与 `product_schema.skus` |
|
||||
| 3 | repository 仅操作 `product.products` 与 `product.skus` |
|
||||
| 4 | 禁止跨 Schema JOIN(**[ARC-PROD-001]**) |
|
||||
| 5 | `BatchGetProducts` 必须支持批量查询与重复输入去重(**[ARC-PROD-003]**) |
|
||||
| 6 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) |
|
||||
@ -190,7 +190,7 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository
|
||||
|
||||
| 开发任务 | 架构约束 |
|
||||
|---|---|
|
||||
| `repository` 仅操作 `product_schema` | [ARC-PROD-001] |
|
||||
| `repository` 仅操作 `product` | [ARC-PROD-001] |
|
||||
| SPU/SKU 只在商品域内关联 | [ARC-PROD-002] |
|
||||
| 批量商品查询去重与稳定返回 | [ARC-PROD-003] |
|
||||
| 价格字段统一 `int64` 分单位 | [ARC-PROD-004] |
|
||||
|
||||
2
go.sum
2
go.sum
@ -11,8 +11,6 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
|
||||
@ -16,7 +16,7 @@ const (
|
||||
defaultPostgresUser = "postgres"
|
||||
defaultPostgresPass = "postgres"
|
||||
defaultPostgresDB = "ids_ecommerce"
|
||||
defaultPostgresSchema = "product_schema"
|
||||
defaultPostgresSchema = "product"
|
||||
defaultNATSURL = "nats://localhost:4222"
|
||||
)
|
||||
|
||||
|
||||
@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@ -18,7 +19,7 @@ var ErrProductNotFound = errors.New("product not found")
|
||||
// ErrSKUNotFound is returned when a SKU does not exist.
|
||||
var ErrSKUNotFound = errors.New("sku not found")
|
||||
|
||||
// ProductRecord is the persistence model for product_schema.products (SPU).
|
||||
// ProductRecord is the persistence model for product.products (SPU).
|
||||
type ProductRecord struct {
|
||||
ID string
|
||||
SPUCode string
|
||||
@ -30,7 +31,7 @@ type ProductRecord struct {
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// SKURecord is the persistence model for product_schema.skus.
|
||||
// SKURecord is the persistence model for product.skus.
|
||||
type SKURecord struct {
|
||||
ID string
|
||||
ProductID string
|
||||
@ -42,7 +43,7 @@ type SKURecord struct {
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// ProductRepository provides CRUD access to product_schema tables only [ARC-PROD-001].
|
||||
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
|
||||
type ProductRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
@ -52,17 +53,12 @@ func NewProductRepository(db *sql.DB) *ProductRepository {
|
||||
return &ProductRepository{db: db}
|
||||
}
|
||||
|
||||
// EnsureSchema adds product-domain columns and the skus table when missing.
|
||||
// EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts.
|
||||
func (r *ProductRepository) EnsureSchema(ctx context.Context) error {
|
||||
const ddl = `
|
||||
ALTER TABLE product_schema.products
|
||||
ADD COLUMN IF NOT EXISTS description TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE product_schema.products
|
||||
ADD COLUMN IF NOT EXISTS status VARCHAR(32) NOT NULL DEFAULT 'draft';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product_schema.skus (
|
||||
id UUID PRIMARY KEY,
|
||||
product_id UUID NOT NULL REFERENCES product_schema.products(id) ON DELETE CASCADE,
|
||||
CREATE TABLE IF NOT EXISTS product.skus (
|
||||
id BIGINT PRIMARY KEY,
|
||||
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||
name VARCHAR(256) NOT NULL,
|
||||
price BIGINT NOT NULL CHECK (price >= 0),
|
||||
stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
|
||||
@ -70,10 +66,10 @@ CREATE TABLE IF NOT EXISTS product_schema.skus (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product_schema.skus(product_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_skus_product_id ON product.skus(product_id);
|
||||
`
|
||||
if _, err := r.db.ExecContext(ctx, ddl); err != nil {
|
||||
return fmt.Errorf("ensure product_schema tables: %w", err)
|
||||
return fmt.Errorf("ensure product tables: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -88,10 +84,15 @@ func (r *ProductRepository) CreateProduct(ctx context.Context, product ProductRe
|
||||
attrs = []byte("{}")
|
||||
}
|
||||
|
||||
id, err := parseID(product.ID, "product id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = r.db.ExecContext(ctx, `
|
||||
INSERT INTO product_schema.products (id, spu_code, title, description, status, attrs)
|
||||
INSERT INTO product.products (id, spu_no, title, sell_point, status, cross_border)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
`, product.ID, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs)
|
||||
`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert product %s: %w", product.ID, err)
|
||||
}
|
||||
@ -108,11 +109,16 @@ func (r *ProductRepository) UpdateProduct(ctx context.Context, product ProductRe
|
||||
attrs = []byte("{}")
|
||||
}
|
||||
|
||||
id, err := parseID(product.ID, "product id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res, err := r.db.ExecContext(ctx, `
|
||||
UPDATE product_schema.products
|
||||
SET spu_code = $2, title = $3, description = $4, status = $5, attrs = $6::jsonb, updated_at = NOW()
|
||||
UPDATE product.products
|
||||
SET spu_no = $2, title = $3, sell_point = $4, status = $5, cross_border = $6::jsonb, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, product.ID, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs)
|
||||
`, id, product.SPUCode, product.Name, product.Description, statusToDB(product.Status), attrs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update product %s: %w", product.ID, err)
|
||||
}
|
||||
@ -129,7 +135,11 @@ WHERE id = $1
|
||||
|
||||
// DeleteProduct removes an SPU and its SKUs via ON DELETE CASCADE.
|
||||
func (r *ProductRepository) DeleteProduct(ctx context.Context, productID string) error {
|
||||
res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.products WHERE id = $1`, productID)
|
||||
id, err := parseID(productID, "product id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := r.db.ExecContext(ctx, `DELETE FROM product.products WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete product %s: %w", productID, err)
|
||||
}
|
||||
@ -151,10 +161,19 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
|
||||
return err
|
||||
}
|
||||
|
||||
id, err := parseID(sku.ID, "sku id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
productID, err := parseID(sku.ProductID, "product id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = r.db.ExecContext(ctx, `
|
||||
INSERT INTO product_schema.skus (id, product_id, name, price, stock, attributes)
|
||||
INSERT INTO product.skus (id, product_id, name, price, stock, attributes)
|
||||
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
`, sku.ID, sku.ProductID, sku.Name, sku.Price, sku.Stock, attrs)
|
||||
`, id, productID, sku.Name, sku.Price, sku.Stock, attrs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert sku %s: %w", sku.ID, err)
|
||||
}
|
||||
@ -168,11 +187,15 @@ func (r *ProductRepository) UpdateSKU(ctx context.Context, sku SKURecord) error
|
||||
return err
|
||||
}
|
||||
|
||||
id, err := parseID(sku.ID, "sku id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := r.db.ExecContext(ctx, `
|
||||
UPDATE product_schema.skus
|
||||
UPDATE product.skus
|
||||
SET name = $2, price = $3, stock = $4, attributes = $5::jsonb, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, sku.ID, sku.Name, sku.Price, sku.Stock, attrs)
|
||||
`, id, sku.Name, sku.Price, sku.Stock, attrs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update sku %s: %w", sku.ID, err)
|
||||
}
|
||||
@ -189,7 +212,11 @@ WHERE id = $1
|
||||
|
||||
// DeleteSKU removes a SKU row.
|
||||
func (r *ProductRepository) DeleteSKU(ctx context.Context, skuID string) error {
|
||||
res, err := r.db.ExecContext(ctx, `DELETE FROM product_schema.skus WHERE id = $1`, skuID)
|
||||
id, err := parseID(skuID, "sku id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := r.db.ExecContext(ctx, `DELETE FROM product.skus WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete sku %s: %w", skuID, err)
|
||||
}
|
||||
@ -262,13 +289,17 @@ func (r *ProductRepository) loadProductsByIDs(ctx context.Context, productIDs []
|
||||
placeholders := make([]string, len(productIDs))
|
||||
args := make([]any, len(productIDs))
|
||||
for i, id := range productIDs {
|
||||
parsed, err := parseID(id, "product id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
args[i] = id
|
||||
args[i] = parsed
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT id, spu_code, title, description, status, attrs, created_at, updated_at
|
||||
FROM product_schema.products
|
||||
SELECT id, spu_no, title, COALESCE(sell_point, ''), status, cross_border, created_at, updated_at
|
||||
FROM product.products
|
||||
WHERE id IN (%s)
|
||||
ORDER BY created_at ASC
|
||||
`, strings.Join(placeholders, ", "))
|
||||
@ -303,13 +334,17 @@ func (r *ProductRepository) loadSKUsByProductIDs(ctx context.Context, productIDs
|
||||
placeholders := make([]string, len(productIDs))
|
||||
args := make([]any, len(productIDs))
|
||||
for i, id := range productIDs {
|
||||
parsed, err := parseID(id, "product id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
||||
args[i] = id
|
||||
args[i] = parsed
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT id, product_id, name, price, stock, attributes, created_at, updated_at
|
||||
FROM product_schema.skus
|
||||
FROM product.skus
|
||||
WHERE product_id IN (%s)
|
||||
ORDER BY created_at ASC
|
||||
`, strings.Join(placeholders, ", "))
|
||||
@ -341,15 +376,17 @@ type rowScanner interface {
|
||||
func scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
||||
var (
|
||||
rec ProductRecord
|
||||
status string
|
||||
id int64
|
||||
status int16
|
||||
attrsJSON []byte
|
||||
)
|
||||
if err := scanner.Scan(
|
||||
&rec.ID, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
||||
&id, &rec.SPUCode, &rec.Name, &rec.Description, &status, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan product: %w", err)
|
||||
}
|
||||
|
||||
rec.ID = formatID(id)
|
||||
rec.Status = statusFromDB(status)
|
||||
if len(attrsJSON) > 0 {
|
||||
if err := json.Unmarshal(attrsJSON, &rec.Attrs); err != nil {
|
||||
@ -362,14 +399,18 @@ func scanProduct(scanner rowScanner) (*ProductRecord, error) {
|
||||
func scanSKU(scanner rowScanner) (*SKURecord, error) {
|
||||
var (
|
||||
rec SKURecord
|
||||
id int64
|
||||
productID int64
|
||||
attrsJSON []byte
|
||||
)
|
||||
if err := scanner.Scan(
|
||||
&rec.ID, &rec.ProductID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
||||
&id, &productID, &rec.Name, &rec.Price, &rec.Stock, &attrsJSON, &rec.CreatedAt, &rec.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan sku: %w", err)
|
||||
}
|
||||
|
||||
rec.ID = formatID(id)
|
||||
rec.ProductID = formatID(productID)
|
||||
rec.AttributesJSONB = string(attrsJSON)
|
||||
if rec.AttributesJSONB == "" {
|
||||
rec.AttributesJSONB = "{}"
|
||||
@ -403,28 +444,40 @@ func normalizeAttributesJSON(raw string) ([]byte, error) {
|
||||
return []byte(raw), nil
|
||||
}
|
||||
|
||||
func statusToDB(status productv1.ProductStatus) string {
|
||||
func statusToDB(status productv1.ProductStatus) int16 {
|
||||
switch status {
|
||||
case productv1.ProductStatus_PRODUCT_STATUS_DRAFT:
|
||||
return "draft"
|
||||
return 0
|
||||
case productv1.ProductStatus_PRODUCT_STATUS_ON_SALE:
|
||||
return "on_sale"
|
||||
return 1
|
||||
case productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE:
|
||||
return "off_sale"
|
||||
return 3
|
||||
default:
|
||||
return "unspecified"
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func statusFromDB(status string) productv1.ProductStatus {
|
||||
func statusFromDB(status int16) productv1.ProductStatus {
|
||||
switch status {
|
||||
case "draft":
|
||||
case 0:
|
||||
return productv1.ProductStatus_PRODUCT_STATUS_DRAFT
|
||||
case "on_sale":
|
||||
case 1:
|
||||
return productv1.ProductStatus_PRODUCT_STATUS_ON_SALE
|
||||
case "off_sale":
|
||||
case 3:
|
||||
return productv1.ProductStatus_PRODUCT_STATUS_OFF_SALE
|
||||
default:
|
||||
return productv1.ProductStatus_PRODUCT_STATUS_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func parseID(raw, field string) (int64, error) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, fmt.Errorf("%s must be a positive snowflake id", field)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func formatID(id int64) string {
|
||||
return strconv.FormatInt(id, 10)
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user