diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 40b35fe..b87e0ce 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -506,7 +506,9 @@ func (c *Cache) putNarInfoInStore(hash string, narInfo *narinfo.NarInfo) error { } func (c *Cache) storeInDatabase(hash string, narInfo *narinfo.NarInfo) error { - c.logger.Info("storing narinfo and nar record in the database", "hash", hash, "nar-url", narInfo.URL) + log := c.logger.New("hash", hash, "nar-url", narInfo.URL) + + log.Info("storing narinfo and nar record in the database") tx, err := c.db.Begin() if err != nil { @@ -523,6 +525,11 @@ func (c *Cache) storeInDatabase(hash string, narInfo *narinfo.NarInfo) error { res, err := c.db.InsertNarInfoRecord(tx, hash) if err != nil { + if errors.Is(err, database.ErrAlreadyExists) { + log.Warn("narinfo record was not added to database because it already exists") + return nil + } + return fmt.Errorf("error inserting the narinfo record for hash %q in the database: %w", hash, err) } @@ -537,6 +544,11 @@ func (c *Cache) storeInDatabase(hash string, narInfo *narinfo.NarInfo) error { } if _, err := c.db.InsertNarRecord(tx, lid, narHash, compression, narInfo.FileSize); err != nil { + if errors.Is(err, database.ErrAlreadyExists) { + log.Warn("nar record was not added to database because it already exists") + return nil + } + return fmt.Errorf("error inserting the nar record in the database: %w", err) } diff --git a/pkg/database/sqlite.go b/pkg/database/sqlite.go index f33ac8d..8f22107 100644 --- a/pkg/database/sqlite.go +++ b/pkg/database/sqlite.go @@ -9,6 +9,7 @@ import ( "github.com/inconshreveable/log15/v3" // Import the SQLite driver. + "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3" ) @@ -77,6 +78,9 @@ const ( var ( // ErrNotFound is returned if record is not found in the database. ErrNotFound = errors.New("not found") + + // ErrAlreadyExists is returned if record insertion failed due to uniqueness constraint. + ErrAlreadyExists = errors.New("error already exists") ) type ( @@ -178,6 +182,11 @@ func (db *DB) InsertNarInfoRecord(tx *sql.Tx, hash string) (sql.Result, error) { res, err := stmt.Exec(hash) if err != nil { + sqliteErr, ok := errors.Unwrap(err).(sqlite3.Error) + if ok && sqliteErr.Code == sqlite3.ErrConstraint { + return nil, ErrAlreadyExists + } + return nil, fmt.Errorf("error executing the statement: %w", err) } @@ -250,6 +259,11 @@ func (db *DB) InsertNarRecord(tx *sql.Tx, narInfoID int64, res, err := stmt.Exec(narInfoID, hash, compression, fileSize) if err != nil { + sqliteErr, ok := errors.Unwrap(err).(sqlite3.Error) + if ok && sqliteErr.Code == sqlite3.ErrConstraint { + return nil, ErrAlreadyExists + } + return nil, fmt.Errorf("error executing the statement: %w", err) }