71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/lib/pq"
|
|
"m8sh.su/d/jules/database"
|
|
)
|
|
|
|
type Contacts struct {
|
|
conn *sql.DB
|
|
}
|
|
|
|
func (c *Contacts) Add(ctx context.Context, contact *database.Contact) error {
|
|
_, err := c.conn.ExecContext(ctx, `
|
|
INSERT INTO contacts (owner_id, target_id, name)
|
|
VALUES ($1, $2, $3)
|
|
`, contact.OwnerID, contact.TargetID, contact.Name)
|
|
if err != nil {
|
|
var pqErr *pq.Error
|
|
if errors.As(err, &pqErr) && pqErr.Code == "23505" {
|
|
return database.ErrAlreadyExists
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Contacts) List(ctx context.Context, ownerID uuid.UUID) ([]database.Contact, error) {
|
|
rows, err := c.conn.QueryContext(ctx, `
|
|
SELECT owner_id, target_id, name
|
|
FROM contacts
|
|
WHERE owner_id = $1
|
|
`, ownerID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var contacts []database.Contact
|
|
for rows.Next() {
|
|
var contact database.Contact
|
|
if err = rows.Scan(&contact.OwnerID, &contact.TargetID, &contact.Name); err != nil {
|
|
return nil, err
|
|
}
|
|
contacts = append(contacts, contact)
|
|
}
|
|
if err = rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return contacts, nil
|
|
}
|
|
|
|
func (c *Contacts) Delete(ctx context.Context, ownerID uuid.UUID, targetID uuid.UUID) error {
|
|
result, err := c.conn.ExecContext(ctx, `
|
|
DELETE FROM contacts
|
|
WHERE owner_id = $1 AND target_id = $2
|
|
`, ownerID, targetID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rows, _ := result.RowsAffected()
|
|
if rows == 0 {
|
|
return database.ErrNotFound
|
|
}
|
|
return nil
|
|
}
|