sqlalchemy.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from __future__ import absolute_import
  2. from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
  3. from apscheduler.util import maybe_ref, datetime_to_utc_timestamp, utc_timestamp_to_datetime
  4. from apscheduler.job import Job
  5. try:
  6. import cPickle as pickle
  7. except ImportError: # pragma: nocover
  8. import pickle
  9. try:
  10. from sqlalchemy import (
  11. create_engine, Table, Column, MetaData, Unicode, Float, LargeBinary, select, and_)
  12. from sqlalchemy.exc import IntegrityError
  13. from sqlalchemy.sql.expression import null
  14. except ImportError: # pragma: nocover
  15. raise ImportError('SQLAlchemyJobStore requires SQLAlchemy installed')
  16. class SQLAlchemyJobStore(BaseJobStore):
  17. """
  18. Stores jobs in a database table using SQLAlchemy.
  19. The table will be created if it doesn't exist in the database.
  20. Plugin alias: ``sqlalchemy``
  21. :param str url: connection string (see
  22. :ref:`SQLAlchemy documentation <sqlalchemy:database_urls>` on this)
  23. :param engine: an SQLAlchemy :class:`~sqlalchemy.engine.Engine` to use instead of creating a
  24. new one based on ``url``
  25. :param str tablename: name of the table to store jobs in
  26. :param metadata: a :class:`~sqlalchemy.schema.MetaData` instance to use instead of creating a
  27. new one
  28. :param int pickle_protocol: pickle protocol level to use (for serialization), defaults to the
  29. highest available
  30. :param str tableschema: name of the (existing) schema in the target database where the table
  31. should be
  32. :param dict engine_options: keyword arguments to :func:`~sqlalchemy.create_engine`
  33. (ignored if ``engine`` is given)
  34. """
  35. def __init__(self, url=None, engine=None, tablename='apscheduler_jobs', metadata=None,
  36. pickle_protocol=pickle.HIGHEST_PROTOCOL, tableschema=None, engine_options=None):
  37. super(SQLAlchemyJobStore, self).__init__()
  38. self.pickle_protocol = pickle_protocol
  39. metadata = maybe_ref(metadata) or MetaData()
  40. if engine:
  41. self.engine = maybe_ref(engine)
  42. elif url:
  43. self.engine = create_engine(url, **(engine_options or {}))
  44. else:
  45. raise ValueError('Need either "engine" or "url" defined')
  46. # 191 = max key length in MySQL for InnoDB/utf8mb4 tables,
  47. # 25 = precision that translates to an 8-byte float
  48. self.jobs_t = Table(
  49. tablename, metadata,
  50. Column('id', Unicode(191), primary_key=True),
  51. Column('next_run_time', Float(25), index=True),
  52. Column('job_state', LargeBinary, nullable=False),
  53. schema=tableschema
  54. )
  55. def start(self, scheduler, alias):
  56. super(SQLAlchemyJobStore, self).start(scheduler, alias)
  57. self.jobs_t.create(self.engine, True)
  58. def lookup_job(self, job_id):
  59. selectable = select(self.jobs_t.c.job_state).where(self.jobs_t.c.id == job_id)
  60. with self.engine.begin() as connection:
  61. job_state = connection.execute(selectable).scalar()
  62. return self._reconstitute_job(job_state) if job_state else None
  63. def get_due_jobs(self, now):
  64. timestamp = datetime_to_utc_timestamp(now)
  65. return self._get_jobs(self.jobs_t.c.next_run_time <= timestamp)
  66. def get_next_run_time(self):
  67. selectable = select(self.jobs_t.c.next_run_time).\
  68. where(self.jobs_t.c.next_run_time != null()).\
  69. order_by(self.jobs_t.c.next_run_time).limit(1)
  70. with self.engine.begin() as connection:
  71. next_run_time = connection.execute(selectable).scalar()
  72. return utc_timestamp_to_datetime(next_run_time)
  73. def get_all_jobs(self):
  74. jobs = self._get_jobs()
  75. self._fix_paused_jobs_sorting(jobs)
  76. return jobs
  77. def add_job(self, job):
  78. insert = self.jobs_t.insert().values(**{
  79. 'id': job.id,
  80. 'next_run_time': datetime_to_utc_timestamp(job.next_run_time),
  81. 'job_state': pickle.dumps(job.__getstate__(), self.pickle_protocol)
  82. })
  83. with self.engine.begin() as connection:
  84. try:
  85. connection.execute(insert)
  86. except IntegrityError:
  87. raise ConflictingIdError(job.id)
  88. def update_job(self, job):
  89. update = self.jobs_t.update().values(**{
  90. 'next_run_time': datetime_to_utc_timestamp(job.next_run_time),
  91. 'job_state': pickle.dumps(job.__getstate__(), self.pickle_protocol)
  92. }).where(self.jobs_t.c.id == job.id)
  93. with self.engine.begin() as connection:
  94. result = connection.execute(update)
  95. if result.rowcount == 0:
  96. raise JobLookupError(job.id)
  97. def remove_job(self, job_id):
  98. delete = self.jobs_t.delete().where(self.jobs_t.c.id == job_id)
  99. with self.engine.begin() as connection:
  100. result = connection.execute(delete)
  101. if result.rowcount == 0:
  102. raise JobLookupError(job_id)
  103. def remove_all_jobs(self):
  104. delete = self.jobs_t.delete()
  105. with self.engine.begin() as connection:
  106. connection.execute(delete)
  107. def shutdown(self):
  108. self.engine.dispose()
  109. def _reconstitute_job(self, job_state):
  110. job_state = pickle.loads(job_state)
  111. job_state['jobstore'] = self
  112. job = Job.__new__(Job)
  113. job.__setstate__(job_state)
  114. job._scheduler = self._scheduler
  115. job._jobstore_alias = self._alias
  116. return job
  117. def _get_jobs(self, *conditions):
  118. jobs = []
  119. selectable = select(self.jobs_t.c.id, self.jobs_t.c.job_state).\
  120. order_by(self.jobs_t.c.next_run_time)
  121. selectable = selectable.where(and_(*conditions)) if conditions else selectable
  122. failed_job_ids = set()
  123. with self.engine.begin() as connection:
  124. for row in connection.execute(selectable):
  125. try:
  126. jobs.append(self._reconstitute_job(row.job_state))
  127. except BaseException:
  128. self._logger.exception('Unable to restore job "%s" -- removing it', row.id)
  129. failed_job_ids.add(row.id)
  130. # Remove all the jobs we failed to restore
  131. if failed_job_ids:
  132. delete = self.jobs_t.delete().where(self.jobs_t.c.id.in_(failed_job_ids))
  133. connection.execute(delete)
  134. return jobs
  135. def __repr__(self):
  136. return '<%s (url=%s)>' % (self.__class__.__name__, self.engine.url)