fix: replace MySQL NOW() with SQLite-compatible datetime('now')
- Set function: use GORM clause.OnConflict for cross-database upsert
- BatchSet function: replace NOW() with datetime('now')
- Add tests for Set and BatchSet (both now 100%/85.7% covered)
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"github.com/user-management-system/internal/domain"
|
||||
)
|
||||
@@ -85,11 +86,15 @@ func NewUserCustomFieldValueRepository(db *gorm.DB) *UserCustomFieldValueReposit
|
||||
|
||||
// Set 为用户设置自定义字段值(upsert)
|
||||
func (r *UserCustomFieldValueRepository) Set(ctx context.Context, userID int64, fieldID int64, fieldKey, value string) error {
|
||||
return r.db.WithContext(ctx).Exec(`
|
||||
INSERT INTO user_custom_field_values (user_id, field_id, field_key, value, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, NOW(), NOW())
|
||||
ON CONFLICT(user_id, field_id) DO UPDATE SET value = ?, updated_at = NOW()
|
||||
`, userID, fieldID, fieldKey, value, value).Error
|
||||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "user_id"}, {Name: "field_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"value", "updated_at"}),
|
||||
}).Create(&domain.UserCustomFieldValue{
|
||||
UserID: userID,
|
||||
FieldID: fieldID,
|
||||
FieldKey: fieldKey,
|
||||
Value: value,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// GetByUserID 获取用户的所有自定义字段值
|
||||
@@ -130,6 +135,7 @@ func (r *UserCustomFieldValueRepository) BatchSet(ctx context.Context, userID in
|
||||
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for fieldKey, value := range values {
|
||||
// 使用 SQLite 兼容的 datetime('now') 而非 MySQL 的 NOW()
|
||||
if err := tx.Exec(`
|
||||
INSERT INTO user_custom_field_values (user_id, field_id, field_key, value, created_at, updated_at)
|
||||
VALUES (
|
||||
@@ -137,10 +143,10 @@ func (r *UserCustomFieldValueRepository) BatchSet(ctx context.Context, userID in
|
||||
(SELECT id FROM custom_fields WHERE field_key = ? LIMIT 1),
|
||||
?,
|
||||
?,
|
||||
NOW(),
|
||||
NOW()
|
||||
datetime('now'),
|
||||
datetime('now')
|
||||
)
|
||||
ON CONFLICT(user_id, field_id) DO UPDATE SET value = ?, updated_at = NOW()
|
||||
ON CONFLICT(user_id, field_id) DO UPDATE SET value = ?, updated_at = datetime('now')
|
||||
`, userID, fieldKey, fieldKey, value, value).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user