I’m trying to execute a raw SQL query in SQLAlchemy, but I’m encountering syntax errors. Here’s the SQL query I’m trying to run:
WITH RECURSIVE dates AS (
SELECT TIMESTAMP '2024-04-01 00:00:00' AS date
UNION ALL
SELECT date + INTERVAL '1 DAY'
FROM dates
WHERE date < TIMESTAMP '2024-04-30 23:59:59'
)
SELECT dates.date::date,
COALESCE(json_agg(json_build_object(
'time_start', ds.time_start,
'schedule_id', ds.id,
'doctor_id', ds.doctor_id,
'doctor_name', d.name,
'time_end', ds.time_end,
'quota', ds.quota,
'day', ds.day
)), '[]') AS schedules
FROM dates
LEFT JOIN doctors_schedules ds ON EXTRACT(DOW FROM dates.date) = ds.day_number
LEFT JOIN doctors d on ds.doctor_id = d.id
GROUP BY dates.date
ORDER BY dates.date;
i did tried with
query = text("""
WITH RECURSIVE dates AS (
SELECT TIMESTAMP '':start_date'' AS DATE
UNION ALL
SELECT date + INTERVAL ''1 DAY''
FROM dates
WHERE date < TIMESTAMP '':end_date'' AS DATE
)
SELECT dates.date::date,
COALESCE(json_agg(json_build_object(
''time_start'', ds.time_start,
''schedule_id'', ds.id,
''doctor_id'', ds.doctor_id,
''doctor_name'', d.name,
''time_end'', ds.time_end,
''quota'', ds.quota,
''day'', ds.day
)), ''[]'') AS schedules
FROM dates
LEFT JOIN doctors_schedules ds ON EXTRACT(DOW FROM dates.date) = ds.day_number
LEFT JOIN doctors d on ds.doctor_id = d.id
WHERE ds.clinic_id = :clinic_id
GROUP BY dates.date
ORDER BY dates.date;
""")
params = {"start_date": start_date, "end_date": end_date, "clinic_id": clinic_id}
result = await session.execute(query, params)
However, I keep getting a syntax error near $1. Can someone please help me understand what’s causing this error and how to fix it? Any insights would be greatly appreciated.