DerivableRequest

The base protocol for all requests that can be refined.

  • Creates a request which returns distinct rows.

    // SELECT DISTINCT * FROM player
    var request = Player.all()
    request = request.distinct()
    
    // SELECT DISTINCT name FROM player
    var request = Player.select(Column("name"))
    request = request.distinct()
    

    Declaration

    Swift

    func distinct() -> Self
  • Returns a request which embeds the common table expression.

    If a common table expression with the same table name had already been embedded, it is replaced by the new one.

    For example, you can build a request that fetches all chats with their latest message:

    let latestMessageRequest = Message
        .annotated(with: max(Column("date")))
        .group(Column("chatID"))
    
    let latestMessageCTE = CommonTableExpression(
        named: "latestMessage",
        request: latestMessageRequest)
    
    let latestMessage = Chat.association(
        to: latestMessageCTE,
        on: { chat, latestMessage in
            chat[Column("id")] == latestMessage[Column("chatID")]
        })
    
    // WITH latestMessage AS
    //   (SELECT *, MAX(date) FROM message GROUP BY chatID)
    // SELECT chat.*, latestMessage.*
    // FROM chat
    // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
    let request = Chat.all()
        .with(latestMessageCTE)
        .including(optional: latestMessage)
    

    Declaration

    Swift

    func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self

DerivableRequest

  • annotated(with:) Extension method

    Creates a request which appends aggregates to the current selection.

    // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
    // FROM player LEFT JOIN book ...
    var request = Player.all()
    request = request.annotated(with: Player.books.count)
    

    Declaration

    Swift

    public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> Self
  • annotated(with:) Extension method

    Creates a request which appends aggregates to the current selection.

    // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
    // FROM player LEFT JOIN book ...
    var request = Player.all()
    request = request.annotated(with: [Player.books.count])
    

    Declaration

    Swift

    public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> Self
  • having(_:) Extension method

    Creates a request which appends the provided aggregate predicate to the eventual set of already applied predicates.

    // SELECT player.*
    // FROM player LEFT JOIN book ...
    // HAVING COUNT(DISTINCT book.id) = 0
    var request = Player.all()
    request = request.having(Player.books.isEmpty)
    

    Declaration

    Swift

    public func having(_ predicate: AssociationAggregate<RowDecoder>) -> Self