bcit-ci / CodeIgniter

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
18.27k stars 7.6k forks source link

Session library set limit to database queries #2518

Closed pert closed 11 years ago

pert commented 11 years ago

Hi everyone,

Should there be limit set to one on all DB queries, from

SELECT * FROM (wf_session) WHERE session_id = '4e42167a634b223d56e99f21b35e231a'

to

SELECT * FROM (wf_session) WHERE session_id = '4e42167a634b223d56e99f21b35e231a' LIMIT 1

Every user should only ever have one active session, so once such record is found or updated, it's safe to stop query.

narfbg commented 11 years ago

If you only match by session ID, then you should have the UNIQUE flag set on that field and that would effectively limit it. If not - you can have 100 users with the same session ID, but e.g. originating from different IP addresses.

That said, I don't know why you're posting this here ... it doesn't seem like something related to CI. Please ask generic questions somewhere else, there are many forums around the web, GitHub isn't a place for it.

pert commented 11 years ago

It is CodeIgniter related.

As per your example, if there are 100 users on the website, the query to set or get session data has always check every single row in that table, even when positive match was made on the first row.

By adding "LIMIT 1" to session library queries it will automatically stop checking as soon as first positive match was made, whether it's with just session ID or with additional browser and IP checks in place - therefore shaving off some time from total execution time.

narfbg commented 11 years ago

As I said, a proper sessions table would have an UNIQUE key combining all the needed fields to make 100% sure match for the client. Actually, for a sessions table a PRIMARY KEY would make more sense, and this suggested by the user guide. Anyway ... both PRIMARY and UNIQUE keys have the same effect for our purpose. They ensure that there aren't 2 rows that match the same session. Database engines know that and they will stop looking up the table once they find a match for WHERE clauses that represent exactly the PRIMARY/UNIQUE key for a table. It doesn't matter if you put the LIMIT clause.