Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot join with a Query #755

Closed
JonathanCabezas opened this issue Sep 27, 2023 · 3 comments
Closed

Cannot join with a Query #755

JonathanCabezas opened this issue Sep 27, 2023 · 3 comments

Comments

@JonathanCabezas
Copy link

JonathanCabezas commented Sep 27, 2023

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 JonathanCabezas changed the title Uncorrelated subquery not working Cannot join with a Query Sep 27, 2023
@JonathanCabezas
Copy link
Author

JonathanCabezas commented Sep 28, 2023

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
Copy link

AzisK commented Sep 29, 2023

Would you like to create a pull request?

@JonathanCabezas
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants