Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Merge pull request #14 from mfuentesg/fix/unique-constraint
Browse files Browse the repository at this point in the history
fix: handle unique constraint for domain + ip
  • Loading branch information
mfuentesg authored Jun 12, 2022
2 parents a85114f + ee0c08a commit e84bafd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion server/grpc/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (srv *Server) PutRecord(ctx context.Context, r *pb.Record) (*pb.Record, err
})

if err != nil {
logEntry.Error("unable to store data")
logEntry.WithField("reason", err).Error("unable to store data")
return nil, err
}

Expand Down
20 changes: 18 additions & 2 deletions storage/sqlite/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,18 @@ import (

"github.com/jmoiron/sqlx"
"github.com/mfuentesg/localdns/storage"
_ "modernc.org/sqlite" // sqlite driver
"modernc.org/sqlite"
)

var (
ErrRecordAlreadyExists = errors.New("record already exists")
)

// SQLite constraint codes
// Reference: https://www.sqlite.org/rescode.html#pve

const (
ErrCodeConstraintUnique = 2067
)

type SQLite struct {
Expand All @@ -23,12 +34,17 @@ func New(dsn string) (*SQLite, error) {
}

func (sq *SQLite) Put(r storage.Record) (string, error) {
query := `insert or replace into records(
query := `insert into records(
domain, ipv4, ipv6, ttl, type
) values(?, ?, ?, ?, ?) returning id`

var id string
err := sq.db.QueryRow(query, r.Domain, r.IPv4, r.IPv6, r.TTL, r.Type).Scan(&id)

errCode := err.(*sqlite.Error).Code()
if errCode == ErrCodeConstraintUnique {
return "", ErrRecordAlreadyExists
}
return id, err
}

Expand Down

0 comments on commit e84bafd

Please sign in to comment.