暂存 PostgreSQL 数据库兼容实现
This commit is contained in:
1 parent
959d14eb2f
commit
eaf474c8e7
14 files changed
+326
-57
No files matched your search
@@ -18,7 +18,7 @@ func (r *SQLAuditRepository) ListAuditLogs(ctx context.Context, limit int) ([]Au
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT action, resource_type, resource_id, status, message, created_at FROM audit_logs ORDER BY created_at DESC, id DESC LIMIT `+fmt.Sprintf("%d", limit))
|
||||
rows, err := r.db.QueryContext(ctx, r.query(`SELECT action, resource_type, resource_id, status, message, created_at FROM audit_logs ORDER BY created_at DESC, id DESC LIMIT `+fmt.Sprintf("%d", limit)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询审计日志失败:%w", err)
|
||||
}
|
||||
|
||||
@@ -23,11 +23,16 @@ type AuditRepository interface {
|
||||
}
|
||||
|
||||
type SQLAuditRepository struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
driver string
|
||||
}
|
||||
|
||||
func NewSQLAuditRepository(db *sql.DB) *SQLAuditRepository {
|
||||
return &SQLAuditRepository{db: db}
|
||||
func NewSQLAuditRepository(db *sql.DB, driver ...string) *SQLAuditRepository {
|
||||
return &SQLAuditRepository{db: db, driver: repositoryDriver(driver)}
|
||||
}
|
||||
|
||||
func (r *SQLAuditRepository) query(value string) string {
|
||||
return Rebind(r.driver, value)
|
||||
}
|
||||
|
||||
func (r *SQLAuditRepository) CreateAuditLog(ctx context.Context, item AuditLog) error {
|
||||
@@ -44,9 +49,9 @@ func (r *SQLAuditRepository) CreateAuditLog(ctx context.Context, item AuditLog)
|
||||
if item.CreatedAt.IsZero() {
|
||||
item.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO audit_logs
|
||||
_, err := r.db.ExecContext(ctx, r.query(`INSERT INTO audit_logs
|
||||
(action, resource_type, resource_id, status, message, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, item.Action, item.ResourceType, item.ResourceID, item.Status, item.Message, item.CreatedAt.UTC())
|
||||
VALUES (?, ?, ?, ?, ?, ?)`), item.Action, item.ResourceType, item.ResourceID, item.Status, item.Message, item.CreatedAt.UTC())
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存审计日志失败:%w", err)
|
||||
}
|
||||
@@ -60,7 +65,7 @@ func (r *SQLAuditRepository) PruneExpiredAuditLogs(ctx context.Context, before t
|
||||
if before.IsZero() {
|
||||
return 0, errors.New("审计日志清理时间不能为空")
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `DELETE FROM audit_logs WHERE created_at < ?`, before.UTC())
|
||||
result, err := r.db.ExecContext(ctx, r.query(`DELETE FROM audit_logs WHERE created_at < ?`), before.UTC())
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("清理过期审计日志失败:%w", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Rebind 将内部统一使用的参数占位符转换为目标数据库驱动所需格式。
|
||||
// 它只处理 SQL 字符串字面量和标识符之外的问号,避免改写业务数据。
|
||||
func Rebind(driver, query string) string {
|
||||
if strings.ToLower(strings.TrimSpace(driver)) != "postgres" || !strings.Contains(query, "?") {
|
||||
return query
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
result.Grow(len(query) + 8)
|
||||
parameter := 0
|
||||
inSingleQuote := false
|
||||
inDoubleQuote := false
|
||||
inBacktick := false
|
||||
|
||||
for index := 0; index < len(query); index++ {
|
||||
char := query[index]
|
||||
switch char {
|
||||
case '\'':
|
||||
if !inDoubleQuote && !inBacktick {
|
||||
if inSingleQuote && index+1 < len(query) && query[index+1] == '\'' {
|
||||
result.WriteByte(char)
|
||||
index++
|
||||
result.WriteByte(query[index])
|
||||
continue
|
||||
}
|
||||
inSingleQuote = !inSingleQuote
|
||||
}
|
||||
case '"':
|
||||
if !inSingleQuote && !inBacktick {
|
||||
inDoubleQuote = !inDoubleQuote
|
||||
}
|
||||
case '`':
|
||||
if !inSingleQuote && !inDoubleQuote {
|
||||
inBacktick = !inBacktick
|
||||
}
|
||||
case '?':
|
||||
if !inSingleQuote && !inDoubleQuote && !inBacktick {
|
||||
parameter++
|
||||
result.WriteByte('$')
|
||||
result.WriteString(strconv.Itoa(parameter))
|
||||
continue
|
||||
}
|
||||
}
|
||||
result.WriteByte(char)
|
||||
}
|
||||
return result.String()
|
||||
}
|
||||
|
||||
func repositoryDriver(driver []string) string {
|
||||
if len(driver) == 0 {
|
||||
return "sqlite"
|
||||
}
|
||||
value := strings.ToLower(strings.TrimSpace(driver[0]))
|
||||
if value == "" {
|
||||
return "sqlite"
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -24,11 +24,16 @@ type ServerRepository interface {
|
||||
}
|
||||
|
||||
type SQLServerRepository struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
driver string
|
||||
}
|
||||
|
||||
func NewSQLServerRepository(db *sql.DB) *SQLServerRepository {
|
||||
return &SQLServerRepository{db: db}
|
||||
func NewSQLServerRepository(db *sql.DB, driver ...string) *SQLServerRepository {
|
||||
return &SQLServerRepository{db: db, driver: repositoryDriver(driver)}
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) query(value string) string {
|
||||
return Rebind(r.driver, value)
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) CreateServer(ctx context.Context, server deployment.Server) error {
|
||||
@@ -52,9 +57,9 @@ func (r *SQLServerRepository) CreateServer(ctx context.Context, server deploymen
|
||||
if updatedAt.IsZero() {
|
||||
updatedAt = createdAt
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO servers
|
||||
_, err = r.db.ExecContext(ctx, r.query(`INSERT INTO servers
|
||||
(id, name, address, port, username, private_key_ref, host_key_fingerprint, certificate_path, private_key_path, certificate_chain_path, web_server, validation_command_json, reload_command_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, server.ID, server.Name, server.Address, server.Port, server.Username, server.PrivateKeyRef,
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), server.ID, server.Name, server.Address, server.Port, server.Username, server.PrivateKeyRef,
|
||||
server.HostKeyFingerprint, server.CertificatePath, server.PrivateKeyPath, server.CertificateChainPath, server.WebServer, string(validationCommand), string(command), createdAt, updatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存服务器失败:%w", err)
|
||||
@@ -79,7 +84,7 @@ func (r *SQLServerRepository) UpdateServer(ctx context.Context, server deploymen
|
||||
if updatedAt.IsZero() {
|
||||
updatedAt = time.Now().UTC()
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE servers SET name = ?, address = ?, port = ?, username = ?, private_key_ref = ?, host_key_fingerprint = ?, certificate_path = ?, private_key_path = ?, certificate_chain_path = ?, web_server = ?, validation_command_json = ?, reload_command_json = ?, updated_at = ? WHERE id = ?`,
|
||||
result, err := r.db.ExecContext(ctx, r.query(`UPDATE servers SET name = ?, address = ?, port = ?, username = ?, private_key_ref = ?, host_key_fingerprint = ?, certificate_path = ?, private_key_path = ?, certificate_chain_path = ?, web_server = ?, validation_command_json = ?, reload_command_json = ?, updated_at = ? WHERE id = ?`),
|
||||
server.Name, server.Address, server.Port, server.Username, server.PrivateKeyRef, server.HostKeyFingerprint, server.CertificatePath, server.PrivateKeyPath, server.CertificateChainPath, server.WebServer, string(validationCommand), string(command), updatedAt, server.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新服务器失败:%w", err)
|
||||
@@ -95,12 +100,12 @@ func (r *SQLServerRepository) UpdateServer(ctx context.Context, server deploymen
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) GetServerByID(ctx context.Context, id string) (deployment.Server, error) {
|
||||
row := r.db.QueryRowContext(ctx, serverSelect+` WHERE id = ?`, strings.TrimSpace(id))
|
||||
row := r.db.QueryRowContext(ctx, r.query(serverSelect+` WHERE id = ?`), strings.TrimSpace(id))
|
||||
return scanServer(row)
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) ListServers(ctx context.Context) ([]deployment.Server, error) {
|
||||
rows, err := r.db.QueryContext(ctx, serverSelect+` ORDER BY name, id`)
|
||||
rows, err := r.db.QueryContext(ctx, r.query(serverSelect+` ORDER BY name, id`))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询服务器失败:%w", err)
|
||||
}
|
||||
@@ -132,10 +137,10 @@ func (r *SQLServerRepository) DeleteServer(ctx context.Context, id string) error
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE server_id = ?", id); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, r.query("DELETE FROM domain_servers WHERE server_id = ?"), id); err != nil {
|
||||
return rollback(fmt.Errorf("删除服务器关联失败:%w", err))
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "DELETE FROM servers WHERE id = ?", id)
|
||||
result, err := tx.ExecContext(ctx, r.query("DELETE FROM servers WHERE id = ?"), id)
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("删除服务器失败:%w", err))
|
||||
}
|
||||
@@ -158,14 +163,14 @@ func (r *SQLServerRepository) IsPrivateKeyRefUsed(ctx context.Context, reference
|
||||
return false, errors.New("SSH 私钥引用不能为空")
|
||||
}
|
||||
var count int
|
||||
if err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM servers WHERE private_key_ref = ?", reference).Scan(&count); err != nil {
|
||||
if err := r.db.QueryRowContext(ctx, r.query("SELECT COUNT(*) FROM servers WHERE private_key_ref = ?"), reference).Scan(&count); err != nil {
|
||||
return false, fmt.Errorf("检查 SSH 私钥引用占用状态失败:%w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *SQLServerRepository) ListServersByDomainID(ctx context.Context, domainID string) ([]deployment.Server, error) {
|
||||
rows, err := r.db.QueryContext(ctx, serverSelectQualified+` INNER JOIN domain_servers ds ON ds.server_id = servers.id WHERE ds.domain_id = ? ORDER BY servers.name, servers.id`, strings.TrimSpace(domainID))
|
||||
rows, err := r.db.QueryContext(ctx, r.query(serverSelectQualified+` INNER JOIN domain_servers ds ON ds.server_id = servers.id WHERE ds.domain_id = ? ORDER BY servers.name, servers.id`), strings.TrimSpace(domainID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询域名部署服务器失败:%w", err)
|
||||
}
|
||||
@@ -209,18 +214,18 @@ func (r *SQLServerRepository) ReplaceDomainServers(ctx context.Context, domainID
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE domain_id = ?", domainID); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, r.query("DELETE FROM domain_servers WHERE domain_id = ?"), domainID); err != nil {
|
||||
return rollback(fmt.Errorf("清理域名服务器关联失败:%w", err))
|
||||
}
|
||||
for _, serverID := range cleaned {
|
||||
var exists int
|
||||
if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM servers WHERE id = ?", serverID).Scan(&exists); err != nil {
|
||||
if err := tx.QueryRowContext(ctx, r.query("SELECT COUNT(*) FROM servers WHERE id = ?"), serverID).Scan(&exists); err != nil {
|
||||
return rollback(fmt.Errorf("校验部署服务器失败:%w", err))
|
||||
}
|
||||
if exists == 0 {
|
||||
return rollback(fmt.Errorf("部署服务器不存在:%s", serverID))
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO domain_servers (domain_id, server_id) VALUES (?, ?)", domainID, serverID); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, r.query("INSERT INTO domain_servers (domain_id, server_id) VALUES (?, ?)"), domainID, serverID); err != nil {
|
||||
return rollback(fmt.Errorf("保存域名服务器关联失败:%w", err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,16 @@ import (
|
||||
)
|
||||
|
||||
type SQLDomainRepository struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
driver string
|
||||
}
|
||||
|
||||
func NewSQLDomainRepository(db *sql.DB) *SQLDomainRepository {
|
||||
return &SQLDomainRepository{db: db}
|
||||
func NewSQLDomainRepository(db *sql.DB, driver ...string) *SQLDomainRepository {
|
||||
return &SQLDomainRepository{db: db, driver: repositoryDriver(driver)}
|
||||
}
|
||||
|
||||
func (r *SQLDomainRepository) query(value string) string {
|
||||
return Rebind(r.driver, value)
|
||||
}
|
||||
|
||||
func (r *SQLDomainRepository) Create(ctx context.Context, item domain.Domain) error {
|
||||
@@ -28,9 +33,9 @@ func (r *SQLDomainRepository) Create(ctx context.Context, item domain.Domain) er
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码 SAN 域名失败:%w", err)
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO domains
|
||||
_, err = r.db.ExecContext(ctx, r.query(`INSERT INTO domains
|
||||
(id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, item.ID, item.Name, item.CertificateType, string(payload), item.AutoRenew,
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), item.ID, item.Name, item.CertificateType, string(payload), item.AutoRenew,
|
||||
item.ACMEEnvironment, item.DNSProvider, item.Status, nullableTime(item.ExpiresAt), item.CreatedAt, item.UpdatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存域名失败:%w", err)
|
||||
@@ -46,9 +51,9 @@ func (r *SQLDomainRepository) Update(ctx context.Context, item domain.Domain) er
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码 SAN 域名失败:%w", err)
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE domains SET
|
||||
result, err := r.db.ExecContext(ctx, r.query(`UPDATE domains SET
|
||||
name = ?, certificate_type = ?, sans_json = ?, auto_renew = ?, acme_environment = ?, dns_provider = ?, updated_at = ?
|
||||
WHERE id = ?`, item.Name, item.CertificateType, string(payload), item.AutoRenew, item.ACMEEnvironment,
|
||||
WHERE id = ?`), item.Name, item.CertificateType, string(payload), item.AutoRenew, item.ACMEEnvironment,
|
||||
item.DNSProvider, item.UpdatedAt, item.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新域名失败:%w", err)
|
||||
@@ -67,8 +72,8 @@ func (r *SQLDomainRepository) GetByID(ctx context.Context, id string) (domain.Do
|
||||
if r == nil || r.db == nil {
|
||||
return domain.Domain{}, errors.New("数据库连接不能为空")
|
||||
}
|
||||
row := r.db.QueryRowContext(ctx, `SELECT id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at
|
||||
FROM domains WHERE id = ?`, id)
|
||||
row := r.db.QueryRowContext(ctx, r.query(`SELECT id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at
|
||||
FROM domains WHERE id = ?`), id)
|
||||
return scanDomain(row)
|
||||
}
|
||||
|
||||
@@ -76,8 +81,8 @@ func (r *SQLDomainRepository) List(ctx context.Context) ([]domain.Domain, error)
|
||||
if r == nil || r.db == nil {
|
||||
return nil, errors.New("数据库连接不能为空")
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, `SELECT id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at
|
||||
FROM domains ORDER BY name`)
|
||||
rows, err := r.db.QueryContext(ctx, r.query(`SELECT id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at
|
||||
FROM domains ORDER BY name`))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询域名失败:%w", err)
|
||||
}
|
||||
@@ -108,10 +113,10 @@ func (r *SQLDomainRepository) Delete(ctx context.Context, id string) error {
|
||||
_ = tx.Rollback()
|
||||
return cause
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM domain_servers WHERE domain_id = ?", id); err != nil {
|
||||
if _, err := tx.ExecContext(ctx, r.query("DELETE FROM domain_servers WHERE domain_id = ?"), id); err != nil {
|
||||
return rollback(fmt.Errorf("删除域名服务器关联失败:%w", err))
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, "DELETE FROM domains WHERE id = ?", id)
|
||||
result, err := tx.ExecContext(ctx, r.query("DELETE FROM domains WHERE id = ?"), id)
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("删除域名失败:%w", err))
|
||||
}
|
||||
@@ -136,7 +141,7 @@ func (r *SQLDomainRepository) UpdateCertificateState(ctx context.Context, id, st
|
||||
if status == "" {
|
||||
return errors.New("证书状态不能为空")
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE domains SET status = ?, expires_at = ?, updated_at = ? WHERE id = ?`,
|
||||
result, err := r.db.ExecContext(ctx, r.query(`UPDATE domains SET status = ?, expires_at = ?, updated_at = ? WHERE id = ?`),
|
||||
status, nullableTime(expiresAt), time.Now().UTC(), id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新证书状态失败:%w", err)
|
||||
|
||||
@@ -85,7 +85,7 @@ func (r *SQLUserRepository) FindByIdentifier(ctx context.Context, identifier str
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
row := r.db.QueryRowContext(ctx, userSelect+` WHERE LOWER(username) = ? OR (email IS NOT NULL AND LOWER(email) = ?) LIMIT 1`, normalized, normalized)
|
||||
row := r.db.QueryRowContext(ctx, r.query(userSelect+` WHERE LOWER(username) = ? OR (email IS NOT NULL AND LOWER(email) = ?) LIMIT 1`), normalized, normalized)
|
||||
return scanUser(row)
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ func (r *SQLUserRepository) ListUsers(ctx context.Context) ([]User, error) {
|
||||
if err := r.ensureDB(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx, userSelect+` ORDER BY role, username, id`)
|
||||
rows, err := r.db.QueryContext(ctx, r.query(userSelect+` ORDER BY role, username, id`))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询用户失败:%w", err)
|
||||
}
|
||||
@@ -120,7 +120,7 @@ func (r *SQLUserRepository) GetUserByID(ctx context.Context, id string) (User, e
|
||||
if id == "" {
|
||||
return User{}, errors.New("用户 ID 不能为空")
|
||||
}
|
||||
return scanUser(r.db.QueryRowContext(ctx, userSelect+` WHERE id = ?`, id))
|
||||
return scanUser(r.db.QueryRowContext(ctx, r.query(userSelect+` WHERE id = ?`), id))
|
||||
}
|
||||
|
||||
func (r *SQLUserRepository) CreateUser(ctx context.Context, item User) error {
|
||||
@@ -137,9 +137,9 @@ func (r *SQLUserRepository) CreateUser(ctx context.Context, item User) error {
|
||||
if item.UpdatedAt.IsZero() {
|
||||
item.UpdatedAt = item.CreatedAt
|
||||
}
|
||||
_, err := r.db.ExecContext(ctx, `INSERT INTO users
|
||||
_, err := r.db.ExecContext(ctx, r.query(`INSERT INTO users
|
||||
(id, username, email, password_hash, role, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`), item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||
item.Role, item.Status, item.CreatedAt, item.UpdatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存用户失败:%w", err)
|
||||
@@ -155,7 +155,7 @@ func (r *SQLUserRepository) UpdateUser(ctx context.Context, item User) error {
|
||||
if err := validateUser(item, false); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||
result, err := r.db.ExecContext(ctx, r.query(`UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`),
|
||||
item.Username, r.emailValue(item.Email), item.PasswordHash, item.Role, item.Status, time.Now().UTC(), item.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新用户失败:%w", err)
|
||||
@@ -181,7 +181,7 @@ func (r *SQLUserRepository) DeleteUser(ctx context.Context, id string) error {
|
||||
if id == "primary-super-admin" {
|
||||
return ErrSuperAdminProtected
|
||||
}
|
||||
result, err := r.db.ExecContext(ctx, `DELETE FROM users WHERE id = ?`, id)
|
||||
result, err := r.db.ExecContext(ctx, r.query(`DELETE FROM users WHERE id = ?`), id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除用户失败:%w", err)
|
||||
}
|
||||
@@ -208,7 +208,7 @@ func (r *SQLUserRepository) upsert(ctx context.Context, item User) error {
|
||||
item.CreatedAt = now
|
||||
}
|
||||
item.UpdatedAt = now
|
||||
result, err := r.db.ExecContext(ctx, `UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||
result, err := r.db.ExecContext(ctx, r.query(`UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`),
|
||||
item.Username, r.emailValue(item.Email), item.PasswordHash, item.Role, item.Status, item.UpdatedAt, item.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -220,20 +220,24 @@ func (r *SQLUserRepository) upsert(ctx context.Context, item User) error {
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
_, err = r.db.ExecContext(ctx, `INSERT INTO users
|
||||
_, err = r.db.ExecContext(ctx, r.query(`INSERT INTO users
|
||||
(id, username, email, password_hash, role, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`), item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||
item.Role, item.Status, item.CreatedAt, item.UpdatedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *SQLUserRepository) emailValue(email string) any {
|
||||
if email == "" && r.driver == "mysql" {
|
||||
if email == "" && (r.driver == "mysql" || r.driver == "postgres") {
|
||||
return nil
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
func (r *SQLUserRepository) query(value string) string {
|
||||
return Rebind(r.driver, value)
|
||||
}
|
||||
|
||||
func normalizeUser(item User) User {
|
||||
item.ID = strings.TrimSpace(item.ID)
|
||||
item.Username = strings.TrimSpace(strings.ToLower(item.Username))
|
||||
|
||||
Reference in new issue
Block a user