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

Already on GitHub? Sign in to your account

Database: explicitly define table in where clause to make queries unambiguous #605

wants to merge 1 commit into


None yet
3 participants

juzna commented Mar 25, 2012

Problem explained:

I've got these three tables joined by foreign keys:

DB schema

When I want to select requests added by me which belong to a movie (transitive dependence via subtitles), I would use:
$this->db->table('requests')->where(array('addedBy' => $userId, 'subtitle.movieId' => $movieId)).
Look at this command. It is obvious that I want to have a condition on addedBy column in requests table and you probably won't even realize there is another column of the same name. And even if you do so, that column is somewhere else and I'm not using it in the db command at all. So I think this command is absolutely clear.

However, Nette Db will fail because of issuing ambiguous SQL query to the database:
SELECT requests.* FROM requests INNER JOIN subtitles AS subtitle ON requests.subtitleid = subtitle.id WHERE (addedBy = ?) AND (subtitle.movieId = ?). Notice the WHERE clause - it says addedBy which is ambiguous for sql server.

I believe Nette Db should make it clear and tell the database what we wanted, but it has to translate it into the database language. Therefore it must make the sql query unambiguous, as what we said to Nette Db was clear and unambiguous. Therefore the sql query should be:
SELECT requests.* FROM requests INNER JOIN subtitles AS subtitle ON requests.subtitleid = subtitle.id WHERE (requests.addedBy = ?) AND (subtitle.movieId = ?) (explicitly define the table name in where clause).

(Discussion expected)


hrach commented Mar 25, 2012

Awesome, please add test. :)

maybe use # as delimeter since it's used across the framework.


juzna commented Mar 25, 2012

I took a shower and looked at it again, and perhaps it's not solved in the best place. Explicit table name in SQL is not really needed when one selects only from one table. Also, decision whether the table name is needed in generated SQL query should probably be within getSql method (or its callees).

icaine commented on 63d0ed9 May 13, 2012

what if you pass as a condition something like "column < ? OR column > ?"?

@juzna juzna closed this May 19, 2012


juzna commented May 19, 2012

@icaine you're right, that would break it. I don't have any proper solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment