Swift-Kuery icon indicating copy to clipboard operation
Swift-Kuery copied to clipboard

Parameter is not working with sub-request

Open mbarnach opened this issue 4 years ago • 0 comments

When using the Parameter type to avoid SQL injection, the queryBuilder is not working with sub-request, restarting the counter to 1 each time.

If building the following query (from the README tables)

let query = Select(from: grades)
    .where(
        courses.name == Parameter() &&
        courses.credit == Parameter() &&
        courses.teacher.in(
        Select(courses.teacher, from: courses)
            .where(courses.teacher == Parameter() )))

We get with PostgreSQL the following SQL request:

SELECT * FROM "Grades" WHERE (("Courses"."name" = $1) AND ("Courses"."credit" = $2)) AND ("Courses"."teacher" IN (SELECT "Courses"."teacher" FROM "Courses" WHERE "Courses"."teacher" = $1))

Notice that in the last part of the request, teacher is assigned the value $1 instead of $3. Or name is assigned the value $1 instead of $3 (depending on the order that should make sense here. The request cannot be run if we provide 3 arguments, as this is checked before.

As far as I can tell, this is coming from the fact that requests are resolved independently, hence the reset of the index.

For reference, MySQL is not suffering from the same issue, as it doesn't use numbered parameters. The same request returns:

SELECT * FROM `Grades` WHERE ((`Courses`.`name` = ?) AND (`Courses`.`credit` = ?)) AND (`Courses`.`teacher` IN (SELECT `Courses`.`teacher` FROM `Courses` WHERE `Courses`.`teacher` = ?))

mbarnach avatar Feb 05 '21 15:02 mbarnach