github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/database/errors.go (about) 1 // Copyright 2022 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package database 5 6 import ( 7 "strings" 8 9 "github.com/juju/errors" 10 "github.com/mattn/go-sqlite3" 11 ) 12 13 // IsErrConstraintUnique returns true if the input error was 14 // returned by SQLite due to violation of a unique constraint. 15 func IsErrConstraintUnique(err error) bool { 16 if err == nil { 17 return false 18 } 19 20 var sqliteErr sqlite3.Error 21 if errors.As(err, &sqliteErr) && sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique { 22 return true 23 } 24 25 // TODO (manadart 2022-12-16): The logic above works in unit tests using an 26 // in-memory SQLite DB, but appears to fail when running with Dqlite. 27 // Extended error codes can be enabled via PRAGMA, but we need to 28 // investigate further. 29 if strings.Contains(strings.ToLower(err.Error()), "unique constraint failed") { 30 return true 31 } 32 33 return false 34 }