__init__.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # -*- coding: utf-8 -*-
  2. """The application's model objects"""
  3. from contextlib import contextmanager
  4. from sqlalchemy import event, inspect, MetaData
  5. from sqlalchemy.ext.declarative import declarative_base
  6. from sqlalchemy.orm import scoped_session, sessionmaker, Session
  7. from sqlalchemy.orm.unitofwork import UOWTransaction
  8. from zope.sqlalchemy import ZopeTransactionExtension
  9. from tracim.lib.exception import ContentRevisionUpdateError, ContentRevisionDeleteError
  10. class RevisionsIntegrity(object):
  11. """
  12. Simple static used class to manage a list with list of ContentRevisionRO who are allowed to be updated.
  13. When modify an already existing (understood have an identity in databse) ContentRevisionRO, if it's not in
  14. RevisionsIntegrity._updatable_revisions list, a ContentRevisionUpdateError thrown.
  15. This class is used by tracim.model.new_revision context manager.
  16. """
  17. _updatable_revisions = []
  18. @classmethod
  19. def add_to_updatable(cls, revision: 'ContentRevisionRO') -> None:
  20. if inspect(revision).has_identity:
  21. raise ContentRevisionUpdateError("ContentRevision is not updatable. %s already have identity." % revision)
  22. if revision not in cls._updatable_revisions:
  23. cls._updatable_revisions.append(revision)
  24. @classmethod
  25. def remove_from_updatable(cls, revision: 'ContentRevisionRO') -> None:
  26. if revision in cls._updatable_revisions:
  27. cls._updatable_revisions.remove(revision)
  28. @classmethod
  29. def is_updatable(cls, revision: 'ContentRevisionRO') -> bool:
  30. return revision in cls._updatable_revisions
  31. # Global session manager: DBSession() returns the Thread-local
  32. # session object appropriate for the current web request.
  33. maker = sessionmaker(
  34. autoflush=True,
  35. autocommit=False,
  36. extension=ZopeTransactionExtension(),
  37. expire_on_commit=False,
  38. )
  39. DBSession = scoped_session(maker)
  40. # Base class for all of our model classes: By default, the data model is
  41. # defined with SQLAlchemy's declarative extension, but if you need more
  42. # control, you can switch to the traditional method.
  43. convention = {
  44. "ix": 'ix__%(column_0_label)s', # Indexes
  45. "uq": "uq__%(table_name)s__%(column_0_name)s", # Unique constrains
  46. "fk": "fk__%(table_name)s__%(column_0_name)s__%(referred_table_name)s", # Foreign keys
  47. "pk": "pk__%(table_name)s" # Primary keys
  48. }
  49. metadata = MetaData(naming_convention=convention)
  50. DeclarativeBase = declarative_base(metadata=metadata)
  51. # There are two convenient ways for you to spare some typing.
  52. # You can have a query property on all your model classes by doing this:
  53. # DeclarativeBase.query = DBSession.query_property()
  54. # Or you can use a session-aware mapper as it was used in TurboGears 1:
  55. # DeclarativeBase = declarative_base(mapper=DBSession.mapper)
  56. # Global metadata.
  57. # The default metadata is the one from the declarative base.
  58. metadata = DeclarativeBase.metadata
  59. # If you have multiple databases with overlapping table names, you'll need a
  60. # metadata for each database. Feel free to rename 'metadata2'.
  61. #metadata2 = MetaData()
  62. #####
  63. # Generally you will not want to define your table's mappers, and data objects
  64. # here in __init__ but will want to create modules them in the model directory
  65. # and import them at the bottom of this file.
  66. #
  67. ######
  68. def init_model(engine):
  69. """Call me before using any of the tables or classes in the model."""
  70. if not DBSession.registry.has(): # Prevent a SQLAlchemy warning
  71. DBSession.configure(bind=engine)
  72. # If you are using reflection to introspect your database and create
  73. # table objects for you, your tables must be defined and mapped inside
  74. # the init_model function, so that the engine is available if you
  75. # use the model outside tg2, you need to make sure this is called before
  76. # you use the model.
  77. #
  78. # See the following example:
  79. #global t_reflected
  80. #t_reflected = Table("Reflected", metadata,
  81. # autoload=True, autoload_with=engine)
  82. #mapper(Reflected, t_reflected)
  83. # Import your model modules here.
  84. from tracim.model.auth import User, Group, Permission
  85. from tracim.model.data import Content, ContentRevisionRO
  86. @event.listens_for(DBSession, 'before_flush')
  87. def prevent_content_revision_delete(session: Session, flush_context: UOWTransaction,
  88. instances: [DeclarativeBase]) -> None:
  89. for instance in session.deleted:
  90. if isinstance(instance, ContentRevisionRO) and instance.revision_id is not None:
  91. raise ContentRevisionDeleteError("ContentRevision is not deletable. You must make a new revision with" +
  92. "is_deleted set to True. Look at tracim.model.new_revision context " +
  93. "manager to make a new revision")
  94. @contextmanager
  95. def new_revision(content: Content) -> Content:
  96. """
  97. Prepare context to update a Content. It will add a new updatable revision to the content.
  98. :param content: Content instance to update
  99. :return:
  100. """
  101. with DBSession.no_autoflush:
  102. try:
  103. if inspect(content.revision).has_identity:
  104. content.new_revision()
  105. RevisionsIntegrity.add_to_updatable(content.revision)
  106. yield content
  107. finally:
  108. RevisionsIntegrity.remove_from_updatable(content.revision)