Files

69 lines
2.2 KiB
Swift

// Import C SQLite functions
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
/// Decimal adopts DatabaseValueConvertible
extension Decimal: DatabaseValueConvertible {
/// Returns a TEXT decimal value.
public var databaseValue: DatabaseValue {
NSDecimalNumber(decimal: self)
.description(withLocale: Locale(identifier: "en_US_POSIX"))
.databaseValue
}
/// Creates a `Decimal` with the specified database value.
///
/// If the database value contains an integer or a double, returns a
/// `Decimal` initialized from this number.
///
/// If the database value contains a string, parses the string with the
/// `en_US_POSIX` locale.
///
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64):
return self.init(int64)
case .double(let double):
return self.init(double)
case let .string(string):
// Must match NSNumber.fromDatabaseValue(_:)
return self.init(string: string, locale: _posixLocale)
default:
return nil
}
}
}
/// Decimal adopts StatementColumnConvertible
extension Decimal: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER:
self.init(sqlite3_column_int64(sqliteStatement, index))
case SQLITE_FLOAT:
self.init(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
let string = String(sqliteStatement: sqliteStatement, index: index)
self.init(string: string, locale: _posixLocale)
default:
return nil
}
}
}
@usableFromInline
let _posixLocale = Locale(identifier: "en_US_POSIX")