DatabaseSerializable
public protocol DatabaseSerializable : ParameterBindable
A type that may be serialized to and deserialized from a database.
This is a more general method for database storage than ParameterBindable
and ColumnConvertible
because it allows types to customize their behavior based on the database value’s data type.
A database value’s data type is the value returned by the sqlite3_column_type()
before any
type conversions have taken place.
Note
Columns in SQLite have a type affinity (declared type) while stored values have an individual storage class/data type. There are rules for conversion which are documented at Datatypes In SQLite Version 3.For example, NSNumber
can choose what to store in the database based on the boxed value:
extension NSNumber: DatabaseSerializable {
public func serialized() -> DatabaseValue {
switch CFNumberGetType(self as CFNumber) {
case .sInt8Type, .sInt16Type, .sInt32Type, .charType, .shortType, .intType,
.sInt64Type, .longType, .longLongType, .cfIndexType, .nsIntegerType:
return DatabaseValue.integer(self.int64Value)
case .float32Type, .float64Type, .floatType, .doubleType, .cgFloatType:
return DatabaseValue.float(self.doubleValue)
}
}
public static func deserialize(from value: DatabaseValue) throws -> Self {
switch value {
case .integer(let i):
return self.init(value: i)
case .float(let f):
return self.init(value: f)
default:
throw DatabaseError("\(value) is not a number")
}
}
}
-
Returns a serialized value of
self
.Declaration
Swift
func serialized() -> DatabaseValue
Return Value
A serialized value representing
self
-
Deserializes and returns
value
asSelf
.Throws
An error if
value
contains an illegal value forSelf
Declaration
Swift
static func deserialize(from value: DatabaseValue) throws -> Self
Parameters
value
A serialized value of
Self
Return Value
An instance of
Self
-
bind(to:
Extension methodparameter: ) Declaration
Swift
public func bind(to stmt: SQLitePreparedStatement, parameter idx: Int32) throws