 
 public extension Query where DS : Table {
     public func filter(_ f: (DS)->Predicate) -> QueryImpl<DS> {
-        return QueryImpl(connection: connection, dataset: dataset, predicate: f(dataset) && predicate, order: order)
+        return QueryImpl(dataset: dataset, predicate: f(dataset) && predicate, order: order)
     }
 }
 
 public extension Query where DS : JoinProtocol, DS.Left : Table {
     public func filter(_ f: (DS.Left, DS.Right)->Predicate) -> QueryImpl<DS> {
-        return QueryImpl(connection: connection, dataset: dataset, predicate: (dataset.datasets |> f) && predicate, order: order)
+        return QueryImpl(dataset: dataset, predicate: (dataset.datasets |> f) && predicate, order: order)
     }
 }
 

}

public extension Query {
    private func render(dialect:Dialect? = nil) throws -> SQL {
        guard let dialect = dialect.or(else: (connection as? DialectRich).map({$0.dialect})) else {
            throw RDBCFrameworkError.noDialect
        }
        
        return dialect.render(dataset: dataset, filter: self.predicate)
    }
    
    public func execute(dialect:Dialect? = nil) -> Future<ResultSet?> {
        let connection = self.connection
        
        return future(context: immediate) {
            try self.render(dialect: dialect)
        }.flatMap { sql in
            connection.execute(sql: sql)
        }
    }
}

public struct QueryImpl<DS : Dataset> : Query {
    public let connection:Connection
    
    public let dataset:DS
    public let predicate:Predicate
    public let order:Any
    
    init(connection:Connection, dataset:DS, predicate:Predicate, order:Any) {
        self.connection = connection
        self.dataset = dataset
        self.predicate = predicate
        self.order = order

    
    public func map(_ f: @autoclosure (DS)->[String]) -> QueryImpl<ErasedTable> {
        let dataset = ErasedTable(name: self.dataset.name, columns: .list(f(self.dataset)))
        return QueryImpl(dataset: dataset,
                         predicate: predicate,
                         order: order)
    }
    
    public func map(_ f: @autoclosure (DS)->String) -> QueryImpl<ErasedTable> {
        let dataset = ErasedTable(name: self.dataset.name, columns: .list([f(self.dataset)]))
        return QueryImpl(dataset: dataset,
                         predicate: predicate,
                         order: order)
    }
}

public extension Query {
    public static func select(_ columns: [String]? = nil, from: String) -> QueryImpl<ErasedTable> {
        let columns:Columns = columns.map { seq in
            .list(seq)
            }.getOr(else: .all)
        
        return QueryImpl(dataset: ErasedTable(name: from, columns: columns),
                         predicate: nil,
                         order: "")
    }
