58 lines
1.1 KiB
Go
58 lines
1.1 KiB
Go
package repository
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
"gitea.gabilandia.com/gabdlr/agenda-web-go/internal/models"
|
|
)
|
|
|
|
type ContactRepository struct {
|
|
baseRepository[models.Contact]
|
|
}
|
|
|
|
func NewContactRepository(db *sql.DB) *ContactRepository {
|
|
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) (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,
|
|
)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
rowsAffected, err := result.RowsAffected()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return rowsAffected, nil
|
|
}
|