1
votes

I have an error, when SQLAlchemy produced wrong SQL query, but I can't determine conditions.

I use Flask-SQLAlchemy and initially it's a just MyModel.query and it represented by simple SELECT with JOINs. But when .limit() method is applied, it transforms and uses subquery for fetch main objects and only then apply JOINs. The problem is in ORDER BY statement, which remains the same and ignores the subquery definition.

Here's example and I've simplify select fields:

-- Initially
SELECT *
FROM customer_rates
LEFT OUTER JOIN seasons AS seasons_1 ON seasons_1.id = customer_rates.season_id
LEFT OUTER JOIN users AS users_1 ON users_1.id = customer_rates.customer_id
-- other joins ...
ORDER BY customer_rates.id, customer_rates.id

-- Then .limit()
SELECT anon_1.*, *
FROM (
    SELECT customer_rates.*
    FROM customer_rates
    LIMIT :param_1) AS anon_1
LEFT OUTER JOIN seasons AS seasons_1 ON seasons_1.id = anon_1.customer_rates_season_id
LEFT OUTER JOIN users AS users_1 ON users_1.id = anon_1.customer_rates_customer_id
-- other joins
ORDER BY customer_rates.id, customer_rates.id

And this query gives following error:

ProgrammingError: (psycopg2.ProgrammingError) missing FROM-clause entry for table "customer_rates"

The last line in query should be:

ORDER BY anon_1.customer_rates_id

The code, that produces this queries is a part of large application. I've tried to implement this from scratch in a small flask application, But I can't reproduce it. In small application it always uses a JOIN. So I need to know, when SQLAlchemy decides to use subquery.

I use python 2.7 and PostgreSQL 9

1

1 Answers

0
votes

The answer is pretty straightforward. It uses subquery when it joined table has many-to-one relations with queried model. So for producing correct number of results it limits the queried rows in the subquery