def __init__(cls, classname, bases, dict_): DeclarativeMeta.__init__(cls, classname, bases, dict_) try: mapper = class_mapper(cls) _history_mapper(mapper) except UnmappedClassError: pass
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) or getattr( self, '__bind_key__', None) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None and hasattr(self, '__table__'): self.__table__.info['bind_key'] = bind_key
def __init__(self, name, bases, namespace): assert isinstance(namespace, dict), 'Invalid namespace %s' % namespace mappings, models = [], [] for cls in bases: model = typeFor(cls) if isinstance(model, TypeModel): if isinstance(cls, MappedSupport): if models: raise MappingError('The mapped class %s needs to be placed before %s' % (cls, ','.join(mappings))) mappings.append(model) else: models.append(model) if not models: assert log.debug('Cannot find any API model class for \'%s\', no merging required', name) or True DeclarativeMeta.__init__(self, name, bases, namespace) return if len(mappings) > 1: raise MappingError('Cannot inherit more then one mapped class, got %s' % ','.join(str(typ) for typ in mappings)) if len(models) > 1: raise MappingError('Cannot merge with more then one API model class, got %s' % ','.join(str(typ) for typ in models)) model = models[0] assert isinstance(model, TypeModel) self._ally_type = model # Provides the TypeSupport self._ally_reference = {name: Reference(prop) for name, prop in model.properties.items()} self._ally_listeners = {} # Provides the BindableSupport DeclarativeMeta.__init__(self, name, bases, namespace) try: mappings = self.metadata._ally_mappers except AttributeError: mappings = self.metadata._ally_mappers = [] mappings.append(self)
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) if bind_key not in self._metadata: self._metadata[bind_key] = MetaData() self.metadata = self._metadata[bind_key] DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info['bind_key'] = bind_key
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) try: bind_key = d.pop('__bind_key__', DEFAULT_BIND_KEY) self.__table__.info['bind_key'] = bind_key except AttributeError: pass
def __init__(cls, name, bases, attrs): """Handle Flask-SQLAlchemy's bind_key without setting tablename.""" bind_key = attrs.pop('__bind_key__', None) BaseDeclarativeMeta.__init__(cls, name, bases, attrs) if bind_key is not None: cls.__table__.info['bind_key'] = bind_key
def __init__(cls, classname, bases, dict_): # add your changes/additions to classes before it go to SQLAlchemy parser # you can make this way multiple table generations from one class, if needed and etc endings = {'y': lambda x: x[:-1] + "ies", 's': lambda x: x + 'es'} base_name = cls.__name__.lower() cls.__tablename__ = endings.get(base_name[-1], lambda x: x + 's')(base_name) DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(cls, name, bases, dct): DeclarativeMeta.__init__(cls, name, bases, dct) if hasattr(cls, '__table__'): if '__bind_key__' in dct: cls.__table__.info['bind_key'] = dct['__bind_key__'] events.register(cls, dct)
def __init__(cls, names, bases, dict_): DeclarativeMeta.__init__(cls, names, bases, dict_) if not hasattr(cls, '_obj_classes'): # This will be set in the 'DomainObject' class. cls._obj_classes = collections.defaultdict(list) else: # Add the subclass to DomainObject._obj_classes base.make_class_properties(cls) cls._obj_classes[cls.obj_name()].append(cls)
def __init__(cls, name, bases, dct): bind_key = dct.pop('__bind_key__', None) DeclarativeMeta.__init__(cls, name, bases, dct) if bind_key is not None: cls.__table__.info['bind_key'] = bind_key events.register(cls, dct)
def __init__(cls, names, bases, dict_): DeclarativeMeta.__init__(cls, names, bases, dict_) if not hasattr(cls, "_obj_classes"): # This will be set in the 'DomainObject' class. cls._obj_classes = collections.defaultdict(list) else: # Add the subclass to DomainObject._obj_classes base.make_class_properties(cls) cls._obj_classes[cls.obj_name()].append(cls)
def __init__(mcs, classname, bases, dict_): """ Permet l'ajout automatique du préfixe aux tables du modèle, lorsque celles-ci sont définies en utilisant le mode "Declarative" de SQLAlchemy. """ if '__tablename__' in dict_: mcs.__tablename__ = dict_['__tablename__'] = \ configure.DB_BASENAME + dict_['__tablename__'] DeclarativeMeta.__init__(mcs, classname, bases, dict_)
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) or getattr( self, '__bind_key__', None) if bind_key: if bind_key not in self._metadata: self._metadata[bind_key] = MetaData() self.metadata = self._metadata[bind_key] DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None and hasattr(self, '__table__'): self.__table__.info['bind_key'] = bind_key
def __init__(self, name, bases, d): route_key = d.pop('__route_key__', None) shard_key = d.pop('__shard_key__', None) shard_lookup = d.pop('__shard_lookup__', None) DeclarativeMeta.__init__(self, name, bases, d) if route_key is not None: self.__table__.info['route_key'] = route_key if shard_key is not None: self.__table__.info['shard_key'] = shard_key if shard_lookup is not None: self.__table__.info['shard_lookup'] = shard_lookup
def __init__(self, name, bases, namespace): assert isinstance(namespace, dict), 'Invalid namespace %s' % namespace mapped, models = [], [] for cls in bases: typ = typeFor(cls) if isinstance(typ, TypeModelMapped): mapped.append(cls) elif isinstance(typ, TypeModel): models.append(cls) if not mapped and not models: assert log.debug( 'Cannot find any API model class for \'%s\', no merging required', name) or True DeclarativeMeta.__init__(self, name, bases, namespace) return if len(mapped) > 1: raise MappingError( 'Cannot inherit more then one mapped class, got %s' % models) if len(models) > 1: raise MappingError( 'Cannot merge with more then one API model class, got %s' % models) if models: typeModel = typeFor(models[0]) else: typeModel = None if mapped: if typeModel is None: typeModel = typeFor(mapped[0]).base assert isinstance(typeModel, TypeModel) typeModel = TypeModelMapped(self, typeModel) self._ally_reference = { prop: Reference(TypeModelProperty(typeModel, prop, propType)) for prop, propType in typeModel.container.properties.items() } self._ally_listeners = {} # Provides the BindableSupport self._ally_type = typeModel # Provides the TypeSupport DeclarativeMeta.__init__(self, name, bases, namespace) # TODO: see if required: self.__clause_element__ = lambda: self.__table__ for prop in typeModel.container.properties: if typeFor(getattr(self, prop)) != typeFor( self._ally_reference[prop]): value, _class = getAttrAndClass(self, prop) setattr(self, prop, value) try: mappings = self.metadata._ally_mappers except AttributeError: mappings = self.metadata._ally_mappers = deque() mappings.append(self)
def __init__(self, name, bases, namespace): assert isinstance(namespace, dict), "Invalid namespace %s" % namespace mapped, models = [], [] for cls in bases: typ = typeFor(cls) if isinstance(typ, TypeModelMapped): mapped.append(cls) elif isinstance(typ, TypeModel): models.append(cls) if not mapped and not models: assert log.debug("Cannot find any API model class for '%s', no merging required", name) or True DeclarativeMeta.__init__(self, name, bases, namespace) return if len(mapped) > 1: raise MappingError("Cannot inherit more then one mapped class, got %s" % models) if len(models) > 1: raise MappingError("Cannot merge with more then one API model class, got %s" % models) if models: typeModel = typeFor(models[0]) else: typeModel = None if mapped: if typeModel is None: typeModel = typeFor(mapped[0]).base assert isinstance(typeModel, TypeModel) typeModel = TypeModelMapped(self, typeModel) self._ally_reference = { prop: Reference(TypeModelProperty(typeModel, prop, propType)) for prop, propType in typeModel.container.properties.items() } self._ally_listeners = {} # Provides the BindableSupport self._ally_type = typeModel # Provides the TypeSupport DeclarativeMeta.__init__(self, name, bases, namespace) # TODO: see if required: self.__clause_element__ = lambda: self.__table__ for prop in typeModel.container.properties: if typeFor(getattr(self, prop)) != typeFor(self._ally_reference[prop]): value, _class = getAttrAndClass(self, prop) setattr(self, prop, value) try: mappings = self.metadata._ally_mappers except AttributeError: mappings = self.metadata._ally_mappers = deque() mappings.append(self)
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) if not hasattr(self, '__table__'): return distribution_method = d.pop('__distribution_method__', None) distribution_column = ( d.pop('__distribute_by__', None) or getattr(self, '__bind_key__', None) ) colocated_table = d.pop('__colocate_with__', None) if distribution_method is not None: self.__table__.info['is_distributed'] = True self.__table__.info['distribution_method'] = distribution_method if distribution_method in {'range', 'hash'}: if distribution_column is None: raise ValueError( 'Table "%s" is distributed by "%s" and must therefore ' 'provide a distribution column via "__distribute_by__".' % (self.__table__.name, distribution_method) ) column_type = self.__table__.c[distribution_column].type if not isinstance(column_type, sqlalchemy.types.Integer): raise TypeError( 'Distribution column "%s" of table "%s" must have type ' '"%s" for distribtion method "%s"' % ( distribution_column, self.__table__.name, sqlalchemy.types.Integer.__name__, table.info['distribution_method'] ) ) columns = self.__table__.c if distribution_column not in columns: raise ValueError( 'Specified distribution column "%s" ' 'is not a column of table "%s".' % (distribution_column, self.__table__.name) ) self.__table__.info['distribute_by'] = distribution_column self.__table__.info['colocate_with'] = colocated_table elif distribution_method == 'replication': self.__table__.info['distribute_by'] = None self.__table__.info['colocate_with'] = None else: raise ValueError( 'Table "%s" specified an unsupported distribution method. ' 'Supported are: "range", "hash" and "replication".' % self.__table__.name ) else: self.__table__.info['is_distributed'] = False
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) try: bind_key = d.pop('__bind_key__', None) if not bind_key: for base in bases: if getattr(base, '__bind_key__', None): bind_key = getattr(base, '__bind_key__') break else: bind_key = DEFAULT_BIND_KEY self.__table__.info['bind_key'] = bind_key except AttributeError: pass
def __init__(self, name, bases, d): meta = d.pop('Meta', None) if meta is not None: bind_key = getattr(meta, 'bind', DEFAULT_BIND_KEY) mount_meta(meta, self) else: bind_key = DEFAULT_BIND_KEY DeclarativeMeta.__init__(self, name, bases, d) try: self.__table__.info['bind_key'] = bind_key except AttributeError: # при создании декларативного # класса еще не будет атрибута __table__, поэтому эта # ситация является нормальной pass
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) if not hasattr(self, '__table__'): return distribution_method = d.pop('__distribution_method__', None) distribution_column = (d.pop('__distribute_by__', None) or getattr(self, '__bind_key__', None)) colocated_table = d.pop('__colocate_with__', None) if distribution_method is not None: self.__table__.info['is_distributed'] = True self.__table__.info['distribution_method'] = distribution_method if distribution_method in {'range', 'hash'}: if distribution_column is None: raise ValueError( 'Table "%s" is distributed by "%s" and must therefore ' 'provide a distribution column via "__distribute_by__".' % (self.__table__.name, distribution_method)) column_type = self.__table__.c[distribution_column].type if not isinstance(column_type, sqlalchemy.types.Integer): raise TypeError( 'Distribution column "%s" of table "%s" must have type ' '"%s" for distribtion method "%s"' % (distribution_column, self.__table__.name, sqlalchemy.types.Integer.__name__, table.info['distribution_method'])) columns = self.__table__.c if distribution_column not in columns: raise ValueError( 'Specified distribution column "%s" ' 'is not a column of table "%s".' % (distribution_column, self.__table__.name)) self.__table__.info['distribute_by'] = distribution_column self.__table__.info['colocate_with'] = colocated_table elif distribution_method == 'replication': self.__table__.info['distribute_by'] = None self.__table__.info['colocate_with'] = None else: raise ValueError( 'Table "%s" specified an unsupported distribution method. ' 'Supported are: "range", "hash" and "replication".' % self.__table__.name) else: self.__table__.info['is_distributed'] = False
def __init__(klass, classname, bases, dict_): """ Create a new class type. DeclarativeMeta stores class attributes in dict_ """ # Additionally, set attributes on the new object. is_pk = True for name in dict_.get('__fields__', []): if name in ['id', 'duration']: kol = Integer() elif name in ['path', 'entry']: kol = String(192) else: kol = String(64) setattr( klass, name, Column(name, kol, primary_key=is_pk)) is_pk = False # Return the new object using super(). return DeclarativeMeta.__init__(klass, classname, bases, dict_)
def __init__(cls, name, bases, dct): DeclarativeMeta.__init__(cls, name, bases, dct) if dct.get("__metaclass__", None) is not TopLevelMeta: event.listen(cls, "before_update", update_timestamp)
def __init__(self, classname, bases, dict_): meta._MODELS[classname] = self return DeclarativeMeta.__init__(self, classname, bases, dict_)
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) if hasattr(bases[0], '_db'): bases[0]._db.models[name] = self bases[0]._db.tables[self.__table__.name] = self.__table__ self._db = bases[0]._db
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) abstract = d.get('__abstract__', False) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None and not abstract: self.__table__.info['bind_key'] = bind_key
def __init__(cls, classname, bases, dict_): cls_registry[classname] = cls return DeclarativeMeta.__init__( cls, classname, bases, dict_)
def __init__(self, name, bases, d): bind_key = d.pop("__bind_key__", None) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info["bind_key"] = bind_key
def __init__(cls, classname, bases, dict_): return DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) abstract_inherit = d.get("__abstract_inherit__") if abstract_inherit: inherit = d['__abstract_inherit__'][0].__dict__ d['super'] = {} for key in inherit: if hasattr(inherit[key], '__module__'): module = str(inherit[key].__module__) if module.startswith('sqlalchemy'): continue if key not in d: d[key] = inherit[key] elif key in d and type(inherit[key]) == types.FunctionType: if not d['super'].get(key): d['super'][key] = list() d['super'][key].append(inherit[key]) db = {} has_one = {} has_many = {} many_many = {} belongs_many_many = {} if abstract_inherit: for b in reversed(abstract_inherit): if hasattr(b, 'db'): db = merge_dicts(db, b.db) if hasattr(b, 'has_one'): has_one = merge_dicts(has_one, b.has_one) if hasattr(b, 'has_many'): has_many = merge_dicts(has_many, b.has_many) if hasattr(b, 'many_many'): many_many = merge_dicts(many_many, b.many_many) if hasattr(b, 'belongs_many_many'): belongs_many_many = merge_dicts(belongs_many_many, b.belongs_many_many) if d.get('db'): db.update(d.get('db')) if d.get('has_one'): has_one.update(d.get('has_one')) if d.get('has_many'): has_many.update(d.get('has_many')) if d.get('many_many'): many_many.update(d.get('many_many')) if d.get('belongs_many_many'): belongs_many_many.update(d.get('belongs_many_many')) if db: for key in db: if type(db[key]) == str: col = sqlalchemy.Column(getattr(sqlalchemy, db[key])) else: v = db[key] t = v['type'] fk = v.get('foreign_key') pk = v.get('primary_key') if v.get('primary_key') else False col = sqlalchemy.Column(getattr(sqlalchemy, t), sqlalchemy.ForeignKey(fk), primary_key=pk) setattr(self, key, col) for key in has_one: ref = has_one[key] rel = sqlalchemy.orm.relationship(ref) col = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(ref.lower() + ".id")) setattr(self, key + "_id", col) setattr(self, key, rel) for key in has_many: ref = has_many[key] rel = sqlalchemy.orm.relationship(ref) setattr(self, key, rel) for key in belongs_many_many: ref = belongs_many_many[key] split_ref = ref.split(".") many_many_cls = split_ref[0] table_name = self.get_assoc_tablename_backref(ref, self.__name__) rel = sqlalchemy.orm.relationship(many_many_cls, secondary=table_name) setattr(self, key, rel) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info['bind_key'] = bind_key many_many_values = list(many_many.values()) many_many_duplicates = [x for x in many_many_values if many_many_values.count(x) > 1] self.assoc_tables = [] for key in many_many: ref = many_many[key] fk2 = ref.lower() + ".id" if ref in many_many_duplicates: table_name = self.get_assoc_tablename(self.__name__, key, ref) else: table_name = self.get_assoc_tablename(self.__name__, '', ref) table = sqlalchemy.Table(table_name, self.metadata, sqlalchemy.Column(name.lower() + '_id', sqlalchemy.Integer, sqlalchemy.ForeignKey(name.lower() + '.id')), sqlalchemy.Column(ref + '_id', sqlalchemy.Integer, sqlalchemy.ForeignKey(fk2))) self.assoc_tables.append(table) rel = sqlalchemy.orm.relationship(ref, secondary=table_name) setattr(self, key, rel)
def __init__(self, name, bases, dic): bind_key = dic.pop('__bind_key__', None) DeclarativeMeta.__init__(self, name, bases, dic) if bind_key is not None: self.__table__.info['bind_key'] = bind_key
def __init__(cls, classname, bases, dict_): cls.__tablename__ = inflection.pluralize(inflection.underscore(classname)) DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(mcs, classname, bases, dict_): SADeclarativeMeta.__init__(mcs, classname, bases, dict_) # load the model into the correct resource manager if 'manager' in dict_: dict_['manager'].models.append(mcs)
def __init__(cls, name, bases, dct): DeclarativeMeta.__init__(cls, name, bases, dct) if hasattr(cls, '__table__'): event.register(cls, dct)
def __init__(cls, classname, bases, dict_): if '__tablename__' in dict_: cls.__tablename__ = dict_['__tablename__'] = APP_NAME + "_" + cls.__tablename__ return DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info['bind_key'] = bind_key
def __init__(cls, classname, bases, dict_): meta._MODELS[classname] = cls return DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(cls, classname, bases, dict_): #@NoSelf cls.__tablename__ = inflection.underscore(classname) DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(cls, classname, bases, dict_): dict_['id'] = Column(Integer, primary_key=True) dict_['uuid'] = Column(Unicode, unique=True) meta._MODELS[classname] = cls return DeclarativeMeta.__init__(cls, classname, bases, dict_)
def __init__(cls, classname, bases, dict_): DeclarativeMeta.__init__(cls, classname, bases, dict_) if not Model in bases: session_mapper(cls)
def __init__(cls, *args): # noqa: N805 DeclarativeMeta.__init__(cls, *args) if hasattr(cls, "database_init"): cls.database_init() self.set_custom_properties(cls)