I have this "complex" (complex to convert it to sqla core) postgres query which calculates a score by different factors and tables. I had the score as an aggregated value but I prefer having it stateless, thus I'm trying to define it as a hybrid property and an expression. The hybrid property was easy, did some simple math operations and conditionals with python and voila.
Is there any chance to achieve that without using sqlalchemy core expressions, just raw SQL? If yes that would be great for future operations too as raw, not so dynamic, SQL query is much easier to write than using sqla core functions. If no, I'd appreciate if you could point me in the right direction, just to declare the with clause without the inner subqueries in sqla core language.
I tried with the expression bellow but it throws error:
@score.expression
def score(cls):
raw = text(calc_score_raw_q) # The sql query bellow
raw.bindparams(product_id=cls.id)
return db.session.query(ProductModel).from_statement(raw).scalar()
Also executed the query straight from the engine
db.engine.execute(raw) but ended up with the same errors.
The error
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'product_id'
as it seems, hybrid expression's cls.id is an instrumented attribute, therefore it doesn't provide any value.
The SQL Query:
WITH gdp AS (
SELECT
SUM(du + de + sc + 1) AS gdp
FROM (
SELECT
(
CASE WHEN description IS NOT NULL THEN
0.5
ELSE
0
END) AS "de",
(
CASE WHEN duration IS NOT NULL THEN
0.5
ELSE
0
END) AS "du",
(
CASE WHEN shipping_cost IS NOT NULL THEN
2.0
ELSE
0
END) AS "sc"
FROM
products
WHERE
id = :product_id) AS a
),
td AS (
SELECT
COUNT(*) AS td
FROM
product_degrees
WHERE
product_id = :product_id
)
SELECT
SUM(
CASE WHEN td <= 50 THEN
td + gdp
WHEN td <= 200 THEN
gdp + 50 + (td - 50) * 1.5
ELSE
gdp + 275 + (td - 200) * 2
END) AS gd_points
FROM
td,
gdp