[hw-8] attempt to fix tests

This commit is contained in:
3ybacTuK
2025-07-28 22:11:42 +03:00
parent 6e0d90a6d5
commit 61757d1a52
8 changed files with 676 additions and 66 deletions

View File

@@ -1,5 +1,5 @@
-- name: InsertComment :one
INSERT INTO comments (user_id, sku, text) VALUES ($1, $2, $3)
INSERT INTO comments (id, user_id, sku, text) VALUES ($1, $2, $3, $4)
RETURNING id, user_id, sku, text, created_at;
-- name: GetCommentByID :one

View File

@@ -27,18 +27,24 @@ func (q *Queries) GetCommentByID(ctx context.Context, id int64) (*Comment, error
}
const insertComment = `-- name: InsertComment :one
INSERT INTO comments (user_id, sku, text) VALUES ($1, $2, $3)
INSERT INTO comments (id, user_id, sku, text) VALUES ($1, $2, $3, $4)
RETURNING id, user_id, sku, text, created_at
`
type InsertCommentParams struct {
ID int64
UserID int64
Sku int64
Text string
}
func (q *Queries) InsertComment(ctx context.Context, arg *InsertCommentParams) (*Comment, error) {
row := q.db.QueryRow(ctx, insertComment, arg.UserID, arg.Sku, arg.Text)
row := q.db.QueryRow(ctx, insertComment,
arg.ID,
arg.UserID,
arg.Sku,
arg.Text,
)
var i Comment
err := row.Scan(
&i.ID,

View File

@@ -3,6 +3,7 @@ package sqlc
import (
"context"
"errors"
"sync"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
@@ -15,21 +16,25 @@ import (
type commentsRepo struct {
shard1 *pgxpool.Pool
shard2 *pgxpool.Pool
curID int64
idMx sync.Mutex
}
func NewCommentsRepository(shard1, shard2 *pgxpool.Pool) *commentsRepo {
return &commentsRepo{
shard1: shard1,
shard2: shard2,
curID: 1,
}
}
func (r *commentsRepo) pickShard(sku int64) *pgxpool.Pool {
func (r *commentsRepo) pickShard(sku int64) (*pgxpool.Pool, int64) {
if sku%2 == 0 {
return r.shard1
return r.shard1, 0
}
return r.shard2
return r.shard2, 1
}
func mapComment(c *Comment) *entity.Comment {
@@ -67,13 +72,19 @@ func (r *commentsRepo) GetCommentByID(ctx context.Context, id int64) (*entity.Co
}
func (r *commentsRepo) InsertComment(ctx context.Context, comment *entity.Comment) (*entity.Comment, error) {
shard := r.pickShard(comment.SKU)
shard, shardID := r.pickShard(comment.SKU)
q := New(shard)
r.idMx.Lock()
id := r.curID*1000 + shardID
r.curID++
r.idMx.Unlock()
req := &InsertCommentParams{
UserID: comment.UserID,
Sku: comment.SKU,
Text: comment.Text,
ID: id,
}
c, err := q.InsertComment(ctx, req)
@@ -85,7 +96,7 @@ func (r *commentsRepo) InsertComment(ctx context.Context, comment *entity.Commen
}
func (r *commentsRepo) ListCommentsBySku(ctx context.Context, sku int64) ([]*entity.Comment, error) {
shard := r.pickShard(sku)
shard, _ := r.pickShard(sku)
q := New(shard)
list, err := q.ListCommentsBySku(ctx, sku)