refactor: update interface contract and applies some fixes
This commit is contained in:
@@ -2,6 +2,7 @@ package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/models"
|
||||
)
|
||||
@@ -10,7 +11,7 @@ type ContactRepository struct {
|
||||
baseRepository[models.Contact]
|
||||
}
|
||||
|
||||
func NewContactRepository(db *sql.DB) *ContactRepository {
|
||||
func NewContactRepository(db *sql.DB) Repository[models.Contact] {
|
||||
return &ContactRepository{
|
||||
baseRepository[models.Contact]{
|
||||
db: db,
|
||||
@@ -38,20 +39,45 @@ func (r *ContactRepository) Create(contact *models.Contact) (int64, error) {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r *ContactRepository) Update(contact *models.Contact) (int64, error) {
|
||||
query := r.BuildQuery("UPDATE %s SET name = ?, company = ?, phone = ? WHERE id = ?")
|
||||
result, err := r.db.Exec(query,
|
||||
contact.Name, contact.Company, contact.Phone, contact.ID,
|
||||
func (r *ContactRepository) Update(contact *models.Contact) error {
|
||||
query := r.BuildQuery("UPDATE %s SET")
|
||||
fieldsToUpdate := make([]string, 0, 4)
|
||||
fields := make([]any, 0)
|
||||
|
||||
if contact.Name != "" {
|
||||
fieldsToUpdate = append(fieldsToUpdate, "name")
|
||||
fields = append(fields, &contact.Name)
|
||||
}
|
||||
|
||||
if contact.Company != "" {
|
||||
fieldsToUpdate = append(fieldsToUpdate, "company")
|
||||
fields = append(fields, &contact.Company)
|
||||
}
|
||||
|
||||
if contact.Phone != "" {
|
||||
fieldsToUpdate = append(fieldsToUpdate, "phone")
|
||||
fields = append(fields, &contact.Phone)
|
||||
}
|
||||
|
||||
fields = append(fields, &contact.ID)
|
||||
|
||||
fieldsToUpdatelen := len(fieldsToUpdate)
|
||||
for i, field := range fieldsToUpdate {
|
||||
query += fmt.Sprintf(" %s = ?", field)
|
||||
if i != fieldsToUpdatelen-1 {
|
||||
query += ","
|
||||
}
|
||||
}
|
||||
|
||||
query += " WHERE id = ?"
|
||||
|
||||
_, err := r.db.Exec(query,
|
||||
fields...,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return err
|
||||
}
|
||||
|
||||
rowsAffected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return rowsAffected, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user