backend barebone done, big chunk of work done
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgerrcode"
|
||||
)
|
||||
|
||||
// AddContact creates a contact relation or returns ErrDuplicate if it exists.
|
||||
func (s *Store) AddContact(ctx context.Context, ownerID, contactID int64) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO contacts(owner_id, contact_id)
|
||||
VALUES($1, $2)
|
||||
`, ownerID, contactID)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
|
||||
return ErrDuplicate
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// RemoveContact deletes a contact relation; no error if not present.
|
||||
func (s *Store) RemoveContact(ctx context.Context, ownerID, contactID int64) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM contacts WHERE owner_id=$1 AND contact_id=$2
|
||||
`, ownerID, contactID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ListContacts returns all contacts for an owner ordered by created_at descending.
|
||||
func (s *Store) ListContacts(ctx context.Context, ownerID int64) ([]Contact, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT owner_id, contact_id, created_at
|
||||
FROM contacts WHERE owner_id=$1
|
||||
ORDER BY created_at DESC
|
||||
`, ownerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var list []Contact
|
||||
for rows.Next() {
|
||||
var c Contact
|
||||
if err := rows.Scan(&c.OwnerID, &c.ContactID, &c.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list = append(list, c)
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// IsContact reports whether a contact relation exists.
|
||||
func (s *Store) IsContact(ctx context.Context, ownerID, contactID int64) (bool, error) {
|
||||
var exists bool
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM contacts WHERE owner_id=$1 AND contact_id=$2
|
||||
)
|
||||
`, ownerID, contactID).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
Reference in New Issue
Block a user