Model
type that is used to interact with that table. Use this Model type for querying, inserting, updating or deleting from the table.
id
property. Each property of your Model
will correspond to a table column with the same name, converted to snake_case
.
Model
APIs rely heavily on Swift’s Codable
. Please avoid overriding the compiler synthesized func encode(to: Encoder)
and init(from: Decoder)
functions. You might be able to get away with it but it could cause issues under the hood. You can however, add custom CodingKeys
if you like, just be aware of the impact it will have on the keyMappingStrategy
described below.
tableName: String
property.
Model
property names will be converted to snake_case
, when mapping to corresponding table columns. You may change this behavior via the keyMapping: DatabaseKeyMapping
. You could set it to .useDefaultKeys
to use the verbatim CodingKey
s of the Model
object, or .custom((String) -> String)
to provide a custom mapping closure.
String
, Bool
, Int
, Double
, UUID
, Date
. Under the hood, these are mapped to relevant types on the concrete Database
you are using.
enum
s and JSON
.
String
or Int
backed Swift enum
s are allowed as fields on a Model
, as long as they conform to ModelEnum
.
Codable
, so any property that isn’t one of the types listed above will be stored as JSON
.
JSON
properties are encoded using a default JSONEncoder()
and stored in the table column. You can use a custom JSONEncoder
by overriding the static Model.jsonEncoder
.
JSONDecoder
for decoding data from JSON columns.
SQLRow
Model
s may be “decoded” from a SQLRow
that was the result of a raw query or query builder query. The Model
’s properties will be mapped to their relevant columns, factoring in any custom keyMappingStrategy
. This will throw an error if there is an issue while decoding, such as a missing column.
SQLRow.decode(_ type:)
because the typed ORM queries described in the next section decode it for you.
Model
with the static .query
function.
ModelQuery<M: Model>
is a subclass of the generic Query
, with a few functions for running and automatically decoding M
from a query.
.allModels()
returns all Model
s that matched the query.
.firstModel()
returns an EventLoopFuture<M?>
containing the first Model
that matched the query, if it exists.
.unwrapFirstModel(or error: Error)
.
Model
.
ensureNotExists(where:error:)
does a query to ensure that a Model
matching the provided where clause doesn’t exist. If it does, it throws the provided error.
unwrapFirstWhere(_:error:)
is essentially the opposite, finding the first Model
that matches the provided where clause or throwing an error if one doesn’t exist.
Model
s.
Model
with the all()
function.
Model
to the database, either inserting it or updating it depending on if it has a nil id.
Model
from the database with delete()
.
Model
.
[Model]
.