84 lines
1.6 KiB
Go
84 lines
1.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/models"
|
|
)
|
|
|
|
type ContactRepository struct {
|
|
baseRepository[models.Contact]
|
|
}
|
|
|
|
func NewContactRepository(db *sql.DB) Repository[models.Contact] {
|
|
return &ContactRepository{
|
|
baseRepository[models.Contact]{
|
|
db: db,
|
|
tableName: "contacts",
|
|
}}
|
|
}
|
|
|
|
func (r *ContactRepository) Create(contact *models.Contact) (int64, error) {
|
|
query := r.BuildQuery("INSERT INTO %s (name, company, phone) VALUES (?, ?, ?)")
|
|
|
|
result, err := r.db.Exec(
|
|
query,
|
|
contact.Name, contact.Company, contact.Phone,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
id, err := result.LastInsertId()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
contact.ID = int(id)
|
|
return id, nil
|
|
}
|
|
|
|
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 err
|
|
}
|
|
|
|
return nil
|
|
}
|