TableAlias

Experimental

A TableAlias identifies a table in a request.

  • Creates a TableAlias, suitable for qualifying requests or associations.

    For example:

    // The request for all books published after their author has died
    //
    // SELECT book.*
    // FROM book
    // JOIN author ON author.id = book.authorId
    // WHERE book.publishDate >= author.deathDate
    let authorAlias = TableAlias()
    let request = Book
        .joining(required: Book.author.aliased(authorAlias))
        .filter(Column("publishDate") >= authorAlias[Column("deathDate")])
    

    When the alias is given a name, this name is guaranteed to be used as the table alias in the SQL query:

    // SELECT book.*
    // FROM book
    // JOIN author a ON a.id = book.authorId
    // WHERE book.publishDate >= a.deathDate
    let authorAlias = TableAlias(name: "a")
    let request = Book
        .joining(required: Book.author.aliased(authorAlias))
        .filter(Column("publishDate") >= authorAlias[Column("deathDate")])
    
  • Returns a qualified value that is able to resolve ambiguities in joined queries.

  • Experimental

    An expression that evaluates to true if the record referred by this TableAlias exists.

    For example, here is how filter books and only keep those that are not associated to any author:

    let books: [Book] = try dbQueue.read { db in
        let authorAlias = TableAlias()
        let request = Book
            .joining(optional: Book.author.aliased(authorAlias))
            .filter(!authorAlias.exists)
        return try request.fetchAll(db)
    }