SchemaBuilder

public protocol SchemaBuilder : AnyObject

Helps you create, update, and delete database schemas for your models. This is usually done in Migration methods like prepare(...) and revert(...).

Use Database.create(...), Database.update(...), and Database.delete(...) to create schema builders.

PostgreSQLDatabase.create(User.self) { builder in
    builder.field(for: \.id)
    builder.field(for: \.name)
}
  • field(for:isIdentifier:) Extension method

    Adds a field.

    builder.field(for: \.name)
    

    You can specify identifier fields as well.

    builder.field(for: \.name, isIdentifier: true)
    

    Declaration

    Swift

    public func field<T>(for key: KeyPath<Model, T>, isIdentifier: Bool? = nil)

    Parameters

    key

    KeyPath to the field.

    isIdentifier

    If true, this field will have appropriate attributes for storing an identifier.

  • field(for:type:) Extension method

    Adds a field with specified type.

    builder.field(for: \.name, type: ...)
    

    Declaration

    Swift

    public func field<T>(for key: KeyPath<Model, T>, type: Model.Database.SchemaFieldType)

    Parameters

    key

    KeyPath to the field.

    type

    Data type to use for this field.

  • field(_:) Extension method

    Adds a custom field.

    Declaration

    Swift

    public func field(_ field: Model.Database.SchemaField)
  • Adds a reference constraint from one field to another.

    builder.reference(from: \.userID, to: \User.id)
    

    Declaration

    Swift

    public func reference<T, U, Other>(
        from: KeyPath<Model, T>,
        to: KeyPath<Other, U>,
        onUpdate: Model.Database.SchemaReferenceAction? = nil,
        onDelete: Model.Database.SchemaReferenceAction? = nil
    ) where Other: Fluent.Model

    Parameters

    from

    KeyPath to the local field.

    to

    KeyPath to the foreign field.

    onUpdate

    Schema reference action to apply when the related model is updated. nil by default.

    onDelete

    Schema reference action to apply when the related model is deleted. nil by default.

  • unique(on:) Extension method

    Adds a unique constraint to a field.

    builder.unique(on: \.email)
    

    Declaration

    Swift

    public func unique<T>(on key: KeyPath<Model, T>)

    Parameters

    key

    KeyPath to the unique field.

  • unique(on:_:) Extension method

    Adds a unique constraint to two fields.

    builder.unique(on: \.email, \.username)
    

    Declaration

    Swift

    public func unique<T, U>(on a: KeyPath<Model, T>, _ b: KeyPath<Model, U>)

    Parameters

    a

    KeyPath to the first unique field.

    b

    KeyPath to the second unique field.