kayak / pypika

PyPika is a python SQL query builder that exposes the full richness of the SQL language using a syntax that reflects the resulting query. PyPika excels at all sorts of SQL queries but is especially useful for data analysis.
http://pypika.readthedocs.io/en/latest/
Apache License 2.0
2.43k stars 293 forks source link

Cannot join with a Query #755

Closed JonathanCabezas closed 8 months ago

JonathanCabezas commented 9 months ago

Here is an example which triggers a pypika.utils.JoinException

order=Table("order")
product=Table("product")
subquery=Query.from_(product).select(product.id).groupby(product.id)
Query.from_(order).join(subquery).on(order.id==product.id).select("*")

The join seems to only work with Tables

JonathanCabezas commented 9 months ago

Here is a quick fix:

class Subquery(Table):
    def __init__(self, query: QueryBuilder) -> None:
        self._query = query
        self._table_name = query._from[0].get_table_name()
        # Using the original table name as alias for the subquery
        # for my use case, you can use something else
        self._query.alias = self._table_name
        super().__init__(self._table_name)

    def get_sql(self, **kwargs: Any) -> str:
        return self._query.get_sql(**kwargs)

order=Table("order")
product=Table("product")
subquery=Subquery(Query.from_(product).select(product.id).groupby(product.id))
Query.from_(order).join(subquery).on(order.id==product.id).select("*")
AzisK commented 9 months ago

Would you like to create a pull request?

JonathanCabezas commented 8 months ago

Would you like to create a pull request?

I don't think this code is anywhere near production-ready, this is just a quick workaround I used in my facade module. Hopefully it gives someone else ideas for a proper Subquery implementation.