feat: add contact repository and base repository for shared db logic
This commit is contained in:
57
internal/repository/contact_repository.go
Normal file
57
internal/repository/contact_repository.go
Normal file
@@ -0,0 +1,57 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user