I want to cache sqlalchemy, I have discovered that using keyword SQL_CACHE in mysql can be helpful in caching queries on demand.
But how do I do it in sqlalchemy?
Is it possible?
Asked
Active
Viewed 1,752 times
1
Super Kai - Kazuya Ito
- 213
- 1
- 8
Jitin Maherchandani
- 145
- 2
- 9
2 Answers
1
This is a rather old question, but deserves an answer.
You have to set the query_cache_type.
Here are the values and their meaning
0 or OFF: Do not cache results in or retrieve results from the query cache. Note that this does not deallocate the query cache buffer. To do that, you should set query_cache_size to 0.1 or ON: Cache all cacheable query results except for those that begin with SELECT SQL_NO_CACHE.2 or DEMANDCache results only for cacheable queries that begin with SELECT SQL_CACHE.
By default, query_cache_type is 0 (Cache Nothing).
You can run this to cache every SELECT that does not have SQL_NO_CACHE directive in your session:
SET query_cache_type = 1;
You can run this to cache every SELECT that has the SQL_CACHE directive in your session:
SET query_cache_type = 2;
If you want it set globally, then run
SET GLOBAL query_cache_type = 2;
Then add that to the my.cnf
[mysqld]
query_cache_type = 2
PLEASE NOTE THIS TOTALLY GOES AWAY IN MySQL 8.0 !!!
This answer is only good for MySQL 5.7 and prior, also older MariaDB versions
What About SQLAlchemy ???
Since you want the caching on demand, please set query_cache_type to 2.
Then you can run
query = session.query(User.name).prefix_with('SQL_CACHE')
RolandoMySQLDBA
- 185,223
- 33
- 326
- 536
0
You need use a prefix_with. For example, this:
query = session.query(User.name).prefix_with('SQL_CACHE')
would render:
SELECT SQL_CACHE users.name AS users_name FROM users