Should Laravel database connections use cached prepared statements? #46808
Replies: 7 comments 8 replies
-
Hi, @tlaverdure.
I think, well prepared and tested implementation could be part of the framework, but nobody just wants to deal with caching. |
Beta Was this translation helpful? Give feedback.
-
I looked into Wordpress caching a few years ago and I can say that getting it right is not easy.
|
Beta Was this translation helpful? Give feedback.
-
Please note, it seems that the database could be already caching prepared statements, as per MySQL 8.x documentation - https://dev.mysql.com/doc/refman/8.0/en/statement-caching.html So maybe the benchmark is misleading here. |
Beta Was this translation helpful? Give feedback.
-
I think this is a very useful change. Many loop commands can benefit from this. Preparestatement cause 3 times database command (prepare, execute, deallocate)
May be |
Beta Was this translation helpful? Give feedback.
-
Whether or not caching prepared statements is advantageous depends on the specific query and its usage. Decent database software will handle statement caching internally and it will be done more efficiently. |
Beta Was this translation helpful? Give feedback.
-
Good idea, but as some already mentioned, Eloquent is not built to properly exploit server side prepared statements. Some query construction logic is quite badly designed (example fetching a has many relationship by running a separate query with an IN + huge id list clause). For sure possible, but you need to ensure that the cache size is limited/controlled as those dynamically generated queries could cause a memory exhaustion. Better set Note: By default emulation is disabled for postgresql. If you enable it, laravel is missing proper boolean casting logic. You need to ensure that you add support for that first. |
Beta Was this translation helpful? Give feedback.
-
If Eloquent doesn't already do this, then that is a major mistake. The whole idea of prepared statements is to prepare them without the variable data (and the IN clause is variable data). |
Beta Was this translation helpful? Give feedback.
-
I was just looking at Illuminate\Database\Connection and noticed that prepared statements are not being reused. It seems like good practice to use an existing prepared statement to avoid recompiling a query and improve performance.
This is also stated in the PHP PDO docs:
https://www.php.net/manual/en/pdo.prepare.php
I've tested this with Laravel Vapor (Octane) and have seen 50-70% improvement on query latency with recurring statements.
Benefits
Implementation:
Are there any known side effects that would discourage this from being part of Laravel?
Beta Was this translation helpful? Give feedback.
All reactions