Skip to content

Commit

Permalink
#171: ~= ResultCode operator
Browse files Browse the repository at this point in the history
  • Loading branch information
groue committed Mar 1, 2017
1 parent 1908f1b commit 5bcfb7f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
22 changes: 22 additions & 0 deletions GRDB/Core/DatabaseError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
return ResultCode(rawValue: rawValue & 0xFF)
}

var isPrimary: Bool {
return self == primaryResultCode
}

public var description: String {
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
}
Expand All @@ -42,6 +46,24 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
return lhs.rawValue == rhs.rawValue
}

/// Returns true if the code on the left matches the code on the right.
///
/// Primary result codes match themselves and their extended result codes,
/// while extended result codes match only themselves:
///
/// switch error.extendedResultCode {
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
/// case .SQLITE_CONSTRAINT: // any other constraint error
/// default: // any other database error
/// }
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
if pattern.isPrimary {
return pattern == code.primaryResultCode
} else {
return pattern == code
}
}

public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4759,7 +4759,7 @@ do {
switch error.extendedResultCode {
case .SQLITE_CONSTRAINT_FOREIGNKEY:
// foreign key constraint error
case .SQLITE_CONSTRAINT
case .SQLITE_CONSTRAINT:
// any other constraint error
default:
// any other database error
Expand Down

0 comments on commit 5bcfb7f

Please sign in to comment.