i face this error when trying to generate my comment attach to the topics:
fail to create comments, err=error while scanning created comment IDs, err=ERROR: insert or update on table “comments” violates foreign key constraint “comments_topic_id_fkey” (SQLSTATE 23503
this is my comment_dao.go
func (d CommentDAO) Create(comments ...dto.Comment) ([]dto.Comment, error) {
if len(comments) == 0 {
return nil, nil
}
query := d.genInsertSQL(len(comments))
var args []any
for _, c := range comments {
args = append(args, c.By, c.TopicID, c.Content, time.Now())
}
res, err := d.db.Query(query, args...)
if err != nil {
return nil, fmt.Errorf("fail to create comments: %w", err)
}
ids := make([]int, 0, len(comments))
for res.Next() {
var id int
if err = res.Scan(&id); err != nil {
return nil, fmt.Errorf("fail to scan for created comment ID: %w", err)
}
ids = append(ids, id)
}
if err = res.Err(); err != nil {
return nil, fmt.Errorf("error while scanning created comment IDs, err=%w", err)
}
for i, c := range comments {
c.ID = ids[i]
}
return comments, nil
}
func (d CommentDAO) genInsertSQL(numComments int) string {
var sb strings.Builder
sb.WriteString(`insert into msg_board.comments(by, topic_id, content, created_at) values `)
genSQLParams(numComments, &sb, 4)
sb.WriteString(` returning id;`)
return sb.String()
}
my seed.go to run generate
const numUsers = 10
func genTopics(db *sql.DB, users []dto.User) ([]dto.Topic, error) {
const minTopic = 2
const maxTopic = 5
topics := make([]dto.Topic, 0, len(users)*minTopic)
now := time.Now()
for _, u := range users {
n := randInt(minTopic, maxTopic)
for i := 0; i < n; i++ {
topics = append(topics, dto.Topic{
By: u.ID,
Title: fmt.Sprintf("topic %d by user %d at %d", i+1, u.ID, now.Unix()),
Body: "random string at " + now.String(),
})
}
}
d := dao.NewTopicDAO(db)
createdTopics, err := d.Create(topics...)
if err != nil {
return nil, err
}
if len(createdTopics) == 0 {
return nil, fmt.Errorf("no topics created")
}
log.Printf("Created topics: %v", createdTopics)
return createdTopics, nil
}
func genComments(db *sql.DB, users []dto.User, topics []dto.Topic) {
const minComments = 1
const maxComments = 5
comments := make([]dto.Comment, 0, len(topics)*maxComments)
now := time.Now()
for _, topic := range topics {
log.Printf("Creating comments for topic ID: %d", topic.ID)
n := randInt(minComments, maxComments)
for i := 0; i < n; i++ {
user := users[rand.Intn(len(users))]
comment := dto.Comment{
By: user.ID,
TopicID: topic.ID,
Content: fmt.Sprintf("Comment %d by user %d on topic %d", i+1, user.ID, topic.ID),
CreatedAt: now,
}
comments = append(comments, comment)
}
}
d := dao.NewCommentDAO(db)
createdComments, err := d.Create(comments...)
if err != nil {
log.Printf("fail to create comments, err=%v", err)
} else {
log.Printf("created comments: %v", createdComments)
}
}
func randInt(min, max int) int {
return rand.Int()%(max-min) + min
}
this is my dto.go
type Topic struct {
ID int json:"id,omitempty"
CreatedAt time.Time json:"created_at"
By int json:"by,omitempty"
Title string json:"title,omitempty"
Body string json:"body,omitempty"
CommentCount int json:"comment_count,omitempty"
Upvotes int json:"upvotes,omitempty"
}
type Comment struct {
ID int json:"id,omitempty"
CreatedAt time.Time json:"created_at"
By int json:"by,omitempty"
Content string json:"content,omitempty"
TopicID int json:"topic_id,omitempty"
} ```
I have try to catching error logs, fix the dto but it not work
New contributor
NervX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.