def test_decorator_actor_send_with_inherit_Core_3(self): def add_in_registry(): from anyblok import Declarations @Declarations.register(Declarations.Core) class SqlBase: @classmethod def add(cls, val): return val @Declarations.register(Declarations.Model) # noqa class Task: id = Integer(primary_key=True) @actor_send() def add(cls, val): return super(Task, cls).add(val) * 2 registry = self.init_registry_with_bloks(('dramatiq',), add_in_registry) self.assertTrue(isinstance(registry.Task.add, AnyBlokActor)) self.assertFalse(EnvironmentManager.get('_postcommit_hook')) registry.Task.add(1) self.assertEqual(registry.Dramatiq.Message.query().count(), 1) self.assertTrue(EnvironmentManager.get('_postcommit_hook'))
def call_directly_the_actor_send(): """Context manager to call directly without use dramatiq""" try: EnvironmentManager.set('is_called_by_dramatiq_actor', True) yield finally: EnvironmentManager.set('is_called_by_dramatiq_actor', False)
def get_needed_blok(cls, blok): """Get and import/load the blok given with dependencies :param blok: :return: """ if cls.has(blok): return True if blok not in cls.bloks: return False cls.get_needed_blok_dependencies(blok) cls.ordered_bloks.append(blok) EnvironmentManager.set('current_blok', blok) if not ImportManager.has(blok): # Import only if the blok doesn't exists, do not reload here mod = ImportManager.add(blok) mod.imports() else: mod = ImportManager.get(blok) mod.reload() if cls.bloks[blok].autoinstall: cls.auto_install.append(blok) return True
def wrapper(self, request): def reset(): EnvironmentManager.define_environment_cls(ThreadEnvironment) request.addfinalizer(reset) EnvironmentManager.define_environment_cls(MockEnvironment)
def init_registry_with_bloks(self, bloks, function, **kwargs): """ call a function to filled the blok manager with new model and bloks to install :param bloks: list of blok's names :param function: function to call :param kwargs: kwargs for the function :rtype: registry instance """ if bloks is None: bloks = [] if isinstance(bloks, tuple): bloks = list(bloks) if 'anyblok-test' not in bloks: bloks.append('anyblok-test') from copy import deepcopy loaded_bloks = deepcopy(RegistryManager.loaded_bloks) if function is not None: EnvironmentManager.set('current_blok', 'anyblok-test') try: function(**kwargs) finally: EnvironmentManager.set('current_blok', None) try: self.registry = registry = self.__class__.getRegistry() if bloks: registry.upgrade(install=bloks) finally: RegistryManager.loaded_bloks = loaded_bloks return registry
def init_registry_with_bloks(bloks, function, **kwargs): if bloks is None: bloks = [] if isinstance(bloks, tuple): bloks = list(bloks) if isinstance(bloks, str): bloks = [bloks] anyblok_test_name = 'anyblok-test' if anyblok_test_name not in bloks: bloks.append(anyblok_test_name) loaded_bloks = deepcopy(RegistryManager.loaded_bloks) if function is not None: EnvironmentManager.set('current_blok', anyblok_test_name) try: function(**kwargs) finally: EnvironmentManager.set('current_blok', None) try: registry = RegistryManager.get(Configuration.get('db_name'), unittest=True) # update required blok registry_bloks = registry.get_bloks_by_states('installed', 'toinstall') toinstall = [x for x in bloks if x not in registry_bloks] toupdate = [x for x in bloks if x in registry_bloks] registry.upgrade(install=toinstall, update=toupdate) finally: RegistryManager.loaded_bloks = loaded_bloks return registry
def init_registry_with_bloks(self, bloks, function, **kwargs): """ call a function to filled the blok manager with new model and bloks to install :param bloks: list of blok's names :param function: function to call :param kwargs: kwargs for the function :rtype: registry instance """ from copy import deepcopy loaded_bloks = deepcopy(RegistryManager.loaded_bloks) if function is not None: EnvironmentManager.set('current_blok', 'anyblok-core') try: function(**kwargs) finally: EnvironmentManager.set('current_blok', None) try: self.registry = registry = self.__class__.getRegistry() if bloks: registry.upgrade(install=bloks) finally: RegistryManager.loaded_bloks = loaded_bloks return registry
def before_process_message(self, broker, message): """Called before process message Invalid the cache, this is mean that if a cache have to be invalidated then it will be invalidated else nothing is done If the message is in the ``Model.Dramatiq.Message`` then the status will be change to **running** :param broker: the broker used :param message: the message send in the broker """ registry = RegistryManager.get(Configuration.get('db_name')) logger.debug("[before_process_message] %s: update message(%s) status ", id(registry.session), message.message_id) # cache may have change, then we do the invalidation in the dramatiq # side registry.System.Cache.clear_invalidate_cache() M = registry.Dramatiq.Message m = M.get_instance_of(message) if m: m.update_status(M.STATUS_RUNNING) registry.commit() EnvironmentManager.set('is_called_by_dramatiq_actor', True)
def add_testCore(self, request, bloks_loaded): def reset(): EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testCore' + self._corename] request.addfinalizer(reset) RegistryManager.init_blok('testCore' + self._corename) EnvironmentManager.set('current_blok', 'testCore' + self._corename)
def test_without_environment_for_get(self): # don't use define_environment_cls, because she must be verify EnvironmentManager.environment = None try: EnvironmentManager.get('db_name') self.fail('No watchdog for None environment') except EnvironmentException: pass
def init_env(self, request): def revert(): EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testModel'] request.addfinalizer(revert) RegistryManager.init_blok('testModel') EnvironmentManager.set('current_blok', 'testModel')
def blok_importers(cls, blok): EnvironmentManager.set('current_blok', blok) if not ImportManager.has(blok): # Import only if the blok doesn't exists, do not reload here mod = ImportManager.add(blok) mod.imports() else: mod = ImportManager.get(blok) mod.reload()
def init_env(self, request): def revert(): EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testCore'] RegistryManager.undeclare_core('test') request.addfinalizer(revert) RegistryManager.declare_core('test') RegistryManager.init_blok('testCore') EnvironmentManager.set('current_blok', 'testCore')
def set(self, context=None, **kwargs): if context is None: context = {} previous_context = EnvironmentManager.get( 'context', default=ImmutableContextDict({})) manager = AttributeContextManager(previous_context) ctx = previous_context.copy() ctx.update(context) ctx.update(kwargs) EnvironmentManager.set('context', ImmutableContextDict(ctx)) return manager
def _finish(self, final_state): assert self.transaction is not None del _SESSION_STATE[self.registry.session] registry = self.registry self.transaction = self.registry = None self.state = final_state if not self.keep_session: registry.session.close() else: registry.session.expire_all() EnvironmentManager.set('_precommit_hook', [])
def after_process_message(self, broker, message, *, result=None, exception=None): """Called after process message If the message is in the ``Model.Dramatiq.Message`` then the status will be change to **done** or **failed**. .. note:: the status is failed if an exception is passed or a rollback is need Before the end, the session is expired to release the Session pool thread :param broker: the broker used :param message: the message send in the broker :param result: return by the process :param exception: any ``Exception`` raised by the process """ registry = RegistryManager.get(Configuration.get('db_name')) logger.debug( "[after_process_message] %s: update message(%s) status " "with result %r and exception %r", id(registry.session), message.message_id, result, exception) EnvironmentManager.set('is_called_by_dramatiq_actor', False) M = registry.Dramatiq.Message STATUS_DONE = M.STATUS_DONE STATUS_FAILED = M.STATUS_FAILED try: m = M.get_instance_of(message) if m: m.update_status( STATUS_FAILED if exception is not None else STATUS_DONE, error=str(exception) if exception else None) registry.commit() except Exception as e: registry.rollback() m = M.get_instance_of(message) if m: m.update_status(M.STATUS_FAILED, error=str(e)) registry.commit() raise e finally: registry.expire_all()
def create_session_factory(self): """Overwrite the creation of Session factory to Use the multi binding """ if self.Session is None or self.must_recreate_session_factory(): if self.Session: if not self.withoutautomigration: # this is the only case to use commit in the construction # of the registry self.commit() # remove all existing instance to create a new instance # because the instance are cached self.Session.remove() query_bases = [] + self.loaded_cores['Query'] query_bases += [self.registry_base] Query = type('Query', tuple(query_bases), {}) session_bases = [self.registry_base, MixinSession] session_bases += self.loaded_cores['Session'] Session = type('Session', tuple(session_bases), { 'registry_query': Query}) extension = self.additional_setting.get('sa.session.extension') if extension: extension = extension() self.Session = scoped_session( sessionmaker(class_=Session, extension=extension), EnvironmentManager.scoped_function_for_session()) self.nb_query_bases = len(self.loaded_cores['Query']) self.nb_session_bases = len(self.loaded_cores['Session']) self.apply_session_events() else: self.flush()
def create_session_factory(self): """Overwrite the creation of Session factory to Use the multi binding """ if self.Session is None or self.must_recreate_session_factory(): query_bases = [] + self.loaded_cores['Query'] query_bases += [self.registry_base] Query = type('Query', tuple(query_bases), {}) session_bases = [self.registry_base, MixinSession] session_bases.extend(self.loaded_cores['Session']) Session = type('Session', tuple(session_bases), { 'registry_query': Query}) self.session_connection = None if self.Session: self.session_connection = self.connection() extension = self.additional_setting.get('sa.session.extension') if extension: extension = extension() self.Session = scoped_session( sessionmaker(class_=Session, extension=extension), EnvironmentManager.scoped_function_for_session()) self.nb_query_bases = len(self.loaded_cores['Query']) self.nb_session_bases = len(self.loaded_cores['Session']) else: self.flush()
def setUpClass(cls): super(TestMigration, cls).setUpClass() cls.init_configuration_manager() cls.createdb() BlokManager.load() register = Declarations.register Model = Declarations.Model cls.loaded_bloks = deepcopy(RegistryManager.loaded_bloks) EnvironmentManager.set('current_blok', 'anyblok-core') @register(Model) class Test: integer = Int(primary_key=True) other = Str() @register(Model) class TestUnique: integer = Int(primary_key=True) other = Str(unique=True) @register(Model) class TestFKTarget: integer = Int(primary_key=True) @register(Model) class TestFK: integer = Int(primary_key=True) other = Int(foreign_key=Model.TestFKTarget.use('integer')) @register(Model) class TestM2M1: idmodel1 = Int(primary_key=True) @register(Model) class TestM2M2: idmodel2 = Int(primary_key=True) rel_m2m = Many2Many(label="Rel", model=Model.TestM2M1, join_table='reltable', remote_columns='idmodel1', m2m_remote_columns='idmodel1', local_columns='idmodel2', m2m_local_columns='idmodel2', many2many='rel_m2m_inv') EnvironmentManager.set('current_blok', None)
def format(self, record): """ Add color to the message :param record: logging record instance :rtype: logging record formatted """ record.database = EnvironmentManager.get('db_name', 'No database') return logging.Formatter.format(self, record)
def test_global_property(self): RegistryManager.declare_entry('Other') blok = 'newblok' RegistryManager.init_blok(blok) try: oldblok = EnvironmentManager.get('current_blok') EnvironmentManager.set('current_blok', blok) assert not RegistryManager.has_blok_property('myproperty') RegistryManager.add_or_replace_blok_property('myproperty', 2) assert RegistryManager.has_blok_property('myproperty') assert RegistryManager.get_blok_property('myproperty') == 2 RegistryManager.add_or_replace_blok_property('myproperty', 3) assert RegistryManager.get_blok_property('myproperty') == 3 RegistryManager.remove_blok_property('myproperty') assert not RegistryManager.has_blok_property('myproperty') finally: EnvironmentManager.set('current_blok', oldblok)
def __call__(self, *args, **kwargs): """Send to the broker or call directly the classmethod""" is_called_by_dramatiq_actor = EnvironmentManager.get( 'is_called_by_dramatiq_actor', False) if is_called_by_dramatiq_actor: kwargs.pop('run_at', None) kwargs.pop('delay', None) return self.fn(*args, **kwargs) return self.send(*args, **kwargs)
def reload(self): """ Reload all the imports for this module :exception: ImportManagerException """ from anyblok.blok import BlokManager from anyblok.registry import RegistryManager from anyblok.environment import EnvironmentManager b = BlokManager.get(self.blok) if not hasattr(b, 'reload_declaration_module'): return try: EnvironmentManager.set('reload', True) RegistryManager.init_blok(self.blok) b.reload_declaration_module(reload_module) finally: EnvironmentManager.set('reload', False)
def reload(self): """ Reload all the imports for this module :exception: ImportManagerException """ from anyblok.blok import BlokManager from anyblok.registry import RegistryManager from anyblok.environment import EnvironmentManager b = BlokManager.get(self.blok) if not hasattr(b, 'reload_declaration_module'): return try: EnvironmentManager.set('reload', True) RegistryManager.init_blok(self.blok) b.reload_declaration_module(reload_wraper) finally: EnvironmentManager.set('reload', False)
def test_global_property(self): RegistryManager.declare_entry('Other') blok = 'newblok' RegistryManager.init_blok(blok) try: oldblok = EnvironmentManager.get('current_blok') EnvironmentManager.set('current_blok', blok) self.assertEqual(RegistryManager.has_blok_property('myproperty'), False) RegistryManager.add_or_replace_blok_property('myproperty', 2) self.assertEqual(RegistryManager.has_blok_property('myproperty'), True) self.assertEqual(RegistryManager.get_blok_property('myproperty'), 2) RegistryManager.add_or_replace_blok_property('myproperty', 3) self.assertEqual(RegistryManager.get_blok_property('myproperty'), 3) RegistryManager.remove_blok_property('myproperty') self.assertEqual(RegistryManager.has_blok_property('myproperty'), False) finally: EnvironmentManager.set('current_blok', oldblok)
def init_registry(self, function, **kwargs): """ call a function to filled the blok manager with new model :param function: function to call :param kwargs: kwargs for the function :rtype: registry instance """ from copy import deepcopy loaded_bloks = deepcopy(RegistryManager.loaded_bloks) if function is not None: EnvironmentManager.set('current_blok', 'anyblok-core') try: function(**kwargs) finally: EnvironmentManager.set('current_blok', None) try: self.registry = registry = self.__class__.getRegistry() finally: RegistryManager.loaded_bloks = loaded_bloks return registry
def test_global_property(self): RegistryManager.declare_entry('Other') blok = 'newblok' RegistryManager.init_blok(blok) try: oldblok = EnvironmentManager.get('current_blok') EnvironmentManager.set('current_blok', blok) self.assertEqual(RegistryManager.has_blok_property('myproperty'), False) RegistryManager.add_or_replace_blok_property('myproperty', 2) self.assertEqual( RegistryManager.has_blok_property('myproperty'), True) self.assertEqual( RegistryManager.get_blok_property('myproperty'), 2) RegistryManager.add_or_replace_blok_property('myproperty', 3) self.assertEqual( RegistryManager.get_blok_property('myproperty'), 3) RegistryManager.remove_blok_property('myproperty') self.assertEqual(RegistryManager.has_blok_property('myproperty'), False) finally: EnvironmentManager.set('current_blok', oldblok)
def test_decorator_actor_send_with_options(self): def add_in_registry(): from anyblok import Declarations @Declarations.register(Declarations.Model) class Task: id = Integer(primary_key=True) @actor_send(queue_name="other", priority=1) def add(cls, val): return val registry = self.init_registry_with_bloks(('dramatiq',), add_in_registry) self.assertTrue(isinstance(registry.Task.add, AnyBlokActor)) self.assertFalse(EnvironmentManager.get('_postcommit_hook')) registry.Task.add(1) self.assertEqual(registry.Dramatiq.Message.query().count(), 1) self.assertEqual(registry.Task.add.queue_name, "other") self.assertEqual(registry.Task.add.priority, 1) self.assertTrue(EnvironmentManager.get('_postcommit_hook'))
def get_need_blok(cls, blok): if cls.has(blok): return True if blok not in cls.bloks: return False cls.get_need_blok_linked_bloks(blok) cls.ordered_bloks.append(blok) EnvironmentManager.set('current_blok', blok) if not ImportManager.has(blok): # Import only if not exist don't reload here mod = ImportManager.add(blok) mod.imports() else: mod = ImportManager.get(blok) mod.reload() if cls.bloks[blok].autoinstall: cls.auto_install.append(blok) return True
def test_precommit_hook_twice(self): def add_in_registry(): from anyblok import Declarations @Declarations.register(Declarations.Model) class Test: pass registry = self.init_registry(add_in_registry) registry.Test.precommit_hook('_precommit_hook') registry.Test.precommit_hook('_precommit_hook') assert len(EnvironmentManager.get('_precommit_hook', [])) == 1
def test_precommit_hook_twice_with_after_another(self): def add_in_registry(): from anyblok import Declarations @Declarations.register(Declarations.Model) class Test: pass registry = self.init_registry(add_in_registry) registry.Test.precommit_hook('_precommit_hook1') registry.Test.precommit_hook('_precommit_hook2') assert len(EnvironmentManager.get('_precommit_hook', [])) == 2 assert [x[1] for x in EnvironmentManager.get('_precommit_hook')] == [ '_precommit_hook1', '_precommit_hook2'] registry.Test.precommit_hook('_precommit_hook1') assert [x[1] for x in EnvironmentManager.get('_precommit_hook')] == [ '_precommit_hook1', '_precommit_hook2'] registry.Test.precommit_hook( '_precommit_hook1', put_at_the_end_if_exist=True) assert [x[1] for x in EnvironmentManager.get('_precommit_hook')] == [ '_precommit_hook2', '_precommit_hook1']
def reload_registry(self, registry, function, **kwargs): """ call a function to filled the blok manager with new model and before reload the registry :param bloks: list of blok's names :param function: function to call :param kwargs: kwargs for the function :rtype: registry instance """ from copy import deepcopy loaded_bloks = deepcopy(RegistryManager.loaded_bloks) if function is not None: EnvironmentManager.set('current_blok', 'anyblok-test') try: function(**kwargs) finally: EnvironmentManager.set('current_blok', None) try: registry.reload() finally: RegistryManager.loaded_bloks = loaded_bloks return registry
def format(self, record): """ Add color to the message :param record: logging record instance :rtype: logging record formatted """ fg_color, bg_color = LEVEL_COLOR_MAPPING[record.levelno] record.levelname = COLOR_PATTERN % ( 30 + fg_color, 40 + bg_color, record.levelname) fg_color, bg_color = CYAN, DEFAULT record.database = COLOR_PATTERN % ( 30 + fg_color, 40 + bg_color, EnvironmentManager.get('db_name', 'No database')) return logging.Formatter.format(self, record)
def format(self, record): """ Add color to the message :param record: logging record instance :rtype: logging record formatted """ fg_color, bg_color = LEVEL_COLOR_MAPPING[record.levelno] record.levelname = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, record.levelname) fg_color, bg_color = CYAN, DEFAULT record.database = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, EnvironmentManager.get( 'db_name', 'No database')) return logging.Formatter.format(self, record)
def load(cls, entry_points=('bloks', )): """ Load all the bloks and import them :param entry_points: Use by ``iter_entry_points`` to get the blok :exception: BlokManagerException """ if not entry_points: raise BlokManagerException("The entry_points mustn't be empty") cls.entry_points = entry_points if EnvironmentManager.get('current_blok'): while EnvironmentManager.get('current_blok'): sleep(0.1) EnvironmentManager.set('current_blok', 'start') bloks = [] for entry_point in entry_points: count = 0 for i in iter_entry_points(entry_point): count += 1 blok = i.load() blok.required_by = [] blok.optional_by = [] blok.conditional_by = [] blok.conflicting_by = [] cls.set(i.name, blok) blok.name = i.name bloks.append((blok.priority, i.name)) if not count: raise BlokManagerException("Invalid bloks group %r" % entry_point) # Empty the ordered blok to reload it depending on the priority cls.ordered_bloks = [] bloks.sort() try: while bloks: blok = bloks.pop(0)[1] cls.get_need_blok(blok) finally: EnvironmentManager.set('current_blok', None)
def load(cls, entry_points=('bloks',)): """ Load all the bloks and import them :param entry_points: Use by ``iter_entry_points`` to get the blok :exception: BlokManagerException """ if not entry_points: raise BlokManagerException("The entry_points mustn't be empty") cls.entry_points = entry_points if EnvironmentManager.get('current_blok'): while EnvironmentManager.get('current_blok'): sleep(0.1) EnvironmentManager.set('current_blok', 'start') bloks = [] for entry_point in entry_points: count = 0 for i in iter_entry_points(entry_point): count += 1 blok = i.load() blok.required_by = [] blok.optional_by = [] blok.conditional_by = [] blok.conflicting_by = [] cls.set(i.name, blok) blok.name = i.name bloks.append((blok.priority, i.name)) if not count: raise BlokManagerException( "Invalid bloks group %r" % entry_point) # Empty the ordered blok to reload it depending on the priority cls.ordered_bloks = [] bloks.sort() try: while bloks: blok = bloks.pop(0)[1] cls.get_need_blok(blok) finally: EnvironmentManager.set('current_blok', None)
def run(cls, job_uuid=None): """dramatiq actor to execute a specific task""" autocommit = EnvironmentManager.get('job_autocommit', True) try: job = cls.query().filter(cls.uuid == job_uuid).one() job.status = cls.STATUS_RUNNING if autocommit: cls.registry.commit() # use to save the state job.task.run(job) if autocommit: cls.registry.commit() # use to save the state except Exception as e: logger.error(str(e)) cls.registry.rollback() job.status = cls.STATUS_FAILED job.error = str(e) if autocommit: cls.registry.commit() # use to save the state raise e
def tearDownClass(cls): super(TestModel, cls).tearDownClass() EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testModel']
def setUpClass(cls): super(TestCoreInterfaceCoreBase, cls).setUpClass() RegistryManager.init_blok('testCore' + cls._corename) EnvironmentManager.set('current_blok', 'testCore' + cls._corename)
def tearDownClass(cls): super(TestCoreInterfaceCoreBase, cls).tearDownClass() EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testCore' + cls._corename]
def test_set_and_get_variable(self): db_name = 'test db name' EnvironmentManager.set('db_name', db_name) self.assertEqual(EnvironmentManager.get('db_name'), db_name)
def setUpClass(cls): super(TestCoreInterfaceMixin, cls).setUpClass() RegistryManager.init_blok('testMixin') EnvironmentManager.set('current_blok', 'testMixin')
def tearDownClass(cls): super(TestRegistryCore, cls).tearDownClass() EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testCore'] RegistryManager.undeclare_core('test')
def setUpClass(cls): super(TestRegistryCore, cls).setUpClass() RegistryManager.declare_core('test') RegistryManager.init_blok('testCore') EnvironmentManager.set('current_blok', 'testCore')
def test_scoped_function_session(self): self.assertEqual(EnvironmentManager.scoped_function_for_session(), MockEnvironment.scoped_function_for_session)
def setUp(self): super(TestEnvironment, self).setUp() EnvironmentManager.define_environment_cls(MockEnvironment)
def setUpClass(cls): super(TestRegistryEntry, cls).setUpClass() RegistryManager.declare_entry('Other') RegistryManager.init_blok('testEntry') EnvironmentManager.set('current_blok', 'testEntry')
def tearDownClass(cls): super(TestRegistryEntry, cls).tearDownClass() EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testEntry'] RegistryManager.undeclare_entry('Other')
def tearDownClass(cls): super(TestCoreInterfaceMixin, cls).tearDownClass() EnvironmentManager.set('current_blok', None) del RegistryManager.loaded_bloks['testMixin']
def check_bad_define_environment(self, env): try: EnvironmentManager.define_environment_cls(env) self.fail("Bad environment class") except EnvironmentException: pass
def tearDown(self): super(TestEnvironment, self).tearDown() EnvironmentManager.define_environment_cls(ThreadEnvironment)
def __init__(self, *args, **kwargs): EnvironmentManager.set('current_blok', None) super(BlokManagerException, self).__init__(*args, **kwargs)
def setUpClass(cls): super(TestMigration, cls).setUpClass() cls.init_configuration_manager() cls.createdb() BlokManager.load() register = Declarations.register Model = Declarations.Model cls.loaded_bloks = deepcopy(RegistryManager.loaded_bloks) EnvironmentManager.set('current_blok', 'anyblok-core') @register(Model) class Test: integer = Int(primary_key=True) other = Str() @register(Model) class TestUnique: integer = Int(primary_key=True) other = Str(unique=True) @register(Model) class TestIndex: integer = Int(primary_key=True) other = Str(index=True) @register(Model) class TestCheck: integer = Int(primary_key=True) @classmethod def define_table_args(cls): table_args = super(TestCheck, cls).define_table_args() return table_args + ( CheckConstraint('integer > 0', name='test'),) @register(Model) class TestCheckLongConstraintName: integer = Int(primary_key=True) @classmethod def define_table_args(cls): table_args = super(TestCheckLongConstraintName, cls).define_table_args() return table_args + ( CheckConstraint('integer > 0', name=( 'long_long_long_long_long_long_long_long_long_long_' 'long_long_long_long_long_long_long_long_test')),) @register(Model) class TestFKTarget: integer = Int(primary_key=True) @register(Model) class TestFK: integer = Int(primary_key=True) other = Int( foreign_key=Model.TestFKTarget.use('integer')) @register(Model) class TestFK2: integer = Int(primary_key=True) other = Int( foreign_key=Model.TestFKTarget.use('integer').options( ondelete='cascade')) @register(Model) class TestM2M1: idmodel1 = Int(primary_key=True) @register(Model) class TestM2M2: idmodel2 = Int(primary_key=True) rel_m2m = Many2Many(label="Rel", model=Model.TestM2M1, join_table='reltable', remote_columns='idmodel1', m2m_remote_columns='idmodel1', local_columns='idmodel2', m2m_local_columns='idmodel2', many2many='rel_m2m_inv') EnvironmentManager.set('current_blok', None)