Skip to content

Commit f9cc5a0

Browse files
committed
upsert file
1 parent d59ad5c commit f9cc5a0

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

model/file.go

+18-3
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ type File struct {
2121
FavoriteCount int `json:"favorite_count" db:"-"`
2222
IsFavoriteByMe bool `json:"is_favorite_by_me" db:"-"`
2323
CreatedAt time.Time `json:"created_at" db:"created_at"`
24+
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
2425
}
2526

2627
func GetFiles(ctx context.Context, userID string) ([]*File, error) {
@@ -164,11 +165,25 @@ func GetFileIDsInMessage(ctx context.Context, messageID string) ([]string, error
164165
}
165166

166167
func InsertFiles(ctx context.Context, files []*File) error {
168+
uniqueFileMap := make(map[string]*File, len(files))
169+
for _, f := range files {
170+
uniqueFileMap[f.ID] = f
171+
}
172+
uniqueFiles := make([]*File, 0, len(uniqueFileMap))
173+
for _, f := range uniqueFileMap {
174+
uniqueFiles = append(uniqueFiles, f)
175+
}
176+
167177
_, err := db.NamedExecContext(
168178
ctx,
169-
`INSERT IGNORE INTO files (id, title, composer_id, composer_name, message_id, created_at)
170-
VALUES (:id, :title, :composer_id, :composer_name, :message_id, :created_at)`,
171-
files,
179+
`INSERT INTO files (id, title, composer_id, composer_name, message_id, created_at)
180+
VALUES (:id, :title, :composer_id, :composer_name, :message_id, :created_at)
181+
ON DUPLICATE KEY UPDATE
182+
title = VALUES(title),
183+
composer_id = VALUES(composer_id),
184+
composer_name = VALUES(composer_name),
185+
message_id = VALUES(message_id)`,
186+
uniqueFiles,
172187
)
173188
if err != nil {
174189
return err

mysql/init/create_db.sql

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ CREATE TABLE IF NOT EXISTS `favorites` (
1616
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
1717

1818
CREATE TABLE IF NOT EXISTS `files` (
19-
`id` char(36) NOT NULL,
19+
`id` char(36) PRIMARY KEY,
2020
`title` text NOT NULL,
2121
`composer_id` char(36) NOT NULL,
2222
`composer_name` varchar(32) NOT NULL,
2323
`message_id` char(36) NOT NULL,
2424
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
25+
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
2526
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

0 commit comments

Comments
 (0)