Guest User

Untitled

a guest
Feb 21st, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. from functools import lru_cache
  2.  
  3. import pymonetdb
  4.  
  5.  
  6. class MonetMemoize:
  7.  
  8. def __init__(self, funcs=None, maxsize=128):
  9. self.maxsize = maxsize
  10. self.type_map = {
  11. 'py_date': pymonetdb.sql.types.DATE,
  12. 'py_time': pymonetdb.sql.types.TIME,
  13. 'py_timestamp': pymonetdb.sql.types.TIMESTAMP,
  14. 'py_timetz': pymonetdb.sql.types.TIMETZ,
  15. 'py_timestamptz': pymonetdb.sql.types.TIMESTAMPTZ,
  16. }
  17. if funcs is None:
  18. self.funcs = tuple(self.type_map.keys())
  19. else:
  20. self.funcs = funcs
  21.  
  22. def __enter__(self):
  23. for func in self.funcs:
  24. old_func = getattr(pymonetdb.sql.pythonize, func)
  25. monet_type = self.type_map[func]
  26. lru_func = lru_cache(maxsize=self.maxsize)(old_func)
  27. pymonetdb.sql.pythonize.mapping[monet_type] = lru_func
  28.  
  29. def __exit__(self, *args, **kwargs):
  30. for func in self.funcs:
  31. old_func = getattr(pymonetdb.sql.pythonize, func)
  32. monet_type = self.type_map[func]
  33. pymonetdb.sql.pythonize.mapping[monet_type] = old_func
  34.  
  35.  
  36. def main():
  37. connection = pymonetdb.connect(username='username', password='password',
  38. hostname='hostname', database='database')
  39. cursor = connection.cursor()
  40.  
  41. with MonetMemoize():
  42. cursor.execute('select * from test;')
  43. print(len(cursor.fetchall()))
  44.  
  45.  
  46. if __name__ == '__main__':
  47. main()
Add Comment
Please, Sign In to add comment