fleet/server/datastore/mysql/errors.go
Zachary Wasserman 0b7747bef0
Fix pack and query UI issues in Fleet 2.0 (#1829)
Replaces (and appropriately refactors) a number of endpoints that were removed long ago when we decided to kill the UI with the fleetctl release. We turned out not to do this, and now need to restore these missing endpoints.

This is not a straight up replacement of the existing code because of refactoring to the DB schemas that was also done in the migration.

Most of the replaced code was removed in #1670 and #1686.

Fixes #1811, fixes #1810
2018-06-15 10:13:11 -04:00

112 lines
2.1 KiB
Go

package mysql
import (
"fmt"
"github.com/VividCortex/mysqlerr"
"github.com/go-sql-driver/mysql"
)
type notFoundError struct {
ID uint
Name string
Message string
ResourceType string
}
func notFound(kind string) *notFoundError {
return &notFoundError{
ResourceType: kind,
}
}
func (e *notFoundError) Error() string {
if e.ID != 0 {
return fmt.Sprintf("%s %d was not found in the datastore", e.ResourceType, e.ID)
}
if e.Name != "" {
return fmt.Sprintf("%s %s was not found in the datastore", e.ResourceType, e.Name)
}
if e.Message != "" {
return fmt.Sprintf("%s %s was not found in the datastore", e.ResourceType, e.Message)
}
return fmt.Sprintf("%s was not found in the datastore", e.ResourceType)
}
func (e *notFoundError) WithID(id uint) error {
e.ID = id
return e
}
func (e *notFoundError) WithName(name string) error {
e.Name = name
return e
}
func (e *notFoundError) WithMessage(msg string) error {
e.Message = msg
return e
}
func (e *notFoundError) IsNotFound() bool {
return true
}
type existsError struct {
ID uint
ResourceType string
}
func alreadyExists(kind string, id uint) error {
return &existsError{
ID: id,
ResourceType: kind,
}
}
func (e *existsError) Error() string {
return fmt.Sprintf("%s %d already exists in the datastore", e.ResourceType, e.ID)
}
func (e *existsError) IsExists() bool {
return true
}
func isDuplicate(err error) bool {
if driverErr, ok := err.(*mysql.MySQLError); ok {
if driverErr.Number == mysqlerr.ER_DUP_ENTRY {
return true
}
}
return false
}
type foreignKeyError struct {
Name string
ResourceType string
}
func foreignKey(kind string, name string) error {
return &foreignKeyError{
Name: name,
ResourceType: kind,
}
}
func (e *foreignKeyError) Error() string {
return fmt.Sprintf("the operation violates a foreign key constraint on %s: %s", e.ResourceType, e.Name)
}
func (e *foreignKeyError) IsForeignKey() bool {
return true
}
func isMySQLForeignKey(err error) bool {
if driverErr, ok := err.(*mysql.MySQLError); ok {
if driverErr.Number == mysqlerr.ER_ROW_IS_REFERENCED_2 {
return true
}
}
return false
}